Skip to content

Commit 1085b5f

Browse files
authored
Merge pull request #19 from 4ms/smallest_integer
Determining smallest integer type that can represent a given value
2 parents 2634b3c + 6e435d3 commit 1085b5f

1 file changed

Lines changed: 39 additions & 0 deletions

File tree

util/smallest_integer.hh

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
#pragma once
2+
3+
#include <cstdint>
4+
#include <limits>
5+
#include <type_traits>
6+
7+
template<uint64_t max_val>
8+
struct SmallestUnsignedInt {
9+
using type = std::conditional_t<
10+
max_val <= std::numeric_limits<uint8_t>::max(),
11+
uint8_t,
12+
std::conditional_t<max_val <= std::numeric_limits<uint16_t>::max(),
13+
uint16_t,
14+
std::conditional_t<max_val <= std::numeric_limits<uint32_t>::max(), uint32_t, uint64_t>>>;
15+
};
16+
17+
template<int64_t min_val, int64_t max_val>
18+
requires(min_val <= max_val)
19+
struct SmallestSignedInt {
20+
using type =
21+
std::make_signed_t<typename SmallestUnsignedInt<(max_val >= -min_val ? max_val : -min_val - 1) << 1>::type>;
22+
};
23+
24+
static_assert(std::is_same_v<SmallestUnsignedInt<0>::type, uint8_t>);
25+
static_assert(std::is_same_v<SmallestUnsignedInt<255>::type, uint8_t>);
26+
static_assert(std::is_same_v<SmallestUnsignedInt<256>::type, uint16_t>);
27+
static_assert(std::is_same_v<SmallestUnsignedInt<65535>::type, uint16_t>);
28+
static_assert(std::is_same_v<SmallestUnsignedInt<65536>::type, uint32_t>);
29+
static_assert(std::is_same_v<SmallestUnsignedInt<(1ull << 32) - 1>::type, uint32_t>);
30+
static_assert(std::is_same_v<SmallestUnsignedInt<1ull << 32>::type, uint64_t>);
31+
32+
static_assert(std::is_same_v<SmallestSignedInt<0, 127>::type, int8_t>);
33+
static_assert(std::is_same_v<SmallestSignedInt<-128, 127>::type, int8_t>);
34+
static_assert(std::is_same_v<SmallestSignedInt<0, 128>::type, int16_t>);
35+
static_assert(std::is_same_v<SmallestSignedInt<-129, 0>::type, int16_t>);
36+
static_assert(std::is_same_v<SmallestSignedInt<0, 32767>::type, int16_t>);
37+
static_assert(std::is_same_v<SmallestSignedInt<-32768, 32767>::type, int16_t>);
38+
static_assert(std::is_same_v<SmallestSignedInt<-32768, 32768>::type, int32_t>);
39+
static_assert(std::is_same_v<SmallestSignedInt<-3293768, 3932768>::type, int32_t>);

0 commit comments

Comments
 (0)