aboutsummaryrefslogtreecommitdiffstats
path: root/nihil.posix/tempfile.ccm
diff options
context:
space:
mode:
authorLexi Winter <lexi@le-fay.org>2025-06-29 19:19:23 +0100
committerLexi Winter <lexi@le-fay.org>2025-06-29 19:19:23 +0100
commita8b0ea58e60bb0326b7f7c8f3c736d89ce9ef1df (patch)
tree6dafcf2674780649dcdc2649855722357837a68e /nihil.posix/tempfile.ccm
parent4fa6821e0645ff61a9380cd090abff472205c630 (diff)
downloadnihil-a8b0ea58e60bb0326b7f7c8f3c736d89ce9ef1df.tar.gz
nihil-a8b0ea58e60bb0326b7f7c8f3c736d89ce9ef1df.tar.bz2
wip macOS port
Diffstat (limited to 'nihil.posix/tempfile.ccm')
-rw-r--r--nihil.posix/tempfile.ccm87
1 files changed, 87 insertions, 0 deletions
diff --git a/nihil.posix/tempfile.ccm b/nihil.posix/tempfile.ccm
new file mode 100644
index 0000000..82f3be4
--- /dev/null
+++ b/nihil.posix/tempfile.ccm
@@ -0,0 +1,87 @@
+/*
+ * This source code is released into the public domain.
+ */
+
+module;
+
+/*
+ * tempfile: create a temporary file.
+ */
+
+#include <cstdint>
+#include <expected>
+#include <filesystem>
+#include <string>
+
+export module nihil.posix:tempfile;
+
+import nihil.error;
+import nihil.flagset;
+import :fd;
+
+namespace nihil {
+
+struct tempfile_flags_tag {};
+export using tempfile_flags_t = flagset<std::uint8_t, tempfile_flags_tag>;
+
+// No flags.
+export inline constexpr auto tempfile_none = tempfile_flags_t();
+
+// Unlink the tempfile immediately after creating it
+export inline constexpr auto tempfile_unlink = tempfile_flags_t::bit<0>();
+
+export struct temporary_file final {
+ /*
+ * Fetch the file's fd.
+ */
+ [[nodiscard]] auto fd(this temporary_file &) -> nihil::fd &;
+
+ /*
+ * Fetch the name of this file. If tempfile_unlink was specified,
+ * throws std::logic_error.
+ */
+ [[nodiscard]] auto path(this temporary_file const &)
+ -> std::filesystem::path const &;
+
+ /*
+ * Release this temporary file, causing it to be deleted immediately.
+ * Throws std::logic_error if the file has already been released.
+ */
+ auto release(this temporary_file &) -> void;
+
+ /*
+ * Destructor; unlink the file if we didn't already.
+ */
+ ~temporary_file();
+
+ // Not copyable.
+ temporary_file(temporary_file const &) = delete;
+
+ // Movable.
+ temporary_file(temporary_file &&other) noexcept;
+
+ // Not assignable.
+ auto operator=(this temporary_file &, temporary_file const &)
+ -> temporary_file & = delete;
+ auto operator=(this temporary_file &, temporary_file &&) noexcept
+ -> temporary_file & = delete;
+
+private:
+ // The file descriptor for the file.
+ nihil::fd m_fd;
+ std::filesystem::path m_path;
+
+ temporary_file(nihil::fd &&fd, std::filesystem::path) noexcept;
+ temporary_file(nihil::fd &&fd) noexcept;
+
+ friend auto tempfile(tempfile_flags_t flags)
+ -> std::expected<temporary_file, error>;
+};
+
+/*
+ * Create a temporary file and return it.
+ */
+export [[nodiscard]] auto tempfile(tempfile_flags_t flags = tempfile_none)
+ -> std::expected<temporary_file, error>;
+
+} // namespace nihil