summaryrefslogtreecommitdiff
path: root/src/io.hh
diff options
context:
space:
mode:
Diffstat (limited to 'src/io.hh')
-rw-r--r--src/io.hh124
1 files changed, 124 insertions, 0 deletions
diff --git a/src/io.hh b/src/io.hh
new file mode 100644
index 0000000..3bfccec
--- /dev/null
+++ b/src/io.hh
@@ -0,0 +1,124 @@
+// -*- mode: c++; c-basic-offset: 2; -*-
+
+#ifndef IO_HH
+#define IO_HH
+
+#include <sys/types.h>
+
+namespace io {
+
+ssize_t read(int fd, void* buf, size_t max);
+ssize_t write(int fd, void const* buf, size_t max);
+
+bool read_all(int fd, void* buf, size_t size);
+bool write_all(int fd, void const* buf, size_t size);
+
+class auto_fd {
+public:
+ auto_fd()
+ : fd_(-1) {
+ }
+ explicit auto_fd(int fd)
+ : fd_(fd) {
+ }
+ auto_fd(auto_fd&& fd)
+ : fd_(fd.fd_) {
+ fd.fd_ = -1;
+ }
+ auto_fd(auto_fd const&) = delete;
+ ~auto_fd() {
+ reset();
+ }
+
+ auto_fd& operator=(auto_fd&& fd) {
+ reset(fd.release());
+ return *this;
+ }
+ auto_fd& operator=(auto_fd&) = delete;
+
+ int get() const {
+ return fd_;
+ }
+
+ explicit operator bool() const {
+ return fd_ >= 0;
+ }
+
+ int release() {
+ auto ret = fd_;
+ fd_ = -1;
+ return ret;
+ }
+
+ bool reset();
+
+ bool reset(int fd) {
+ auto ret = reset();
+ fd_ = fd;
+ return ret;
+ }
+
+ void swap(auto_fd& fd) {
+ auto tmp = fd_;
+ fd_ = fd.fd_;
+ fd.fd_ = tmp;
+ }
+private:
+ int fd_;
+};
+
+class auto_pipe {
+public:
+ auto_pipe()
+ : read_(-1), write_(-1) {
+ }
+ auto_pipe(auto_pipe&& pipe)
+ : read_(pipe.read_), write_(pipe.write_) {
+ pipe.read_ = -1;
+ pipe.write_ = -1;
+ }
+ auto_pipe(auto_pipe const&) = delete;
+ ~auto_pipe() {
+ reset();
+ }
+
+ auto_pipe& operator=(auto_pipe&& pipe) {
+ reset();
+ read_ = pipe.read_;
+ write_ = pipe.write_;
+ pipe.read_ = -1;
+ pipe.write_ = -1;
+ return *this;
+ }
+ auto_pipe& operator=(auto_pipe&) = delete;
+
+ int read() const {
+ return read_;
+ }
+ int write() const {
+ return write_;
+ }
+
+ explicit operator bool() const {
+ return read_ >= 0 /* && write_ >= 0 */;
+ }
+
+ bool open();
+
+ void reset();
+
+ void swap(auto_pipe& pipe) {
+ auto r = read_;
+ auto w = write_;
+ read_ = pipe.read_;
+ write_ = pipe.write_;
+ pipe.read_ = r;
+ pipe.write_ = w;
+ }
+private:
+ int read_, write_;
+};
+
+} // namespace io
+
+#endif // IO_HH