HikoGUI
A low latency retained GUI
Loading...
Searching...
No Matches
bits.hpp
1// Copyright Take Vos 2020-2022.
2// Distributed under the Boost Software License, Version 1.0.
3// (See accompanying file LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt)
4
5#pragma once
6
7#include "exception.hpp"
8#include "assert.hpp"
9#include <span>
10#include <cstddef>
11
12namespace hi::inline v1 {
13
20[[nodiscard]] inline bool get_bit(std::span<std::byte const> buffer, std::size_t &index) noexcept
21{
22 hilet byte_index = index >> 3;
23 hilet bit_index = index & 7;
24 ++index;
25
26 hi_axiom(byte_index < buffer.size());
27 return to_bool(std::bit_cast<uint8_t>(buffer[byte_index] >> bit_index) & 1);
28}
29
48[[nodiscard]] inline std::size_t get_bits(std::span<std::byte const> buffer, std::size_t &index, std::size_t length) noexcept
49{
50 hi_axiom(length <= sizeof(std::size_t) * CHAR_BIT);
51
52 auto value = 0;
53
54 auto todo = length;
55 auto done = 0_uz;
56 while (todo) {
57 hilet byte_index = index >> 3;
58 hilet bit_index = index & 7;
59 hi_axiom(byte_index < buffer.size());
60
61 hilet available_bits = 8 - bit_index;
62 hilet nr_bits = std::min(available_bits, todo);
63
64 hilet mask = (1 << nr_bits) - 1;
65
66 hilet tmp = static_cast<int>(buffer[byte_index] >> bit_index) & mask;
67 value |= tmp << done;
68
69 todo -= nr_bits;
70 done += nr_bits;
71 index += nr_bits;
72 }
73
74 return value;
75}
76
77} // namespace hi::inline v1
Utilities to assert and bound check.
#define hi_axiom(expression)
Specify an axiom; an expression that is true.
Definition assert.hpp:133
#define hilet
Invariant should be the default for variables.
Definition utility.hpp:23
DOXYGEN BUG.
Definition algorithm.hpp:15
bool get_bit(std::span< std::byte const > buffer, std::size_t &index) noexcept
Read a single bit from span of bytes Bits are ordered LSB first.
Definition bits.hpp:20
std::size_t get_bits(std::span< std::byte const > buffer, std::size_t &index, std::size_t length) noexcept
Read a bits from of span of bytes Bits are ordered LSB first.
Definition bits.hpp:48
T min(T... args)