summaryrefslogtreecommitdiff
path: root/src/data_buffer.h
blob: 52068063660440123ee325acdb233976479a1e21 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#pragma once

/* SPDX-License-Identifier: Unlicense
 */

#include "common.h"

#include <cstddef>
#include <cstdint>
#include <cstdio>

struct DataView {
    const uint8_t *const buffer{};
    const size_t size{};
};

struct DataBuffer {
    DataBuffer(){};
    DataBuffer(const DataBuffer&) = delete;
    constexpr DataBuffer(DataBuffer&& other)
        : buffer(other.buffer)
        , buffer_size(other.buffer_size)
        , occupied_size(other.occupied_size)
    {
        other.occupied_size = 0;
        other.buffer_size = 0;
        other.buffer = nullptr;
    };
    static constexpr size_t kInitialSize = 4 * 1024;
    uint8_t *buffer{new uint8_t[kInitialSize]};
    size_t buffer_size{kInitialSize};
    size_t occupied_size{};
    void Expand(size_t new_size);
    constexpr auto View(size_t offset = 0, size_t size = SIZE_MAX) const
    {
        if (offset >= occupied_size) {
            return DataView{};
        }
        return DataView{buffer + offset, Min(occupied_size - offset, size)};
    };
    ~DataBuffer();
    static DataBuffer FromStream(FILE *stream);
};