annotate win32-mingw/include/capnp/serialize.h @ 50:37d53a7e8262

Headers for KJ/Capnp Win32
author Chris Cannam
date Wed, 26 Oct 2016 13:18:45 +0100
parents
children eccd51b72864
rev   line source
Chris@50 1 // Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors
Chris@50 2 // Licensed under the MIT License:
Chris@50 3 //
Chris@50 4 // Permission is hereby granted, free of charge, to any person obtaining a copy
Chris@50 5 // of this software and associated documentation files (the "Software"), to deal
Chris@50 6 // in the Software without restriction, including without limitation the rights
Chris@50 7 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
Chris@50 8 // copies of the Software, and to permit persons to whom the Software is
Chris@50 9 // furnished to do so, subject to the following conditions:
Chris@50 10 //
Chris@50 11 // The above copyright notice and this permission notice shall be included in
Chris@50 12 // all copies or substantial portions of the Software.
Chris@50 13 //
Chris@50 14 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
Chris@50 15 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
Chris@50 16 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
Chris@50 17 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
Chris@50 18 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
Chris@50 19 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
Chris@50 20 // THE SOFTWARE.
Chris@50 21
Chris@50 22 // This file implements a simple serialization format for Cap'n Proto messages. The format
Chris@50 23 // is as follows:
Chris@50 24 //
Chris@50 25 // * 32-bit little-endian segment count (4 bytes).
Chris@50 26 // * 32-bit little-endian size of each segment (4*(segment count) bytes).
Chris@50 27 // * Padding so that subsequent data is 64-bit-aligned (0 or 4 bytes). (I.e., if there are an even
Chris@50 28 // number of segments, there are 4 bytes of zeros here, otherwise there is no padding.)
Chris@50 29 // * Data from each segment, in order (8*sum(segment sizes) bytes)
Chris@50 30 //
Chris@50 31 // This format has some important properties:
Chris@50 32 // - It is self-delimiting, so multiple messages may be written to a stream without any external
Chris@50 33 // delimiter.
Chris@50 34 // - The total size and position of each segment can be determined by reading only the first part
Chris@50 35 // of the message, allowing lazy and random-access reading of the segment data.
Chris@50 36 // - A message is always at least 8 bytes.
Chris@50 37 // - A single-segment message can be read entirely in two system calls with no buffering.
Chris@50 38 // - A multi-segment message can be read entirely in three system calls with no buffering.
Chris@50 39 // - The format is appropriate for mmap()ing since all data is aligned.
Chris@50 40
Chris@50 41 #ifndef CAPNP_SERIALIZE_H_
Chris@50 42 #define CAPNP_SERIALIZE_H_
Chris@50 43
Chris@50 44 #if defined(__GNUC__) && !defined(CAPNP_HEADER_WARNINGS)
Chris@50 45 #pragma GCC system_header
Chris@50 46 #endif
Chris@50 47
Chris@50 48 #include "message.h"
Chris@50 49 #include <kj/io.h>
Chris@50 50
Chris@50 51 namespace capnp {
Chris@50 52
Chris@50 53 class FlatArrayMessageReader: public MessageReader {
Chris@50 54 // Parses a message from a flat array. Note that it makes sense to use this together with mmap()
Chris@50 55 // for extremely fast parsing.
Chris@50 56
Chris@50 57 public:
Chris@50 58 FlatArrayMessageReader(kj::ArrayPtr<const word> array, ReaderOptions options = ReaderOptions());
Chris@50 59 // The array must remain valid until the MessageReader is destroyed.
Chris@50 60
Chris@50 61 kj::ArrayPtr<const word> getSegment(uint id) override;
Chris@50 62
Chris@50 63 const word* getEnd() const { return end; }
Chris@50 64 // Get a pointer just past the end of the message as determined by reading the message header.
Chris@50 65 // This could actually be before the end of the input array. This pointer is useful e.g. if
Chris@50 66 // you know that the input array has extra stuff appended after the message and you want to
Chris@50 67 // get at it.
Chris@50 68
Chris@50 69 private:
Chris@50 70 // Optimize for single-segment case.
Chris@50 71 kj::ArrayPtr<const word> segment0;
Chris@50 72 kj::Array<kj::ArrayPtr<const word>> moreSegments;
Chris@50 73 const word* end;
Chris@50 74 };
Chris@50 75
Chris@50 76 kj::ArrayPtr<const word> initMessageBuilderFromFlatArrayCopy(
Chris@50 77 kj::ArrayPtr<const word> array, MessageBuilder& target,
Chris@50 78 ReaderOptions options = ReaderOptions());
Chris@50 79 // Convenience function which reads a message using `FlatArrayMessageReader` then copies the
Chris@50 80 // content into the target `MessageBuilder`, verifying that the message structure is valid
Chris@50 81 // (although not necessarily that it matches the desired schema).
Chris@50 82 //
Chris@50 83 // Returns an ArrayPtr containing any words left over in the array after consuming the whole
Chris@50 84 // message. This is useful when reading multiple messages that have been concatenated. See also
Chris@50 85 // FlatArrayMessageReader::getEnd().
Chris@50 86 //
Chris@50 87 // (Note that it's also possible to initialize a `MessageBuilder` directly without a copy using one
Chris@50 88 // of `MessageBuilder`'s constructors. However, this approach skips the validation step and is not
Chris@50 89 // safe to use on untrusted input. Therefore, we do not provide a convenience method for it.)
Chris@50 90
Chris@50 91 kj::Array<word> messageToFlatArray(MessageBuilder& builder);
Chris@50 92 // Constructs a flat array containing the entire content of the given message.
Chris@50 93 //
Chris@50 94 // To output the message as bytes, use `.asBytes()` on the returned word array. Keep in mind that
Chris@50 95 // `asBytes()` returns an ArrayPtr, so you have to save the Array as well to prevent it from being
Chris@50 96 // deleted. For example:
Chris@50 97 //
Chris@50 98 // kj::Array<capnp::word> words = messageToFlatArray(myMessage);
Chris@50 99 // kj::ArrayPtr<kj::byte> bytes = words.asBytes();
Chris@50 100 // write(fd, bytes.begin(), bytes.size());
Chris@50 101
Chris@50 102 kj::Array<word> messageToFlatArray(kj::ArrayPtr<const kj::ArrayPtr<const word>> segments);
Chris@50 103 // Version of messageToFlatArray that takes a raw segment array.
Chris@50 104
Chris@50 105 size_t computeSerializedSizeInWords(MessageBuilder& builder);
Chris@50 106 // Returns the size, in words, that will be needed to serialize the message, including the header.
Chris@50 107
Chris@50 108 size_t computeSerializedSizeInWords(kj::ArrayPtr<const kj::ArrayPtr<const word>> segments);
Chris@50 109 // Version of computeSerializedSizeInWords that takes a raw segment array.
Chris@50 110
Chris@50 111 size_t expectedSizeInWordsFromPrefix(kj::ArrayPtr<const word> messagePrefix);
Chris@50 112 // Given a prefix of a serialized message, try to determine the expected total size of the message,
Chris@50 113 // in words. The returned size is based on the information known so far; it may be an underestimate
Chris@50 114 // if the prefix doesn't contain the full segment table.
Chris@50 115 //
Chris@50 116 // If the returned value is greater than `messagePrefix.size()`, then the message is not yet
Chris@50 117 // complete and the app cannot parse it yet. If the returned value is less than or equal to
Chris@50 118 // `messagePrefix.size()`, then the returned value is the exact total size of the message; any
Chris@50 119 // remaining bytes are part of the next message.
Chris@50 120 //
Chris@50 121 // This function is useful when reading messages from a stream in an asynchronous way, but when
Chris@50 122 // using the full KJ async infrastructure would be too difficult. Each time bytes are received,
Chris@50 123 // use this function to determine if an entire message is ready to be parsed.
Chris@50 124
Chris@50 125 // =======================================================================================
Chris@50 126
Chris@50 127 class InputStreamMessageReader: public MessageReader {
Chris@50 128 // A MessageReader that reads from an abstract kj::InputStream. See also StreamFdMessageReader
Chris@50 129 // for a subclass specific to file descriptors.
Chris@50 130
Chris@50 131 public:
Chris@50 132 InputStreamMessageReader(kj::InputStream& inputStream,
Chris@50 133 ReaderOptions options = ReaderOptions(),
Chris@50 134 kj::ArrayPtr<word> scratchSpace = nullptr);
Chris@50 135 ~InputStreamMessageReader() noexcept(false);
Chris@50 136
Chris@50 137 // implements MessageReader ----------------------------------------
Chris@50 138 kj::ArrayPtr<const word> getSegment(uint id) override;
Chris@50 139
Chris@50 140 private:
Chris@50 141 kj::InputStream& inputStream;
Chris@50 142 byte* readPos;
Chris@50 143
Chris@50 144 // Optimize for single-segment case.
Chris@50 145 kj::ArrayPtr<const word> segment0;
Chris@50 146 kj::Array<kj::ArrayPtr<const word>> moreSegments;
Chris@50 147
Chris@50 148 kj::Array<word> ownedSpace;
Chris@50 149 // Only if scratchSpace wasn't big enough.
Chris@50 150
Chris@50 151 kj::UnwindDetector unwindDetector;
Chris@50 152 };
Chris@50 153
Chris@50 154 void readMessageCopy(kj::InputStream& input, MessageBuilder& target,
Chris@50 155 ReaderOptions options = ReaderOptions(),
Chris@50 156 kj::ArrayPtr<word> scratchSpace = nullptr);
Chris@50 157 // Convenience function which reads a message using `InputStreamMessageReader` then copies the
Chris@50 158 // content into the target `MessageBuilder`, verifying that the message structure is valid
Chris@50 159 // (although not necessarily that it matches the desired schema).
Chris@50 160 //
Chris@50 161 // (Note that it's also possible to initialize a `MessageBuilder` directly without a copy using one
Chris@50 162 // of `MessageBuilder`'s constructors. However, this approach skips the validation step and is not
Chris@50 163 // safe to use on untrusted input. Therefore, we do not provide a convenience method for it.)
Chris@50 164
Chris@50 165 void writeMessage(kj::OutputStream& output, MessageBuilder& builder);
Chris@50 166 // Write the message to the given output stream.
Chris@50 167
Chris@50 168 void writeMessage(kj::OutputStream& output, kj::ArrayPtr<const kj::ArrayPtr<const word>> segments);
Chris@50 169 // Write the segment array to the given output stream.
Chris@50 170
Chris@50 171 // =======================================================================================
Chris@50 172 // Specializations for reading from / writing to file descriptors.
Chris@50 173
Chris@50 174 class StreamFdMessageReader: private kj::FdInputStream, public InputStreamMessageReader {
Chris@50 175 // A MessageReader that reads from a steam-based file descriptor.
Chris@50 176
Chris@50 177 public:
Chris@50 178 StreamFdMessageReader(int fd, ReaderOptions options = ReaderOptions(),
Chris@50 179 kj::ArrayPtr<word> scratchSpace = nullptr)
Chris@50 180 : FdInputStream(fd), InputStreamMessageReader(*this, options, scratchSpace) {}
Chris@50 181 // Read message from a file descriptor, without taking ownership of the descriptor.
Chris@50 182
Chris@50 183 StreamFdMessageReader(kj::AutoCloseFd fd, ReaderOptions options = ReaderOptions(),
Chris@50 184 kj::ArrayPtr<word> scratchSpace = nullptr)
Chris@50 185 : FdInputStream(kj::mv(fd)), InputStreamMessageReader(*this, options, scratchSpace) {}
Chris@50 186 // Read a message from a file descriptor, taking ownership of the descriptor.
Chris@50 187
Chris@50 188 ~StreamFdMessageReader() noexcept(false);
Chris@50 189 };
Chris@50 190
Chris@50 191 void readMessageCopyFromFd(int fd, MessageBuilder& target,
Chris@50 192 ReaderOptions options = ReaderOptions(),
Chris@50 193 kj::ArrayPtr<word> scratchSpace = nullptr);
Chris@50 194 // Convenience function which reads a message using `StreamFdMessageReader` then copies the
Chris@50 195 // content into the target `MessageBuilder`, verifying that the message structure is valid
Chris@50 196 // (although not necessarily that it matches the desired schema).
Chris@50 197 //
Chris@50 198 // (Note that it's also possible to initialize a `MessageBuilder` directly without a copy using one
Chris@50 199 // of `MessageBuilder`'s constructors. However, this approach skips the validation step and is not
Chris@50 200 // safe to use on untrusted input. Therefore, we do not provide a convenience method for it.)
Chris@50 201
Chris@50 202 void writeMessageToFd(int fd, MessageBuilder& builder);
Chris@50 203 // Write the message to the given file descriptor.
Chris@50 204 //
Chris@50 205 // This function throws an exception on any I/O error. If your code is not exception-safe, be sure
Chris@50 206 // you catch this exception at the call site. If throwing an exception is not acceptable, you
Chris@50 207 // can implement your own OutputStream with arbitrary error handling and then use writeMessage().
Chris@50 208
Chris@50 209 void writeMessageToFd(int fd, kj::ArrayPtr<const kj::ArrayPtr<const word>> segments);
Chris@50 210 // Write the segment array to the given file descriptor.
Chris@50 211 //
Chris@50 212 // This function throws an exception on any I/O error. If your code is not exception-safe, be sure
Chris@50 213 // you catch this exception at the call site. If throwing an exception is not acceptable, you
Chris@50 214 // can implement your own OutputStream with arbitrary error handling and then use writeMessage().
Chris@50 215
Chris@50 216 // =======================================================================================
Chris@50 217 // inline stuff
Chris@50 218
Chris@50 219 inline kj::Array<word> messageToFlatArray(MessageBuilder& builder) {
Chris@50 220 return messageToFlatArray(builder.getSegmentsForOutput());
Chris@50 221 }
Chris@50 222
Chris@50 223 inline size_t computeSerializedSizeInWords(MessageBuilder& builder) {
Chris@50 224 return computeSerializedSizeInWords(builder.getSegmentsForOutput());
Chris@50 225 }
Chris@50 226
Chris@50 227 inline void writeMessage(kj::OutputStream& output, MessageBuilder& builder) {
Chris@50 228 writeMessage(output, builder.getSegmentsForOutput());
Chris@50 229 }
Chris@50 230
Chris@50 231 inline void writeMessageToFd(int fd, MessageBuilder& builder) {
Chris@50 232 writeMessageToFd(fd, builder.getSegmentsForOutput());
Chris@50 233 }
Chris@50 234
Chris@50 235 } // namespace capnp
Chris@50 236
Chris@50 237 #endif // SERIALIZE_H_