summaryrefslogtreecommitdiffstats
path: root/src/common/virtual_buffer.h
blob: cac4f489556465725ad6b3df2cce3520a427ae76 (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
79
80
81
82
83
// Copyright 2020 yuzu Emulator Project
// Licensed under GPLv2 or any later version
// Refer to the license.txt file included.

#pragma once

#include <utility>

namespace Common {

void* AllocateMemoryPages(std::size_t size) noexcept;
void FreeMemoryPages(void* base, std::size_t size) noexcept;

template <typename T>
class VirtualBuffer final {
public:
    // TODO: Uncomment this and change Common::PageTable::PageInfo to be trivially constructible
    // using std::atomic_ref once libc++ has support for it
    // static_assert(
    //     std::is_trivially_constructible_v<T>,
    //     "T must be trivially constructible, as non-trivial constructors will not be executed "
    //     "with the current allocator");

    constexpr VirtualBuffer() = default;
    explicit VirtualBuffer(std::size_t count) : alloc_size{count * sizeof(T)} {
        base_ptr = reinterpret_cast<T*>(AllocateMemoryPages(alloc_size));
    }

    ~VirtualBuffer() noexcept {
        FreeMemoryPages(base_ptr, alloc_size);
    }

    VirtualBuffer(const VirtualBuffer&) = delete;
    VirtualBuffer& operator=(const VirtualBuffer&) = delete;

    VirtualBuffer(VirtualBuffer&& other) noexcept
        : alloc_size{std::exchange(other.alloc_size, 0)}, base_ptr{std::exchange(other.base_ptr),
                                                                   nullptr} {}

    VirtualBuffer& operator=(VirtualBuffer&& other) noexcept {
        alloc_size = std::exchange(other.alloc_size, 0);
        base_ptr = std::exchange(other.base_ptr, nullptr);
        return *this;
    }

    void resize(std::size_t count) {
        const auto new_size = count * sizeof(T);
        if (new_size == alloc_size) {
            return;
        }

        FreeMemoryPages(base_ptr, alloc_size);

        alloc_size = new_size;
        base_ptr = reinterpret_cast<T*>(AllocateMemoryPages(alloc_size));
    }

    [[nodiscard]] constexpr const T& operator[](std::size_t index) const {
        return base_ptr[index];
    }

    [[nodiscard]] constexpr T& operator[](std::size_t index) {
        return base_ptr[index];
    }

    [[nodiscard]] constexpr T* data() {
        return base_ptr;
    }

    [[nodiscard]] constexpr const T* data() const {
        return base_ptr;
    }

    [[nodiscard]] constexpr std::size_t size() const {
        return alloc_size / sizeof(T);
    }

private:
    std::size_t alloc_size{};
    T* base_ptr{};
};

} // namespace Common