From c029d90d1975e124d237605f1edb2be16bd05b5d Mon Sep 17 00:00:00 2001 From: Joel Klinghed Date: Tue, 28 Feb 2017 21:50:44 +0100 Subject: Initial commit --- src/io.hh | 124 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 124 insertions(+) create mode 100644 src/io.hh (limited to 'src/io.hh') 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 + +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 -- cgit v1.2.3-70-g09d2