Chris@47: // Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors Chris@47: // Licensed under the MIT License: Chris@47: // Chris@47: // Permission is hereby granted, free of charge, to any person obtaining a copy Chris@47: // of this software and associated documentation files (the "Software"), to deal Chris@47: // in the Software without restriction, including without limitation the rights Chris@47: // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell Chris@47: // copies of the Software, and to permit persons to whom the Software is Chris@47: // furnished to do so, subject to the following conditions: Chris@47: // Chris@47: // The above copyright notice and this permission notice shall be included in Chris@47: // all copies or substantial portions of the Software. Chris@47: // Chris@47: // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR Chris@47: // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, Chris@47: // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE Chris@47: // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER Chris@47: // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, Chris@47: // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN Chris@47: // THE SOFTWARE. Chris@47: Chris@47: #ifndef KJ_IO_H_ Chris@47: #define KJ_IO_H_ Chris@47: Chris@47: #if defined(__GNUC__) && !KJ_HEADER_WARNINGS Chris@47: #pragma GCC system_header Chris@47: #endif Chris@47: Chris@47: #include Chris@47: #include "common.h" Chris@47: #include "array.h" Chris@47: #include "exception.h" Chris@47: Chris@47: namespace kj { Chris@47: Chris@47: // ======================================================================================= Chris@47: // Abstract interfaces Chris@47: Chris@47: class InputStream { Chris@47: public: Chris@47: virtual ~InputStream() noexcept(false); Chris@47: Chris@47: size_t read(void* buffer, size_t minBytes, size_t maxBytes); Chris@47: // Reads at least minBytes and at most maxBytes, copying them into the given buffer. Returns Chris@47: // the size read. Throws an exception on errors. Implemented in terms of tryRead(). Chris@47: // Chris@47: // maxBytes is the number of bytes the caller really wants, but minBytes is the minimum amount Chris@47: // needed by the caller before it can start doing useful processing. If the stream returns less Chris@47: // than maxBytes, the caller will usually call read() again later to get the rest. Returning Chris@47: // less than maxBytes is useful when it makes sense for the caller to parallelize processing Chris@47: // with I/O. Chris@47: // Chris@47: // Never blocks if minBytes is zero. If minBytes is zero and maxBytes is non-zero, this may Chris@47: // attempt a non-blocking read or may just return zero. To force a read, use a non-zero minBytes. Chris@47: // To detect EOF without throwing an exception, use tryRead(). Chris@47: // Chris@47: // If the InputStream can't produce minBytes, it MUST throw an exception, as the caller is not Chris@47: // expected to understand how to deal with partial reads. Chris@47: Chris@47: virtual size_t tryRead(void* buffer, size_t minBytes, size_t maxBytes) = 0; Chris@47: // Like read(), but may return fewer than minBytes on EOF. Chris@47: Chris@47: inline void read(void* buffer, size_t bytes) { read(buffer, bytes, bytes); } Chris@47: // Convenience method for reading an exact number of bytes. Chris@47: Chris@47: virtual void skip(size_t bytes); Chris@47: // Skips past the given number of bytes, discarding them. The default implementation read()s Chris@47: // into a scratch buffer. Chris@47: }; Chris@47: Chris@47: class OutputStream { Chris@47: public: Chris@47: virtual ~OutputStream() noexcept(false); Chris@47: Chris@47: virtual void write(const void* buffer, size_t size) = 0; Chris@47: // Always writes the full size. Throws exception on error. Chris@47: Chris@47: virtual void write(ArrayPtr> pieces); Chris@47: // Equivalent to write()ing each byte array in sequence, which is what the default implementation Chris@47: // does. Override if you can do something better, e.g. use writev() to do the write in a single Chris@47: // syscall. Chris@47: }; Chris@47: Chris@47: class BufferedInputStream: public InputStream { Chris@47: // An input stream which buffers some bytes in memory to reduce system call overhead. Chris@47: // - OR - Chris@47: // An input stream that actually reads from some in-memory data structure and wants to give its Chris@47: // caller a direct pointer to that memory to potentially avoid a copy. Chris@47: Chris@47: public: Chris@47: virtual ~BufferedInputStream() noexcept(false); Chris@47: Chris@47: ArrayPtr getReadBuffer(); Chris@47: // Get a direct pointer into the read buffer, which contains the next bytes in the input. If the Chris@47: // caller consumes any bytes, it should then call skip() to indicate this. This always returns a Chris@47: // non-empty buffer or throws an exception. Implemented in terms of tryGetReadBuffer(). Chris@47: Chris@47: virtual ArrayPtr tryGetReadBuffer() = 0; Chris@47: // Like getReadBuffer() but may return an empty buffer on EOF. Chris@47: }; Chris@47: Chris@47: class BufferedOutputStream: public OutputStream { Chris@47: // An output stream which buffers some bytes in memory to reduce system call overhead. Chris@47: // - OR - Chris@47: // An output stream that actually writes into some in-memory data structure and wants to give its Chris@47: // caller a direct pointer to that memory to potentially avoid a copy. Chris@47: Chris@47: public: Chris@47: virtual ~BufferedOutputStream() noexcept(false); Chris@47: Chris@47: virtual ArrayPtr getWriteBuffer() = 0; Chris@47: // Get a direct pointer into the write buffer. The caller may choose to fill in some prefix of Chris@47: // this buffer and then pass it to write(), in which case write() may avoid a copy. It is Chris@47: // incorrect to pass to write any slice of this buffer which is not a prefix. Chris@47: }; Chris@47: Chris@47: // ======================================================================================= Chris@47: // Buffered streams implemented as wrappers around regular streams Chris@47: Chris@47: class BufferedInputStreamWrapper: public BufferedInputStream { Chris@47: // Implements BufferedInputStream in terms of an InputStream. Chris@47: // Chris@47: // Note that the underlying stream's position is unpredictable once the wrapper is destroyed, Chris@47: // unless the entire stream was consumed. To read a predictable number of bytes in a buffered Chris@47: // way without going over, you'd need this wrapper to wrap some other wrapper which itself Chris@47: // implements an artificial EOF at the desired point. Such a stream should be trivial to write Chris@47: // but is not provided by the library at this time. Chris@47: Chris@47: public: Chris@47: explicit BufferedInputStreamWrapper(InputStream& inner, ArrayPtr buffer = nullptr); Chris@47: // Creates a buffered stream wrapping the given non-buffered stream. No guarantee is made about Chris@47: // the position of the inner stream after a buffered wrapper has been created unless the entire Chris@47: // input is read. Chris@47: // Chris@47: // If the second parameter is non-null, the stream uses the given buffer instead of allocating Chris@47: // its own. This may improve performance if the buffer can be reused. Chris@47: Chris@47: KJ_DISALLOW_COPY(BufferedInputStreamWrapper); Chris@47: ~BufferedInputStreamWrapper() noexcept(false); Chris@47: Chris@47: // implements BufferedInputStream ---------------------------------- Chris@47: ArrayPtr tryGetReadBuffer() override; Chris@47: size_t tryRead(void* buffer, size_t minBytes, size_t maxBytes) override; Chris@47: void skip(size_t bytes) override; Chris@47: Chris@47: private: Chris@47: InputStream& inner; Chris@47: Array ownedBuffer; Chris@47: ArrayPtr buffer; Chris@47: ArrayPtr bufferAvailable; Chris@47: }; Chris@47: Chris@47: class BufferedOutputStreamWrapper: public BufferedOutputStream { Chris@47: // Implements BufferedOutputStream in terms of an OutputStream. Note that writes to the Chris@47: // underlying stream may be delayed until flush() is called or the wrapper is destroyed. Chris@47: Chris@47: public: Chris@47: explicit BufferedOutputStreamWrapper(OutputStream& inner, ArrayPtr buffer = nullptr); Chris@47: // Creates a buffered stream wrapping the given non-buffered stream. Chris@47: // Chris@47: // If the second parameter is non-null, the stream uses the given buffer instead of allocating Chris@47: // its own. This may improve performance if the buffer can be reused. Chris@47: Chris@47: KJ_DISALLOW_COPY(BufferedOutputStreamWrapper); Chris@47: ~BufferedOutputStreamWrapper() noexcept(false); Chris@47: Chris@47: void flush(); Chris@47: // Force the wrapper to write any remaining bytes in its buffer to the inner stream. Note that Chris@47: // this only flushes this object's buffer; this object has no idea how to flush any other buffers Chris@47: // that may be present in the underlying stream. Chris@47: Chris@47: // implements BufferedOutputStream --------------------------------- Chris@47: ArrayPtr getWriteBuffer() override; Chris@47: void write(const void* buffer, size_t size) override; Chris@47: Chris@47: private: Chris@47: OutputStream& inner; Chris@47: Array ownedBuffer; Chris@47: ArrayPtr buffer; Chris@47: byte* bufferPos; Chris@47: UnwindDetector unwindDetector; Chris@47: }; Chris@47: Chris@47: // ======================================================================================= Chris@47: // Array I/O Chris@47: Chris@47: class ArrayInputStream: public BufferedInputStream { Chris@47: public: Chris@47: explicit ArrayInputStream(ArrayPtr array); Chris@47: KJ_DISALLOW_COPY(ArrayInputStream); Chris@47: ~ArrayInputStream() noexcept(false); Chris@47: Chris@47: // implements BufferedInputStream ---------------------------------- Chris@47: ArrayPtr tryGetReadBuffer() override; Chris@47: size_t tryRead(void* buffer, size_t minBytes, size_t maxBytes) override; Chris@47: void skip(size_t bytes) override; Chris@47: Chris@47: private: Chris@47: ArrayPtr array; Chris@47: }; Chris@47: Chris@47: class ArrayOutputStream: public BufferedOutputStream { Chris@47: public: Chris@47: explicit ArrayOutputStream(ArrayPtr array); Chris@47: KJ_DISALLOW_COPY(ArrayOutputStream); Chris@47: ~ArrayOutputStream() noexcept(false); Chris@47: Chris@47: ArrayPtr getArray() { Chris@47: // Get the portion of the array which has been filled in. Chris@47: return arrayPtr(array.begin(), fillPos); Chris@47: } Chris@47: Chris@47: // implements BufferedInputStream ---------------------------------- Chris@47: ArrayPtr getWriteBuffer() override; Chris@47: void write(const void* buffer, size_t size) override; Chris@47: Chris@47: private: Chris@47: ArrayPtr array; Chris@47: byte* fillPos; Chris@47: }; Chris@47: Chris@47: class VectorOutputStream: public BufferedOutputStream { Chris@47: public: Chris@47: explicit VectorOutputStream(size_t initialCapacity = 4096); Chris@47: KJ_DISALLOW_COPY(VectorOutputStream); Chris@47: ~VectorOutputStream() noexcept(false); Chris@47: Chris@47: ArrayPtr getArray() { Chris@47: // Get the portion of the array which has been filled in. Chris@47: return arrayPtr(vector.begin(), fillPos); Chris@47: } Chris@47: Chris@47: // implements BufferedInputStream ---------------------------------- Chris@47: ArrayPtr getWriteBuffer() override; Chris@47: void write(const void* buffer, size_t size) override; Chris@47: Chris@47: private: Chris@47: Array vector; Chris@47: byte* fillPos; Chris@47: Chris@47: void grow(size_t minSize); Chris@47: }; Chris@47: Chris@47: // ======================================================================================= Chris@47: // File descriptor I/O Chris@47: Chris@47: class AutoCloseFd { Chris@47: // A wrapper around a file descriptor which automatically closes the descriptor when destroyed. Chris@47: // The wrapper supports move construction for transferring ownership of the descriptor. If Chris@47: // close() returns an error, the destructor throws an exception, UNLESS the destructor is being Chris@47: // called during unwind from another exception, in which case the close error is ignored. Chris@47: // Chris@47: // If your code is not exception-safe, you should not use AutoCloseFd. In this case you will Chris@47: // have to call close() yourself and handle errors appropriately. Chris@47: Chris@47: public: Chris@47: inline AutoCloseFd(): fd(-1) {} Chris@47: inline AutoCloseFd(decltype(nullptr)): fd(-1) {} Chris@47: inline explicit AutoCloseFd(int fd): fd(fd) {} Chris@47: inline AutoCloseFd(AutoCloseFd&& other) noexcept: fd(other.fd) { other.fd = -1; } Chris@47: KJ_DISALLOW_COPY(AutoCloseFd); Chris@47: ~AutoCloseFd() noexcept(false); Chris@47: Chris@47: inline AutoCloseFd& operator=(AutoCloseFd&& other) { Chris@47: AutoCloseFd old(kj::mv(*this)); Chris@47: fd = other.fd; Chris@47: other.fd = -1; Chris@47: return *this; Chris@47: } Chris@47: Chris@47: inline AutoCloseFd& operator=(decltype(nullptr)) { Chris@47: AutoCloseFd old(kj::mv(*this)); Chris@47: return *this; Chris@47: } Chris@47: Chris@47: inline operator int() const { return fd; } Chris@47: inline int get() const { return fd; } Chris@47: Chris@47: operator bool() const = delete; Chris@47: // Deleting this operator prevents accidental use in boolean contexts, which Chris@47: // the int conversion operator above would otherwise allow. Chris@47: Chris@47: inline bool operator==(decltype(nullptr)) { return fd < 0; } Chris@47: inline bool operator!=(decltype(nullptr)) { return fd >= 0; } Chris@47: Chris@47: private: Chris@47: int fd; Chris@47: UnwindDetector unwindDetector; Chris@47: }; Chris@47: Chris@47: inline auto KJ_STRINGIFY(const AutoCloseFd& fd) Chris@47: -> decltype(kj::toCharSequence(implicitCast(fd))) { Chris@47: return kj::toCharSequence(implicitCast(fd)); Chris@47: } Chris@47: Chris@47: class FdInputStream: public InputStream { Chris@47: // An InputStream wrapping a file descriptor. Chris@47: Chris@47: public: Chris@47: explicit FdInputStream(int fd): fd(fd) {} Chris@47: explicit FdInputStream(AutoCloseFd fd): fd(fd), autoclose(mv(fd)) {} Chris@47: KJ_DISALLOW_COPY(FdInputStream); Chris@47: ~FdInputStream() noexcept(false); Chris@47: Chris@47: size_t tryRead(void* buffer, size_t minBytes, size_t maxBytes) override; Chris@47: Chris@47: private: Chris@47: int fd; Chris@47: AutoCloseFd autoclose; Chris@47: }; Chris@47: Chris@47: class FdOutputStream: public OutputStream { Chris@47: // An OutputStream wrapping a file descriptor. Chris@47: Chris@47: public: Chris@47: explicit FdOutputStream(int fd): fd(fd) {} Chris@47: explicit FdOutputStream(AutoCloseFd fd): fd(fd), autoclose(mv(fd)) {} Chris@47: KJ_DISALLOW_COPY(FdOutputStream); Chris@47: ~FdOutputStream() noexcept(false); Chris@47: Chris@47: void write(const void* buffer, size_t size) override; Chris@47: void write(ArrayPtr> pieces) override; Chris@47: Chris@47: private: Chris@47: int fd; Chris@47: AutoCloseFd autoclose; Chris@47: }; Chris@47: Chris@47: } // namespace kj Chris@47: Chris@47: #endif // KJ_IO_H_