~aleteoryx/muditaos

muditaos/module-utils/utility/integer.hpp -rw-r--r-- 1.4 KiB
a405cad6Aleteoryx trim readme 6 days ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
// Copyright (c) 2017-2024, Mudita Sp. z.o.o. All rights reserved.
// For licensing, see https://github.com/mudita/MuditaOS/blob/master/LICENSE.md

#pragma once

#include <cstdint>

namespace utils::integer
{

    /**
     * @brief number bits in bytes constant for greater clarity
     */
    constexpr inline auto BitsInByte = 8U;

    /**
     * @brief Allows to pass type as a return value with no overhead; used by
     * getIntegerType.
     *
     * @tparam T - type to return
     */
    template <typename T>
    struct TypeHolder
    {
        using type = T;
    };

    /**
     * @brief Discovers the type of integer which is best suited to hold
     * N bits of information, e.g.: returns std::uint8_t for 5 bits,
     * std::uint32_t for 18.
     *
     * @tparam Bits - number of bits which must an integer be able to hold.
     * @return integer type best suited to hold value Bits bits long.
     */
    template <unsigned int Bits>
    auto getIntegerType()
    {
        static_assert(Bits <= 64);

        if constexpr (Bits <= 8) {
            return TypeHolder<std::uint8_t>();
        }
        else if constexpr (Bits <= 16) {
            return TypeHolder<std::uint16_t>();
        }
        else if constexpr (Bits <= 32) {
            return TypeHolder<std::uint32_t>();
        }
        else {
            return TypeHolder<std::uint64_t>();
        }
    }

} // namespace utils::integer