Pixie
Loading...
Searching...
No Matches
read_only_view.h
1#pragma once
2
3#include <pixie/storage.h>
4
5#include <cstring>
6#include <span>
7#include <stdexcept>
8
9namespace pixie {
10
17class ReadOnlyStorageView : public StorageBase<ReadOnlyStorageView> {
18 public:
19 ReadOnlyStorageView() = default;
20
22 explicit ReadOnlyStorageView(std::span<const std::byte> data) : data_(data) {}
23
25 std::size_t size_bytes_impl() const { return data_.size(); }
26
28 std::span<const std::byte> as_bytes_impl() const { return data_; }
29
31 ReadOnlyStorageView view_impl(std::size_t offset_bytes,
32 std::size_t count_bytes) const {
33 if (offset_bytes > data_.size() ||
34 count_bytes > data_.size() - offset_bytes) {
35 throw std::out_of_range("Storage view is outside the backing storage");
36 }
37 return ReadOnlyStorageView(data_.subspan(offset_bytes, count_bytes));
38 }
39
44 static ReadOnlyStorageView deserialize(std::span<const std::byte>& data) {
45 if (data.size() < sizeof(std::size_t)) {
46 throw std::invalid_argument("Truncated storage size prefix");
47 }
48 std::size_t size = 0;
49 std::memcpy(&size, data.data(), sizeof(size));
50 if (size > data.size() - sizeof(size)) {
51 throw std::invalid_argument("Truncated storage payload");
52 }
53 ReadOnlyStorageView result(data.subspan(sizeof(size), size));
54 data = data.subspan(sizeof(size) + size);
55 return result;
56 }
57
58 private:
59 std::span<const std::byte> data_;
60};
61
62} // namespace pixie
ReadOnlyStorageView(std::span< const std::byte > data)
Construct a view over data.
Definition read_only_view.h:22
ReadOnlyStorageView view_impl(std::size_t offset_bytes, std::size_t count_bytes) const
Return a checked read-only byte subrange.
Definition read_only_view.h:31
std::span< const std::byte > as_bytes_impl() const
Return the viewed bytes.
Definition read_only_view.h:28
static ReadOnlyStorageView deserialize(std::span< const std::byte > &data)
Deserialize a size-prefixed view and advance data.
Definition read_only_view.h:44
std::size_t size_bytes_impl() const
Return the number of viewed bytes.
Definition read_only_view.h:25
CRTP facade for byte-addressable storage.
Definition storage.h:27
Common interface for byte-addressable storage.