blob: 6716fb5341b773f64479c69fe88f1911d7116f47 [file] [log] [blame]
James Kuszmaul3224b8e2022-01-07 19:00:39 -08001#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 Kuszmaul731a05d2022-01-07 17:59:26 -08009#include "absl/types/span.h"
10
James Kuszmaul3224b8e2022-01-07 19:00:39 -080011namespace aos::util {
12
13// RAII Pipe for sending individual ints between reader and writer.
14class 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
36class ScopedPipe::ScopedReadPipe : public ScopedPipe {
37 public:
38 std::optional<uint32_t> Read();
James Kuszmaul731a05d2022-01-07 17:59:26 -080039 // 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 Kuszmaul3224b8e2022-01-07 19:00:39 -080043
44 private:
45 using ScopedPipe::ScopedPipe;
46
47 friend class ScopedPipe;
48};
49
50class ScopedPipe::ScopedWritePipe : public ScopedPipe {
51 public:
52 void Write(uint32_t data);
James Kuszmaul731a05d2022-01-07 17:59:26 -080053 // Writes the entirety of the specified buffer to the pipe. Dies on failure.
54 void Write(absl::Span<const uint8_t> data);
James Kuszmaul3224b8e2022-01-07 19:00:39 -080055
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_