Fix panic when string character index is OOB.

This commit is contained in:
Stephen Chung
2020-05-01 23:39:55 +08:00
parent de4120b3bc
commit fc99b981a1
2 changed files with 18 additions and 14 deletions

View File

@@ -1057,15 +1057,25 @@ impl Engine {
.as_int()
.map_err(|_| EvalAltResult::ErrorNumericIndexExpr(idx_pos))?;
let num_chars = s.chars().count();
if index >= 0 {
let index = index as usize;
let ch = s.chars().nth(index).unwrap();
Ok(Target::StringChar(Box::new((val, index, ch.into()))))
let ch = s.chars().nth(index as usize).ok_or_else(|| {
Box::new(EvalAltResult::ErrorStringBounds(
s.chars().count(),
index,
idx_pos,
))
})?;
Ok(Target::StringChar(Box::new((
val,
index as usize,
ch.into(),
))))
} else {
Err(Box::new(EvalAltResult::ErrorStringBounds(
num_chars, index, idx_pos,
s.chars().count(),
index,
idx_pos,
)))
}
}