annotate win64-msvc/include/capnp/serialize.h @ 134:41e769c91eca

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