Merge pull request #573 from totalgee/fix_erase_at_bounds

Fix  crash with out of bounds index (issue #572)
This commit is contained in:
Rob Loach 2021-07-08 19:55:50 -04:00 committed by GitHub
commit 6411aa7498
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
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 itr = container.begin();
auto end = container.end(); 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"); throw std::range_error("Cannot erase past end of range");
} }

View File

@ -1,3 +1,24 @@
auto x = [1, 2, 3] auto x = [1, 2, 3]
x.erase_at(1) x.erase_at(1)
assert_equal([1,3], x); 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] auto x = [1, 2, 3]
x.insert_at(1, 6) x.insert_at(1, 6)
assert_equal([1,6,2,3], x); 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)