Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[stdlib] Make List.__copyinit__() smarter. #3762

Open
wants to merge 1 commit into
base: nightly
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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