Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 12 additions & 1 deletion ndc_stdlib/src/index.rs
Original file line number Diff line number Diff line change
Expand Up @@ -225,6 +225,13 @@ enum VmOffset {
Range(usize, usize),
}

fn char_index_to_byte_offset(string: &str, index: usize) -> usize {
string
.char_indices()
.nth(index)
.map_or(string.len(), |(byte_offset, _)| byte_offset)
}

fn extract_vm_offset(index_value: &Value, size: usize) -> Result<VmOffset, VmError> {
if let Value::Object(obj) = index_value
&& let Object::Iterator(iter) = obj.as_ref()
Expand Down Expand Up @@ -514,9 +521,13 @@ fn vm_set_at_index(container: &Value, index_value: &Value, rhs: Value) -> Result
let mut s = s.borrow_mut();
match extract_vm_offset(index_value, size)? {
VmOffset::Element(idx) => {
s.replace_range(idx..=idx, &rhs_str);
let from = char_index_to_byte_offset(&s, idx);
let to = char_index_to_byte_offset(&s, idx + 1);
s.replace_range(from..to, &rhs_str);
}
VmOffset::Range(from, to) => {
let from = char_index_to_byte_offset(&s, from);
let to = char_index_to_byte_offset(&s, to);
s.replace_range(from..to, &rhs_str);
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,9 @@
let str = "foobar";
str[0] = "w";
assert_eq(str, "woobar");

let unicode = "a茅馃z";
unicode[1] = "酶";
assert_eq(unicode, "a酶馃z");
unicode[2] = "X";
assert_eq(unicode, "a酶Xz");
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
let str = "foobak";
str[-1] = "r";
assert_eq(str, "foobar");

let unicode = "a茅馃z";
unicode[-2] = "X";
assert_eq(unicode, "a茅Xz");
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,6 @@ let s = "The world is mine";
s[4..8] = "foo";
assert_eq(s, "The food is mine");

let unicode = "a茅馃z";
unicode[1..3] = "惟";
assert_eq(unicode, "a惟z");
Loading