diff options
author | Clément Foucault <foucault.clem@gmail.com> | 2022-09-17 13:26:28 +0300 |
---|---|---|
committer | Clément Foucault <foucault.clem@gmail.com> | 2022-09-17 13:27:00 +0300 |
commit | a4027658eeaff868a68675594bf774a87454344e (patch) | |
tree | 17d8f3e7415e24eadb8bf9fa60d4558ac0b0508c /source/blender/blenlib/BLI_index_range.hh | |
parent | 9dcce5be90614fef9b44cb0606a930238009b3d0 (diff) |
IndexRange: Add new `intersect` method
Returns a new range, that contains the intersection of the current one
with the given range.
This is helpful to select a portion of a range without having to deal with
all the asserts of other functions. The resulting range being always a
valid subrange, it can be used to iterate or copy a part of a vector.
Diffstat (limited to 'source/blender/blenlib/BLI_index_range.hh')
-rw-r--r-- | source/blender/blenlib/BLI_index_range.hh | 17 |
1 files changed, 17 insertions, 0 deletions
diff --git a/source/blender/blenlib/BLI_index_range.hh b/source/blender/blenlib/BLI_index_range.hh index a0f129c7324..ba49664e91f 100644 --- a/source/blender/blenlib/BLI_index_range.hh +++ b/source/blender/blenlib/BLI_index_range.hh @@ -140,6 +140,10 @@ class IndexRange { { return (a.size_ == b.size_) && (a.start_ == b.start_ || a.size_ == 0); } + constexpr friend bool operator!=(IndexRange a, IndexRange b) + { + return !(a == b); + } /** * Get the amount of numbers in the range. @@ -248,6 +252,19 @@ class IndexRange { } /** + * Returns a new range, that contains the intersection of the current one with the given range. + * Returns empty range is no intersection exists. + * Returned range is always a valid slice of this range. + */ + constexpr IndexRange intersect(IndexRange other) const + { + const int64_t old_end = start_ + size_; + const int64_t new_start = std::min(old_end, std::max(start_, other.start_)); + const int64_t new_end = std::max(new_start, std::min(old_end, other.start_ + other.size_)); + return IndexRange(new_start, new_end - new_start); + } + + /** * Returns a new IndexRange with n elements removed from the beginning of the range. * This invokes undefined behavior when n is negative. */ |