Skip to content

Commit

Permalink
Refactor String StringSlice constructor
Browse files Browse the repository at this point in the history
Signed-off-by: martinvuyk <[email protected]>
  • Loading branch information
martinvuyk committed Dec 11, 2024
1 parent 2ace785 commit 17d4b79
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 15 deletions.
23 changes: 9 additions & 14 deletions stdlib/src/collections/string.mojo
Original file line number Diff line number Diff line change
Expand Up @@ -887,24 +887,19 @@ struct String(
fn __init__(out self, str_slice: StringSlice):
"""Construct a string from a string slice.
This will allocate a new string that copies the string contents from
the provided string slice `str_slice`.
Args:
str_slice: The string slice from which to construct this string.
Notes:
This will allocate a new string that copies the string contents from
the provided string slice.
"""

# Calculate length in bytes
var length: Int = len(str_slice.as_bytes())
var buffer = Self._buffer_type()
# +1 for null terminator, initialized to 0
buffer.resize(length + 1, 0)
memcpy(
dest=buffer.data,
src=str_slice.as_bytes().unsafe_ptr(),
count=length,
)
self = Self(buffer^)
var length = str_slice.byte_length()
var ptr = UnsafePointer[Byte].alloc(length + 1)
memcpy(ptr, str_slice.unsafe_ptr(), length)
ptr[length] = 0
self = String(ptr=ptr, length=length + 1)

@always_inline
@implicit
Expand Down
3 changes: 2 additions & 1 deletion stdlib/test/python/my_module.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,8 @@ def __init__(self, bar):

class AbstractPerson(ABC):
@abstractmethod
def method(self): ...
def method(self):
...


def my_function(name):
Expand Down

0 comments on commit 17d4b79

Please sign in to comment.