Skip to content

Commit f104ee1

Browse files
committed
mutable str
1 parent 006eb2b commit f104ee1

File tree

2 files changed

+24
-6
lines changed

2 files changed

+24
-6
lines changed

src/interpreter/value/slash_value.c

+22-3
Original file line numberDiff line numberDiff line change
@@ -670,8 +670,6 @@ SlashValue str_to_str(Interpreter *interpreter, SlashValue self)
670670
return self;
671671
}
672672

673-
674-
// SlashValue range_item_get(Interpreter *interpreter, SlashValue self, SlashValue other)
675673
SlashValue str_item_get(Interpreter *interpreter, SlashValue self, SlashValue other)
676674
{
677675
assert(IS_STR(self));
@@ -705,6 +703,27 @@ SlashValue str_item_get(Interpreter *interpreter, SlashValue self, SlashValue ot
705703
return AS_VALUE(new);
706704
}
707705

706+
void str_item_assign(Interpreter *interpreter, SlashValue self, SlashValue index, SlashValue other)
707+
{
708+
assert(IS_STR(self));
709+
assert(IS_STR(other));
710+
assert(IS_NUM(index)); // TODO: implement for range
711+
if (!NUM_IS_INT(index))
712+
REPORT_RUNTIME_ERROR("Str index can not be a floating point number: '%f'", index.num);
713+
714+
SlashStr *str = AS_STR(self);
715+
/* Ensure the index is valid */
716+
int idx = (int)index.num;
717+
if (idx < 0 || (size_t)idx >= str->len)
718+
REPORT_RUNTIME_ERROR("Str index '%d' out of range for str with len '%zu'", idx, str->len);
719+
720+
SlashStr *str_other = AS_STR(other);
721+
if (str_other->len != 1)
722+
REPORT_RUNTIME_ERROR("Can only assign a string of length one, not length.");
723+
724+
str->str[idx] = str_other->str[0];
725+
}
726+
708727
bool str_item_in(SlashValue self, SlashValue other)
709728
{
710729
assert(IS_STR(self) && IS_STR(other));
@@ -968,7 +987,7 @@ SlashTypeInfo str_type_info = { .name = "str",
968987
.print = str_print,
969988
.to_str = str_to_str,
970989
.item_get = str_item_get,
971-
.item_assign = NULL,
990+
.item_assign = str_item_assign,
972991
.item_in = str_item_in,
973992
.truthy = str_truthy,
974993
.eq = str_eq,

test/str.slash

+2-3
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,8 @@
44
assert $a[0] == "h"
55
assert $a[..5] == "hello"
66
# item assign
7-
# $a[0] = "H"
8-
# assert $a[0] == "H"
9-
# item in
7+
$a[0] = "H"
8+
assert $a[0] == "H"
109
}
1110

1211
# string comparison

0 commit comments

Comments
 (0)