Skip to content

Commit f013b6d

Browse files
committed
fix(get): Don't crash on bad negative bounds
1 parent 4814f53 commit f013b6d

File tree

2 files changed

+7
-8
lines changed

2 files changed

+7
-8
lines changed

src/path/mod.rs

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -40,11 +40,11 @@ impl std::fmt::Display for ParseError {
4040

4141
impl std::error::Error for ParseError {}
4242

43-
fn sindex_to_uindex(index: isize, len: usize) -> usize {
43+
fn sindex_to_uindex(index: isize, len: usize) -> Option<usize> {
4444
if index >= 0 {
45-
index as usize
45+
Some(index as usize)
4646
} else {
47-
len - index.unsigned_abs()
47+
len.checked_sub(index.unsigned_abs())
4848
}
4949
}
5050

@@ -80,7 +80,7 @@ impl Expression {
8080
Self::Subscript(expr, index) => match expr.get(root) {
8181
Some(value) => match value.kind {
8282
ValueKind::Array(ref array) => {
83-
let index = sindex_to_uindex(index, array.len());
83+
let index = sindex_to_uindex(index, array.len())?;
8484

8585
if index >= array.len() {
8686
None
@@ -141,7 +141,7 @@ impl Expression {
141141

142142
match value.kind {
143143
ValueKind::Array(ref mut array) => {
144-
let index = sindex_to_uindex(index, array.len());
144+
let index = sindex_to_uindex(index, array.len())?;
145145

146146
if index >= array.len() {
147147
array.resize(index + 1, Value::new(None, ValueKind::Nil));
@@ -216,7 +216,7 @@ impl Expression {
216216
}
217217

218218
if let ValueKind::Array(ref mut array) = parent.kind {
219-
let uindex = sindex_to_uindex(index, array.len());
219+
let uindex = sindex_to_uindex(index, array.len()).unwrap();
220220
if uindex >= array.len() {
221221
array.resize(uindex + 1, Value::new(None, ValueKind::Nil));
222222
}

tests/testsuite/errors.rs

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,6 @@ fn test_error_path_index_bounds() {
2828

2929
#[test]
3030
#[cfg(feature = "json")]
31-
#[should_panic]
3231
fn test_error_path_index_negative_bounds() {
3332
let c = Config::builder()
3433
.add_source(File::from_str(
@@ -46,7 +45,7 @@ fn test_error_path_index_negative_bounds() {
4645
assert!(res.is_err());
4746
assert_data_eq!(
4847
res.unwrap_err().to_string(),
49-
str![[r#"configuration property "arr[2]" not found"#]]
48+
str![[r#"configuration property "arr[-1]" not found"#]]
5049
);
5150
}
5251

0 commit comments

Comments
 (0)