-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMappedFd.cpp
62 lines (49 loc) · 1.18 KB
/
MappedFd.cpp
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
#include "MappedFd.hpp"
#include <sys/mman.h>
#include <unistd.h>
static constexpr int BAD_FD = -1;
MappedFd::MappedFd(int fd, size_t size)
{
_fd = fd;
_size = size;
if (size) {
_mapping = mmap(nullptr, _size, PROT_READ, MAP_PRIVATE, _fd, 0);
} else {
_mapping = nullptr;
}
}
MappedFd::MappedFd(MappedFd&& other) noexcept {
_fd = other._fd;
_size = other._size;
_mapping = other._mapping;
other._fd = BAD_FD;
other._size = 0;
other._mapping = nullptr;
}
MappedFd::~MappedFd() {
if (_mapping) {
munmap(_mapping, _size);
}
if (_fd >= 0) {
close(_fd);
}
}
MappedFd& MappedFd::operator=(MappedFd&& other) noexcept {
if (_mapping) {
munmap(_mapping, _size);
}
if (_fd >= 0) {
close(_fd);
}
_fd = other._fd;
_size = other._size;
_mapping = other._mapping;
other._fd = BAD_FD;
other._size = 0;
other._mapping = nullptr;
return *this;
}
int MappedFd::fd() noexcept { return _fd; }
void *MappedFd::map() noexcept { return _mapping; }
const void *MappedFd::map() const noexcept { return _mapping; }
size_t MappedFd::size() const noexcept { return _size; }