BCNP 3.2.1
Batched Command Network Protocol
Loading...
Searching...
No Matches
stream_parser.h
Go to the documentation of this file.
1#pragma once
2
3#include "bcnp/packet.h"
4
5#include <array>
6#include <cstddef>
7#include <cstdint>
8#include <functional>
9#include <utility>
10
11namespace bcnp {
12
22public:
23 using PacketCallback = std::function<void(const PacketView&)>;
24 struct ErrorInfo {
26 std::size_t offset{0};
27 uint64_t consecutiveErrors{0};
28 };
29 using ErrorCallback = std::function<void(const ErrorInfo&)>;
30
33 using WireSizeLookup = std::function<std::size_t(MessageTypeId)>;
34
35 StreamParser(PacketCallback onPacket, ErrorCallback onError = {}, std::size_t bufferSize = 4096);
36
37 void Push(const uint8_t* data, std::size_t length);
38
39 void Reset(bool resetErrorState = true);
40
42 void SetWireSizeLookup(WireSizeLookup lookup) { m_wireSizeLookup = std::move(lookup); }
43
44 static constexpr std::size_t kMaxParseIterationsPerPush = 1024;
45
46private:
47 void EmitPacket(const PacketView& packet);
48 void EmitError(PacketError error, std::size_t offset);
49
50 void WriteToBuffer(const uint8_t* data, std::size_t length);
51 void CopyOut(std::size_t offset, std::size_t length, uint8_t* dest) const;
52 void Discard(std::size_t count);
53 void ParseBuffer(std::size_t& iterationBudget);
54 std::size_t FindNextHeaderCandidate() const;
55 std::size_t LookupWireSize(MessageTypeId typeId) const;
56
57 PacketCallback m_onPacket;
58 ErrorCallback m_onError;
59 WireSizeLookup m_wireSizeLookup;
60 std::vector<uint8_t> m_buffer;
61 std::vector<uint8_t> m_decodeScratch;
62 std::size_t m_head{0};
63 std::size_t m_size{0};
64 std::size_t m_streamOffset{0};
65 uint64_t m_consecutiveErrors{0};
66};
67
68} // namespace bcnp
Parses a byte stream into BCNP packets.
static constexpr std::size_t kMaxParseIterationsPerPush
std::function< void(const PacketView &)> PacketCallback
void SetWireSizeLookup(WireSizeLookup lookup)
Set custom wire size lookup (for testing with custom message types)
StreamParser(PacketCallback onPacket, ErrorCallback onError={}, std::size_t bufferSize=4096)
Construct a stream parser with callbacks and buffer size.
void Reset(bool resetErrorState=true)
Reset the parser to its initial state.
std::function< std::size_t(MessageTypeId)> WireSizeLookup
std::function< void(const ErrorInfo &)> ErrorCallback
void Push(const uint8_t *data, std::size_t length)
Push raw bytes into the parser for processing.
PacketError
Error codes returned by packet decoding operations.
Definition packet.h:268
@ None
No error - packet decoded successfully.
BCNP packet structures, encoding, and decoding utilities.
Zero-copy view into a decoded packet buffer.
Definition packet.h:170