-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMapFile.cpp
50 lines (42 loc) · 841 Bytes
/
MapFile.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
#include "MapFile.h"
#include "SDL.h"
#include <sys/mman.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
MappedFile::MappedFile(const char* fileName)
{
int f = open(fileName, O_RDONLY);
if (f < 0) {
SDL_SetError("open() failed");
return;
}
struct stat fileMetadata;
if (fstat(f, &fileMetadata) != 0) {
SDL_SetError("fstat() failed");
close(f);
return;
}
size_t mappedSize = fileMetadata.st_size;
data = static_cast<uint8_t*>(mmap(nullptr, mappedSize, PROT_READ, MAP_PRIVATE, f, 0));
if (data == MAP_FAILED) {
SDL_SetError("mmap() failed");
close(f);
return;
}
close(f); // no more needed, mapping persists
data = data;
byteSize = mappedSize;
}
MappedFile::~MappedFile()
{
Unmap();
}
void MappedFile::Unmap()
{
if (!data) {
munmap(data, byteSize);
}
data = nullptr;
byteSize = 0;
}