Skip to content

Commit 78ea165

Browse files
committed
Fix panic when truncating value at multi-byte character
1 parent 6445380 commit 78ea165

File tree

2 files changed

+14
-7
lines changed

2 files changed

+14
-7
lines changed

lib/src/db/query_index.rs

Lines changed: 2 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
44
use crate::{
55
agents::ForAgent, atoms::IndexAtom, errors::AtomicResult, storelike::Query,
6-
values::SortableValue, Atom, Db, Resource, Storelike, Value,
6+
utils::truncate_string, values::SortableValue, Atom, Db, Resource, Storelike, Value,
77
};
88
use serde::{Deserialize, Serialize};
99

@@ -339,12 +339,7 @@ pub fn create_query_index_key(
339339
q_filter_bytes.push(SEPARATION_BIT);
340340

341341
let mut value_bytes: Vec<u8> = if let Some(val) = value {
342-
let val_string = val;
343-
let shorter = if val_string.len() > MAX_LEN {
344-
&val_string[0..MAX_LEN]
345-
} else {
346-
val_string
347-
};
342+
let shorter = truncate_string(val, MAX_LEN);
348343
let lowercase = shorter.to_lowercase();
349344
lowercase.as_bytes().to_vec()
350345
} else {

lib/src/utils.rs

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,3 +69,15 @@ pub fn check_timestamp_in_past(timestamp: i64, difference: i64) -> AtomicResult<
6969
}
7070
return Ok(());
7171
}
72+
73+
pub fn truncate_string(s: &str, max_len: usize) -> String {
74+
if s.len() <= max_len {
75+
return s.to_string();
76+
}
77+
78+
let mut end = max_len;
79+
while !s.is_char_boundary(end) {
80+
end -= 1;
81+
}
82+
s[0..end].to_string()
83+
}

0 commit comments

Comments
 (0)