KItinerary

bitvectorview.h
1/*
2 SPDX-FileCopyrightText: 2022 Volker Krause <vkrause@kde.org>
3 SPDX-License-Identifier: LGPL-2.0-or-later
4*/
5
6#ifndef KITINERARY_BITVECTOR_H
7#define KITINERARY_BITVECTOR_H
8
9#include <bitset>
10#include <cassert>
11#include <cstdint>
12#include <string_view>
13#include <type_traits>
14
15class QByteArray;
16
17namespace KItinerary {
18
19/** Non-owning bit-level view for working with data that isn't byte-aligned. */
21{
22public:
24 explicit BitVectorView(std::string_view data);
26
27 using size_type = std::string_view::size_type;
28
29 /** Size of this vector in bits. */
30 size_type size() const;
31
32 /** Returns the bit value at @p index. */
33 uint8_t at(size_type index) const;
34
35 /** Read a big endian unsigned number at bit offset @p index
36 * and @p bits in length.
37 */
38 template <typename T>
39 T valueAtMSB(size_type index, size_type bits) const
40 {
41 static_assert(std::is_integral_v<T>);
42 assert(size_type(sizeof(T) * 8) >= bits);
43
44 T result = {};
45 for (size_type i = 0; i < bits; ++i) {
46 result <<= 1;
47 result |= at(index + i);
48 }
49
50 return result;
51 }
52
53 /** Returns @p bytes starting at bit offset @p index. */
54 QByteArray byteArrayAt(size_type index, size_type bytes) const;
55
56 /** Reads a std::bitset from @p index. */
57 template <std::size_t N>
58 std::bitset<N> bitsetAt(size_type index) const
59 {
60 std::bitset<N> result = {};
61 for (size_type i = 0; i < (size_type)N; ++i) {
62 result[N - i - 1] = at(index + i);
63 }
64 return result;
65 }
66
67private:
68 std::string_view m_data;
69};
70
71}
72
73#endif // KITINERARY_BITVECTOR_H
Non-owning bit-level view for working with data that isn't byte-aligned.
uint8_t at(size_type index) const
Returns the bit value at index.
size_type size() const
Size of this vector in bits.
QByteArray byteArrayAt(size_type index, size_type bytes) const
Returns bytes starting at bit offset index.
std::bitset< N > bitsetAt(size_type index) const
Reads a std::bitset from index.
T valueAtMSB(size_type index, size_type bits) const
Read a big endian unsigned number at bit offset index and bits in length.
Classes for reservation/travel data models, data extraction and data augmentation.
Definition berelement.h:17
This file is part of the KDE documentation.
Documentation copyright © 1996-2024 The KDE developers.
Generated on Mon Nov 18 2024 12:09:58 by doxygen 1.12.0 written by Dimitri van Heesch, © 1997-2006

KDE's Doxygen guidelines are available online.