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.
This commit is contained in:
Rémi Verschelde 2022-01-10 13:56:55 +01:00
parent 4acc819f9b
commit c6cefb1b79
No known key found for this signature in database
GPG key ID: C3336907360768E1
16 changed files with 129 additions and 52 deletions

View file

@ -33,6 +33,8 @@
#include "core/typedefs.h"
#include <climits>
class Variant;
class ArrayPrivate;
class Object;
@ -102,7 +104,7 @@ public:
Array duplicate(bool p_deep = false) const;
Array recursive_duplicate(bool p_deep, int recursion_count) const;
Array slice(int p_begin, int p_end, int p_step = 1, bool p_deep = false) const;
Array slice(int p_begin, int p_end = INT_MAX, int p_step = 1, bool p_deep = false) const;
Array filter(const Callable &p_callable) const;
Array map(const Callable &p_callable) const;
Variant reduce(const Callable &p_callable, const Variant &p_accum) const;