Implement "set" function for strings

This commit is contained in:
Konstantin Nazarov 2024-09-30 01:29:35 +01:00
parent 9e8f857836
commit 2e3032ad26
Signed by: knazarov
GPG key ID: 4CFE0A42FA409C22
2 changed files with 27 additions and 3 deletions

View file

@ -228,6 +228,29 @@ Result<Value> String::get(const Value& key) const {
return res;
}
Result<Value> String::set_value(const Value& key, const Value& value) const {
if (!key.is<Int64>()) {
return ERROR(TypeMismatch);
}
if (!value.is<String>()) {
return ERROR(TypeMismatch);
}
uint64_t idx = (uint64_t)key.to<Int64>()->value();
const String& value_str = *value.to<String>();
auto str_size = TRY(size());
if (idx >= str_size + 1) return ERROR(IndexOutOfRange);
auto res = TRY(slice(0, idx));
res = TRY(res.concat(value_str));
auto rem = TRY(slice(std::min(str_size, idx + 1), str_size));
res = TRY(res.concat(rem));
return Value(std::move(res));
}
Result<Value> Symbol::copy_value() const {
return Value(Symbol(TRY(_value.copy())));
}

View file

@ -541,8 +541,9 @@ class String : public Object {
}
Result<Value> get(const Value& key) const;
Result<Value> set_value(const Value& key, const Value& value) const;
Result<String> concat(const char* rhs, uint64_t rhs_size) {
Result<String> concat(const char* rhs, uint64_t rhs_size) const {
uint64_t lhs_size = TRY(size());
uint64_t res_size = lhs_size + rhs_size;
@ -557,7 +558,7 @@ class String : public Object {
Result<String> concat(const char* rhs) { return concat(rhs, strlen(rhs)); }
Result<String> concat(const char32_t* rhs, uint64_t rhs_size) {
Result<String> concat(const char32_t* rhs, uint64_t rhs_size) const {
uint64_t lhs_size = TRY(size());
uint64_t res_size = lhs_size + rhs_size;
@ -570,7 +571,7 @@ class String : public Object {
return String(TRY(MkGcRoot(pod)));
}
Result<String> concat(String& rhs) {
Result<String> concat(const String& rhs) const {
uint64_t rhs_size = TRY(rhs.size());
uint64_t lhs_size = TRY(size());
uint64_t res_size = lhs_size + rhs_size;