Skip to content

Commit

Permalink
fix(set): Dont crash on bad negative bounds
Browse files Browse the repository at this point in the history
Fixes #619
  • Loading branch information
epage committed Dec 19, 2024
1 parent 3638cdc commit da18a36
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 10 deletions.
31 changes: 22 additions & 9 deletions src/path/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,11 +41,13 @@ impl std::fmt::Display for ParseError {
impl std::error::Error for ParseError {}

/// Convert a relative index into an absolute index
fn abs_index(index: isize, len: usize) -> Option<usize> {
fn abs_index(index: isize, len: usize) -> Result<usize, usize> {
if index >= 0 {
Some(index as usize)
Ok(index as usize)
} else if let Some(index) = len.checked_sub(index.unsigned_abs()) {
Ok(index)
} else {
len.checked_sub(index.unsigned_abs())
Err((len as isize + index).unsigned_abs())
}
}

Expand Down Expand Up @@ -81,7 +83,7 @@ impl Expression {
Self::Subscript(expr, index) => match expr.get(root) {
Some(value) => match value.kind {
ValueKind::Array(ref array) => {
let index = abs_index(index, array.len())?;
let index = abs_index(index, array.len()).ok()?;
array.get(index)
}

Expand Down Expand Up @@ -137,7 +139,7 @@ impl Expression {

match value.kind {
ValueKind::Array(ref mut array) => {
let index = abs_index(index, array.len())?;
let index = abs_index(index, array.len()).ok()?;

if index >= array.len() {
array.resize(index + 1, Value::new(None, ValueKind::Nil));
Expand Down Expand Up @@ -212,10 +214,21 @@ impl Expression {
}

if let ValueKind::Array(ref mut array) = parent.kind {
let uindex = abs_index(index, array.len()).unwrap();
if uindex >= array.len() {
array.resize(uindex + 1, Value::new(None, ValueKind::Nil));
}
let uindex = match abs_index(index, array.len()) {
Ok(uindex) => {
if uindex >= array.len() {
array.resize(uindex + 1, Value::new(None, ValueKind::Nil));
}
uindex
}
Err(insertion) => {
array.splice(
0..0,
(0..insertion).map(|_| Value::new(None, ValueKind::Nil)),
);
0
}
};

array[uindex] = value;
}
Expand Down
1 change: 0 additions & 1 deletion tests/testsuite/set.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,6 @@ fn test_set_scalar_path() {

#[test]
#[cfg(feature = "json")]
#[should_panic]
fn test_set_arr_path() {
let config = Config::builder()
.set_override("present[0].name", "Ivan")
Expand Down

0 comments on commit da18a36

Please sign in to comment.