HikoGUI
A low latency retained GUI
Loading...
Searching...
No Matches
bits.hpp
1// Copyright Take Vos 2020.
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 tt {
13
20[[nodiscard]] inline bool get_bit(std::span<std::byte const> buffer, ssize_t &index) noexcept
21{
22 auto byte_index = index >> 3;
23 auto bit_index = static_cast<uint8_t>(index & 7);
24 ++index;
25
26 tt_axiom(byte_index < std::ssize(buffer));
27 return static_cast<bool>(
28 static_cast<int>(buffer[byte_index] >> bit_index) & 1
29 );
30}
31
50[[nodiscard]] inline int get_bits(std::span<std::byte const> buffer, ssize_t &index, int length) noexcept
51{
52 auto value = 0;
53
54 auto todo = length;
55 auto done = 0;
56 while (todo) {
57 auto byte_index = index >> 3;
58 auto bit_index = static_cast<int>(index & 7);
59 tt_axiom(byte_index < std::ssize(buffer));
60
61 auto available_bits = 8 - bit_index;
62 auto nr_bits = std::min(available_bits, todo);
63
64 auto mask = (1 << nr_bits) - 1;
65
66 auto 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}
T min(T... args)