diff options
author | Rémi Verschelde <rverschelde@gmail.com> | 2022-01-10 13:56:55 +0100 |
---|---|---|
committer | Rémi Verschelde <rverschelde@gmail.com> | 2022-01-10 22:42:03 +0100 |
commit | c6cefb1b79d207af1bc78ce20c01b5788e806252 (patch) | |
tree | ca713ba3bf904b57a7408ec50029c9fbcc275d40 /tests/core/variant/test_array.h | |
parent | 4acc819f9bafacf5f912caf5ba2ebc15f70e3dbb (diff) |
`Array`: Relax `slice` bound checks to properly handle negative indices
The same is done for `Vector` (and thus `Packed*Array`).
`begin` and `end` can now take any value and will be clamped to
`[-size(), size()]`. Negative values are a shorthand for indexing the array
from the last element upward.
`end` is given a default `INT_MAX` value (which will be clamped to `size()`)
so that the `end` parameter can be omitted to go from `begin` to the max size
of the array.
This makes `slice` works similarly to numpy's and JavaScript's.
Diffstat (limited to 'tests/core/variant/test_array.h')
-rw-r--r-- | tests/core/variant/test_array.h | 35 |
1 files changed, 30 insertions, 5 deletions
diff --git a/tests/core/variant/test_array.h b/tests/core/variant/test_array.h index 205e34daea..6093048307 100644 --- a/tests/core/variant/test_array.h +++ b/tests/core/variant/test_array.h @@ -254,27 +254,52 @@ TEST_CASE("[Array] slice()") { array.push_back(3); array.push_back(4); + Array slice0 = array.slice(0, 0); + CHECK(slice0.size() == 0); + Array slice1 = array.slice(1, 3); CHECK(slice1.size() == 2); CHECK(slice1[0] == Variant(1)); CHECK(slice1[1] == Variant(2)); Array slice2 = array.slice(1, -1); - CHECK(slice2.size() == 4); + CHECK(slice2.size() == 3); CHECK(slice2[0] == Variant(1)); CHECK(slice2[1] == Variant(2)); CHECK(slice2[2] == Variant(3)); - CHECK(slice2[3] == Variant(4)); - Array slice3 = array.slice(3, -1); + Array slice3 = array.slice(3); CHECK(slice3.size() == 2); CHECK(slice3[0] == Variant(3)); CHECK(slice3[1] == Variant(4)); Array slice4 = array.slice(2, -2); - CHECK(slice4.size() == 2); + CHECK(slice4.size() == 1); CHECK(slice4[0] == Variant(2)); - CHECK(slice4[1] == Variant(3)); + + Array slice5 = array.slice(-2); + CHECK(slice5.size() == 2); + CHECK(slice5[0] == Variant(3)); + CHECK(slice5[1] == Variant(4)); + + Array slice6 = array.slice(2, 42); + CHECK(slice6.size() == 3); + CHECK(slice6[0] == Variant(2)); + CHECK(slice6[1] == Variant(3)); + CHECK(slice6[2] == Variant(4)); + + Array slice7 = array.slice(4, 0, -2); + CHECK(slice7.size() == 2); + CHECK(slice7[0] == Variant(4)); + CHECK(slice7[1] == Variant(2)); + + ERR_PRINT_OFF; + Array slice8 = array.slice(4, 1); + CHECK(slice8.size() == 0); + + Array slice9 = array.slice(3, -4); + CHECK(slice9.size() == 0); + ERR_PRINT_ON; } TEST_CASE("[Array] Duplicate array") { |