From e82785d6b5da237931288255481143f7b1430e51 Mon Sep 17 00:00:00 2001 From: Maksim Denisov Date: Mon, 17 Feb 2025 14:30:30 +0100 Subject: TmpDir: Create temporary files ... and keep parent directories alive while nested directories exist. --- src/utils/cpp/tmp_dir.hpp | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) (limited to 'src/utils/cpp/tmp_dir.hpp') diff --git a/src/utils/cpp/tmp_dir.hpp b/src/utils/cpp/tmp_dir.hpp index 28805e3d..4312d97e 100644 --- a/src/utils/cpp/tmp_dir.hpp +++ b/src/utils/cpp/tmp_dir.hpp @@ -17,8 +17,11 @@ #include #include +#include #include +class TmpFile; + class TmpDir final { public: using Ptr = std::shared_ptr; @@ -43,6 +46,14 @@ class TmpDir final { [[nodiscard]] static auto CreateNestedDirectory( TmpDir::Ptr const& parent) noexcept -> Ptr; + /// \brief Create a new unique temporary file. To guarantee uniqueness, + /// every file gets created in a new temporary directory. This file remains + /// valid even if the parent directory goes out of scope. + [[nodiscard]] static auto CreateFile( + TmpDir::Ptr const& parent, + std::string const& file_name = "file") noexcept + -> std::shared_ptr; + private: explicit TmpDir(TmpDir::Ptr parent, std::filesystem::path path) noexcept : parent_{std::move(parent)}, tmp_dir_{std::move(path)} {} @@ -55,4 +66,30 @@ class TmpDir final { std::filesystem::path tmp_dir_; }; +class TmpFile final { + friend class TmpDir; + + public: + using Ptr = std::shared_ptr; + + TmpFile(TmpFile const&) = delete; + auto operator=(TmpFile const&) -> TmpFile& = delete; + TmpFile(TmpFile&& other) = delete; + auto operator=(TmpFile&&) -> TmpFile& = delete; + ~TmpFile() noexcept = default; + + [[nodiscard]] auto GetPath() const& noexcept + -> std::filesystem::path const& { + return file_path_; + } + + private: + explicit TmpFile(TmpDir::Ptr parent, + std::filesystem::path file_path) noexcept + : parent_{std::move(parent)}, file_path_{std::move(file_path)} {} + + TmpDir::Ptr parent_; + std::filesystem::path file_path_; +}; + #endif // INCLUDED_SRC_OTHER_TOOLS_TMP_DIR_HPP -- cgit v1.2.3