./
Coverage:
low: ≥ 0%
medium: ≥ 75.0%
high: ≥ 90.0%
Lines:
18 / 21
85.7%
Branches:
13 / 13
100.0%
Functions:
4 / 5, 2 excl
80.0%

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
11/11
<unknown function 17>:
✓ Branch 0 taken 23 times.
✓ Branch 1 taken 776 times.
<unknown function 37>:
✓ Branch 0 taken 1 time.
✓ Branch 1 taken 240624 times.
✓ Branch 2 taken 972 times.
✓ Branch 3 taken 1 time.
✓ Branch 4 taken 6 times.
✓ Branch 5 taken 138 times.
✓ Branch 5 taken 95 times.
✓ Branch 6 taken 2 times.
✓ Branch 7 taken 1 time.
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
2/2
✓ Branch 0 taken 295165 times.
✓ Branch 1 taken 408090035 times.
408385200 return static_cast<std::size_t>(std::clamp(index, 0.0, static_cast<double>(size - 1)));
44 }
45
46 } // namespace terraingen
47