63 lines
1.6 KiB
C++
63 lines
1.6 KiB
C++
|
#include "MmapFile.hpp"
|
||
|
#include <fcntl.h>
|
||
|
#include <sys/file.h>
|
||
|
#include <sys/mman.h>
|
||
|
|
||
|
namespace lightningbolt {
|
||
|
|
||
|
struct MmapFile::Impl {
|
||
|
|
||
|
~Impl() {
|
||
|
Close();
|
||
|
}
|
||
|
|
||
|
void Close() {
|
||
|
if(mapping) {
|
||
|
munmap(mapping, mappingSize);
|
||
|
mapping = nullptr;
|
||
|
mappingSize = 0;
|
||
|
}
|
||
|
}
|
||
|
|
||
|
ErrorOr<void> Open(const fs::path& path) {
|
||
|
int fd = open(path.string().c_str(), O_RDONLY);
|
||
|
|
||
|
// Error opening file.
|
||
|
if(fd == -1)
|
||
|
return std::error_code{errno, std::system_category()};
|
||
|
|
||
|
{
|
||
|
auto last = lseek64(fd, 0, SEEK_END);
|
||
|
mappingSize = lseek64(fd, 0, SEEK_CUR);
|
||
|
lseek64(fd, last, SEEK_SET);
|
||
|
}
|
||
|
|
||
|
mapping = static_cast<u8*>(mmap(nullptr, mappingSize, PROT_READ, MAP_PRIVATE, fd, 0));
|
||
|
if(mapping == static_cast<u8*>(MAP_FAILED)) {
|
||
|
mappingSize = 0;
|
||
|
return std::error_code{errno, std::system_category()};
|
||
|
}
|
||
|
|
||
|
// Once the mapping has successfully been created
|
||
|
// we can close the file descriptor instead of needing
|
||
|
// to remember it (the kernel will do so for us.)
|
||
|
close(fd);
|
||
|
|
||
|
// No error.
|
||
|
return {};
|
||
|
}
|
||
|
|
||
|
u8* GetMapping() const {
|
||
|
return mapping;
|
||
|
}
|
||
|
|
||
|
usize GetMappingSize() const {
|
||
|
return mappingSize;
|
||
|
}
|
||
|
|
||
|
private:
|
||
|
u8* mapping;
|
||
|
usize mappingSize;
|
||
|
};
|
||
|
|
||
|
} // namespace lightningbolt
|