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