diff --git a/builtin/builtin.mbti b/builtin/builtin.mbti index 3bc337632..a44b299ce 100644 --- a/builtin/builtin.mbti +++ b/builtin/builtin.mbti @@ -533,6 +533,7 @@ fn FixedArray::set_utf16le_char(Self[Byte], Int, Char) -> Int fn FixedArray::set_utf8_char(Self[Byte], Int, Char) -> Int fn[A] FixedArray::unsafe_blit(Self[A], Int, Self[A], Int, Int) -> Unit fn[T] FixedArray::unsafe_get(Self[T], Int) -> T +fn FixedArray::unsafe_reinterpret_as_bytes(Self[Byte]) -> Bytes fn[T] FixedArray::unsafe_set(Self[T], Int, T) -> Unit fn Bytes::copy(Bytes) -> Bytes diff --git a/builtin/bytes.mbt b/builtin/bytes.mbt index 20c73538d..535ac5498 100644 --- a/builtin/bytes.mbt +++ b/builtin/bytes.mbt @@ -14,7 +14,14 @@ ///| /// Reinterpret the byte sequence as Bytes. -fn FixedArray::unsafe_to_bytes(self : FixedArray[Byte]) -> Bytes = "%identity" +/// +/// Notice that this will make the `Bytes` object to be a view of the original +/// byte sequence, so any modification to the original byte sequence will be +/// reflected in the `Bytes` object. +#internal(unsafe, "Creating mutable Bytes") +pub fn FixedArray::unsafe_reinterpret_as_bytes( + self : FixedArray[Byte] +) -> Bytes = "%identity" ///| /// Creates a new byte sequence of the specified length, where each byte is @@ -44,7 +51,7 @@ pub fn Bytes::makei(length : Int, value : (Int) -> Byte) -> Bytes { for i in 1.. Byte) -> Bytes { pub fn Bytes::of_string(str : String) -> Bytes { FixedArray::make(str.length() * 2, Byte::default()) ..blit_from_string(0, str, 0, str.length()) - .unsafe_to_bytes() + .unsafe_reinterpret_as_bytes() } ///| diff --git a/builtin/string.mbt b/builtin/string.mbt index ff0117b94..237355150 100644 --- a/builtin/string.mbt +++ b/builtin/string.mbt @@ -200,7 +200,7 @@ fn unsafe_substring(str : String, start : Int, end : Int) -> String { let len = end - start let bytes = FixedArray::make(len * 2, Byte::default()) bytes.blit_from_string(0, str, start, len) - bytes.unsafe_to_bytes().to_unchecked_string() + bytes.unsafe_reinterpret_as_bytes().to_unchecked_string() } ///| diff --git a/builtin/stringbuilder_buffer.mbt b/builtin/stringbuilder_buffer.mbt index 985dd612e..eacc9f2b0 100644 --- a/builtin/stringbuilder_buffer.mbt +++ b/builtin/stringbuilder_buffer.mbt @@ -109,14 +109,18 @@ pub impl Logger for StringBuilder with write_substring( ///| /// Returns the current content of the StringBuilder as a string. pub fn StringBuilder::to_string(self : StringBuilder) -> String { - self.data.unsafe_to_bytes().to_unchecked_string(offset=0, length=self.len) + self.data + .unsafe_reinterpret_as_bytes() + .to_unchecked_string(offset=0, length=self.len) } ///| /// TODO: improve perf pub impl Show for StringBuilder with output(self, logger) { logger.write_string( - self.data.unsafe_to_bytes().to_unchecked_string(offset=0, length=self.len), + self.data + .unsafe_reinterpret_as_bytes() + .to_unchecked_string(offset=0, length=self.len), ) }