From c6cefb1b79d207af1bc78ce20c01b5788e806252 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Verschelde?= Date: Mon, 10 Jan 2022 13:56:55 +0100 Subject: `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. --- tests/core/variant/test_array.h | 35 ++++++++++++++++++++++++++++++----- 1 file changed, 30 insertions(+), 5 deletions(-) (limited to 'tests/core/variant/test_array.h') 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") { -- cgit v1.2.3