Skip to content

Commit 67f6056

Browse files
committed
Handling long index and better PInt index in List.insert method.
1 parent 3e73923 commit 67f6056

File tree

2 files changed

+29
-4
lines changed
  • graalpython

2 files changed

+29
-4
lines changed

graalpython/com.oracle.graal.python.test/src/tests/test_list.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -305,3 +305,10 @@ def __index__(self):
305305
a = [0,0,0,0,0]
306306
a.insert(SecondIndex(1), 1)
307307
self.assertEqual([0,1,0,0,0,0], a)
308+
309+
a = [0]
310+
a.insert(LONG_NUMBER, 1)
311+
self.assertEqual([0,1], a)
312+
313+
a.insert(False, -1)
314+
self.assertEqual([-1,0,1], a)

graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/list/ListBuiltins.java

Lines changed: 22 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -539,10 +539,28 @@ public PNone insert(PList list, int index, Object value) {
539539
}
540540

541541
@Specialization
542-
public PNone insert(PList list, PInt index, Object value) {
543-
int where = normalizeIndex(index.intValue(), list.len());
544-
list.insert(where, value);
545-
return PNone.NONE;
542+
public PNone insertLongIndex(PList list, long index, Object value,
543+
@Cached("createListInsertNode()") ListInsertNode insertNode) {
544+
int where = index < Integer.MIN_VALUE ? 0 : index > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) index;
545+
where = normalizeIndex(where, list.len());
546+
return insertNode.execute(list, where, value);
547+
}
548+
549+
@Specialization
550+
@TruffleBoundary
551+
public PNone insertPIntIndex(PList list, PInt index, Object value,
552+
@Cached("createListInsertNode()") ListInsertNode insertNode) {
553+
int where = 0;
554+
BigInteger bigIndex = index.getValue();
555+
if (bigIndex.compareTo(BigInteger.valueOf(Integer.MIN_VALUE)) == -1) {
556+
where = 0;
557+
} else if (bigIndex.compareTo(BigInteger.valueOf(Integer.MAX_VALUE)) == 1) {
558+
where = Integer.MAX_VALUE;
559+
} else {
560+
where = bigIndex.intValue();
561+
}
562+
where = normalizeIndex(where, list.len());
563+
return insertNode.execute(list, where, value);
546564
}
547565

548566
@Specialization(guards = {"!isIntegerOrPInt(i)"})

0 commit comments

Comments
 (0)