Files
limen/util/parse_buffer.h

36 lines
1014 B
C
Raw Normal View History

2026-04-19 17:28:44 -07:00
#pragma once
#include <cstddef>
#include <cstdint>
#include <span>
// Bounds-checked sequential reader for byte streams. consume<T>() returns a
// typed pointer into the underlying buffer or nullptr on underflow. Used to
// walk packet headers in order without UB and without copies.
2026-04-19 17:28:44 -07:00
class parse_buffer {
const uint8_t* m_data;
size_t m_remaining;
public:
parse_buffer(std::span<const uint8_t> data)
: m_data(data.data()), m_remaining(data.size()) {}
template <typename T>
const T* consume() {
if (m_remaining < sizeof(T)) return nullptr;
auto* p = reinterpret_cast<const T*>(m_data);
m_data += sizeof(T);
m_remaining -= sizeof(T);
return p;
}
bool skip(size_t len) {
if (m_remaining < len) return false;
m_data += len;
m_remaining -= len;
return true;
}
std::span<const uint8_t> remaining() const { return {m_data, m_remaining}; }
size_t remaining_size() const { return m_remaining; }
};