From 6ed8f5151719fbc14ec0ac6d28a346d1f74cf2ca Mon Sep 17 00:00:00 2001 From: Joel Klinghed Date: Fri, 2 Jan 2026 22:42:31 +0100 Subject: Initial commit --- src/io.hh | 109 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 109 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..90ad52e --- /dev/null +++ b/src/io.hh @@ -0,0 +1,109 @@ +#ifndef IO_HH +#define IO_HH + +#include +#include +#include +#include +#include + +namespace io { + +enum class ReadError : uint8_t { + Error, + Eof, + InvalidData, // invalid data read (not used by raw file) + MaxTooSmall, // max argument needs to be bigger (not used by raw file) +}; + +enum class WriteError : uint8_t { + Error, +}; + +enum class OpenError : uint8_t { + NoSuchFile, + NoAccess, + Error, +}; + +enum class CreateError : uint8_t { + Exists, + NoAccess, + Error, +}; + +enum class PipeError : uint8_t { + Error, +}; + +class Reader { + public: + virtual ~Reader() = default; + + [[nodiscard]] virtual std::expected read(void* dst, + size_t max) = 0; + [[nodiscard]] virtual std::expected skip(size_t max) = 0; + + [[nodiscard]] std::expected repeat_read(void* dst, + size_t max); + [[nodiscard]] std::expected repeat_skip(size_t max); + + [[nodiscard]] + virtual int raw_fd() const = 0; + + protected: + Reader() = default; + + Reader(Reader const&) = delete; + Reader& operator=(Reader const&) = delete; +}; + +class Writer { + public: + virtual ~Writer() = default; + + [[nodiscard]] + virtual std::expected write(void const* dst, + size_t size) = 0; + + // Use this instead of the destructor if you care if the call returned an + // error or not. Regardless of returned value, after this method is called + // write will always fail. + [[nodiscard]] + virtual std::expected close() = 0; + + [[nodiscard]] + virtual int raw_fd() const = 0; + + [[nodiscard]] std::expected repeat_write(void const* dst, + size_t size); + + protected: + Writer() = default; + + Writer(Writer const&) = delete; + Writer& operator=(Writer const&) = delete; +}; + +[[nodiscard]] std::expected, OpenError> open( + const std::string& file_path); +[[nodiscard]] std::expected, OpenError> openat( + int dirfd, const std::string& file_path); +[[nodiscard]] std::unique_ptr memory(std::string data); + +[[nodiscard]] std::expected, CreateError> create( + const std::string& file_path, bool replace_existing); +[[nodiscard]] std::expected, CreateError> createat( + int dirfd, const std::string& file_path, bool replace_existing); + +[[nodiscard]] std::expected< + std::pair, std::unique_ptr>, PipeError> +pipe(); + +// Takes ownership of the fd. +[[nodiscard]] std::unique_ptr reader_from_raw(int fd); +[[nodiscard]] std::unique_ptr writer_from_raw(int fd); + +} // namespace io + +#endif // IO_HH -- cgit v1.2.3-70-g09d2