Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 7 additions & 4 deletions docs/bit.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -121,17 +121,20 @@ static_assert(stdx::bit_pack<std::uint32_t>(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
Expand Down
8 changes: 4 additions & 4 deletions include/stdx/bit.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -421,13 +421,13 @@ template <typename T> constexpr auto bit_size() -> std::size_t {

template <std::size_t N> CONSTEVAL auto smallest_uint() {
if constexpr (N <= std::numeric_limits<std::uint8_t>::digits) {
return std::uint8_t{N};
return std::uint8_t{};
} else if constexpr (N <= std::numeric_limits<std::uint16_t>::digits) {
return std::uint16_t{N};
return std::uint16_t{};
} else if constexpr (N <= std::numeric_limits<std::uint32_t>::digits) {
return std::uint32_t{N};
return std::uint32_t{};
} else {
return std::uint64_t{N};
return std::uint64_t{};
}
}

Expand Down
11 changes: 11 additions & 0 deletions test/bit.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -421,3 +421,14 @@ TEST_CASE("bit_pack/unpack round trip 64 <-> 32", "[bit]") {
auto const [a, b] = stdx::bit_unpack<std::uint32_t>(x);
CHECK(stdx::bit_pack<std::uint64_t>(a, b) == x);
}

TEST_CASE("smallest_uint", "[bit]") {
STATIC_REQUIRE(std::is_same_v<stdx::smallest_uint_t<8>, std::uint8_t>);
STATIC_REQUIRE(std::is_same_v<stdx::smallest_uint_t<9>, std::uint16_t>);
STATIC_REQUIRE(std::is_same_v<stdx::smallest_uint_t<16>, std::uint16_t>);
STATIC_REQUIRE(std::is_same_v<stdx::smallest_uint_t<17>, std::uint32_t>);
STATIC_REQUIRE(std::is_same_v<stdx::smallest_uint_t<32>, std::uint32_t>);
STATIC_REQUIRE(std::is_same_v<stdx::smallest_uint_t<33>, std::uint64_t>);
STATIC_REQUIRE(std::is_same_v<stdx::smallest_uint_t<64>, std::uint64_t>);
STATIC_REQUIRE(std::is_same_v<stdx::smallest_uint_t<65>, std::uint64_t>);
}