Files
2026-09-07 00:45:35 +02:00

62 lines
2.5 KiB
C++

/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ByteBuffer.hpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: acossari <acossari@student.codam.nl> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2026/08/25 09:30:45 by acossari #+# #+# */
/* Updated: 2026/08/25 13:26:00 by acossari ### ########.fr */
/* */
/* ************************************************************************** */
#pragma once
#include <cstddef>
#include <span>
#include <vector>
namespace webserv {
class ByteBuffer final {
public:
// The fixed 64 KiB capacity is also the maximum request-head size. It
// leaves room for large headers while keeping memory bounded. The server
// accepts at most 256 simultaneous connections, each with one receive and
// one send buffer. In the worst-case scenario, their storage is 32 MiB, a
// modest fixed ceiling for all connection buffers combined.
// The C++23 uz suffix makes 64 a std::size_t, so multiplication occurs in
// std::size_t instead of int and avoids implicit widening (clang-tidy).
static constexpr std::size_t CAPACITY = 64uz * 1024;
std::span<const char> readable() const {
return {storage_.data() + readPos_, writePos_ - readPos_};
}
std::span<char> writableTail() {
return {storage_.data() + writePos_, CAPACITY - writePos_};
}
// Makes count bytes already written in writableTail() readable. count must
// not exceed writableTail().size().
void commit(std::size_t count);
// Discards count bytes from the start of readable(). count must not exceed
// readable().size().
void consume(std::size_t count);
void compact();
private:
// C++17 guaranteed copy elision constructs this vector directly in
// storage_, with no temporary vector or move.
std::vector<char> storage_ = std::vector<char>(CAPACITY);
// Only bytes from readPos_ up to, but not including, writePos_ are live.
// Values outside this range can remain in storage_ and are ignored.
std::size_t readPos_ = 0;
std::size_t writePos_ = 0;
};
} // namespace webserv