diff options
author | Jacques Lucke <jacques@blender.org> | 2020-08-24 12:51:28 +0300 |
---|---|---|
committer | Jacques Lucke <jacques@blender.org> | 2020-08-24 12:51:41 +0300 |
commit | 4883cc572888e281ee27f02b307d6fc827477686 (patch) | |
tree | 38be4a25862faa62c2ddc83bf9b209a420e1dfc7 /source | |
parent | afbc727da2514e41406d023dede23ccace422672 (diff) |
BLI: add Array.last method
This makes it consistent with Vector and Span.
Diffstat (limited to 'source')
-rw-r--r-- | source/blender/blenlib/BLI_array.hh | 15 | ||||
-rw-r--r-- | source/blender/blenlib/tests/BLI_array_test.cc | 9 |
2 files changed, 24 insertions, 0 deletions
diff --git a/source/blender/blenlib/BLI_array.hh b/source/blender/blenlib/BLI_array.hh index 0ffe6b9a750..d6b7ab03203 100644 --- a/source/blender/blenlib/BLI_array.hh +++ b/source/blender/blenlib/BLI_array.hh @@ -269,6 +269,21 @@ class Array { } /** + * Return a reference to the last element in the array. + * This invokes undefined behavior when the array is empty. + */ + const T &last() const + { + BLI_assert(size_ > 0); + return *(data_ + size_ - 1); + } + T &last() + { + BLI_assert(size_ > 0); + return *(data_ + size_ - 1); + } + + /** * Get a pointer to the beginning of the array. */ const T *data() const diff --git a/source/blender/blenlib/tests/BLI_array_test.cc b/source/blender/blenlib/tests/BLI_array_test.cc index 251cff833f7..3d45a9f5277 100644 --- a/source/blender/blenlib/tests/BLI_array_test.cc +++ b/source/blender/blenlib/tests/BLI_array_test.cc @@ -227,4 +227,13 @@ TEST(array, MoveAssignmentExceptions) EXPECT_ANY_THROW({ array_moved = std::move(array); }); } +TEST(array, Last) +{ + Array<int> array = {5, 7, 8, 9}; + EXPECT_EQ(array.last(), 9); + array.last() = 1; + EXPECT_EQ(array[3], 1); + EXPECT_EQ(const_cast<const Array<int> &>(array).last(), 1); +} + } // namespace blender::tests |