From 3c4f1946101c68d60d6538bb11e80a9a71c15e0c Mon Sep 17 00:00:00 2001 From: Tobie Morgan Hitchcock Date: Sat, 3 Dec 2022 23:30:38 +0000 Subject: [PATCH] Ensure string::slice does not panic with usize overflow --- lib/src/fnc/string.rs | 8 ++++++-- lib/tests/function.rs | 7 ++++++- 2 files changed, 12 insertions(+), 3 deletions(-) diff --git a/lib/src/fnc/string.rs b/lib/src/fnc/string.rs index e2d8969f..746f73f5 100644 --- a/lib/src/fnc/string.rs +++ b/lib/src/fnc/string.rs @@ -53,12 +53,16 @@ pub fn reverse((string,): (String,)) -> Result { pub fn slice((val, beg, lim): (String, Option, Option)) -> Result { let val = match beg { - Some(v) if v < 0 => val.chars().skip(val.len() - v.unsigned_abs()).collect::(), + Some(v) if v < 0 => { + val.chars().skip(val.len().saturating_sub(v.unsigned_abs())).collect::() + } Some(v) => val.chars().skip(v as usize).collect::(), None => val, }; let val = match lim { - Some(v) if v < 0 => val.chars().take(val.len() - v.unsigned_abs()).collect::(), + Some(v) if v < 0 => { + val.chars().take(val.len().saturating_sub(v.unsigned_abs())).collect::() + } Some(v) => val.chars().take(v as usize).collect::(), None => val, }; diff --git a/lib/tests/function.rs b/lib/tests/function.rs index cf15ae49..35f3bf28 100644 --- a/lib/tests/function.rs +++ b/lib/tests/function.rs @@ -235,11 +235,12 @@ async fn function_string_slice() -> Result<(), Error> { RETURN string::slice("the quick brown fox jumps over the lazy dog.", 0, -1); RETURN string::slice("the quick brown fox jumps over the lazy dog.", 16, -1); RETURN string::slice("the quick brown fox jumps over the lazy dog.", -9, -1); + RETURN string::slice("the quick brown fox jumps over the lazy dog.", -100, -100); "#; let dbs = Datastore::new("memory").await?; let ses = Session::for_kv().with_ns("test").with_db("test"); let res = &mut dbs.execute(&sql, &ses, None, false).await?; - assert_eq!(res.len(), 6); + assert_eq!(res.len(), 7); // let tmp = res.remove(0).result?; let val = Value::parse("'the quick brown fox jumps over the lazy dog.'"); @@ -265,5 +266,9 @@ async fn function_string_slice() -> Result<(), Error> { let val = Value::parse("'lazy dog'"); assert_eq!(tmp, val); // + let tmp = res.remove(0).result?; + let val = Value::parse("''"); + assert_eq!(tmp, val); + // Ok(()) }