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
30 changes: 22 additions & 8 deletions builtin/stringbuilder_buffer.mbt
Original file line number Diff line number Diff line change
Expand Up @@ -62,15 +62,26 @@ fn StringBuilder::grow_if_necessary(
self.data = new_data
}

///|
fn FixedArray::unsafe_blit_from_string(
self : FixedArray[UInt16],
dst_offset : Int,
str : String,
str_offset : Int,
len : Int,
) -> Unit {
let end_str_offset = str_offset + len
for i = str_offset, j = dst_offset; i < end_str_offset; i = i + 1, j = j + 1 {
self[j] = str.unsafe_get(i)
}
}

///|
/// Writes a string to the StringBuilder.
pub impl Logger for StringBuilder with write_string(self, str) {
let str_len = str.length()
self.grow_if_necessary(self.len + str_len)
// TODO: add an intrinsic to copy UTF-16 code units from String directly.
for i in 0..<str_len {
self.data[self.len + i] = str.unsafe_get(i)
}
self.data.unsafe_blit_from_string(self.len, str, 0, str_len)
self.len += str_len
}

Expand Down Expand Up @@ -118,10 +129,12 @@ pub impl Logger for StringBuilder with write_view(
) -> Unit {
let str_len = str.length()
self.grow_if_necessary(self.len + str_len)
// TODO: add an intrinsic to copy UTF-16 code units from StringView directly.
for i in 0..<str_len {
self.data[self.len + i] = str.unsafe_get(i)
}
self.data.unsafe_blit_from_string(
self.len,
str.data(),
str.start_offset(),
str_len,
)
self.len += str_len
}

Expand All @@ -146,5 +159,6 @@ pub impl Show for StringBuilder with output(self, logger) {
///|
/// Resets the string builder to an empty state.
pub fn StringBuilder::reset(self : StringBuilder) -> Unit {
self.data = FixedArray::make(self.data.length(), UInt16::default())
self.len = 0
}
11 changes: 11 additions & 0 deletions builtin/stringbuilder_test.mbt
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,17 @@ test "is_empty method" {
inspect(buf.is_empty(), content="true")
}

///|
test "reset does not mutate returned string" {
let buf = StringBuilder::new(size_hint=10)
buf.write_string("hello")
let first = buf.to_string()
buf.reset()
buf.write_string("bye")
inspect(first, content="hello")
inspect(buf.to_string(), content="bye")
}

///|
test {
let data = ["a", "b", "c", "hello world"]
Expand Down
Loading