feat(Math): checked Euclidean division for signed grid coordinates (#11)
This commit is contained in:
1 parent
7b0fea6095
commit
4f67fd2b93
1 file changed
+41
@@ -298,6 +298,47 @@ template <std::integral T>
|
|||||||
return a / b;
|
return a / b;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Euclidean quotient and remainder for a strictly positive divisor:
|
||||||
|
/// `a == quotient * divisor + remainder` and `0 <= remainder < divisor`.
|
||||||
|
template <std::integral T> struct EuclideanDivision {
|
||||||
|
T quotient{};
|
||||||
|
T remainder{};
|
||||||
|
|
||||||
|
[[nodiscard]] constexpr bool
|
||||||
|
operator==(const EuclideanDivision&) const noexcept = default;
|
||||||
|
};
|
||||||
|
|
||||||
|
/// Checked Euclidean division. Unlike C++ integer division (which truncates
|
||||||
|
/// toward zero), this floors toward negative infinity so the remainder is
|
||||||
|
/// always nonnegative, e.g. (-1, 32) -> (-1, 31).
|
||||||
|
///
|
||||||
|
/// `divisor == 0` reports `DivisionByZero`; a negative divisor reports
|
||||||
|
/// `InvalidInput`. The signed minimum is handled without negating it, so no
|
||||||
|
/// intermediate overflows.
|
||||||
|
template <std::integral T>
|
||||||
|
[[nodiscard]] constexpr std::expected<EuclideanDivision<T>, Error>
|
||||||
|
checked_euclidean_div(T a, T divisor) noexcept
|
||||||
|
{
|
||||||
|
if (divisor == T{0}) {
|
||||||
|
return std::unexpected{Error::DivisionByZero};
|
||||||
|
}
|
||||||
|
if constexpr (std::is_signed_v<T>) {
|
||||||
|
if (divisor < T{0}) {
|
||||||
|
return std::unexpected{Error::InvalidInput};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
T quotient = static_cast<T>(a / divisor);
|
||||||
|
T remainder = static_cast<T>(a % divisor);
|
||||||
|
if constexpr (std::is_signed_v<T>) {
|
||||||
|
if (remainder < T{0}) {
|
||||||
|
// Truncated division rounded toward zero: step one page down.
|
||||||
|
quotient = static_cast<T>(quotient - T{1});
|
||||||
|
remainder = static_cast<T>(remainder + divisor);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return EuclideanDivision<T>{.quotient = quotient, .remainder = remainder};
|
||||||
|
}
|
||||||
|
|
||||||
template <std::integral T>
|
template <std::integral T>
|
||||||
[[nodiscard]] constexpr std::expected<T, Error>
|
[[nodiscard]] constexpr std::expected<T, Error>
|
||||||
checked_neg(T a) noexcept
|
checked_neg(T a) noexcept
|
||||||
|
|||||||
Reference in new issue
Block a user