annotate win64-msvc/include/capnp/serialize.h @ 166:cbd6d7e562c7

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