James Kuszmaul | 3224b8e | 2022-01-07 19:00:39 -0800 | [diff] [blame^] | 1 | #ifndef AOS_UTIL_SCOPED_PIPE_H_ |
| 2 | #define AOS_UTIL_SCOPED_PIPE_H_ |
| 3 | |
| 4 | #include <stdint.h> |
| 5 | |
| 6 | #include <optional> |
| 7 | #include <tuple> |
| 8 | |
| 9 | namespace aos::util { |
| 10 | |
| 11 | // RAII Pipe for sending individual ints between reader and writer. |
| 12 | class ScopedPipe { |
| 13 | public: |
| 14 | class ScopedReadPipe; |
| 15 | class ScopedWritePipe; |
| 16 | |
| 17 | static std::tuple<ScopedReadPipe, ScopedWritePipe> MakePipe(); |
| 18 | |
| 19 | virtual ~ScopedPipe(); |
| 20 | |
| 21 | int fd() const { return fd_; } |
| 22 | |
| 23 | private: |
| 24 | ScopedPipe(int fd = -1); |
| 25 | |
| 26 | int fd_; |
| 27 | |
| 28 | ScopedPipe(const ScopedPipe &) = delete; |
| 29 | ScopedPipe &operator=(const ScopedPipe &) = delete; |
| 30 | ScopedPipe(ScopedPipe &&); |
| 31 | ScopedPipe &operator=(ScopedPipe &&); |
| 32 | }; |
| 33 | |
| 34 | class ScopedPipe::ScopedReadPipe : public ScopedPipe { |
| 35 | public: |
| 36 | std::optional<uint32_t> Read(); |
| 37 | |
| 38 | private: |
| 39 | using ScopedPipe::ScopedPipe; |
| 40 | |
| 41 | friend class ScopedPipe; |
| 42 | }; |
| 43 | |
| 44 | class ScopedPipe::ScopedWritePipe : public ScopedPipe { |
| 45 | public: |
| 46 | void Write(uint32_t data); |
| 47 | |
| 48 | private: |
| 49 | using ScopedPipe::ScopedPipe; |
| 50 | |
| 51 | friend class ScopedPipe; |
| 52 | }; |
| 53 | |
| 54 | } // namespace aos::util |
| 55 | |
| 56 | #endif // AOS_UTIL_SCOPED_PIPE_H_ |