From a60577c66b373f5aeecf33e86b2a2a324cbb94b6 Mon Sep 17 00:00:00 2001 From: Max Brylski Date: Sun, 10 Nov 2024 14:10:16 -0600 Subject: [PATCH] Make `List.__copyinit__()` smarter. Signed-off-by: Max Brylski --- stdlib/src/collections/list.mojo | 15 +++++++++------ stdlib/test/collections/test_list.mojo | 4 +++- 2 files changed, 12 insertions(+), 7 deletions(-) diff --git a/stdlib/src/collections/list.mojo b/stdlib/src/collections/list.mojo index 6fa162fd2e..c82d71135c 100644 --- a/stdlib/src/collections/list.mojo +++ b/stdlib/src/collections/list.mojo @@ -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. @@ -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.""" diff --git a/stdlib/test/collections/test_list.mojo b/stdlib/test/collections/test_list.mojo index 35365af488..26ed5ba6c3 100644 --- a/stdlib/test/collections/test_list.mojo +++ b/stdlib/test/collections/test_list.mojo @@ -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)