diff --git a/lib/std/core/dstring.c3 b/lib/std/core/dstring.c3 index 1dcc482ab..d42f16507 100644 --- a/lib/std/core/dstring.c3 +++ b/lib/std/core/dstring.c3 @@ -132,7 +132,7 @@ fn usz DString.capacity(self) return self.data().capacity; } -fn usz DString.len(&self) @dynamic +fn usz DString.len(&self) @dynamic @operator(len) { if (!*self) return 0; return self.data().len; @@ -154,6 +154,24 @@ fn String DString.str_view(self) return (String)data.chars[:data.len]; } +<* + @require index < self.len() + @require self.data() "Empty string" +*> +fn char DString.char_at(self, usz index) @operator([]) +{ + return self.data().chars[index]; +} + +<* + @require index < self.len() + @require self.data() "Empty string" +*> +fn char* DString.char_ref(&self, usz index) @operator(&[]) +{ + return &self.data().chars[index]; +} + fn usz DString.append_utf32(&self, Char32[] chars) { self.reserve(chars.len); @@ -168,7 +186,7 @@ fn usz DString.append_utf32(&self, Char32[] chars) <* @require index < self.len() *> -fn void DString.set(self, usz index, char c) +fn void DString.set(self, usz index, char c) @operator([]=) { self.data().chars[index] = c; } diff --git a/releasenotes.md b/releasenotes.md index f21c2d536..53136ac62 100644 --- a/releasenotes.md +++ b/releasenotes.md @@ -8,6 +8,7 @@ - `a++` may be discarded if `a` is optional and ++/-- works for overloaded operators. - Improve support for Windows cross compilation on targets with case sensitive file systems. - Add "sources" support to library `manifest.json`, defaults to root folder if unspecified. +- Add char_at method in DString and operators [], len, []= and &[]. ### Fixes - Fix bug where `a > 0 ? f() : g()` could cause a compiler crash if both returned `void!`. diff --git a/test/unit/stdlib/core/dstring.c3 b/test/unit/stdlib/core/dstring.c3 index e7132bb81..654ff0afc 100644 --- a/test/unit/stdlib/core/dstring.c3 +++ b/test/unit/stdlib/core/dstring.c3 @@ -246,4 +246,29 @@ fn void test_insert_at_overlaps() str.chop(3); s = str.str_view(); assert(s == "def", "got '%s'; want 'def'", s); -} \ No newline at end of file +} + +fn void test_char_at() +{ + DString str = dstring::new("hello"); + defer str.free(); + + char c = str.char_at(1); + assert(c == 'e'); + + char c_with_operator = str[4]; + assert(c_with_operator == 'o'); +} + +fn void test_operators() +{ + DString str = dstring::new("hello"); + defer str.free(); + + str[0] = 'p'; + assert(str.str_view() == "pello"); + + char* c = &str[1]; + assert(*c == 'e'); +} +