From c1c2b677dda99bf1713ba28df21fd57d676b8eec Mon Sep 17 00:00:00 2001 From: Felix Morgner Date: Tue, 18 Aug 2026 14:16:02 +0200 Subject: kstd: introduce basic offset type --- libs/kstd/kstd/units.hpp | 46 +++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 45 insertions(+), 1 deletion(-) (limited to 'libs/kstd') diff --git a/libs/kstd/kstd/units.hpp b/libs/kstd/kstd/units.hpp index e3868aa7..61224336 100644 --- a/libs/kstd/kstd/units.hpp +++ b/libs/kstd/kstd/units.hpp @@ -2,6 +2,8 @@ #define KSTD_UNITS_HPP #include +#include +#include #include #include @@ -11,6 +13,8 @@ namespace kstd using bytes = basic_unit; + using offset = basic_unit; + // NOLINTNEXTLINE(readability-identifier-naming) constexpr auto KiB(std::unsigned_integral auto value) noexcept -> bytes { @@ -30,11 +34,31 @@ namespace kstd } template - constexpr auto operator+(ValueType * pointer, bytes offset) -> ValueType * + constexpr auto operator+(ValueType * pointer, bytes offset) noexcept -> ValueType * { return pointer + offset.value; } + constexpr auto operator+(bytes value, offset offset) noexcept -> result + { + if (offset.value < 0 && value.value < static_cast(-offset.value)) + { + return failure(make_error_code(errc::argument_out_of_domain)); + } + value.value += offset.value; + return value; + } + + constexpr auto operator-(bytes value, offset offset) noexcept -> result + { + if (offset.value > 0 && value.value < static_cast(offset.value)) + { + return failure(make_error_code(errc::argument_out_of_domain)); + } + value.value -= offset.value; + return value; + } + inline namespace literals { inline namespace units_literals @@ -59,6 +83,26 @@ namespace kstd return GiB(value); } + constexpr auto operator""_B_off(unsigned long long value) noexcept -> offset + { + return offset{static_cast(value)}; + } + + constexpr auto operator""_KiB_off(unsigned long long value) noexcept -> offset + { + return offset{static_cast(value * 1024)}; + } + + constexpr auto operator""_MiB_off(unsigned long long value) noexcept -> offset + { + return offset{static_cast(value * 1024 * 1024)}; + } + + constexpr auto operator""_GiB_off(unsigned long long value) noexcept -> offset + { + return offset{static_cast(value * 1024 * 1024 * 1024)}; + } + } // namespace units_literals } // namespace literals -- cgit v1.2.3