Skip to content

Commit bd0985b

Browse files
authored
py: Fix __mul__ of list and tuple on negative case (#67)
1 parent c5b8c68 commit bd0985b

File tree

4 files changed

+19
-0
lines changed

4 files changed

+19
-0
lines changed

py/list.go

+3
Original file line numberDiff line numberDiff line change
@@ -259,6 +259,9 @@ func (l *List) M__mul__(other Object) (Object, error) {
259259
if b, ok := convertToInt(other); ok {
260260
m := len(l.Items)
261261
n := int(b) * m
262+
if n < 0 {
263+
n = 0
264+
}
262265
newList := NewListSized(n)
263266
for i := 0; i < n; i += m {
264267
copy(newList.Items[i:i+m], l.Items)

py/tests/list.py

+6
Original file line numberDiff line numberDiff line change
@@ -33,4 +33,10 @@
3333
assert repr(a) == "['a', 'b', 'c', 'd', 'e', 'f']"
3434
assertRaises(TypeError, lambda: [].append())
3535

36+
doc="mul"
37+
a = [1, 2, 3]
38+
assert a * 2 == [1, 2, 3, 1, 2, 3]
39+
assert a * 0 == []
40+
assert a * -1 == []
41+
3642
doc="finished"

py/tests/tuple.py

+6
Original file line numberDiff line numberDiff line change
@@ -14,4 +14,10 @@
1414
assert repr((1,(2,3),4)) == "(1, (2, 3), 4)"
1515
assert repr(("1",(2.5,17,()))) == "('1', (2.5, 17, ()))"
1616

17+
doc="mul"
18+
a = (1, 2, 3)
19+
assert a * 2 == (1, 2, 3, 1, 2, 3)
20+
assert a * 0 == ()
21+
assert a * -1 == ()
22+
1723
doc="finished"

py/tuple.go

+4
Original file line numberDiff line numberDiff line change
@@ -113,6 +113,7 @@ func (a Tuple) M__add__(other Object) (Object, error) {
113113
copy(newTuple[len(b):], b)
114114
return newTuple, nil
115115
}
116+
116117
return NotImplemented, nil
117118
}
118119

@@ -131,6 +132,9 @@ func (l Tuple) M__mul__(other Object) (Object, error) {
131132
if b, ok := convertToInt(other); ok {
132133
m := len(l)
133134
n := int(b) * m
135+
if n < 0 {
136+
n = 0
137+
}
134138
newTuple := make(Tuple, n)
135139
for i := 0; i < n; i += m {
136140
copy(newTuple[i:i+m], l)

0 commit comments

Comments
 (0)