aboutsummaryrefslogtreecommitdiff
path: root/src/memory/memory.hh
blob: c35feea4f7deaa412927c7e327384fea6e98b8a8 (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
#ifndef MEMORY_MEMORY_HH_
#define MEMORY_MEMORY_HH_

#include <cstddef>
#include <cstring>
#include <sys/uio.h>
#include <vector>
#include <stdexcept>

namespace memory {

using buffer_t = std::vector<std::byte>;

buffer_t read_buffer(const std::size_t num_bytes, const pid_t& pid,
                            const void* const address);
void write_buffer(const buffer_t& buffer, const pid_t& pid,
                  const void* const address);

template <typename T>
T read(const pid_t& pid, const void* const address) {
    static_assert(std::is_trivially_copyable<T>::value);

    const buffer_t data = read_buffer(sizeof(T), pid, address);
    T ret;
    std::memcpy(&ret, std::data(data), sizeof(T));
    return std::move(ret);
}

template <typename T>
void write(const T& data, const pid_t& pid, const void* const address) {
    static_assert(std::is_trivially_copyable<T>::value);

    const buffer_t buffer = [&]() {
        buffer_t buffer{sizeof(T)};
        std::memcpy(std::data(buffer), &data, sizeof(T));
        return buffer;
    }();
    write_buffer(buffer, pid, address);
}

} // namespace memory

#endif