Echo Writes Code

bits.hpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#ifndef CRUCIBLE_PARSING_BITS_HPP
#define CRUCIBLE_PARSING_BITS_HPP

#include "crucible/core/constant_error.inl"
#include "crucible/core/error_chain.inl"
#include "crucible/core/none.hpp"
#include "crucible/parsing/outcomes.inl"

#include <concepts>
#include <cstddef>
#include <cstdint>
#include <span>

namespace crucible::parsing::bits {
  template<typename T>
  concept FixedWidthUnsignedInteger =
    std::same_as<T, std::uint8_t> ||
    std::same_as<T, std::uint16_t> ||
    std::same_as<T, std::uint32_t> ||
    std::same_as<T, std::uint64_t>;

  struct ByteSequenceMismatch final : core::constant_error::ConstantError<ByteSequenceMismatch> {
    static constexpr char const message[] = "Byte sequence mismatch";
  };

  struct UnexpectedEndOfInput final : core::constant_error::ConstantError<UnexpectedEndOfInput> {
    static constexpr char const message[] = "Unexpected end of input";
  };

  struct ParseError final : core::error_chain::ErrorChain<ParseError, ByteSequenceMismatch, UnexpectedEndOfInput> {
    using ErrorChain::ErrorChain;

    static constexpr char const message[] = "Parse error in bits primitive";
  };

  class ParseState final {
  public:
    explicit ParseState(std::span<std::byte const> const &input);

    ParseState(std::span<std::byte const> const &input, std::size_t const byte_offset, std::size_t const bit_offset);

    [[nodiscard]]
    auto is_finished() const -> bool;

    [[nodiscard]]
    auto get_remaining_bytes_in_input() const -> std::span<std::byte const>;

    [[nodiscard]]
    auto get_remaining_bits_in_byte() const -> std::byte;

    [[nodiscard]]
    auto advance_by_bytes(std::size_t const byte_count) const -> ParseState;

    [[nodiscard]]
    auto advance_by_bits(std::size_t const bit_count) const -> ParseState;

  private:
    std::span<std::byte const> my_input;

    std::size_t my_byte_offset = 0;

    std::size_t my_bit_offset = 0;
  };

  template<typename VALUE>
  using ParseResult = outcomes::ParseResult<ParseState, ParseError, VALUE>;

  class ByteSequence final {
  public:
    using StateType = ParseState;

    using ValueType = core::none::None;

    explicit ByteSequence(std::span<std::byte const> byte_sequence);

    [[nodiscard]]
    auto operator()(ParseState const &state) const -> ParseResult<core::none::None>;

  private:
    std::span<std::byte const> my_byte_sequence;
  };

  template<FixedWidthUnsignedInteger T>
  struct LittleEndianUnsignedInteger final {
    [[nodiscard]]
    auto operator()(ParseState const &state) const -> ParseResult<T>;
  };
}

#endif // CRUCIBLE_PARSING_BITS_HPP