Slick Sim 0.10.1
Exchange simulator that shadows real venues for risk-free strategy testing
Loading...
Searching...
No Matches
control_stream.hpp
Go to the documentation of this file.
1#pragma once
2
4#include <cstddef>
5#include <cstdint>
6#include <cstring>
7#include <unordered_map>
8#include <vector>
9
10namespace slick::sim {
11
16public:
19 explicit ControlStreams(size_t max_length) noexcept : max_length_(max_length) {}
20
25 template <typename OnMessage>
26 bool feed(int connection, const uint8_t *data, size_t size, OnMessage &&on_message) {
27 auto &buffer = partial_[connection];
28 if (buffer.empty()) {
29 // On a message boundary: read straight out of the socket buffer.
30 const size_t used = split(data, size, on_message);
31 if (used == SIZE_MAX) {
32 return false;
33 }
34 if (used < size) {
35 buffer.assign(data + used, data + size);
36 }
37 return true;
38 }
39 buffer.insert(buffer.end(), data, data + size);
40 const size_t used = split(buffer.data(), buffer.size(), on_message);
41 if (used == SIZE_MAX) {
42 return false;
43 }
44 buffer.erase(buffer.begin(), buffer.begin() + static_cast<std::ptrdiff_t>(used));
45 return true;
46 }
47
48 void erase(int connection) { partial_.erase(connection); }
49
50private:
52 template <typename OnMessage>
53 size_t split(const uint8_t *data, size_t size, OnMessage &on_message) {
54 size_t used = 0;
55 while (size - used >= sizeof(ControlHeader)) {
56 ControlHeader header;
57 std::memcpy(&header, data + used, sizeof(header));
58 if (header.length < sizeof(ControlHeader) || header.length > max_length_) {
59 return SIZE_MAX;
60 }
61 if (size - used < header.length) {
62 break;
63 }
64 if (!on_message(header, data + used)) {
65 return SIZE_MAX;
66 }
67 used += header.length;
68 }
69 return used;
70 }
71
72 size_t max_length_;
73 std::unordered_map<int, std::vector<uint8_t>> partial_;
74};
75
76} // namespace slick::sim
bool feed(int connection, const uint8_t *data, size_t size, OnMessage &&on_message)
Hands on_message(const ControlHeader &, const uint8_t *message) every whole message data completes,...
void erase(int connection)
ControlStreams(size_t max_length) noexcept
max_length is the longest message the server accepts.
Every control message starts with this.