blob: fb91e02aea076e94234cec76686f1eb6c37bd172 [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
James Kuszmauld42edb42022-01-07 18:00:16 -08006#include <memory>
James Kuszmaul3224b8e2022-01-07 19:00:39 -08007#include <optional>
James Kuszmaul3224b8e2022-01-07 19:00:39 -08008
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
James Kuszmauld42edb42022-01-07 18:00:16 -080019 struct PipePair {
20 std::unique_ptr<ScopedReadPipe> read;
21 std::unique_ptr<ScopedWritePipe> write;
22 };
23
24 static PipePair MakePipe();
James Kuszmaul3224b8e2022-01-07 19:00:39 -080025
26 virtual ~ScopedPipe();
27
28 int fd() const { return fd_; }
James Kuszmauld42edb42022-01-07 18:00:16 -080029 // Sets FD_CLOEXEC on the file descriptor.
30 void SetCloexec();
James Kuszmaul3224b8e2022-01-07 19:00:39 -080031
32 private:
33 ScopedPipe(int fd = -1);
34
35 int fd_;
36
37 ScopedPipe(const ScopedPipe &) = delete;
38 ScopedPipe &operator=(const ScopedPipe &) = delete;
39 ScopedPipe(ScopedPipe &&);
40 ScopedPipe &operator=(ScopedPipe &&);
41};
42
43class ScopedPipe::ScopedReadPipe : public ScopedPipe {
44 public:
45 std::optional<uint32_t> Read();
James Kuszmaul731a05d2022-01-07 17:59:26 -080046 // Reads as many bytes as possible out of the pipe, appending them to the end
47 // of the provided buffer. Returns the number of bytes read. Dies on errors
48 // other than EAGAIN or EWOULDBLOCK.
49 size_t Read(std::string *buffer);
James Kuszmaul3224b8e2022-01-07 19:00:39 -080050
51 private:
52 using ScopedPipe::ScopedPipe;
53
54 friend class ScopedPipe;
55};
56
57class ScopedPipe::ScopedWritePipe : public ScopedPipe {
58 public:
59 void Write(uint32_t data);
James Kuszmaul731a05d2022-01-07 17:59:26 -080060 // Writes the entirety of the specified buffer to the pipe. Dies on failure.
61 void Write(absl::Span<const uint8_t> data);
James Kuszmaul3224b8e2022-01-07 19:00:39 -080062
63 private:
64 using ScopedPipe::ScopedPipe;
65
66 friend class ScopedPipe;
67};
68
69} // namespace aos::util
70
71#endif // AOS_UTIL_SCOPED_PIPE_H_