-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMappedFile.cpp
More file actions
118 lines (95 loc) · 2.44 KB
/
MappedFile.cpp
File metadata and controls
118 lines (95 loc) · 2.44 KB
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
#include <stdexcept>
#include <string>
#ifdef _WIN32
# define WIN32_LEAN_AND_MEAN
# include <windows.h>
# define FN_CA(x) x.c_str()
#else
# ifndef __USE_LARGEFILE64
# define __USE_LARGEFILE64
# define _LARGEFILE_SOURCE
# define _LARGEFILE64_SOURCE
# endif
# include <sys/mman.h>
# include <fcntl.h>
# include <unistd.h>
# include <locale>
# include <codecvt>
# define FN_CA(x) std::wstring_convert<std::codecvt_utf8<wchar_t>, wchar_t>().to_bytes(x).c_str()
#endif
#include "MappedFile.h"
MappedFile::MappedFile() : mappedData(nullptr), fileSize(0), offset(0)
{
}
MappedFile::~MappedFile()
{
if (mappedData) {
#ifdef _WIN32
UnmapViewOfFile(mappedData);
#else
munmap(const_cast<uint8_t*>(mappedData), fileSize);
#endif
}
}
bool MappedFile::open(const std::wstring& fileName)
{
filePath = fileName;
#ifdef _WIN32
HANDLE hFile = CreateFile(FN_CA(filePath), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
return false;
fileSize = GetFileSize(hFile, NULL);
if (fileSize == INVALID_FILE_SIZE || fileSize == 0)
{
CloseHandle(hFile);
return false;
}
HANDLE hMap = CreateFileMappingA(hFile, NULL, PAGE_READONLY, 0, fileSize, NULL);
if (!hMap)
{
CloseHandle(hFile);
fileSize = 0;
return false;
}
mappedData = static_cast<const uint8_t*>(MapViewOfFile(hMap, FILE_MAP_READ, 0, 0, fileSize));
/* We can call CloseHandle here, but it will not be closed until
* we unmap the view */
CloseHandle(hMap);
CloseHandle(hFile);
#else
int fd = ::open(FN_CA(filePath), O_RDONLY | O_CLOEXEC);
if (fd < 0)
return false;
fileSize = lseek64(fd, 0, SEEK_END);
if (fileSize > INT64_MAX) {
close(fd);
fileSize = 0;
return false;
}
lseek64(fd, 0, SEEK_SET);
mappedData = static_cast<const uint8_t*>(mmap(nullptr, fileSize, PROT_READ, MAP_SHARED, fd, 0));
close(fd);
if (mappedData == MAP_FAILED) {
mappedData = nullptr;
fileSize = 0;
return false;
}
#endif
return true;
}
const uint8_t* MappedFile::data() const
{
return mappedData + offset;
}
uint64_t MappedFile::size() const
{
return fileSize - offset;
}
void MappedFile::setOffset(const uint64_t off)
{
offset = off;
}
void MappedFile::addOffset(const uint64_t off)
{
offset += off;
}