| 1 |
/* SPDX-License-Identifier: BSL-1.0 OR BSD-3-Clause */ |
| 2 |
|
| 3 |
#ifndef MPT_BASE_WRAPPING_DIVIDE_HPP |
| 4 |
#define MPT_BASE_WRAPPING_DIVIDE_HPP |
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
#include "mpt/base/namespace.hpp" |
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
namespace mpt { |
| 13 |
inline namespace MPT_INLINE_NS { |
| 14 |
|
| 15 |
|
| 16 |
// Modulo with more intuitive behaviour for some contexts: |
| 17 |
// Instead of being symmetrical around 0, the pattern for positive numbers is repeated in the negative range. |
| 18 |
// For example, wrapping_modulo(-1, m) == (m - 1). |
| 19 |
// Behaviour is undefined if m<=0. |
| 20 |
template <typename T, typename M> |
| 21 |
constexpr auto wrapping_modulo(T x, M m) -> decltype(x % m) { |
| 22 |
return (x >= 0) ? (x % m) : (m - 1 - ((-1 - x) % m)); |
| 23 |
} |
| 24 |
|
| 25 |
template <typename T, typename D> |
| 26 |
constexpr auto wrapping_divide(T x, D d) -> decltype(x / d) { |
| 27 |
return (x >= 0) ? (x / d) : (((x + 1) / d) - 1); |
| 28 |
} |
| 29 |
|
| 30 |
|
| 31 |
} // namespace MPT_INLINE_NS |
| 32 |
} // namespace mpt |
| 33 |
|
| 34 |
|
| 35 |
|
| 36 |
#endif // MPT_BASE_WRAPPING_DIVIDE_HPP |