37 throw std::runtime_error(
"MappedFile: " + path +
" needs a size");
39 const std::filesystem::path file_path(path);
40 if (file_path.has_parent_path()) {
42 std::filesystem::create_directories(file_path.parent_path(), ec);
45#if defined(_WIN32) || defined(_WIN64)
46 HANDLE file = CreateFileW(file_path.c_str(), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ,
nullptr, OPEN_ALWAYS,
47 FILE_ATTRIBUTE_NORMAL,
nullptr);
48 if (file == INVALID_HANDLE_VALUE) {
49 fail(path,
"open", GetLastError());
51 created_ = GetLastError() != ERROR_ALREADY_EXISTS;
53 LARGE_INTEGER existing{};
54 if (!GetFileSizeEx(file, &existing)) {
55 const DWORD error = GetLastError();
57 fail(path,
"size", error);
59 size_ =
static_cast<std::uint64_t
>(existing.QuadPart) >
size ?
static_cast<std::size_t
>(existing.QuadPart) :
size;
62 const auto wide =
static_cast<std::uint64_t
>(size_);
63 HANDLE mapping = CreateFileMappingW(file,
nullptr, PAGE_READWRITE,
static_cast<DWORD
>(wide >> 32),
64 static_cast<DWORD
>(wide & 0xFFFFFFFFu),
nullptr);
66 const DWORD error = GetLastError();
68 fail(path,
"map", error);
70 void* view = MapViewOfFile(mapping, FILE_MAP_ALL_ACCESS, 0, 0, size_);
72 const DWORD error = GetLastError();
75 fail(path,
"map", error);
79 data_ =
static_cast<std::uint8_t*
>(view);
81 int fd = ::open(path.c_str(), O_RDWR | O_CREAT | O_EXCL, 0644);
83 if (fd < 0 && errno == EEXIST) {
84 fd = ::open(path.c_str(), O_RDWR);
87 fail(path,
"open", errno);
90 if (::fstat(fd, &info) != 0) {
91 const int error = errno;
93 fail(path,
"size", error);
95 size_ =
static_cast<std::size_t
>(info.st_size) >
size ?
static_cast<std::size_t
>(info.st_size) :
size;
96 if (
static_cast<std::size_t
>(info.st_size) < size_ && ::ftruncate(fd,
static_cast<off_t
>(size_)) != 0) {
97 const int error = errno;
99 fail(path,
"grow", error);
101 void* view = ::mmap(
nullptr, size_, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
102 if (view == MAP_FAILED) {
103 const int error = errno;
105 fail(path,
"map", error);
108 data_ =
static_cast<std::uint8_t*
>(view);
121 if (
this != &other) {
123 data_ = std::exchange(other.data_,
nullptr);
124 size_ = std::exchange(other.size_, 0);
125 created_ = std::exchange(other.created_,
false);
126#if defined(_WIN32) || defined(_WIN64)
127 file_ = std::exchange(other.file_,
nullptr);
128 mapping_ = std::exchange(other.mapping_,
nullptr);
130 fd_ = std::exchange(other.fd_, -1);