summaryrefslogtreecommitdiffstats
path: root/src/common/scratch_buffer.h
blob: 59bb8a9ea98a9c9a4983e8314acb1c89103ac354 (plain) (blame)
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
// SPDX-FileCopyrightText: Copyright 2022 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later

#pragma once

#include "common/make_unique_for_overwrite.h"

namespace Common {

/**
 * ScratchBuffer class
 * This class creates a default initialized heap allocated buffer for cases such as intermediate
 * buffers being copied into entirely, where value initializing members during allocation or resize
 * is redundant.
 */
template <typename T>
class ScratchBuffer {
public:
    ScratchBuffer() = default;

    explicit ScratchBuffer(size_t initial_capacity)
        : last_requested_size{initial_capacity}, buffer_capacity{initial_capacity},
          buffer{Common::make_unique_for_overwrite<T[]>(initial_capacity)} {}

    ~ScratchBuffer() = default;

    /// This will only grow the buffer's capacity if size is greater than the current capacity.
    void resize(size_t size) {
        if (size > buffer_capacity) {
            buffer_capacity = size;
            buffer = Common::make_unique_for_overwrite<T[]>(buffer_capacity);
        }
        last_requested_size = size;
    }

    [[nodiscard]] T* data() noexcept {
        return buffer.get();
    }

    [[nodiscard]] const T* data() const noexcept {
        return buffer.get();
    }

    [[nodiscard]] T* begin() noexcept {
        return data();
    }

    [[nodiscard]] const T* begin() const noexcept {
        return data();
    }

    [[nodiscard]] T* end() noexcept {
        return data() + last_requested_size;
    }

    [[nodiscard]] const T* end() const noexcept {
        return data() + last_requested_size;
    }

    [[nodiscard]] T& operator[](size_t i) {
        return buffer[i];
    }

    [[nodiscard]] size_t size() const noexcept {
        return last_requested_size;
    }

    [[nodiscard]] size_t capacity() const noexcept {
        return buffer_capacity;
    }

private:
    size_t last_requested_size{};
    size_t buffer_capacity{};
    std::unique_ptr<T[]> buffer{};
};

} // namespace Common