Brian Silverman | 58899fd | 2019-03-24 11:03:11 -0700 | [diff] [blame] | 1 | #ifndef AOS_SCOPED_SCOPED_FD_H_ |
| 2 | #define AOS_SCOPED_SCOPED_FD_H_ |
Parker Schuh | 2cd173d | 2017-01-28 00:12:01 -0800 | [diff] [blame] | 3 | |
brians | 343bc11 | 2013-02-10 01:53:46 +0000 | [diff] [blame] | 4 | namespace aos { |
| 5 | |
| 6 | // Smart "pointer" (container) for a file descriptor. |
| 7 | class ScopedFD { |
| 8 | public: |
| 9 | explicit ScopedFD(int fd = -1) : fd_(fd) {} |
Austin Schuh | 56c5cf5 | 2022-12-25 22:20:40 -0800 | [diff] [blame] | 10 | ScopedFD(ScopedFD &) = delete; |
| 11 | ScopedFD(ScopedFD &&other) : ScopedFD(other.release()) {} |
| 12 | |
| 13 | void operator=(const ScopedFD &) = delete; |
| 14 | void operator=(ScopedFD &&other) { |
| 15 | int tmp = fd_; |
| 16 | fd_ = other.fd_; |
| 17 | other.fd_ = tmp; |
| 18 | } |
| 19 | |
Parker Schuh | 2cd173d | 2017-01-28 00:12:01 -0800 | [diff] [blame] | 20 | ~ScopedFD() { Close(); } |
Austin Schuh | 56c5cf5 | 2022-12-25 22:20:40 -0800 | [diff] [blame] | 21 | |
brians | 343bc11 | 2013-02-10 01:53:46 +0000 | [diff] [blame] | 22 | int get() const { return fd_; } |
| 23 | int release() { |
| 24 | const int r = fd_; |
| 25 | fd_ = -1; |
| 26 | return r; |
| 27 | } |
| 28 | void reset(int new_fd = -1) { |
| 29 | if (fd_ != new_fd) { |
| 30 | Close(); |
| 31 | fd_ = new_fd; |
| 32 | } |
| 33 | } |
Maxwell Henderson | b963ffc | 2024-02-02 21:55:04 -0800 | [diff] [blame] | 34 | explicit operator bool() const { return fd_ != -1; } |
Parker Schuh | 2cd173d | 2017-01-28 00:12:01 -0800 | [diff] [blame] | 35 | |
brians | 343bc11 | 2013-02-10 01:53:46 +0000 | [diff] [blame] | 36 | private: |
| 37 | int fd_; |
Austin Schuh | 56c5cf5 | 2022-12-25 22:20:40 -0800 | [diff] [blame] | 38 | |
Brian Silverman | 58899fd | 2019-03-24 11:03:11 -0700 | [diff] [blame] | 39 | void Close(); |
brians | 343bc11 | 2013-02-10 01:53:46 +0000 | [diff] [blame] | 40 | }; |
| 41 | |
| 42 | } // namespace aos |
Parker Schuh | 2cd173d | 2017-01-28 00:12:01 -0800 | [diff] [blame] | 43 | |
Brian Silverman | 58899fd | 2019-03-24 11:03:11 -0700 | [diff] [blame] | 44 | #endif // AOS_SCOPED_SCOPED_FD_H_ |