forked from frc971/971-Robot-Code
-
Notifications
You must be signed in to change notification settings - Fork 0
/
scoped_pipe.h
74 lines (53 loc) · 1.58 KB
/
scoped_pipe.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#ifndef AOS_UTIL_SCOPED_PIPE_H_
#define AOS_UTIL_SCOPED_PIPE_H_
#include <stddef.h>
#include <stdint.h>
#include <memory>
#include <optional>
#include <string>
#include "absl/types/span.h"
namespace aos::util {
// RAII Pipe for sending individual ints between reader and writer.
class ScopedPipe {
public:
class ScopedReadPipe;
class ScopedWritePipe;
struct PipePair {
std::unique_ptr<ScopedReadPipe> read;
std::unique_ptr<ScopedWritePipe> write;
};
static PipePair MakePipe();
virtual ~ScopedPipe();
int fd() const { return fd_; }
// Sets FD_CLOEXEC on the file descriptor.
void SetCloexec();
private:
ScopedPipe(int fd = -1);
int fd_;
ScopedPipe(const ScopedPipe &) = delete;
ScopedPipe &operator=(const ScopedPipe &) = delete;
ScopedPipe(ScopedPipe &&);
ScopedPipe &operator=(ScopedPipe &&);
};
class ScopedPipe::ScopedReadPipe : public ScopedPipe {
public:
std::optional<uint32_t> Read();
// Reads as many bytes as possible out of the pipe, appending them to the end
// of the provided buffer. Returns the number of bytes read. Dies on errors
// other than EAGAIN or EWOULDBLOCK.
size_t Read(std::string *buffer);
private:
using ScopedPipe::ScopedPipe;
friend class ScopedPipe;
};
class ScopedPipe::ScopedWritePipe : public ScopedPipe {
public:
void Write(uint32_t data);
// Writes the entirety of the specified buffer to the pipe. Dies on failure.
void Write(absl::Span<const uint8_t> data);
private:
using ScopedPipe::ScopedPipe;
friend class ScopedPipe;
};
} // namespace aos::util
#endif // AOS_UTIL_SCOPED_PIPE_H_