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