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: // This file implements a simple serialization format for Cap'n Proto messages. The format Chris@50: // is as follows: Chris@50: // Chris@50: // * 32-bit little-endian segment count (4 bytes). Chris@50: // * 32-bit little-endian size of each segment (4*(segment count) bytes). Chris@50: // * Padding so that subsequent data is 64-bit-aligned (0 or 4 bytes). (I.e., if there are an even Chris@50: // number of segments, there are 4 bytes of zeros here, otherwise there is no padding.) Chris@50: // * Data from each segment, in order (8*sum(segment sizes) bytes) Chris@50: // Chris@50: // This format has some important properties: Chris@50: // - It is self-delimiting, so multiple messages may be written to a stream without any external Chris@50: // delimiter. Chris@50: // - The total size and position of each segment can be determined by reading only the first part Chris@50: // of the message, allowing lazy and random-access reading of the segment data. Chris@50: // - A message is always at least 8 bytes. Chris@50: // - A single-segment message can be read entirely in two system calls with no buffering. Chris@50: // - A multi-segment message can be read entirely in three system calls with no buffering. Chris@50: // - The format is appropriate for mmap()ing since all data is aligned. Chris@50: Chris@50: #ifndef CAPNP_SERIALIZE_H_ Chris@50: #define CAPNP_SERIALIZE_H_ Chris@50: Chris@50: #if defined(__GNUC__) && !defined(CAPNP_HEADER_WARNINGS) Chris@50: #pragma GCC system_header Chris@50: #endif Chris@50: Chris@50: #include "message.h" Chris@50: #include Chris@50: Chris@50: namespace capnp { Chris@50: Chris@50: class FlatArrayMessageReader: public MessageReader { Chris@50: // Parses a message from a flat array. Note that it makes sense to use this together with mmap() Chris@50: // for extremely fast parsing. Chris@50: Chris@50: public: Chris@50: FlatArrayMessageReader(kj::ArrayPtr array, ReaderOptions options = ReaderOptions()); Chris@50: // The array must remain valid until the MessageReader is destroyed. Chris@50: Chris@50: kj::ArrayPtr getSegment(uint id) override; Chris@50: Chris@50: const word* getEnd() const { return end; } Chris@50: // Get a pointer just past the end of the message as determined by reading the message header. Chris@50: // This could actually be before the end of the input array. This pointer is useful e.g. if Chris@50: // you know that the input array has extra stuff appended after the message and you want to Chris@50: // get at it. Chris@50: Chris@50: private: Chris@50: // Optimize for single-segment case. Chris@50: kj::ArrayPtr segment0; Chris@50: kj::Array> moreSegments; Chris@50: const word* end; Chris@50: }; Chris@50: Chris@50: kj::ArrayPtr initMessageBuilderFromFlatArrayCopy( Chris@50: kj::ArrayPtr array, MessageBuilder& target, Chris@50: ReaderOptions options = ReaderOptions()); Chris@50: // Convenience function which reads a message using `FlatArrayMessageReader` then copies the Chris@50: // content into the target `MessageBuilder`, verifying that the message structure is valid Chris@50: // (although not necessarily that it matches the desired schema). Chris@50: // Chris@50: // Returns an ArrayPtr containing any words left over in the array after consuming the whole Chris@50: // message. This is useful when reading multiple messages that have been concatenated. See also Chris@50: // FlatArrayMessageReader::getEnd(). Chris@50: // Chris@50: // (Note that it's also possible to initialize a `MessageBuilder` directly without a copy using one Chris@50: // of `MessageBuilder`'s constructors. However, this approach skips the validation step and is not Chris@50: // safe to use on untrusted input. Therefore, we do not provide a convenience method for it.) Chris@50: Chris@50: kj::Array messageToFlatArray(MessageBuilder& builder); Chris@50: // Constructs a flat array containing the entire content of the given message. Chris@50: // Chris@50: // To output the message as bytes, use `.asBytes()` on the returned word array. Keep in mind that Chris@50: // `asBytes()` returns an ArrayPtr, so you have to save the Array as well to prevent it from being Chris@50: // deleted. For example: Chris@50: // Chris@50: // kj::Array words = messageToFlatArray(myMessage); Chris@50: // kj::ArrayPtr bytes = words.asBytes(); Chris@50: // write(fd, bytes.begin(), bytes.size()); Chris@50: Chris@50: kj::Array messageToFlatArray(kj::ArrayPtr> segments); Chris@50: // Version of messageToFlatArray that takes a raw segment array. Chris@50: Chris@50: size_t computeSerializedSizeInWords(MessageBuilder& builder); Chris@50: // Returns the size, in words, that will be needed to serialize the message, including the header. Chris@50: Chris@50: size_t computeSerializedSizeInWords(kj::ArrayPtr> segments); Chris@50: // Version of computeSerializedSizeInWords that takes a raw segment array. Chris@50: Chris@50: size_t expectedSizeInWordsFromPrefix(kj::ArrayPtr messagePrefix); Chris@50: // Given a prefix of a serialized message, try to determine the expected total size of the message, Chris@50: // in words. The returned size is based on the information known so far; it may be an underestimate Chris@50: // if the prefix doesn't contain the full segment table. Chris@50: // Chris@50: // If the returned value is greater than `messagePrefix.size()`, then the message is not yet Chris@50: // complete and the app cannot parse it yet. If the returned value is less than or equal to Chris@50: // `messagePrefix.size()`, then the returned value is the exact total size of the message; any Chris@50: // remaining bytes are part of the next message. Chris@50: // Chris@50: // This function is useful when reading messages from a stream in an asynchronous way, but when Chris@50: // using the full KJ async infrastructure would be too difficult. Each time bytes are received, Chris@50: // use this function to determine if an entire message is ready to be parsed. Chris@50: Chris@50: // ======================================================================================= Chris@50: Chris@50: class InputStreamMessageReader: public MessageReader { Chris@50: // A MessageReader that reads from an abstract kj::InputStream. See also StreamFdMessageReader Chris@50: // for a subclass specific to file descriptors. Chris@50: Chris@50: public: Chris@50: InputStreamMessageReader(kj::InputStream& inputStream, Chris@50: ReaderOptions options = ReaderOptions(), Chris@50: kj::ArrayPtr scratchSpace = nullptr); Chris@50: ~InputStreamMessageReader() noexcept(false); Chris@50: Chris@50: // implements MessageReader ---------------------------------------- Chris@50: kj::ArrayPtr getSegment(uint id) override; Chris@50: Chris@50: private: Chris@50: kj::InputStream& inputStream; Chris@50: byte* readPos; Chris@50: Chris@50: // Optimize for single-segment case. Chris@50: kj::ArrayPtr segment0; Chris@50: kj::Array> moreSegments; Chris@50: Chris@50: kj::Array ownedSpace; Chris@50: // Only if scratchSpace wasn't big enough. Chris@50: Chris@50: kj::UnwindDetector unwindDetector; Chris@50: }; Chris@50: Chris@50: void readMessageCopy(kj::InputStream& input, MessageBuilder& target, Chris@50: ReaderOptions options = ReaderOptions(), Chris@50: kj::ArrayPtr scratchSpace = nullptr); Chris@50: // Convenience function which reads a message using `InputStreamMessageReader` then copies the Chris@50: // content into the target `MessageBuilder`, verifying that the message structure is valid Chris@50: // (although not necessarily that it matches the desired schema). Chris@50: // Chris@50: // (Note that it's also possible to initialize a `MessageBuilder` directly without a copy using one Chris@50: // of `MessageBuilder`'s constructors. However, this approach skips the validation step and is not Chris@50: // safe to use on untrusted input. Therefore, we do not provide a convenience method for it.) Chris@50: Chris@50: void writeMessage(kj::OutputStream& output, MessageBuilder& builder); Chris@50: // Write the message to the given output stream. Chris@50: Chris@50: void writeMessage(kj::OutputStream& output, kj::ArrayPtr> segments); Chris@50: // Write the segment array to the given output stream. Chris@50: Chris@50: // ======================================================================================= Chris@50: // Specializations for reading from / writing to file descriptors. Chris@50: Chris@50: class StreamFdMessageReader: private kj::FdInputStream, public InputStreamMessageReader { Chris@50: // A MessageReader that reads from a steam-based file descriptor. Chris@50: Chris@50: public: Chris@50: StreamFdMessageReader(int fd, ReaderOptions options = ReaderOptions(), Chris@50: kj::ArrayPtr scratchSpace = nullptr) Chris@50: : FdInputStream(fd), InputStreamMessageReader(*this, options, scratchSpace) {} Chris@50: // Read message from a file descriptor, without taking ownership of the descriptor. Chris@50: Chris@50: StreamFdMessageReader(kj::AutoCloseFd fd, ReaderOptions options = ReaderOptions(), Chris@50: kj::ArrayPtr scratchSpace = nullptr) Chris@50: : FdInputStream(kj::mv(fd)), InputStreamMessageReader(*this, options, scratchSpace) {} Chris@50: // Read a message from a file descriptor, taking ownership of the descriptor. Chris@50: Chris@50: ~StreamFdMessageReader() noexcept(false); Chris@50: }; Chris@50: Chris@50: void readMessageCopyFromFd(int fd, MessageBuilder& target, Chris@50: ReaderOptions options = ReaderOptions(), Chris@50: kj::ArrayPtr scratchSpace = nullptr); Chris@50: // Convenience function which reads a message using `StreamFdMessageReader` then copies the Chris@50: // content into the target `MessageBuilder`, verifying that the message structure is valid Chris@50: // (although not necessarily that it matches the desired schema). Chris@50: // Chris@50: // (Note that it's also possible to initialize a `MessageBuilder` directly without a copy using one Chris@50: // of `MessageBuilder`'s constructors. However, this approach skips the validation step and is not Chris@50: // safe to use on untrusted input. Therefore, we do not provide a convenience method for it.) Chris@50: Chris@50: void writeMessageToFd(int fd, MessageBuilder& builder); Chris@50: // Write the message to the given file descriptor. Chris@50: // Chris@50: // This function throws an exception on any I/O error. If your code is not exception-safe, be sure Chris@50: // you catch this exception at the call site. If throwing an exception is not acceptable, you Chris@50: // can implement your own OutputStream with arbitrary error handling and then use writeMessage(). Chris@50: Chris@50: void writeMessageToFd(int fd, kj::ArrayPtr> segments); Chris@50: // Write the segment array to the given file descriptor. Chris@50: // Chris@50: // This function throws an exception on any I/O error. If your code is not exception-safe, be sure Chris@50: // you catch this exception at the call site. If throwing an exception is not acceptable, you Chris@50: // can implement your own OutputStream with arbitrary error handling and then use writeMessage(). Chris@50: Chris@50: // ======================================================================================= Chris@50: // inline stuff Chris@50: Chris@50: inline kj::Array messageToFlatArray(MessageBuilder& builder) { Chris@50: return messageToFlatArray(builder.getSegmentsForOutput()); Chris@50: } Chris@50: Chris@50: inline size_t computeSerializedSizeInWords(MessageBuilder& builder) { Chris@50: return computeSerializedSizeInWords(builder.getSegmentsForOutput()); Chris@50: } Chris@50: Chris@50: inline void writeMessage(kj::OutputStream& output, MessageBuilder& builder) { Chris@50: writeMessage(output, builder.getSegmentsForOutput()); Chris@50: } Chris@50: Chris@50: inline void writeMessageToFd(int fd, MessageBuilder& builder) { Chris@50: writeMessageToFd(fd, builder.getSegmentsForOutput()); Chris@50: } Chris@50: Chris@50: } // namespace capnp Chris@50: Chris@50: #endif // SERIALIZE_H_