Merge pull request 'Checked Euclidean division for signed grid coordinates (#11)' (#27) from issue/11-euclidean-division into main
This commit was merged in pull request #27.
This commit is contained in:
commit
86bde8b172
2 files changed
+157
No files matched your search
@@ -298,6 +298,47 @@ template <std::integral T>
|
||||
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>
|
||||
[[nodiscard]] constexpr std::expected<T, Error>
|
||||
checked_neg(T a) noexcept
|
||||
|
||||
Reference in new issue
Block a user