summaryrefslogtreecommitdiff
path: root/lib/filesystem.cpp
diff options
context:
space:
mode:
authorDan Goodliffe <dan@randomdan.homeip.net>2022-12-11 12:39:26 +0000
committerDan Goodliffe <dan@randomdan.homeip.net>2022-12-11 12:39:26 +0000
commitf4fa52d7633d9d67d4c41f76b0e317c6232eb907 (patch)
tree54f24ace52d7a9c4a1302a9762cef5b3d2537905 /lib/filesystem.cpp
parentSave texture to TGA using mmap (diff)
downloadilt-f4fa52d7633d9d67d4c41f76b0e317c6232eb907.tar.bz2
ilt-f4fa52d7633d9d67d4c41f76b0e317c6232eb907.tar.xz
ilt-f4fa52d7633d9d67d4c41f76b0e317c6232eb907.zip
Add a mini C filesystem wrapper library with mmap support
Diffstat (limited to 'lib/filesystem.cpp')
-rw-r--r--lib/filesystem.cpp64
1 files changed, 64 insertions, 0 deletions
diff --git a/lib/filesystem.cpp b/lib/filesystem.cpp
new file mode 100644
index 0000000..181fb07
--- /dev/null
+++ b/lib/filesystem.cpp
@@ -0,0 +1,64 @@
+#include "filesystem.h"
+#include <fcntl.h>
+#include <filesystem>
+#include <string>
+#include <sys/mman.h>
+#include <system_error>
+#include <unistd.h>
+
+namespace filesystem {
+ template<typename... Args>
+ [[noreturn]] static void
+ throw_filesystem_error(std::string operation, int err, Args &&... args)
+ {
+ throw std::filesystem::filesystem_error {
+ std::move(operation), std::forward<Args>(args)..., std::error_code {err, std::system_category()}};
+ }
+
+ memmap::memmap(size_t length, int prot, int flags, int fd, off_t offset) :
+ addr {mmap(nullptr, length, prot, flags, fd, offset)}, length {length}
+ {
+ if (addr == MAP_FAILED) {
+ throw std::filesystem::filesystem_error {"mmap", std::error_code {errno, std::system_category()}};
+ }
+ }
+
+ memmap::~memmap()
+ {
+ ::munmap(addr, length);
+ }
+
+ void
+ memmap::msync(int flags) const
+ {
+ if (::msync(addr, length, flags)) {
+ throw_filesystem_error("msync", errno);
+ }
+ }
+
+ fh::fh(const char * path, int flags, int mode) : h {open(path, flags, mode)}
+ {
+ if (h == -1) {
+ throw_filesystem_error("open", errno, path);
+ }
+ }
+
+ fh::~fh()
+ {
+ ::close(h);
+ }
+
+ void
+ fh::truncate(size_t size)
+ {
+ if (::ftruncate(h, static_cast<off_t>(size))) {
+ throw_filesystem_error("ftruncate", errno);
+ }
+ }
+
+ memmap
+ fh::mmap(size_t length, size_t offset, int prot, int flags)
+ {
+ return memmap {length, prot, flags, h, static_cast<off_t>(offset)};
+ }
+}