Skip to content

Commit

Permalink
add get bytes func
Browse files Browse the repository at this point in the history
  • Loading branch information
thatstoasty committed Mar 24, 2024
1 parent 69fc09b commit e4214e3
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 0 deletions.
8 changes: 8 additions & 0 deletions gojo/builtins/_bytes.mojo
Original file line number Diff line number Diff line change
Expand Up @@ -212,3 +212,11 @@ struct Bytes(Stringable, Sized, CollectionElement):
fn capacity(self) -> Int:
"""Returns the capacity of the Bytes struct."""
return self._vector.capacity

fn copy(self) -> Self:
"""Returns a copy of the Bytes struct. Only copies up to what has been written to the Bytes struct."""
# Copy elements up to the write position, don't need to copy over empty elements from end of the vector.
var bytes_copy = Self(size=self.write_position)
for i in range(self.write_position):
bytes_copy.append(self._vector[i])
return bytes_copy
20 changes: 20 additions & 0 deletions gojo/strings/builder.mojo
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,26 @@ struct StringBuilder(Stringable, Sized, io.Writer, io.ByteWriter, io.StringWrite
"""
# Don't need to add a null terminator because we can pass the length of the string.
return str(self._vector)

fn get_bytes(self) -> DynamicVector[Int8]:
"""
Returns a copy of the byte array of the string builder.
Returns:
The byte array of the string builder.
"""
return self._vector.copy()._vector

fn get_null_terminated_bytes(self) -> DynamicVector[Int8]:
"""
Returns a copy of the byte array of the string builder with a null terminator.
Returns:
The byte array of the string builder with a null terminator.
"""
var new_bytes = self._vector.copy()._vector
new_bytes.append(0)
return new_bytes

fn write(inout self, src: Bytes) -> Result[Int]:
"""
Expand Down

0 comments on commit e4214e3

Please sign in to comment.