From 17d4b79586aadfe8a7942b6076b16c45b62fe3a2 Mon Sep 17 00:00:00 2001 From: martinvuyk Date: Wed, 11 Dec 2024 13:59:34 -0300 Subject: [PATCH] Refactor String StringSlice constructor Signed-off-by: martinvuyk --- stdlib/src/collections/string.mojo | 23 +++++++++-------------- stdlib/test/python/my_module.py | 3 ++- 2 files changed, 11 insertions(+), 15 deletions(-) diff --git a/stdlib/src/collections/string.mojo b/stdlib/src/collections/string.mojo index fe9746584d..88b2f3ee4f 100644 --- a/stdlib/src/collections/string.mojo +++ b/stdlib/src/collections/string.mojo @@ -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 diff --git a/stdlib/test/python/my_module.py b/stdlib/test/python/my_module.py index 8147b0a382..c78c39556e 100644 --- a/stdlib/test/python/my_module.py +++ b/stdlib/test/python/my_module.py @@ -25,7 +25,8 @@ def __init__(self, bar): class AbstractPerson(ABC): @abstractmethod - def method(self): ... + def method(self): + ... def my_function(name):