summaryrefslogtreecommitdiff
path: root/view/sharedcache/core/MappedFile.h
diff options
context:
space:
mode:
authorMason Reed <mason@vector35.com>2025-03-10 11:05:40 -0400
committerMason Reed <mason@vector35.com>2025-04-02 05:36:54 -0400
commit25cc02431b61097b2adfc2fbc493b648b0300c3b (patch)
treea79d9c4f4f67234d3bf9bda413e8608f479a4cc8 /view/sharedcache/core/MappedFile.h
parentfa85bf28502286c4821427c5d0ed91a7ed46f8f6 (diff)
[SharedCache] Refactor Shared Cache
In absence of a better name, this commit refactors the shared cache code.
Diffstat (limited to 'view/sharedcache/core/MappedFile.h')
-rw-r--r--view/sharedcache/core/MappedFile.h86
1 files changed, 86 insertions, 0 deletions
diff --git a/view/sharedcache/core/MappedFile.h b/view/sharedcache/core/MappedFile.h
new file mode 100644
index 00000000..ced79f52
--- /dev/null
+++ b/view/sharedcache/core/MappedFile.h
@@ -0,0 +1,86 @@
+#pragma once
+
+#include <string>
+#include <cstdint>
+#include <cstdio>
+#include <optional>
+
+// Call this when initializing the plugin so that the process file descriptor limit is raised.
+uint64_t AdjustFileDescriptorLimit();
+
+enum MapStatus : int
+{
+ Success,
+ // TODO: Split this error out into more contextual errors.
+ Error,
+};
+
+struct MappedFile
+{
+ uint8_t* _mmap = nullptr;
+ size_t len = 0;
+
+#ifdef _MSC_VER
+ HANDLE hFile = INVALID_HANDLE_VALUE;
+#else
+ FILE* fd = nullptr;
+#endif
+
+ MappedFile() = default;
+
+ ~MappedFile();
+
+ MappedFile(const MappedFile&) = delete;
+
+ MappedFile& operator=(const MappedFile&) = delete;
+
+ MappedFile(MappedFile&& other) noexcept : _mmap(other._mmap), len(other.len)
+ {
+#ifdef _MSC_VER
+ hFile = other.hFile;
+ // Don't close the hFile in the move.
+ other.hFile = nullptr;
+#else
+ fd = other.fd;
+ // Don't close the fd in the move.
+ other.fd = nullptr;
+#endif
+ other._mmap = nullptr;
+ }
+
+ // I hate C++
+ MappedFile& operator=(MappedFile&& other) noexcept
+ {
+ if (this != &other)
+ {
+ Unmap();
+#ifdef _MSC_VER
+ if (hFile != nullptr)
+ {
+ CloseHandle(hFile);
+ }
+ hFile = other.hFile;
+ // Don't close the hFile in the move.
+ other.hFile = nullptr;
+#else
+ if (fd != nullptr)
+ {
+ fclose(fd);
+ }
+ fd = other.fd;
+ // Don't close the fd in the move.
+ other.fd = nullptr;
+#endif
+ len = other.len;
+ _mmap = other._mmap;
+ other._mmap = nullptr;
+ }
+ return *this;
+ }
+
+ static std::optional<MappedFile> OpenFile(const std::string& path);
+
+ MapStatus Map();
+
+ MapStatus Unmap();
+};