From b8b20bc8c0331e7c68cc7f4a8f5a52cbced0b8fc Mon Sep 17 00:00:00 2001 From: Ben Deane Date: Mon, 9 Jun 2025 19:41:38 -0600 Subject: [PATCH] :bug: Fix the docs for `smallest_uint` Problem: - `smallest_uint` docs are incorrect. Solution: - `smallest_uint` takes the size required in bits. --- docs/bit.adoc | 11 +++++++---- include/stdx/bit.hpp | 8 ++++---- test/bit.cpp | 11 +++++++++++ 3 files changed, 22 insertions(+), 8 deletions(-) diff --git a/docs/bit.adoc b/docs/bit.adoc index db5ea96..189f419 100644 --- a/docs/bit.adoc +++ b/docs/bit.adoc @@ -121,17 +121,20 @@ static_assert(stdx::bit_pack(a[0], a[1]) == 0x1234'5678u); === `smallest_uint` `smallest_uint` is a function template that selects the smallest unsigned -integral type that will fit a compile-time value. +integral type that will fit a number of bits. [source,cpp] ---- -constexpr auto x = stdx::smallest_uint<42>(); // std::uint8_t{42} -constexpr auto y = stdx::smallest_uint<1337>(); // std::uint16_t{1337} +constexpr auto x = stdx::smallest_uint<4>(); // std::uint8_t{} +constexpr auto y = stdx::smallest_uint<9>(); // std::uint16_t{} // smallest_uint_t is the type of a call to smallest_uint -using T = stdx::smallest_uint_t<1337>; // std::uint16_t +using T = stdx::smallest_uint_t<9>; // std::uint16_t ---- +NOTE: Giving `smallest_uint_t` any bit size over 64 will still return a +`std::uint64_t`. + === `to_be`, `from_be`, `to_le`, `from_le` `to_be` and `from_be` are variations on `byteswap` that do the job of diff --git a/include/stdx/bit.hpp b/include/stdx/bit.hpp index 58c8ff5..657f555 100644 --- a/include/stdx/bit.hpp +++ b/include/stdx/bit.hpp @@ -421,13 +421,13 @@ template constexpr auto bit_size() -> std::size_t { template CONSTEVAL auto smallest_uint() { if constexpr (N <= std::numeric_limits::digits) { - return std::uint8_t{N}; + return std::uint8_t{}; } else if constexpr (N <= std::numeric_limits::digits) { - return std::uint16_t{N}; + return std::uint16_t{}; } else if constexpr (N <= std::numeric_limits::digits) { - return std::uint32_t{N}; + return std::uint32_t{}; } else { - return std::uint64_t{N}; + return std::uint64_t{}; } } diff --git a/test/bit.cpp b/test/bit.cpp index fba10f2..8a8e1ad 100644 --- a/test/bit.cpp +++ b/test/bit.cpp @@ -421,3 +421,14 @@ TEST_CASE("bit_pack/unpack round trip 64 <-> 32", "[bit]") { auto const [a, b] = stdx::bit_unpack(x); CHECK(stdx::bit_pack(a, b) == x); } + +TEST_CASE("smallest_uint", "[bit]") { + STATIC_REQUIRE(std::is_same_v, std::uint8_t>); + STATIC_REQUIRE(std::is_same_v, std::uint16_t>); + STATIC_REQUIRE(std::is_same_v, std::uint16_t>); + STATIC_REQUIRE(std::is_same_v, std::uint32_t>); + STATIC_REQUIRE(std::is_same_v, std::uint32_t>); + STATIC_REQUIRE(std::is_same_v, std::uint64_t>); + STATIC_REQUIRE(std::is_same_v, std::uint64_t>); + STATIC_REQUIRE(std::is_same_v, std::uint64_t>); +}