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