diff options
author | Jacques Lucke <jacques@blender.org> | 2022-02-24 16:45:41 +0300 |
---|---|---|
committer | Jacques Lucke <jacques@blender.org> | 2022-02-24 16:50:13 +0300 |
commit | 9be720d85efb307ad37b73f0f5fffd95629c7e20 (patch) | |
tree | 8b0c0f074c9f6616ff2b79992974177b2d4215ef /source/blender/blenlib/BLI_span.hh | |
parent | 7cab7eb3d6cd929f5c354416b4baa6c608f08d82 (diff) |
BLI: support accessing nth last element in Array/Span/Vector
This often helps to make the intend of code more clear compared
to computing the index manually in the caller.
Diffstat (limited to 'source/blender/blenlib/BLI_span.hh')
-rw-r--r-- | source/blender/blenlib/BLI_span.hh | 22 |
1 files changed, 12 insertions, 10 deletions
diff --git a/source/blender/blenlib/BLI_span.hh b/source/blender/blenlib/BLI_span.hh index d82f21a57ff..9ab096094de 100644 --- a/source/blender/blenlib/BLI_span.hh +++ b/source/blender/blenlib/BLI_span.hh @@ -307,13 +307,14 @@ template<typename T> class Span { } /** - * Returns a reference to the last element in the array. This invokes undefined behavior when the - * array is empty. + * Returns a reference to the nth last element. This invokes undefined behavior when the span is + * too short. */ - constexpr const T &last() const + constexpr const T &last(const int64_t n = 0) const { - BLI_assert(size_ > 0); - return data_[size_ - 1]; + BLI_assert(n >= 0); + BLI_assert(n < size_); + return data_[size_ - 1 - n]; } /** @@ -673,13 +674,14 @@ template<typename T> class MutableSpan { } /** - * Returns a reference to the last element. This invokes undefined behavior when the array is - * empty. + * Returns a reference to the nth last element. This invokes undefined behavior when the span is + * too short. */ - constexpr T &last() const + constexpr T &last(const int64_t n = 0) const { - BLI_assert(size_ > 0); - return data_[size_ - 1]; + BLI_assert(n >= 0); + BLI_assert(n < size_); + return data_[size_ - 1 - n]; } /** |