Skip to content

Commit

Permalink
Make List.__copyinit__() smarter.
Browse files Browse the repository at this point in the history
Signed-off-by: Max Brylski <[email protected]>
  • Loading branch information
helehex committed Nov 10, 2024
1 parent e1fcc49 commit a60577c
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 7 deletions.
15 changes: 9 additions & 6 deletions stdlib/src/collections/list.mojo
Original file line number Diff line number Diff line change
Expand Up @@ -121,9 +121,14 @@ struct List[T: CollectionElement, hint_trivial_type: Bool = False](
Args:
other: The list to copy.
"""
self.__init__(capacity=other.capacity)
for e in other:
self.append(e[])
if other.data:
self.data = UnsafePointer[T].alloc(other.capacity)
self.size = other.size
self.capacity = other.capacity
for idx in range(len(other)):
(self.data + idx).init_pointee_copy((other.data + idx)[])
else:
self = Self()

fn __init__(inout self, *, capacity: Int):
"""Constructs a list with the given capacity.
Expand Down Expand Up @@ -204,9 +209,7 @@ struct List[T: CollectionElement, hint_trivial_type: Bool = False](
Args:
existing: The list to copy.
"""
self = Self(capacity=existing.capacity)
for i in range(len(existing)):
self.append(existing[i])
self = Self(other=existing)

fn __del__(owned self):
"""Destroy all elements in the list and free its memory."""
Expand Down
4 changes: 3 additions & 1 deletion stdlib/test/collections/test_list.mojo
Original file line number Diff line number Diff line change
Expand Up @@ -531,8 +531,10 @@ def test_2d_dynamic_list():

def test_list_explicit_copy():
var list = List[CopyCounter]()
list.append(CopyCounter())
var list_copy = List(other=list)
assert_false(list_copy.data)
list.append(CopyCounter())
list_copy = List(other=list)
assert_equal(0, list[0].copy_count)
assert_equal(1, list_copy[0].copy_count)

Expand Down

0 comments on commit a60577c

Please sign in to comment.