Use memcpy to concatenate lists

pull/54/head
A. R. Shajii 2022-09-18 16:43:42 -04:00
parent 70a9515ff5
commit 8a63e73c82
2 changed files with 35 additions and 7 deletions

View File

@ -200,16 +200,26 @@ class List:
i -= 1
def __add__(self, other: List[T]) -> List[T]:
v = List[T](self.len + other.len)
for a in self:
v.append(a)
for a in other:
v.append(a)
n = self.len + other.len
v = List[T](n)
v.len = n
p = v.arr.ptr
str.memcpy(p.as_byte(),
self.arr.ptr.as_byte(),
self.len * gc.sizeof(T))
str.memcpy((p + self.len).as_byte(),
other.arr.ptr.as_byte(),
other.len * gc.sizeof(T))
return v
def __iadd__(self, other: List[T]) -> List[T]:
for a in other:
self.append(a)
n = self.len + other.len
if self.arr.len < n:
self._resize(n)
str.memcpy((self.arr.ptr + self.len).as_byte(),
other.arr.ptr.as_byte(),
other.len * gc.sizeof(T))
self.len = n
return self
def __mul__(self, n: int) -> List[T]:

View File

@ -138,6 +138,24 @@ def test_list():
assert list(test_cmp([1,2,-1], [2])) == [('EQ', False), ('NE', True), ('LT', True), ('GT', False), ('LE', True), ('GE', False)]
assert list(test_cmp([1,2,-1], [1,2,-1,3])) == [('EQ', False), ('NE', True), ('LT', True), ('GT', False), ('LE', True), ('GE', False)]
assert list(test_cmp([1,2,-1,3], [1,2,-1])) == [('EQ', False), ('NE', True), ('LT', False), ('GT', True), ('LE', False), ('GE', True)]
assert str([1] + [2] + [] + [3]) == '[1, 2, 3]'
assert ['a', 'b'] + ['x', 'y', 'z'] == ['a', 'b'] + ['x', 'y', 'z']
assert [(1,1), (2,2)] + [] == [(1,1), (2,2)]
assert [] + [(1,1), (2,2)] == [(1,1), (2,2)]
assert List[int]() + List[int]() == List[int]()
l7 = [3.14, 2.5]
l7 += [9.99, -1.0]
assert l7 == [3.14, 2.5, 9.99, -1.0]
l8 = []
l8 += [11, 22, 33]
assert l8 == [11, 22, 33]
l8 = [11, 22, 33]
l8 += []
assert l8 == [11, 22, 33]
l8 = List[int]()
l8 += List[int]()
assert l8 == List[int]()
test_list()
@test