group2 0.1.0
CSE 125 Group 2
Loading...
Searching...
No Matches
MessageStream.hpp
Go to the documentation of this file.
1
3
4#pragma once
5
6#include <SDL3/SDL_stdinc.h>
7
8#include <SDL3_net/SDL_net.h>
9#include <functional>
10#include <vector>
11
29{
30
31public:
36 MessageStream() = default;
37
38 MessageStream(NET_StreamSocket* sock) : socket(sock) {}
39
40 NET_StreamSocket* socket = nullptr;
41
46 bool send(const void* data, Uint32 size);
47
52 bool poll(const std::function<void(const void* data, Uint32 size)>& callback);
53
62 bool pumpReads();
63
70 void drainComplete(const std::function<void(const void* data, Uint32 size)>& callback);
71
72private:
74 [[nodiscard]] Uint32 recvAvailable() const noexcept { return static_cast<Uint32>(recvBuf.size()) - recvHead; }
75
77 [[nodiscard]] const Uint8* recvFront() const noexcept { return recvBuf.data() + recvHead; }
78
80 void recvCompact();
81
82 std::vector<Uint8> recvBuf;
83 Uint32 recvHead = 0;
84};
std::vector< Uint8 > recvBuf
Accumulates partial data between poll() calls.
Definition MessageStream.hpp:82
MessageStream()=default
PR-5b: default-construct so server Connection (which embeds a MessageStream) can be try_emplace'd int...
MessageStream(NET_StreamSocket *sock)
Definition MessageStream.hpp:38
void drainComplete(const std::function< void(const void *data, Uint32 size)> &callback)
Decode-only half of poll(): invoke the callback for each complete message currently buffered.
Definition MessageStream.cpp:72
bool pumpReads()
Read-only half of poll(): drain the kernel into recvBuf.
Definition MessageStream.cpp:44
Uint32 recvAvailable() const noexcept
Bytes available for parsing in recvBuf, starting at recvHead.
Definition MessageStream.hpp:74
void recvCompact()
Compact recvBuf: shift unconsumed bytes to the front, reset head.
Definition MessageStream.cpp:32
bool poll(const std::function< void(const void *data, Uint32 size)> &callback)
Read all available bytes from the socket and invoke the callback once per complete message frame.
Definition MessageStream.cpp:102
NET_StreamSocket * socket
Underlying SDL_net stream socket.
Definition MessageStream.hpp:40
const Uint8 * recvFront() const noexcept
Pointer to the first unconsumed byte.
Definition MessageStream.hpp:77
Uint32 recvHead
Offset of next unconsumed byte in recvBuf (avoids O(N) erase).
Definition MessageStream.hpp:83
bool send(const void *data, Uint32 size)
Send a framed message over the socket.
Definition MessageStream.cpp:22