Skip to content

Commit

Permalink
Simplify String List[Byte] constructor
Browse files Browse the repository at this point in the history
Signed-off-by: martinvuyk <martin.vuyklop@gmail.com>
  • Loading branch information
martinvuyk committed Dec 10, 2024
1 parent 2ace785 commit 3d33f5e
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 52 deletions.
59 changes: 8 additions & 51 deletions stdlib/src/collections/string.mojo
Original file line number Diff line number Diff line change
Expand Up @@ -784,68 +784,25 @@ struct String(

@always_inline
@implicit
fn __init__(out self, owned impl: List[UInt8, *_]):
"""Construct a string from a buffer of bytes without copying the
allocated data.
The buffer must be terminated with a null byte:
```mojo
var buf = List[UInt8]()
buf.append(ord('H'))
buf.append(ord('i'))
buf.append(0)
var hi = String(buf)
```
fn __init__(out self, impl: List[Byte, *_]):
"""Construct a string from a buffer of null-terminated bytes, copying
the allocated data. Use the transfer operator `^` to avoid the copy.
Args:
impl: The buffer.
"""
debug_assert(
len(impl) > 0 and impl[-1] == 0,
"expected last element of String buffer to be null terminator",
)
# We make a backup because steal_data() will clear size and capacity.
var size = impl.size
debug_assert(
impl[size - 1] == 0,
"expected last element of String buffer to be null terminator",
)
var capacity = impl.capacity
self._buffer = Self._buffer_type(
ptr=impl.steal_data(), length=size, capacity=capacity
)

@always_inline
@implicit
fn __init__(out self, impl: Self._buffer_type):
"""Construct a string from a buffer of bytes, copying the allocated
data. Use the transfer operator ^ to avoid the copy.
impl: The null-terminated buffer.
The buffer must be terminated with a null byte:
Examples:
```mojo
var buf = List[UInt8]()
buf.append(ord('H'))
buf.append(ord('i'))
buf.append(0)
var hi = String(buf)
print(String(List[Byte](ord('h'), ord('i'), 0))) # hi
```
Args:
impl: The buffer.
.
"""
debug_assert(
len(impl) > 0 and impl[-1] == 0,
"expected last element of String buffer to be null terminator",
)
# We make a backup because steal_data() will clear size and capacity.
var size = impl.size
debug_assert(
impl[size - 1] == 0,
"expected last element of String buffer to be null terminator",
)
self._buffer = impl
self._buffer = rebind[Self._buffer_type](impl)

@always_inline
fn __init__(out self):
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 3d33f5e

Please sign in to comment.