2#include <ossia/detail/pod_vector.hpp>
3#include <ossia/network/sockets/writers.hpp>
5#include <boost/asio/buffer.hpp>
6#include <boost/asio/error.hpp>
7#include <boost/asio/write.hpp>
12template <u
int8_t Start = 0x02, u
int8_t End = 0x03, u
int8_t Escape = 0x10>
13struct delimiter_framing
16 Start != End && Start != Escape && End != Escape,
17 "start, end, and escape bytes must be distinct");
19 template <
typename Socket>
23 alignas(64) uint8_t m_readbuf[4096];
24 ossia::pod_vector<char> m_decoded;
30 } m_status{waiting_start};
31 lifetime_token m_lifetime;
33 explicit decoder(Socket& socket)
36 m_decoded.reserve(1024);
42 socket.async_read_some(
43 boost::asio::buffer(m_readbuf),
44 [
this, alive = m_lifetime.watch(),
45 f = std::move(f)](boost::system::error_code ec, std::size_t sz)
mutable {
50 if(!f.validate_stream(ec))
54 process_bytes(f, m_readbuf, sz);
56 receive(std::move(f));
61 void process_bytes(
const F& f,
const uint8_t* data, std::size_t sz)
63 const uint8_t* ptr = data;
64 const uint8_t* end = data + sz;
68 if(m_status == reading_data)
71 const uint8_t* run_end = ptr;
72 while(run_end < end && *run_end != End && *run_end != Escape
79 m_decoded.end(),
reinterpret_cast<const char*
>(ptr),
80 reinterpret_cast<const char*
>(run_end));
85 process_byte(f, *ptr++);
89 process_byte(f, *ptr++);
95 void process_byte(
const F& f, uint8_t
byte)
102 m_status = reading_data;
111 m_status = waiting_start;
112 if(m_decoded.size() > 0)
113 f((
const unsigned char*)m_decoded.data(), m_decoded.size());
117 m_status = reading_escape;
124 m_decoded.push_back(
byte);
130 m_decoded.push_back(
byte);
131 m_status = reading_data;
137 template <
typename Socket>
141 ossia::pod_vector<uint8_t> m_buf;
143 void write(
const char* data, std::size_t sz)
146 m_buf.reserve(sz * 2 + 2);
147 m_buf.push_back(Start);
149 auto* src =
reinterpret_cast<const uint8_t*
>(data);
150 for(std::size_t i = 0; i < sz; ++i)
157 m_buf.push_back(Escape);
158 m_buf.push_back(src[i]);
161 m_buf.push_back(src[i]);
165 m_buf.push_back(End);
167 this->do_write(socket, boost::asio::buffer(m_buf.data(), m_buf.size()));
170 template <
typename T>
171 void do_write(T& sock,
const boost::asio::const_buffer& buf)
173 boost::asio::write(sock, buf);
176 template <
typename T>
177 void do_write(multi_socket_writer<T>& sock,
const boost::asio::const_buffer& buf)
185using stx_etx_framing = delimiter_framing<0x02, 0x03, 0x10>;