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 "utility/module.hpp"
8#include <span>
9#include <cstddef>
10
11namespace hi::inline v1 {
12
19[[nodiscard]] inline bool get_bit(std::span<std::byte const> buffer, std::size_t &index) noexcept
20{
21 hilet byte_index = index >> 3;
22 hilet bit_index = index & 7;
23 ++index;
24
25 hi_axiom(byte_index < buffer.size());
26 return to_bool(std::bit_cast<uint8_t>(buffer[byte_index] >> bit_index) & 1);
27}
28
47[[nodiscard]] inline std::size_t get_bits(std::span<std::byte const> buffer, std::size_t &index, std::size_t length) noexcept
48{
49 hi_axiom(length <= sizeof(std::size_t) * CHAR_BIT);
50
51 auto value = 0;
52
53 auto todo = length;
54 auto done = 0_uz;
55 while (todo) {
56 hilet byte_index = index >> 3;
57 hilet bit_index = index & 7;
58 hi_axiom(byte_index < buffer.size());
59
60 hilet available_bits = 8 - bit_index;
61 hilet nr_bits = std::min(available_bits, todo);
62
63 hilet mask = (1 << nr_bits) - 1;
64
65 hilet tmp = static_cast<int>(buffer[byte_index] >> bit_index) & mask;
66 value |= tmp << done;
67
68 todo -= nr_bits;
69 done += nr_bits;
70 index += nr_bits;
71 }
72
73 return value;
74}
75
76} // namespace hi::inline v1
#define hi_axiom(expression,...)
Specify an axiom; an expression that is true.
Definition assert.hpp:253
#define hilet
Invariant should be the default for variables.
Definition utility.hpp:23
DOXYGEN BUG.
Definition algorithm.hpp:13
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:19
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:47
T min(T... args)