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

#pragma once

#include "common/common_funcs.h"

namespace Common {

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

template <typename T>
class VirtualBuffer final : NonCopyable {
public:
    constexpr VirtualBuffer() = default;
    explicit VirtualBuffer(std::size_t count) : alloc_size{count * sizeof(T)} {
        base_ptr = reinterpret_cast<T*>(AllocateMemoryPages(alloc_size));
    }

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

    void resize(std::size_t count) {
        FreeMemoryPages(base_ptr, alloc_size);

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

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

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

    constexpr T* data() {
        return base_ptr;
    }

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

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

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

} // namespace Common