From c87f9627efc8b612eb9b000acfcc6731cad15765 Mon Sep 17 00:00:00 2001 From: Joel Klinghed Date: Tue, 7 Oct 2025 09:12:22 +0200 Subject: Initial commit --- src/unique_fd.hh | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 src/unique_fd.hh (limited to 'src/unique_fd.hh') diff --git a/src/unique_fd.hh b/src/unique_fd.hh new file mode 100644 index 0000000..2950905 --- /dev/null +++ b/src/unique_fd.hh @@ -0,0 +1,36 @@ +#ifndef UNIQUE_FD_HH +#define UNIQUE_FD_HH + +class unique_fd { + public: + constexpr unique_fd() : fd_(-1) {} + explicit constexpr unique_fd(int fd) : fd_(fd) {} + unique_fd(unique_fd& fd) = delete; + unique_fd& operator=(unique_fd& fd) = delete; + unique_fd(unique_fd&& fd) : fd_(fd.release()) {} + unique_fd& operator=(unique_fd&& fd) { + reset(fd.release()); + return *this; + } + ~unique_fd() { reset(); } + + bool operator==(unique_fd const& fd) const { return get() == fd.get(); } + bool operator!=(unique_fd const& fd) const { return get() != fd.get(); } + + int get() const { return fd_; } + explicit operator bool() const { return fd_ != -1; } + int operator*() const { return fd_; } + + int release() { + int ret = fd_; + fd_ = -1; + return ret; + } + + void reset(int fd = -1); + + private: + int fd_; +}; + +#endif // UNIQUE_FD_HH -- cgit v1.2.3-70-g09d2