Fix crash with out of bounds index (issue #572)

This commit is contained in:
Glen Fraser 2021-07-08 18:55:36 +02:00
parent 3703a78813
commit 5722a5177d
3 changed files with 44 additions and 1 deletions

View File

@ -130,7 +130,7 @@ namespace chaiscript::bootstrap::standard_library {
auto itr = container.begin();
auto end = container.end();
if (pos < 0 || std::distance(itr, end) < (pos - 1)) {
if (pos < 0 || std::distance(itr, end) <= pos) {
throw std::range_error("Cannot erase past end of range");
}

View File

@ -1,3 +1,24 @@
auto x = [1, 2, 3]
x.erase_at(1)
assert_equal([1,3], x);
try {
// We expect this to throw because of erasing an out of bounds index
x.erase_at(2)
assert_true(false)
} catch (e) {
assert_true(true)
}
try {
// We expect this to throw because of erasing an out of bounds index
x.erase_at(-1)
assert_true(false)
} catch (e) {
assert_true(true)
}
x.erase_at(0)
assert_equal([3], x)
x.erase_at(0)
assert_equal([], x)

View File

@ -1,3 +1,25 @@
auto x = [1, 2, 3]
x.insert_at(1, 6)
assert_equal([1,6,2,3], x);
try {
// We expect this to throw because of inserting an out of bounds index
x.insert_at(5, 55)
assert_true(false)
} catch (e) {
assert_true(true)
}
// Inserting to the end should be allowed
x.insert_at(4, 44)
try {
// We expect this to throw because of inserting an out of bounds index
x.insert_at(-1, 111)
assert_true(false)
} catch (e) {
assert_true(true)
}
x.insert_at(0, 100)
assert_equal([100, 1, 6, 2, 3, 44], x)