Skip to content

Commit da18a36

Browse files
committed
fix(set): Dont crash on bad negative bounds
Fixes #619
1 parent 3638cdc commit da18a36

File tree

2 files changed

+22
-10
lines changed

2 files changed

+22
-10
lines changed

src/path/mod.rs

Lines changed: 22 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -41,11 +41,13 @@ impl std::fmt::Display for ParseError {
4141
impl std::error::Error for ParseError {}
4242

4343
/// Convert a relative index into an absolute index
44-
fn abs_index(index: isize, len: usize) -> Option<usize> {
44+
fn abs_index(index: isize, len: usize) -> Result<usize, usize> {
4545
if index >= 0 {
46-
Some(index as usize)
46+
Ok(index as usize)
47+
} else if let Some(index) = len.checked_sub(index.unsigned_abs()) {
48+
Ok(index)
4749
} else {
48-
len.checked_sub(index.unsigned_abs())
50+
Err((len as isize + index).unsigned_abs())
4951
}
5052
}
5153

@@ -81,7 +83,7 @@ impl Expression {
8183
Self::Subscript(expr, index) => match expr.get(root) {
8284
Some(value) => match value.kind {
8385
ValueKind::Array(ref array) => {
84-
let index = abs_index(index, array.len())?;
86+
let index = abs_index(index, array.len()).ok()?;
8587
array.get(index)
8688
}
8789

@@ -137,7 +139,7 @@ impl Expression {
137139

138140
match value.kind {
139141
ValueKind::Array(ref mut array) => {
140-
let index = abs_index(index, array.len())?;
142+
let index = abs_index(index, array.len()).ok()?;
141143

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

214216
if let ValueKind::Array(ref mut array) = parent.kind {
215-
let uindex = abs_index(index, array.len()).unwrap();
216-
if uindex >= array.len() {
217-
array.resize(uindex + 1, Value::new(None, ValueKind::Nil));
218-
}
217+
let uindex = match abs_index(index, array.len()) {
218+
Ok(uindex) => {
219+
if uindex >= array.len() {
220+
array.resize(uindex + 1, Value::new(None, ValueKind::Nil));
221+
}
222+
uindex
223+
}
224+
Err(insertion) => {
225+
array.splice(
226+
0..0,
227+
(0..insertion).map(|_| Value::new(None, ValueKind::Nil)),
228+
);
229+
0
230+
}
231+
};
219232

220233
array[uindex] = value;
221234
}

tests/testsuite/set.rs

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,6 @@ fn test_set_scalar_path() {
6363

6464
#[test]
6565
#[cfg(feature = "json")]
66-
#[should_panic]
6766
fn test_set_arr_path() {
6867
let config = Config::builder()
6968
.set_override("present[0].name", "Ivan")

0 commit comments

Comments
 (0)