Aegis2D
Modular C++26 2D game engine for networked games
Loading...
Searching...
No Matches
bits.hpp
Go to the documentation of this file.
1
3#pragma once
4#include <aegis2d/net/export.hpp>
5
6#include <cstddef>
7#include <cstdint>
8#include <optional>
9#include <span>
10#include <vector>
11
12namespace aegis2d::net {
13
18class AEGIS2D_NET_EXPORT BitWriter {
19public:
21 static constexpr unsigned max_width = 64;
22
27 void write_bits(std::uint64_t value, unsigned width);
32 void write_signed(std::int64_t value, unsigned width);
35 void write_bool(bool value);
36
39 [[nodiscard]] std::span<const std::byte> data() const noexcept;
42 [[nodiscard]] std::size_t size() const noexcept;
45 [[nodiscard]] std::size_t bit_size() const noexcept;
47 void clear() noexcept;
48
49private:
50 std::vector<std::byte> buffer_;
51 std::size_t bit_size_ = 0;
52};
53
60class AEGIS2D_NET_EXPORT BitReader {
61public:
64 explicit BitReader(std::span<const std::byte> bytes) noexcept;
65
70 [[nodiscard]] std::optional<std::uint64_t> read_bits(unsigned width) noexcept;
75 [[nodiscard]] std::optional<std::int64_t> read_signed(unsigned width) noexcept;
78 [[nodiscard]] std::optional<bool> read_bool() noexcept;
79
82 [[nodiscard]] bool failed() const noexcept;
87 [[nodiscard]] bool at_end() const noexcept;
90 [[nodiscard]] std::size_t bit_position() const noexcept;
93 [[nodiscard]] std::size_t bits_remaining() const noexcept;
94
95private:
96 std::span<const std::byte> bytes_;
97 std::size_t bit_position_ = 0;
98 bool failed_ = false;
99};
100
101} // namespace aegis2d::net
Reads values written by BitWriter from untrusted bytes, never past their end.
Definition bits.hpp:60
std::optional< std::int64_t > read_signed(unsigned width) noexcept
Reads a signed value in two's complement.
std::optional< std::uint64_t > read_bits(unsigned width) noexcept
Reads an unsigned value.
std::optional< bool > read_bool() noexcept
Reads a boolean, one bit.
BitReader(std::span< const std::byte > bytes) noexcept
Starts reading at the first bit of bytes.
Writes values of any width from 0 to 64 bits into a growing byte buffer.
Definition bits.hpp:18
void write_bits(std::uint64_t value, unsigned width)
Appends an unsigned value.
std::span< const std::byte > data() const noexcept
Bytes written so far, the last one completed with 0 bits.
void write_signed(std::int64_t value, unsigned width)
Appends a signed value in two's complement.
void write_bool(bool value)
Appends a boolean as one bit.
Binary serialization, UDP/TCP sockets and the network thread.
Definition binary.hpp:14
Definition endpoint.hpp:85