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 "../macros.hpp"
8#include "cast.hpp"
9#include "terminate.hpp"
10#include "exception.hpp"
11#include "misc.hpp"
12#include <span>
13#include <cstddef>
14#include <exception>
15#include <bit>
16
17hi_export_module(hikogui.utility.bits);
18
19hi_export namespace hi { inline namespace v1 {
20
27[[nodiscard]] inline bool get_bit(std::span<std::byte const> buffer, std::size_t &index) noexcept
28{
29 auto const byte_index = index >> 3;
30 auto const bit_index = index & 7;
31 ++index;
32
33 hi_axiom(byte_index < buffer.size());
34 return to_bool(std::bit_cast<uint8_t>(buffer[byte_index] >> bit_index) & 1);
35}
36
55[[nodiscard]] inline std::size_t get_bits(std::span<std::byte const> buffer, std::size_t &index, std::size_t length) noexcept
56{
57 hi_axiom(length <= sizeof(std::size_t) * CHAR_BIT);
58
59 auto value = 0;
60
61 auto todo = length;
62 auto done = 0_uz;
63 while (todo) {
64 auto const byte_index = index >> 3;
65 auto const bit_index = index & 7;
66 hi_axiom(byte_index < buffer.size());
67
68 auto const available_bits = 8 - bit_index;
69 auto const nr_bits = std::min(available_bits, todo);
70
71 auto const mask = (1 << nr_bits) - 1;
72
73 auto const tmp = static_cast<int>(buffer[byte_index] >> bit_index) & mask;
74 value |= tmp << done;
75
76 todo -= nr_bits;
77 done += nr_bits;
78 index += nr_bits;
79 }
80
81 return value;
82}
83
84}} // namespace hi::inline v1
Functions for casting values between types savely.
Utilities for throwing exceptions and terminating the application.
The HikoGUI namespace.
Definition array_generic.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:55
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:27
DOXYGEN BUG.
Definition algorithm_misc.hpp:20
T min(T... args)