diff options
author | Rémi Verschelde <remi@verschelde.fr> | 2022-01-18 13:22:35 +0100 |
---|---|---|
committer | GitHub <noreply@github.com> | 2022-01-18 13:22:35 +0100 |
commit | 9912492e937d2454a21ec7465538aab2431ac249 (patch) | |
tree | 4afd7886de16fabdd4da07f3922f68c55b0cb6a8 /core/variant/array.cpp | |
parent | 366d3930ac96db5561afd23b1063085fccf6dcd6 (diff) | |
parent | c6cefb1b79d207af1bc78ce20c01b5788e806252 (diff) | |
download | redot-engine-9912492e937d2454a21ec7465538aab2431ac249.tar.gz |
Merge pull request #56668 from akien-mga/array-slice-nicer-bound-checks
Diffstat (limited to 'core/variant/array.cpp')
-rw-r--r-- | core/variant/array.cpp | 22 |
1 files changed, 13 insertions, 9 deletions
diff --git a/core/variant/array.cpp b/core/variant/array.cpp index 8d20b1bc79..3d2f337442 100644 --- a/core/variant/array.cpp +++ b/core/variant/array.cpp @@ -370,20 +370,24 @@ Array Array::slice(int p_begin, int p_end, int p_step, bool p_deep) const { ERR_FAIL_COND_V_MSG(p_step == 0, result, "Slice step cannot be zero."); - if (p_end < 0) { - p_end += size() + 1; - } + const int s = size(); - ERR_FAIL_INDEX_V(p_begin, size(), result); - ERR_FAIL_INDEX_V(p_end, size() + 1, result); + int begin = CLAMP(p_begin, -s, s); + if (begin < 0) { + begin += s; + } + int end = CLAMP(p_end, -s, s); + if (end < 0) { + end += s; + } - ERR_FAIL_COND_V_MSG(p_step > 0 && p_begin > p_end, result, "Slice is positive, but bounds is decreasing"); - ERR_FAIL_COND_V_MSG(p_step < 0 && p_begin < p_end, result, "Slice is negative, but bounds is increasing"); + ERR_FAIL_COND_V_MSG(p_step > 0 && begin > end, result, "Slice is positive, but bounds is decreasing."); + ERR_FAIL_COND_V_MSG(p_step < 0 && begin < end, result, "Slice is negative, but bounds is increasing."); - int result_size = (p_end - p_begin) / p_step; + int result_size = (end - begin) / p_step; result.resize(result_size); - for (int src_idx = p_begin, dest_idx = 0; dest_idx < result_size; ++dest_idx) { + for (int src_idx = begin, dest_idx = 0; dest_idx < result_size; ++dest_idx) { result[dest_idx] = p_deep ? get(src_idx).duplicate(true) : get(src_idx); src_idx += p_step; } |