nanoMMO 0.97.8
Building an MMO: The Engineering Series
Loading...
Searching...
No Matches
framing.cc
Go to the documentation of this file.
1#include "protocol/framing.h"
2
3#include <cstdint>
4#include <string>
5
6namespace nanommo {
7
8std::string Header(std::size_t size) {
9 const auto value = static_cast<uint32_t>(size);
10 return {static_cast<char>(value >> 24), static_cast<char>(value >> 16),
11 static_cast<char>(value >> 8), static_cast<char>(value)};
12}
13
14std::string Frame(const google::protobuf::MessageLite& message) {
15 const std::string body = message.SerializeAsString();
16 return Header(body.size()) + body;
17}
18
19void FrameReader::Append(std::string_view bytes) { buffer_.append(bytes); }
20
21std::optional<std::string> FrameReader::Next() {
22 if (buffer_.size() < kHeaderSize) {
23 return std::nullopt;
24 }
25 uint32_t size = 0;
26 for (std::size_t i = 0; i < kHeaderSize; ++i) {
27 size = (size << 8) | static_cast<uint8_t>(buffer_[i]);
28 }
29 if (size > kMaxMessageSize) {
30 status_ = absl::InvalidArgumentError("message of " + std::to_string(size) +
31 " bytes is too large");
32 return std::nullopt;
33 }
34 if (buffer_.size() < kHeaderSize + size) {
35 return std::nullopt;
36 }
37
38 std::string message = buffer_.substr(kHeaderSize, size);
39 buffer_.erase(0, kHeaderSize + size);
40 return message;
41}
42
43} // namespace nanommo
void Append(std::string_view bytes)
Definition framing.cc:19
std::optional< std::string > Next()
Definition framing.cc:21
Definition chat.cc:9
constexpr std::size_t kHeaderSize
Definition framing.h:14
std::string Header(std::size_t size)
Definition framing.cc:8
constexpr std::size_t kMaxMessageSize
Anything bigger is garbage. Without a cap, we might buffer up to 4 GB.
Definition framing.h:17
std::string Frame(const google::protobuf::MessageLite &message)
The size goes in front, as four bytes in network byte order.
Definition framing.cc:14