OSSIA
Open Scenario System for Interactive Application
Loading...
Searching...
No Matches
no_framing.hpp
1#pragma once
2#include <ossia/network/sockets/writers.hpp>
3
4#include <boost/asio/buffer.hpp>
5#include <boost/asio/error.hpp>
6#include <boost/asio/read.hpp>
7#include <boost/asio/streambuf.hpp>
8#include <boost/asio/write.hpp>
9
10namespace ossia::net
11{
12
13struct no_framing
14{
15 template <typename Socket>
16 struct encoder
17 {
18 Socket& socket;
19 void write(const char* data, std::size_t sz)
20 {
21 this->write(socket, boost::asio::buffer(data, sz));
22 }
23
24 template <typename T>
25 void write(T& sock, const boost::asio::const_buffer& buf)
26 {
27 boost::asio::write(sock, buf);
28 }
29
30 template <typename T>
31 void write(multi_socket_writer<T>& sock, const boost::asio::const_buffer& buf)
32 {
33 sock.write(buf);
34 }
35 };
36
37 template <typename Socket>
38 struct decoder
39 {
40 Socket& socket;
41 boost::asio::streambuf m_data;
42
43 explicit decoder(Socket& s)
44 : socket{s}
45 {
46 }
47
48 decoder() = delete;
49 decoder(const decoder&) = delete;
50 decoder(decoder&&) = delete;
51 decoder& operator=(const decoder&) = delete;
52 decoder& operator=(decoder&&) = delete;
53 template <typename F>
54 void receive(F f)
55 {
56 socket.async_read_some(
57 boost::asio::mutable_buffer(m_data.prepare(1024)),
58 [this,
59 f = std::move(f)](boost::system::error_code ec, std::size_t sz) mutable {
60 if(!f.validate_stream(ec))
61 return;
62
63 auto data = (const uint8_t*)m_data.data().data();
64 f(data, sz);
65 receive(std::move(f));
66 });
67 }
68 };
69};
70
71}