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 | |
James Kuszmaul | 731a05d | 2022-01-07 17:59:26 -0800 | [diff] [blame^] | 9 | #include "absl/types/span.h" |
| 10 | |
James Kuszmaul | 3224b8e | 2022-01-07 19:00:39 -0800 | [diff] [blame] | 11 | namespace aos::util { |
| 12 | |
| 13 | // RAII Pipe for sending individual ints between reader and writer. |
| 14 | class ScopedPipe { |
| 15 | public: |
| 16 | class ScopedReadPipe; |
| 17 | class ScopedWritePipe; |
| 18 | |
| 19 | static std::tuple<ScopedReadPipe, ScopedWritePipe> MakePipe(); |
| 20 | |
| 21 | virtual ~ScopedPipe(); |
| 22 | |
| 23 | int fd() const { return fd_; } |
| 24 | |
| 25 | private: |
| 26 | ScopedPipe(int fd = -1); |
| 27 | |
| 28 | int fd_; |
| 29 | |
| 30 | ScopedPipe(const ScopedPipe &) = delete; |
| 31 | ScopedPipe &operator=(const ScopedPipe &) = delete; |
| 32 | ScopedPipe(ScopedPipe &&); |
| 33 | ScopedPipe &operator=(ScopedPipe &&); |
| 34 | }; |
| 35 | |
| 36 | class ScopedPipe::ScopedReadPipe : public ScopedPipe { |
| 37 | public: |
| 38 | std::optional<uint32_t> Read(); |
James Kuszmaul | 731a05d | 2022-01-07 17:59:26 -0800 | [diff] [blame^] | 39 | // Reads as many bytes as possible out of the pipe, appending them to the end |
| 40 | // of the provided buffer. Returns the number of bytes read. Dies on errors |
| 41 | // other than EAGAIN or EWOULDBLOCK. |
| 42 | size_t Read(std::string *buffer); |
James Kuszmaul | 3224b8e | 2022-01-07 19:00:39 -0800 | [diff] [blame] | 43 | |
| 44 | private: |
| 45 | using ScopedPipe::ScopedPipe; |
| 46 | |
| 47 | friend class ScopedPipe; |
| 48 | }; |
| 49 | |
| 50 | class ScopedPipe::ScopedWritePipe : public ScopedPipe { |
| 51 | public: |
| 52 | void Write(uint32_t data); |
James Kuszmaul | 731a05d | 2022-01-07 17:59:26 -0800 | [diff] [blame^] | 53 | // Writes the entirety of the specified buffer to the pipe. Dies on failure. |
| 54 | void Write(absl::Span<const uint8_t> data); |
James Kuszmaul | 3224b8e | 2022-01-07 19:00:39 -0800 | [diff] [blame] | 55 | |
| 56 | private: |
| 57 | using ScopedPipe::ScopedPipe; |
| 58 | |
| 59 | friend class ScopedPipe; |
| 60 | }; |
| 61 | |
| 62 | } // namespace aos::util |
| 63 | |
| 64 | #endif // AOS_UTIL_SCOPED_PIPE_H_ |