aboutsummaryrefslogtreecommitdiff
path: root/include/cru/base/Range.h
diff options
context:
space:
mode:
authorcrupest <crupest@outlook.com>2024-10-06 13:57:39 +0800
committercrupest <crupest@outlook.com>2024-10-06 13:57:39 +0800
commitdfe62dcf8bcefc523b466e127c3edc4dc2756629 (patch)
tree1c751a14ba0da07ca2ff805633f97568060aa4c9 /include/cru/base/Range.h
parentf51eb955e188858272230a990565931e7403f23b (diff)
downloadcru-dfe62dcf8bcefc523b466e127c3edc4dc2756629.tar.gz
cru-dfe62dcf8bcefc523b466e127c3edc4dc2756629.tar.bz2
cru-dfe62dcf8bcefc523b466e127c3edc4dc2756629.zip
Rename common to base.
Diffstat (limited to 'include/cru/base/Range.h')
-rw-r--r--include/cru/base/Range.h42
1 files changed, 42 insertions, 0 deletions
diff --git a/include/cru/base/Range.h b/include/cru/base/Range.h
new file mode 100644
index 00000000..edc2ec55
--- /dev/null
+++ b/include/cru/base/Range.h
@@ -0,0 +1,42 @@
+#pragma once
+#include "Base.h"
+
+namespace cru {
+struct Range final {
+ constexpr static Range FromTwoSides(Index start, Index end) {
+ return Range(start, end - start);
+ }
+
+ constexpr static Range FromTwoSides(Index start, Index end, Index offset) {
+ return Range(start + offset, end - start);
+ }
+
+ constexpr Range() = default;
+ constexpr Range(const Index position, const Index count = 0)
+ : position(position), count(count) {}
+
+ Index GetStart() const { return position; }
+ Index GetEnd() const { return position + count; }
+
+ void ChangeEnd(Index new_end) { count = new_end - position; }
+
+ Range Normalize() const {
+ auto result = *this;
+ if (result.count < 0) {
+ result.position += result.count;
+ result.count = -result.count;
+ }
+ return result;
+ }
+
+ Range CoerceInto(Index min, Index max) const {
+ auto coerce = [min, max](Index index) {
+ return index > max ? max : (index < min ? min : index);
+ };
+ return Range::FromTwoSides(coerce(GetStart()), coerce(GetEnd()));
+ }
+
+ Index position = 0;
+ Index count = 0;
+};
+} // namespace cru