Line data Source code
1 : /*
2 : * Protobuf serialization library - bit-fields support.
3 : *
4 : * Copyright (c) 2024 Antonin Kriz <antonin.kriz@gmail.com>
5 : * Released under the MIT License. See LICENSE in the project root.
6 : */
7 :
8 : #pragma once
9 :
10 : #include <cassert>
11 : #include <climits>
12 : #include <cstdint>
13 : #include <stdexcept>
14 :
15 : namespace spb::detail
16 : {
17 : template <typename T>
18 : concept signed_int = std::is_signed_v<T> && std::is_integral_v<T>;
19 :
20 : template <typename T>
21 : concept unsigned_int = !std::is_signed_v<T> && std::is_integral_v<T>;
22 :
23 542 : static inline void check_if_value_fit_in_bits(signed_int auto value, uint32_t bits)
24 : {
25 542 : assert(sizeof(value) * CHAR_BIT >= bits);
26 542 : assert(bits > 0);
27 :
28 542 : decltype(value) max = (1LL << (bits - 1)) - 1;
29 542 : decltype(value) min = -(1LL << (bits - 1));
30 :
31 542 : if ((value < min) | (value > max)) [[unlikely]]
32 56 : throw std::runtime_error("bitfield overflow");
33 486 : }
34 :
35 435 : static inline void check_if_value_fit_in_bits(unsigned_int auto value, uint32_t bits)
36 : {
37 435 : assert(sizeof(value) * CHAR_BIT >= bits);
38 :
39 435 : decltype(value) max = (1LL << bits) - 1;
40 :
41 435 : if (value > max) [[unlikely]]
42 37 : throw std::runtime_error("bitfield overflow");
43 398 : }
44 :
45 : } // namespace spb::detail
|