include/terraingen/util/bits.h
| Line | Branch | Exec | Source |
|---|---|---|---|
| 1 | // SPDX-License-Identifier: BSD-3-Clause | ||
| 2 | |||
| 3 | /// @file | ||
| 4 | /// @brief Pi, bit casts, byte order and integer arithmetic, in C++17. | ||
| 5 | #pragma once | ||
| 6 | |||
| 7 | #include <algorithm> | ||
| 8 | #include <cstddef> | ||
| 9 | #include <cstring> | ||
| 10 | #include <type_traits> | ||
| 11 | |||
| 12 | namespace terraingen { | ||
| 13 | |||
| 14 | inline constexpr double kPi = 3.141592653589793238462643383279502884; ///< pi. | ||
| 15 | |||
| 16 | /// The bits of `from` read as a `To` of the same size, as `std::bit_cast` does. | ||
| 17 | 27210886 | template <typename To, typename From> To BitCast(const From& from) noexcept { | |
| 18 | static_assert(sizeof(To) == sizeof(From), "BitCast needs types of the same size"); | ||
| 19 | static_assert(std::is_trivially_copyable_v<To> && std::is_trivially_copyable_v<From>, | ||
| 20 | "BitCast needs trivially copyable types"); | ||
| 21 | To to; | ||
| 22 | 27210886 | std::memcpy(&to, &from, sizeof(To)); | |
| 23 | 27210886 | return to; | |
| 24 | } | ||
| 25 | |||
| 26 | /// Whether the target stores the least significant byte first. | ||
| 27 | #if defined(_MSC_VER) | ||
| 28 | inline constexpr bool kLittleEndian = true; | ||
| 29 | #else | ||
| 30 | inline constexpr bool kLittleEndian = __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__; | ||
| 31 | #endif | ||
| 32 | |||
| 33 | /// `value` / `divisor` rounded up, for a positive `divisor`: the tiles or batches of `divisor` | ||
| 34 | /// items that cover `value` items. | ||
| 35 | template <typename T, typename = std::enable_if_t<std::is_integral_v<T> && std::is_unsigned_v<T> && | ||
| 36 | !std::is_same_v<T, bool>>> | ||
| 37 | 245045 | constexpr T CeilDiv(T value, T divisor) { | |
| 38 | 244069 | return (value + divisor - 1) / divisor; | |
| 39 | } | ||
| 40 | |||
| 41 | /// A whole-number `index` clamped to the valid indices [0, `size` - 1] of `size` > 0 items. | ||
| 42 | 408385200 | constexpr std::size_t ClampIndex(double index, std::size_t size) { | |
| 43 | 408385200 | return static_cast<std::size_t>(std::clamp(index, 0.0, static_cast<double>(size - 1))); | |
| 44 | } | ||
| 45 | |||
| 46 | } // namespace terraingen | ||
| 47 |