cannam@148: // Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors cannam@148: // Licensed under the MIT License: cannam@148: // cannam@148: // Permission is hereby granted, free of charge, to any person obtaining a copy cannam@148: // of this software and associated documentation files (the "Software"), to deal cannam@148: // in the Software without restriction, including without limitation the rights cannam@148: // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell cannam@148: // copies of the Software, and to permit persons to whom the Software is cannam@148: // furnished to do so, subject to the following conditions: cannam@148: // cannam@148: // The above copyright notice and this permission notice shall be included in cannam@148: // all copies or substantial portions of the Software. cannam@148: // cannam@148: // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR cannam@148: // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, cannam@148: // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE cannam@148: // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER cannam@148: // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, cannam@148: // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN cannam@148: // THE SOFTWARE. cannam@148: cannam@148: // This file implements a simple serialization format for Cap'n Proto messages. The format cannam@148: // is as follows: cannam@148: // cannam@148: // * 32-bit little-endian segment count (4 bytes). cannam@148: // * 32-bit little-endian size of each segment (4*(segment count) bytes). cannam@148: // * Padding so that subsequent data is 64-bit-aligned (0 or 4 bytes). (I.e., if there are an even cannam@148: // number of segments, there are 4 bytes of zeros here, otherwise there is no padding.) cannam@148: // * Data from each segment, in order (8*sum(segment sizes) bytes) cannam@148: // cannam@148: // This format has some important properties: cannam@148: // - It is self-delimiting, so multiple messages may be written to a stream without any external cannam@148: // delimiter. cannam@148: // - The total size and position of each segment can be determined by reading only the first part cannam@148: // of the message, allowing lazy and random-access reading of the segment data. cannam@148: // - A message is always at least 8 bytes. cannam@148: // - A single-segment message can be read entirely in two system calls with no buffering. cannam@148: // - A multi-segment message can be read entirely in three system calls with no buffering. cannam@148: // - The format is appropriate for mmap()ing since all data is aligned. cannam@148: cannam@148: #ifndef CAPNP_SERIALIZE_H_ cannam@148: #define CAPNP_SERIALIZE_H_ cannam@148: cannam@148: #if defined(__GNUC__) && !defined(CAPNP_HEADER_WARNINGS) cannam@148: #pragma GCC system_header cannam@148: #endif cannam@148: cannam@148: #include "message.h" cannam@148: #include cannam@148: cannam@148: namespace capnp { cannam@148: cannam@148: class FlatArrayMessageReader: public MessageReader { cannam@148: // Parses a message from a flat array. Note that it makes sense to use this together with mmap() cannam@148: // for extremely fast parsing. cannam@148: cannam@148: public: cannam@148: FlatArrayMessageReader(kj::ArrayPtr array, ReaderOptions options = ReaderOptions()); cannam@148: // The array must remain valid until the MessageReader is destroyed. cannam@148: cannam@148: kj::ArrayPtr getSegment(uint id) override; cannam@148: cannam@148: const word* getEnd() const { return end; } cannam@148: // Get a pointer just past the end of the message as determined by reading the message header. cannam@148: // This could actually be before the end of the input array. This pointer is useful e.g. if cannam@148: // you know that the input array has extra stuff appended after the message and you want to cannam@148: // get at it. cannam@148: cannam@148: private: cannam@148: // Optimize for single-segment case. cannam@148: kj::ArrayPtr segment0; cannam@148: kj::Array> moreSegments; cannam@148: const word* end; cannam@148: }; cannam@148: cannam@148: kj::ArrayPtr initMessageBuilderFromFlatArrayCopy( cannam@148: kj::ArrayPtr array, MessageBuilder& target, cannam@148: ReaderOptions options = ReaderOptions()); cannam@148: // Convenience function which reads a message using `FlatArrayMessageReader` then copies the cannam@148: // content into the target `MessageBuilder`, verifying that the message structure is valid cannam@148: // (although not necessarily that it matches the desired schema). cannam@148: // cannam@148: // Returns an ArrayPtr containing any words left over in the array after consuming the whole cannam@148: // message. This is useful when reading multiple messages that have been concatenated. See also cannam@148: // FlatArrayMessageReader::getEnd(). cannam@148: // cannam@148: // (Note that it's also possible to initialize a `MessageBuilder` directly without a copy using one cannam@148: // of `MessageBuilder`'s constructors. However, this approach skips the validation step and is not cannam@148: // safe to use on untrusted input. Therefore, we do not provide a convenience method for it.) cannam@148: cannam@148: kj::Array messageToFlatArray(MessageBuilder& builder); cannam@148: // Constructs a flat array containing the entire content of the given message. cannam@148: // cannam@148: // To output the message as bytes, use `.asBytes()` on the returned word array. Keep in mind that cannam@148: // `asBytes()` returns an ArrayPtr, so you have to save the Array as well to prevent it from being cannam@148: // deleted. For example: cannam@148: // cannam@148: // kj::Array words = messageToFlatArray(myMessage); cannam@148: // kj::ArrayPtr bytes = words.asBytes(); cannam@148: // write(fd, bytes.begin(), bytes.size()); cannam@148: cannam@148: kj::Array messageToFlatArray(kj::ArrayPtr> segments); cannam@148: // Version of messageToFlatArray that takes a raw segment array. cannam@148: cannam@148: size_t computeSerializedSizeInWords(MessageBuilder& builder); cannam@148: // Returns the size, in words, that will be needed to serialize the message, including the header. cannam@148: cannam@148: size_t computeSerializedSizeInWords(kj::ArrayPtr> segments); cannam@148: // Version of computeSerializedSizeInWords that takes a raw segment array. cannam@148: cannam@148: size_t expectedSizeInWordsFromPrefix(kj::ArrayPtr messagePrefix); cannam@148: // Given a prefix of a serialized message, try to determine the expected total size of the message, cannam@148: // in words. The returned size is based on the information known so far; it may be an underestimate cannam@148: // if the prefix doesn't contain the full segment table. cannam@148: // cannam@148: // If the returned value is greater than `messagePrefix.size()`, then the message is not yet cannam@148: // complete and the app cannot parse it yet. If the returned value is less than or equal to cannam@148: // `messagePrefix.size()`, then the returned value is the exact total size of the message; any cannam@148: // remaining bytes are part of the next message. cannam@148: // cannam@148: // This function is useful when reading messages from a stream in an asynchronous way, but when cannam@148: // using the full KJ async infrastructure would be too difficult. Each time bytes are received, cannam@148: // use this function to determine if an entire message is ready to be parsed. cannam@148: cannam@148: // ======================================================================================= cannam@148: cannam@148: class InputStreamMessageReader: public MessageReader { cannam@148: // A MessageReader that reads from an abstract kj::InputStream. See also StreamFdMessageReader cannam@148: // for a subclass specific to file descriptors. cannam@148: cannam@148: public: cannam@148: InputStreamMessageReader(kj::InputStream& inputStream, cannam@148: ReaderOptions options = ReaderOptions(), cannam@148: kj::ArrayPtr scratchSpace = nullptr); cannam@148: ~InputStreamMessageReader() noexcept(false); cannam@148: cannam@148: // implements MessageReader ---------------------------------------- cannam@148: kj::ArrayPtr getSegment(uint id) override; cannam@148: cannam@148: private: cannam@148: kj::InputStream& inputStream; cannam@148: byte* readPos; cannam@148: cannam@148: // Optimize for single-segment case. cannam@148: kj::ArrayPtr segment0; cannam@148: kj::Array> moreSegments; cannam@148: cannam@148: kj::Array ownedSpace; cannam@148: // Only if scratchSpace wasn't big enough. cannam@148: cannam@148: kj::UnwindDetector unwindDetector; cannam@148: }; cannam@148: cannam@148: void readMessageCopy(kj::InputStream& input, MessageBuilder& target, cannam@148: ReaderOptions options = ReaderOptions(), cannam@148: kj::ArrayPtr scratchSpace = nullptr); cannam@148: // Convenience function which reads a message using `InputStreamMessageReader` then copies the cannam@148: // content into the target `MessageBuilder`, verifying that the message structure is valid cannam@148: // (although not necessarily that it matches the desired schema). cannam@148: // cannam@148: // (Note that it's also possible to initialize a `MessageBuilder` directly without a copy using one cannam@148: // of `MessageBuilder`'s constructors. However, this approach skips the validation step and is not cannam@148: // safe to use on untrusted input. Therefore, we do not provide a convenience method for it.) cannam@148: cannam@148: void writeMessage(kj::OutputStream& output, MessageBuilder& builder); cannam@148: // Write the message to the given output stream. cannam@148: cannam@148: void writeMessage(kj::OutputStream& output, kj::ArrayPtr> segments); cannam@148: // Write the segment array to the given output stream. cannam@148: cannam@148: // ======================================================================================= cannam@148: // Specializations for reading from / writing to file descriptors. cannam@148: cannam@148: class StreamFdMessageReader: private kj::FdInputStream, public InputStreamMessageReader { cannam@148: // A MessageReader that reads from a steam-based file descriptor. cannam@148: cannam@148: public: cannam@148: StreamFdMessageReader(int fd, ReaderOptions options = ReaderOptions(), cannam@148: kj::ArrayPtr scratchSpace = nullptr) cannam@148: : FdInputStream(fd), InputStreamMessageReader(*this, options, scratchSpace) {} cannam@148: // Read message from a file descriptor, without taking ownership of the descriptor. cannam@148: cannam@148: StreamFdMessageReader(kj::AutoCloseFd fd, ReaderOptions options = ReaderOptions(), cannam@148: kj::ArrayPtr scratchSpace = nullptr) cannam@148: : FdInputStream(kj::mv(fd)), InputStreamMessageReader(*this, options, scratchSpace) {} cannam@148: // Read a message from a file descriptor, taking ownership of the descriptor. cannam@148: cannam@148: ~StreamFdMessageReader() noexcept(false); cannam@148: }; cannam@148: cannam@148: void readMessageCopyFromFd(int fd, MessageBuilder& target, cannam@148: ReaderOptions options = ReaderOptions(), cannam@148: kj::ArrayPtr scratchSpace = nullptr); cannam@148: // Convenience function which reads a message using `StreamFdMessageReader` then copies the cannam@148: // content into the target `MessageBuilder`, verifying that the message structure is valid cannam@148: // (although not necessarily that it matches the desired schema). cannam@148: // cannam@148: // (Note that it's also possible to initialize a `MessageBuilder` directly without a copy using one cannam@148: // of `MessageBuilder`'s constructors. However, this approach skips the validation step and is not cannam@148: // safe to use on untrusted input. Therefore, we do not provide a convenience method for it.) cannam@148: cannam@148: void writeMessageToFd(int fd, MessageBuilder& builder); cannam@148: // Write the message to the given file descriptor. cannam@148: // cannam@148: // This function throws an exception on any I/O error. If your code is not exception-safe, be sure cannam@148: // you catch this exception at the call site. If throwing an exception is not acceptable, you cannam@148: // can implement your own OutputStream with arbitrary error handling and then use writeMessage(). cannam@148: cannam@148: void writeMessageToFd(int fd, kj::ArrayPtr> segments); cannam@148: // Write the segment array to the given file descriptor. cannam@148: // cannam@148: // This function throws an exception on any I/O error. If your code is not exception-safe, be sure cannam@148: // you catch this exception at the call site. If throwing an exception is not acceptable, you cannam@148: // can implement your own OutputStream with arbitrary error handling and then use writeMessage(). cannam@148: cannam@148: // ======================================================================================= cannam@148: // inline stuff cannam@148: cannam@148: inline kj::Array messageToFlatArray(MessageBuilder& builder) { cannam@148: return messageToFlatArray(builder.getSegmentsForOutput()); cannam@148: } cannam@148: cannam@148: inline size_t computeSerializedSizeInWords(MessageBuilder& builder) { cannam@148: return computeSerializedSizeInWords(builder.getSegmentsForOutput()); cannam@148: } cannam@148: cannam@148: inline void writeMessage(kj::OutputStream& output, MessageBuilder& builder) { cannam@148: writeMessage(output, builder.getSegmentsForOutput()); cannam@148: } cannam@148: cannam@148: inline void writeMessageToFd(int fd, MessageBuilder& builder) { cannam@148: writeMessageToFd(fd, builder.getSegmentsForOutput()); cannam@148: } cannam@148: cannam@148: } // namespace capnp cannam@148: cannam@148: #endif // SERIALIZE_H_