诸暨麻将添加redis
25개 이상의 토픽을 선택하실 수 없습니다. Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

1715 lines
69 KiB

  1. // Protocol Buffers - Google's data interchange format
  2. // Copyright 2008 Google Inc. All rights reserved.
  3. // https://developers.google.com/protocol-buffers/
  4. //
  5. // Redistribution and use in source and binary forms, with or without
  6. // modification, are permitted provided that the following conditions are
  7. // met:
  8. //
  9. // * Redistributions of source code must retain the above copyright
  10. // notice, this list of conditions and the following disclaimer.
  11. // * Redistributions in binary form must reproduce the above
  12. // copyright notice, this list of conditions and the following disclaimer
  13. // in the documentation and/or other materials provided with the
  14. // distribution.
  15. // * Neither the name of Google Inc. nor the names of its
  16. // contributors may be used to endorse or promote products derived from
  17. // this software without specific prior written permission.
  18. //
  19. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  20. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  21. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  22. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  23. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  24. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  25. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  26. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  27. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  28. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  29. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  30. // Author: kenton@google.com (Kenton Varda)
  31. // Based on original Protocol Buffers design by
  32. // Sanjay Ghemawat, Jeff Dean, and others.
  33. //
  34. // This file contains the CodedInputStream and CodedOutputStream classes,
  35. // which wrap a ZeroCopyInputStream or ZeroCopyOutputStream, respectively,
  36. // and allow you to read or write individual pieces of data in various
  37. // formats. In particular, these implement the varint encoding for
  38. // integers, a simple variable-length encoding in which smaller numbers
  39. // take fewer bytes.
  40. //
  41. // Typically these classes will only be used internally by the protocol
  42. // buffer library in order to encode and decode protocol buffers. Clients
  43. // of the library only need to know about this class if they wish to write
  44. // custom message parsing or serialization procedures.
  45. //
  46. // CodedOutputStream example:
  47. // // Write some data to "myfile". First we write a 4-byte "magic number"
  48. // // to identify the file type, then write a length-delimited string. The
  49. // // string is composed of a varint giving the length followed by the raw
  50. // // bytes.
  51. // int fd = open("myfile", O_CREAT | O_WRONLY);
  52. // ZeroCopyOutputStream* raw_output = new FileOutputStream(fd);
  53. // CodedOutputStream* coded_output = new CodedOutputStream(raw_output);
  54. //
  55. // int magic_number = 1234;
  56. // char text[] = "Hello world!";
  57. // coded_output->WriteLittleEndian32(magic_number);
  58. // coded_output->WriteVarint32(strlen(text));
  59. // coded_output->WriteRaw(text, strlen(text));
  60. //
  61. // delete coded_output;
  62. // delete raw_output;
  63. // close(fd);
  64. //
  65. // CodedInputStream example:
  66. // // Read a file created by the above code.
  67. // int fd = open("myfile", O_RDONLY);
  68. // ZeroCopyInputStream* raw_input = new FileInputStream(fd);
  69. // CodedInputStream* coded_input = new CodedInputStream(raw_input);
  70. //
  71. // coded_input->ReadLittleEndian32(&magic_number);
  72. // if (magic_number != 1234) {
  73. // cerr << "File not in expected format." << endl;
  74. // return;
  75. // }
  76. //
  77. // uint32 size;
  78. // coded_input->ReadVarint32(&size);
  79. //
  80. // char* text = new char[size + 1];
  81. // coded_input->ReadRaw(buffer, size);
  82. // text[size] = '\0';
  83. //
  84. // delete coded_input;
  85. // delete raw_input;
  86. // close(fd);
  87. //
  88. // cout << "Text is: " << text << endl;
  89. // delete [] text;
  90. //
  91. // For those who are interested, varint encoding is defined as follows:
  92. //
  93. // The encoding operates on unsigned integers of up to 64 bits in length.
  94. // Each byte of the encoded value has the format:
  95. // * bits 0-6: Seven bits of the number being encoded.
  96. // * bit 7: Zero if this is the last byte in the encoding (in which
  97. // case all remaining bits of the number are zero) or 1 if
  98. // more bytes follow.
  99. // The first byte contains the least-significant 7 bits of the number, the
  100. // second byte (if present) contains the next-least-significant 7 bits,
  101. // and so on. So, the binary number 1011000101011 would be encoded in two
  102. // bytes as "10101011 00101100".
  103. //
  104. // In theory, varint could be used to encode integers of any length.
  105. // However, for practicality we set a limit at 64 bits. The maximum encoded
  106. // length of a number is thus 10 bytes.
  107. #ifndef GOOGLE_PROTOBUF_IO_CODED_STREAM_H__
  108. #define GOOGLE_PROTOBUF_IO_CODED_STREAM_H__
  109. #include <assert.h>
  110. #include <atomic>
  111. #include <climits>
  112. #include <cstddef>
  113. #include <cstring>
  114. #include <string>
  115. #include <type_traits>
  116. #include <utility>
  117. #ifdef _MSC_VER
  118. // Assuming windows is always little-endian.
  119. #if !defined(PROTOBUF_DISABLE_LITTLE_ENDIAN_OPT_FOR_TEST)
  120. #define PROTOBUF_LITTLE_ENDIAN 1
  121. #endif
  122. #if _MSC_VER >= 1300 && !defined(__INTEL_COMPILER)
  123. // If MSVC has "/RTCc" set, it will complain about truncating casts at
  124. // runtime. This file contains some intentional truncating casts.
  125. #pragma runtime_checks("c", off)
  126. #endif
  127. #else
  128. #include <sys/param.h> // __BYTE_ORDER
  129. #if ((defined(__LITTLE_ENDIAN__) && !defined(__BIG_ENDIAN__)) || \
  130. (defined(__BYTE_ORDER) && __BYTE_ORDER == __LITTLE_ENDIAN)) && \
  131. !defined(PROTOBUF_DISABLE_LITTLE_ENDIAN_OPT_FOR_TEST)
  132. #define PROTOBUF_LITTLE_ENDIAN 1
  133. #endif
  134. #endif
  135. #include <google/protobuf/stubs/common.h>
  136. #include <google/protobuf/stubs/logging.h>
  137. #include <google/protobuf/stubs/strutil.h>
  138. #include <google/protobuf/port.h>
  139. #include <google/protobuf/stubs/port.h>
  140. #include <google/protobuf/port_def.inc>
  141. namespace google {
  142. namespace protobuf {
  143. class DescriptorPool;
  144. class MessageFactory;
  145. class ZeroCopyCodedInputStream;
  146. namespace internal {
  147. void MapTestForceDeterministic();
  148. class EpsCopyByteStream;
  149. } // namespace internal
  150. namespace io {
  151. // Defined in this file.
  152. class CodedInputStream;
  153. class CodedOutputStream;
  154. // Defined in other files.
  155. class ZeroCopyInputStream; // zero_copy_stream.h
  156. class ZeroCopyOutputStream; // zero_copy_stream.h
  157. // Class which reads and decodes binary data which is composed of varint-
  158. // encoded integers and fixed-width pieces. Wraps a ZeroCopyInputStream.
  159. // Most users will not need to deal with CodedInputStream.
  160. //
  161. // Most methods of CodedInputStream that return a bool return false if an
  162. // underlying I/O error occurs or if the data is malformed. Once such a
  163. // failure occurs, the CodedInputStream is broken and is no longer useful.
  164. // After a failure, callers also should assume writes to "out" args may have
  165. // occurred, though nothing useful can be determined from those writes.
  166. class PROTOBUF_EXPORT CodedInputStream {
  167. public:
  168. // Create a CodedInputStream that reads from the given ZeroCopyInputStream.
  169. explicit CodedInputStream(ZeroCopyInputStream* input);
  170. // Create a CodedInputStream that reads from the given flat array. This is
  171. // faster than using an ArrayInputStream. PushLimit(size) is implied by
  172. // this constructor.
  173. explicit CodedInputStream(const uint8* buffer, int size);
  174. // Destroy the CodedInputStream and position the underlying
  175. // ZeroCopyInputStream at the first unread byte. If an error occurred while
  176. // reading (causing a method to return false), then the exact position of
  177. // the input stream may be anywhere between the last value that was read
  178. // successfully and the stream's byte limit.
  179. ~CodedInputStream();
  180. // Return true if this CodedInputStream reads from a flat array instead of
  181. // a ZeroCopyInputStream.
  182. inline bool IsFlat() const;
  183. // Skips a number of bytes. Returns false if an underlying read error
  184. // occurs.
  185. inline bool Skip(int count);
  186. // Sets *data to point directly at the unread part of the CodedInputStream's
  187. // underlying buffer, and *size to the size of that buffer, but does not
  188. // advance the stream's current position. This will always either produce
  189. // a non-empty buffer or return false. If the caller consumes any of
  190. // this data, it should then call Skip() to skip over the consumed bytes.
  191. // This may be useful for implementing external fast parsing routines for
  192. // types of data not covered by the CodedInputStream interface.
  193. bool GetDirectBufferPointer(const void** data, int* size);
  194. // Like GetDirectBufferPointer, but this method is inlined, and does not
  195. // attempt to Refresh() if the buffer is currently empty.
  196. PROTOBUF_ALWAYS_INLINE
  197. void GetDirectBufferPointerInline(const void** data, int* size);
  198. // Read raw bytes, copying them into the given buffer.
  199. bool ReadRaw(void* buffer, int size);
  200. // Like ReadRaw, but reads into a string.
  201. bool ReadString(std::string* buffer, int size);
  202. // Read a 32-bit little-endian integer.
  203. bool ReadLittleEndian32(uint32* value);
  204. // Read a 64-bit little-endian integer.
  205. bool ReadLittleEndian64(uint64* value);
  206. // These methods read from an externally provided buffer. The caller is
  207. // responsible for ensuring that the buffer has sufficient space.
  208. // Read a 32-bit little-endian integer.
  209. static const uint8* ReadLittleEndian32FromArray(const uint8* buffer,
  210. uint32* value);
  211. // Read a 64-bit little-endian integer.
  212. static const uint8* ReadLittleEndian64FromArray(const uint8* buffer,
  213. uint64* value);
  214. // Read an unsigned integer with Varint encoding, truncating to 32 bits.
  215. // Reading a 32-bit value is equivalent to reading a 64-bit one and casting
  216. // it to uint32, but may be more efficient.
  217. bool ReadVarint32(uint32* value);
  218. // Read an unsigned integer with Varint encoding.
  219. bool ReadVarint64(uint64* value);
  220. // Reads a varint off the wire into an "int". This should be used for reading
  221. // sizes off the wire (sizes of strings, submessages, bytes fields, etc).
  222. //
  223. // The value from the wire is interpreted as unsigned. If its value exceeds
  224. // the representable value of an integer on this platform, instead of
  225. // truncating we return false. Truncating (as performed by ReadVarint32()
  226. // above) is an acceptable approach for fields representing an integer, but
  227. // when we are parsing a size from the wire, truncating the value would result
  228. // in us misparsing the payload.
  229. bool ReadVarintSizeAsInt(int* value);
  230. // Read a tag. This calls ReadVarint32() and returns the result, or returns
  231. // zero (which is not a valid tag) if ReadVarint32() fails. Also, ReadTag
  232. // (but not ReadTagNoLastTag) updates the last tag value, which can be checked
  233. // with LastTagWas().
  234. //
  235. // Always inline because this is only called in one place per parse loop
  236. // but it is called for every iteration of said loop, so it should be fast.
  237. // GCC doesn't want to inline this by default.
  238. PROTOBUF_ALWAYS_INLINE uint32 ReadTag() {
  239. return last_tag_ = ReadTagNoLastTag();
  240. }
  241. PROTOBUF_ALWAYS_INLINE uint32 ReadTagNoLastTag();
  242. // This usually a faster alternative to ReadTag() when cutoff is a manifest
  243. // constant. It does particularly well for cutoff >= 127. The first part
  244. // of the return value is the tag that was read, though it can also be 0 in
  245. // the cases where ReadTag() would return 0. If the second part is true
  246. // then the tag is known to be in [0, cutoff]. If not, the tag either is
  247. // above cutoff or is 0. (There's intentional wiggle room when tag is 0,
  248. // because that can arise in several ways, and for best performance we want
  249. // to avoid an extra "is tag == 0?" check here.)
  250. PROTOBUF_ALWAYS_INLINE
  251. std::pair<uint32, bool> ReadTagWithCutoff(uint32 cutoff) {
  252. std::pair<uint32, bool> result = ReadTagWithCutoffNoLastTag(cutoff);
  253. last_tag_ = result.first;
  254. return result;
  255. }
  256. PROTOBUF_ALWAYS_INLINE
  257. std::pair<uint32, bool> ReadTagWithCutoffNoLastTag(uint32 cutoff);
  258. // Usually returns true if calling ReadVarint32() now would produce the given
  259. // value. Will always return false if ReadVarint32() would not return the
  260. // given value. If ExpectTag() returns true, it also advances past
  261. // the varint. For best performance, use a compile-time constant as the
  262. // parameter.
  263. // Always inline because this collapses to a small number of instructions
  264. // when given a constant parameter, but GCC doesn't want to inline by default.
  265. PROTOBUF_ALWAYS_INLINE bool ExpectTag(uint32 expected);
  266. // Like above, except this reads from the specified buffer. The caller is
  267. // responsible for ensuring that the buffer is large enough to read a varint
  268. // of the expected size. For best performance, use a compile-time constant as
  269. // the expected tag parameter.
  270. //
  271. // Returns a pointer beyond the expected tag if it was found, or NULL if it
  272. // was not.
  273. PROTOBUF_ALWAYS_INLINE
  274. static const uint8* ExpectTagFromArray(const uint8* buffer, uint32 expected);
  275. // Usually returns true if no more bytes can be read. Always returns false
  276. // if more bytes can be read. If ExpectAtEnd() returns true, a subsequent
  277. // call to LastTagWas() will act as if ReadTag() had been called and returned
  278. // zero, and ConsumedEntireMessage() will return true.
  279. bool ExpectAtEnd();
  280. // If the last call to ReadTag() or ReadTagWithCutoff() returned the given
  281. // value, returns true. Otherwise, returns false.
  282. // ReadTagNoLastTag/ReadTagWithCutoffNoLastTag do not preserve the last
  283. // returned value.
  284. //
  285. // This is needed because parsers for some types of embedded messages
  286. // (with field type TYPE_GROUP) don't actually know that they've reached the
  287. // end of a message until they see an ENDGROUP tag, which was actually part
  288. // of the enclosing message. The enclosing message would like to check that
  289. // tag to make sure it had the right number, so it calls LastTagWas() on
  290. // return from the embedded parser to check.
  291. bool LastTagWas(uint32 expected);
  292. void SetLastTag(uint32 tag) { last_tag_ = tag; }
  293. // When parsing message (but NOT a group), this method must be called
  294. // immediately after MergeFromCodedStream() returns (if it returns true)
  295. // to further verify that the message ended in a legitimate way. For
  296. // example, this verifies that parsing did not end on an end-group tag.
  297. // It also checks for some cases where, due to optimizations,
  298. // MergeFromCodedStream() can incorrectly return true.
  299. bool ConsumedEntireMessage();
  300. void SetConsumed() { legitimate_message_end_ = true; }
  301. // Limits ----------------------------------------------------------
  302. // Limits are used when parsing length-delimited embedded messages.
  303. // After the message's length is read, PushLimit() is used to prevent
  304. // the CodedInputStream from reading beyond that length. Once the
  305. // embedded message has been parsed, PopLimit() is called to undo the
  306. // limit.
  307. // Opaque type used with PushLimit() and PopLimit(). Do not modify
  308. // values of this type yourself. The only reason that this isn't a
  309. // struct with private internals is for efficiency.
  310. typedef int Limit;
  311. // Places a limit on the number of bytes that the stream may read,
  312. // starting from the current position. Once the stream hits this limit,
  313. // it will act like the end of the input has been reached until PopLimit()
  314. // is called.
  315. //
  316. // As the names imply, the stream conceptually has a stack of limits. The
  317. // shortest limit on the stack is always enforced, even if it is not the
  318. // top limit.
  319. //
  320. // The value returned by PushLimit() is opaque to the caller, and must
  321. // be passed unchanged to the corresponding call to PopLimit().
  322. Limit PushLimit(int byte_limit);
  323. // Pops the last limit pushed by PushLimit(). The input must be the value
  324. // returned by that call to PushLimit().
  325. void PopLimit(Limit limit);
  326. // Returns the number of bytes left until the nearest limit on the
  327. // stack is hit, or -1 if no limits are in place.
  328. int BytesUntilLimit() const;
  329. // Returns current position relative to the beginning of the input stream.
  330. int CurrentPosition() const;
  331. // Total Bytes Limit -----------------------------------------------
  332. // To prevent malicious users from sending excessively large messages
  333. // and causing memory exhaustion, CodedInputStream imposes a hard limit on
  334. // the total number of bytes it will read.
  335. // Sets the maximum number of bytes that this CodedInputStream will read
  336. // before refusing to continue. To prevent servers from allocating enormous
  337. // amounts of memory to hold parsed messages, the maximum message length
  338. // should be limited to the shortest length that will not harm usability.
  339. // The default limit is INT_MAX (~2GB) and apps should set shorter limits
  340. // if possible. An error will always be printed to stderr if the limit is
  341. // reached.
  342. //
  343. // Note: setting a limit less than the current read position is interpreted
  344. // as a limit on the current position.
  345. //
  346. // This is unrelated to PushLimit()/PopLimit().
  347. void SetTotalBytesLimit(int total_bytes_limit);
  348. PROTOBUF_DEPRECATED_MSG(
  349. "Please use the single parameter version of SetTotalBytesLimit(). The "
  350. "second parameter is ignored.")
  351. void SetTotalBytesLimit(int total_bytes_limit, int) {
  352. SetTotalBytesLimit(total_bytes_limit);
  353. }
  354. // The Total Bytes Limit minus the Current Position, or -1 if the total bytes
  355. // limit is INT_MAX.
  356. int BytesUntilTotalBytesLimit() const;
  357. // Recursion Limit -------------------------------------------------
  358. // To prevent corrupt or malicious messages from causing stack overflows,
  359. // we must keep track of the depth of recursion when parsing embedded
  360. // messages and groups. CodedInputStream keeps track of this because it
  361. // is the only object that is passed down the stack during parsing.
  362. // Sets the maximum recursion depth. The default is 100.
  363. void SetRecursionLimit(int limit);
  364. int RecursionBudget() { return recursion_budget_; }
  365. static int GetDefaultRecursionLimit() { return default_recursion_limit_; }
  366. // Increments the current recursion depth. Returns true if the depth is
  367. // under the limit, false if it has gone over.
  368. bool IncrementRecursionDepth();
  369. // Decrements the recursion depth if possible.
  370. void DecrementRecursionDepth();
  371. // Decrements the recursion depth blindly. This is faster than
  372. // DecrementRecursionDepth(). It should be used only if all previous
  373. // increments to recursion depth were successful.
  374. void UnsafeDecrementRecursionDepth();
  375. // Shorthand for make_pair(PushLimit(byte_limit), --recursion_budget_).
  376. // Using this can reduce code size and complexity in some cases. The caller
  377. // is expected to check that the second part of the result is non-negative (to
  378. // bail out if the depth of recursion is too high) and, if all is well, to
  379. // later pass the first part of the result to PopLimit() or similar.
  380. std::pair<CodedInputStream::Limit, int> IncrementRecursionDepthAndPushLimit(
  381. int byte_limit);
  382. // Shorthand for PushLimit(ReadVarint32(&length) ? length : 0).
  383. Limit ReadLengthAndPushLimit();
  384. // Helper that is equivalent to: {
  385. // bool result = ConsumedEntireMessage();
  386. // PopLimit(limit);
  387. // UnsafeDecrementRecursionDepth();
  388. // return result; }
  389. // Using this can reduce code size and complexity in some cases.
  390. // Do not use unless the current recursion depth is greater than zero.
  391. bool DecrementRecursionDepthAndPopLimit(Limit limit);
  392. // Helper that is equivalent to: {
  393. // bool result = ConsumedEntireMessage();
  394. // PopLimit(limit);
  395. // return result; }
  396. // Using this can reduce code size and complexity in some cases.
  397. bool CheckEntireMessageConsumedAndPopLimit(Limit limit);
  398. // Extension Registry ----------------------------------------------
  399. // ADVANCED USAGE: 99.9% of people can ignore this section.
  400. //
  401. // By default, when parsing extensions, the parser looks for extension
  402. // definitions in the pool which owns the outer message's Descriptor.
  403. // However, you may call SetExtensionRegistry() to provide an alternative
  404. // pool instead. This makes it possible, for example, to parse a message
  405. // using a generated class, but represent some extensions using
  406. // DynamicMessage.
  407. // Set the pool used to look up extensions. Most users do not need to call
  408. // this as the correct pool will be chosen automatically.
  409. //
  410. // WARNING: It is very easy to misuse this. Carefully read the requirements
  411. // below. Do not use this unless you are sure you need it. Almost no one
  412. // does.
  413. //
  414. // Let's say you are parsing a message into message object m, and you want
  415. // to take advantage of SetExtensionRegistry(). You must follow these
  416. // requirements:
  417. //
  418. // The given DescriptorPool must contain m->GetDescriptor(). It is not
  419. // sufficient for it to simply contain a descriptor that has the same name
  420. // and content -- it must be the *exact object*. In other words:
  421. // assert(pool->FindMessageTypeByName(m->GetDescriptor()->full_name()) ==
  422. // m->GetDescriptor());
  423. // There are two ways to satisfy this requirement:
  424. // 1) Use m->GetDescriptor()->pool() as the pool. This is generally useless
  425. // because this is the pool that would be used anyway if you didn't call
  426. // SetExtensionRegistry() at all.
  427. // 2) Use a DescriptorPool which has m->GetDescriptor()->pool() as an
  428. // "underlay". Read the documentation for DescriptorPool for more
  429. // information about underlays.
  430. //
  431. // You must also provide a MessageFactory. This factory will be used to
  432. // construct Message objects representing extensions. The factory's
  433. // GetPrototype() MUST return non-NULL for any Descriptor which can be found
  434. // through the provided pool.
  435. //
  436. // If the provided factory might return instances of protocol-compiler-
  437. // generated (i.e. compiled-in) types, or if the outer message object m is
  438. // a generated type, then the given factory MUST have this property: If
  439. // GetPrototype() is given a Descriptor which resides in
  440. // DescriptorPool::generated_pool(), the factory MUST return the same
  441. // prototype which MessageFactory::generated_factory() would return. That
  442. // is, given a descriptor for a generated type, the factory must return an
  443. // instance of the generated class (NOT DynamicMessage). However, when
  444. // given a descriptor for a type that is NOT in generated_pool, the factory
  445. // is free to return any implementation.
  446. //
  447. // The reason for this requirement is that generated sub-objects may be
  448. // accessed via the standard (non-reflection) extension accessor methods,
  449. // and these methods will down-cast the object to the generated class type.
  450. // If the object is not actually of that type, the results would be undefined.
  451. // On the other hand, if an extension is not compiled in, then there is no
  452. // way the code could end up accessing it via the standard accessors -- the
  453. // only way to access the extension is via reflection. When using reflection,
  454. // DynamicMessage and generated messages are indistinguishable, so it's fine
  455. // if these objects are represented using DynamicMessage.
  456. //
  457. // Using DynamicMessageFactory on which you have called
  458. // SetDelegateToGeneratedFactory(true) should be sufficient to satisfy the
  459. // above requirement.
  460. //
  461. // If either pool or factory is NULL, both must be NULL.
  462. //
  463. // Note that this feature is ignored when parsing "lite" messages as they do
  464. // not have descriptors.
  465. void SetExtensionRegistry(const DescriptorPool* pool,
  466. MessageFactory* factory);
  467. // Get the DescriptorPool set via SetExtensionRegistry(), or NULL if no pool
  468. // has been provided.
  469. const DescriptorPool* GetExtensionPool();
  470. // Get the MessageFactory set via SetExtensionRegistry(), or NULL if no
  471. // factory has been provided.
  472. MessageFactory* GetExtensionFactory();
  473. private:
  474. GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(CodedInputStream);
  475. const uint8* buffer_;
  476. const uint8* buffer_end_; // pointer to the end of the buffer.
  477. ZeroCopyInputStream* input_;
  478. int total_bytes_read_; // total bytes read from input_, including
  479. // the current buffer
  480. // If total_bytes_read_ surpasses INT_MAX, we record the extra bytes here
  481. // so that we can BackUp() on destruction.
  482. int overflow_bytes_;
  483. // LastTagWas() stuff.
  484. uint32 last_tag_; // result of last ReadTag() or ReadTagWithCutoff().
  485. // This is set true by ReadTag{Fallback/Slow}() if it is called when exactly
  486. // at EOF, or by ExpectAtEnd() when it returns true. This happens when we
  487. // reach the end of a message and attempt to read another tag.
  488. bool legitimate_message_end_;
  489. // See EnableAliasing().
  490. bool aliasing_enabled_;
  491. // Limits
  492. Limit current_limit_; // if position = -1, no limit is applied
  493. // For simplicity, if the current buffer crosses a limit (either a normal
  494. // limit created by PushLimit() or the total bytes limit), buffer_size_
  495. // only tracks the number of bytes before that limit. This field
  496. // contains the number of bytes after it. Note that this implies that if
  497. // buffer_size_ == 0 and buffer_size_after_limit_ > 0, we know we've
  498. // hit a limit. However, if both are zero, it doesn't necessarily mean
  499. // we aren't at a limit -- the buffer may have ended exactly at the limit.
  500. int buffer_size_after_limit_;
  501. // Maximum number of bytes to read, period. This is unrelated to
  502. // current_limit_. Set using SetTotalBytesLimit().
  503. int total_bytes_limit_;
  504. // Current recursion budget, controlled by IncrementRecursionDepth() and
  505. // similar. Starts at recursion_limit_ and goes down: if this reaches
  506. // -1 we are over budget.
  507. int recursion_budget_;
  508. // Recursion depth limit, set by SetRecursionLimit().
  509. int recursion_limit_;
  510. // See SetExtensionRegistry().
  511. const DescriptorPool* extension_pool_;
  512. MessageFactory* extension_factory_;
  513. // Private member functions.
  514. // Fallback when Skip() goes past the end of the current buffer.
  515. bool SkipFallback(int count, int original_buffer_size);
  516. // Advance the buffer by a given number of bytes.
  517. void Advance(int amount);
  518. // Back up input_ to the current buffer position.
  519. void BackUpInputToCurrentPosition();
  520. // Recomputes the value of buffer_size_after_limit_. Must be called after
  521. // current_limit_ or total_bytes_limit_ changes.
  522. void RecomputeBufferLimits();
  523. // Writes an error message saying that we hit total_bytes_limit_.
  524. void PrintTotalBytesLimitError();
  525. // Called when the buffer runs out to request more data. Implies an
  526. // Advance(BufferSize()).
  527. bool Refresh();
  528. // When parsing varints, we optimize for the common case of small values, and
  529. // then optimize for the case when the varint fits within the current buffer
  530. // piece. The Fallback method is used when we can't use the one-byte
  531. // optimization. The Slow method is yet another fallback when the buffer is
  532. // not large enough. Making the slow path out-of-line speeds up the common
  533. // case by 10-15%. The slow path is fairly uncommon: it only triggers when a
  534. // message crosses multiple buffers. Note: ReadVarint32Fallback() and
  535. // ReadVarint64Fallback() are called frequently and generally not inlined, so
  536. // they have been optimized to avoid "out" parameters. The former returns -1
  537. // if it fails and the uint32 it read otherwise. The latter has a bool
  538. // indicating success or failure as part of its return type.
  539. int64 ReadVarint32Fallback(uint32 first_byte_or_zero);
  540. int ReadVarintSizeAsIntFallback();
  541. std::pair<uint64, bool> ReadVarint64Fallback();
  542. bool ReadVarint32Slow(uint32* value);
  543. bool ReadVarint64Slow(uint64* value);
  544. int ReadVarintSizeAsIntSlow();
  545. bool ReadLittleEndian32Fallback(uint32* value);
  546. bool ReadLittleEndian64Fallback(uint64* value);
  547. // Fallback/slow methods for reading tags. These do not update last_tag_,
  548. // but will set legitimate_message_end_ if we are at the end of the input
  549. // stream.
  550. uint32 ReadTagFallback(uint32 first_byte_or_zero);
  551. uint32 ReadTagSlow();
  552. bool ReadStringFallback(std::string* buffer, int size);
  553. // Return the size of the buffer.
  554. int BufferSize() const;
  555. static const int kDefaultTotalBytesLimit = INT_MAX;
  556. static int default_recursion_limit_; // 100 by default.
  557. friend class google::protobuf::ZeroCopyCodedInputStream;
  558. friend class google::protobuf::internal::EpsCopyByteStream;
  559. };
  560. // EpsCopyOutputStream wraps a ZeroCopyOutputStream and exposes a new stream,
  561. // which has the property you can write kSlopBytes (16 bytes) from the current
  562. // position without bounds checks. The cursor into the stream is managed by
  563. // the user of the class and is an explicit parameter in the methods. Careful
  564. // use of this class, ie. keep ptr a local variable, eliminates the need to
  565. // for the compiler to sync the ptr value between register and memory.
  566. class PROTOBUF_EXPORT EpsCopyOutputStream {
  567. public:
  568. enum { kSlopBytes = 16 };
  569. // Initialize from a stream.
  570. EpsCopyOutputStream(ZeroCopyOutputStream* stream, bool deterministic,
  571. uint8** pp)
  572. : end_(buffer_),
  573. stream_(stream),
  574. is_serialization_deterministic_(deterministic) {
  575. *pp = buffer_;
  576. }
  577. // Only for array serialization. No overflow protection, end_ will be the
  578. // pointed to the end of the array. When using this the total size is already
  579. // known, so no need to maintain the slop region.
  580. EpsCopyOutputStream(void* data, int size, bool deterministic)
  581. : end_(static_cast<uint8*>(data) + size),
  582. buffer_end_(nullptr),
  583. stream_(nullptr),
  584. is_serialization_deterministic_(deterministic) {}
  585. // Initialize from stream but with the first buffer already given (eager).
  586. EpsCopyOutputStream(void* data, int size, ZeroCopyOutputStream* stream,
  587. bool deterministic, uint8** pp)
  588. : stream_(stream), is_serialization_deterministic_(deterministic) {
  589. *pp = SetInitialBuffer(data, size);
  590. }
  591. // Flush everything that's written into the underlying ZeroCopyOutputStream
  592. // and trims the underlying stream to the location of ptr.
  593. uint8* Trim(uint8* ptr);
  594. // After this it's guaranteed you can safely write kSlopBytes to ptr. This
  595. // will never fail! The underlying stream can produce an error. Use HadError
  596. // to check for errors.
  597. PROTOBUF_MUST_USE_RESULT uint8* EnsureSpace(uint8* ptr) {
  598. if (PROTOBUF_PREDICT_FALSE(ptr >= end_)) {
  599. return EnsureSpaceFallback(ptr);
  600. }
  601. return ptr;
  602. }
  603. uint8* WriteRaw(const void* data, int size, uint8* ptr) {
  604. if (PROTOBUF_PREDICT_FALSE(end_ - ptr < size)) {
  605. return WriteRawFallback(data, size, ptr);
  606. }
  607. std::memcpy(ptr, data, size);
  608. return ptr + size;
  609. }
  610. // Writes the buffer specified by data, size to the stream. Possibly by
  611. // aliasing the buffer (ie. not copying the data). The caller is responsible
  612. // to make sure the buffer is alive for the duration of the
  613. // ZeroCopyOutputStream.
  614. uint8* WriteRawMaybeAliased(const void* data, int size, uint8* ptr) {
  615. if (aliasing_enabled_) {
  616. return WriteAliasedRaw(data, size, ptr);
  617. } else {
  618. return WriteRaw(data, size, ptr);
  619. }
  620. }
  621. uint8* WriteStringMaybeAliased(uint32 num, const std::string& s, uint8* ptr) {
  622. std::ptrdiff_t size = s.size();
  623. if (PROTOBUF_PREDICT_FALSE(
  624. size >= 128 || end_ - ptr + 16 - TagSize(num << 3) - 1 < size)) {
  625. return WriteStringMaybeAliasedOutline(num, s, ptr);
  626. }
  627. ptr = UnsafeVarint((num << 3) | 2, ptr);
  628. *ptr++ = static_cast<uint8>(size);
  629. std::memcpy(ptr, s.data(), size);
  630. return ptr + size;
  631. }
  632. uint8* WriteBytesMaybeAliased(uint32 num, const std::string& s, uint8* ptr) {
  633. return WriteStringMaybeAliased(num, s, ptr);
  634. }
  635. template <typename T>
  636. PROTOBUF_ALWAYS_INLINE uint8* WriteString(uint32 num, const T& s,
  637. uint8* ptr) {
  638. std::ptrdiff_t size = s.size();
  639. if (PROTOBUF_PREDICT_FALSE(
  640. size >= 128 || end_ - ptr + 16 - TagSize(num << 3) - 1 < size)) {
  641. return WriteStringOutline(num, s, ptr);
  642. }
  643. ptr = UnsafeVarint((num << 3) | 2, ptr);
  644. *ptr++ = static_cast<uint8>(size);
  645. std::memcpy(ptr, s.data(), size);
  646. return ptr + size;
  647. }
  648. template <typename T>
  649. uint8* WriteBytes(uint32 num, const T& s, uint8* ptr) {
  650. return WriteString(num, s, ptr);
  651. }
  652. template <typename T>
  653. PROTOBUF_ALWAYS_INLINE uint8* WriteInt32Packed(int num, const T& r, int size,
  654. uint8* ptr) {
  655. return WriteVarintPacked(num, r, size, ptr, Encode64);
  656. }
  657. template <typename T>
  658. PROTOBUF_ALWAYS_INLINE uint8* WriteUInt32Packed(int num, const T& r, int size,
  659. uint8* ptr) {
  660. return WriteVarintPacked(num, r, size, ptr, Encode32);
  661. }
  662. template <typename T>
  663. PROTOBUF_ALWAYS_INLINE uint8* WriteSInt32Packed(int num, const T& r, int size,
  664. uint8* ptr) {
  665. return WriteVarintPacked(num, r, size, ptr, ZigZagEncode32);
  666. }
  667. template <typename T>
  668. PROTOBUF_ALWAYS_INLINE uint8* WriteInt64Packed(int num, const T& r, int size,
  669. uint8* ptr) {
  670. return WriteVarintPacked(num, r, size, ptr, Encode64);
  671. }
  672. template <typename T>
  673. PROTOBUF_ALWAYS_INLINE uint8* WriteUInt64Packed(int num, const T& r, int size,
  674. uint8* ptr) {
  675. return WriteVarintPacked(num, r, size, ptr, Encode64);
  676. }
  677. template <typename T>
  678. PROTOBUF_ALWAYS_INLINE uint8* WriteSInt64Packed(int num, const T& r, int size,
  679. uint8* ptr) {
  680. return WriteVarintPacked(num, r, size, ptr, ZigZagEncode64);
  681. }
  682. template <typename T>
  683. PROTOBUF_ALWAYS_INLINE uint8* WriteEnumPacked(int num, const T& r, int size,
  684. uint8* ptr) {
  685. return WriteVarintPacked(num, r, size, ptr, Encode64);
  686. }
  687. template <typename T>
  688. PROTOBUF_ALWAYS_INLINE uint8* WriteFixedPacked(int num, const T& r,
  689. uint8* ptr) {
  690. ptr = EnsureSpace(ptr);
  691. constexpr auto element_size = sizeof(typename T::value_type);
  692. auto size = r.size() * element_size;
  693. ptr = WriteLengthDelim(num, size, ptr);
  694. return WriteRawLittleEndian<element_size>(r.data(), static_cast<int>(size),
  695. ptr);
  696. }
  697. // Returns true if there was an underlying I/O error since this object was
  698. // created.
  699. bool HadError() const { return had_error_; }
  700. // Instructs the EpsCopyOutputStream to allow the underlying
  701. // ZeroCopyOutputStream to hold pointers to the original structure instead of
  702. // copying, if it supports it (i.e. output->AllowsAliasing() is true). If the
  703. // underlying stream does not support aliasing, then enabling it has no
  704. // affect. For now, this only affects the behavior of
  705. // WriteRawMaybeAliased().
  706. //
  707. // NOTE: It is caller's responsibility to ensure that the chunk of memory
  708. // remains live until all of the data has been consumed from the stream.
  709. void EnableAliasing(bool enabled);
  710. // See documentation on CodedOutputStream::SetSerializationDeterministic.
  711. void SetSerializationDeterministic(bool value) {
  712. is_serialization_deterministic_ = value;
  713. }
  714. // See documentation on CodedOutputStream::IsSerializationDeterministic.
  715. bool IsSerializationDeterministic() const {
  716. return is_serialization_deterministic_;
  717. }
  718. // The number of bytes writen to the stream at position ptr, relative to the
  719. // stream's overall position.
  720. int64 ByteCount(uint8* ptr) const;
  721. private:
  722. uint8* end_;
  723. uint8* buffer_end_ = buffer_;
  724. uint8 buffer_[2 * kSlopBytes];
  725. ZeroCopyOutputStream* stream_;
  726. bool had_error_ = false;
  727. bool aliasing_enabled_ = false; // See EnableAliasing().
  728. bool is_serialization_deterministic_;
  729. uint8* EnsureSpaceFallback(uint8* ptr);
  730. inline uint8* Next();
  731. int Flush(uint8* ptr);
  732. std::ptrdiff_t GetSize(uint8* ptr) const {
  733. GOOGLE_DCHECK(ptr <= end_ + kSlopBytes); // NOLINT
  734. return end_ + kSlopBytes - ptr;
  735. }
  736. uint8* Error() {
  737. had_error_ = true;
  738. // We use the patch buffer to always guarantee space to write to.
  739. end_ = buffer_ + kSlopBytes;
  740. return buffer_;
  741. }
  742. static constexpr int TagSize(uint32 tag) {
  743. return (tag < (1 << 7))
  744. ? 1
  745. : (tag < (1 << 14))
  746. ? 2
  747. : (tag < (1 << 21)) ? 3 : (tag < (1 << 28)) ? 4 : 5;
  748. }
  749. PROTOBUF_ALWAYS_INLINE uint8* WriteTag(uint32 num, uint32 wt, uint8* ptr) {
  750. GOOGLE_DCHECK(ptr < end_); // NOLINT
  751. return UnsafeVarint((num << 3) | wt, ptr);
  752. }
  753. PROTOBUF_ALWAYS_INLINE uint8* WriteLengthDelim(int num, uint32 size,
  754. uint8* ptr) {
  755. ptr = WriteTag(num, 2, ptr);
  756. return UnsafeWriteSize(size, ptr);
  757. }
  758. uint8* WriteRawFallback(const void* data, int size, uint8* ptr);
  759. uint8* WriteAliasedRaw(const void* data, int size, uint8* ptr);
  760. uint8* WriteStringMaybeAliasedOutline(uint32 num, const std::string& s,
  761. uint8* ptr);
  762. uint8* WriteStringOutline(uint32 num, const std::string& s, uint8* ptr);
  763. template <typename T, typename E>
  764. PROTOBUF_ALWAYS_INLINE uint8* WriteVarintPacked(int num, const T& r, int size,
  765. uint8* ptr, const E& encode) {
  766. ptr = EnsureSpace(ptr);
  767. ptr = WriteLengthDelim(num, size, ptr);
  768. auto it = r.data();
  769. auto end = it + r.size();
  770. do {
  771. ptr = EnsureSpace(ptr);
  772. ptr = UnsafeVarint(encode(*it++), ptr);
  773. } while (it < end);
  774. return ptr;
  775. }
  776. static uint32 Encode32(uint32 v) { return v; }
  777. static uint64 Encode64(uint64 v) { return v; }
  778. static uint32 ZigZagEncode32(int32 v) {
  779. return (static_cast<uint32>(v) << 1) ^ static_cast<uint32>(v >> 31);
  780. }
  781. static uint64 ZigZagEncode64(int64 v) {
  782. return (static_cast<uint64>(v) << 1) ^ static_cast<uint64>(v >> 63);
  783. }
  784. template <typename T>
  785. PROTOBUF_ALWAYS_INLINE static uint8* UnsafeVarint(T value, uint8* ptr) {
  786. static_assert(std::is_unsigned<T>::value,
  787. "Varint serialization must be unsigned");
  788. if (value < 0x80) {
  789. ptr[0] = static_cast<uint8>(value);
  790. return ptr + 1;
  791. }
  792. ptr[0] = static_cast<uint8>(value | 0x80);
  793. value >>= 7;
  794. if (value < 0x80) {
  795. ptr[1] = static_cast<uint8>(value);
  796. return ptr + 2;
  797. }
  798. ptr++;
  799. do {
  800. *ptr = static_cast<uint8>(value | 0x80);
  801. value >>= 7;
  802. ++ptr;
  803. } while (PROTOBUF_PREDICT_FALSE(value >= 0x80));
  804. *ptr++ = static_cast<uint8>(value);
  805. return ptr;
  806. }
  807. PROTOBUF_ALWAYS_INLINE static uint8* UnsafeWriteSize(uint32 value,
  808. uint8* ptr) {
  809. while (PROTOBUF_PREDICT_FALSE(value >= 0x80)) {
  810. *ptr = static_cast<uint8>(value | 0x80);
  811. value >>= 7;
  812. ++ptr;
  813. }
  814. *ptr++ = static_cast<uint8>(value);
  815. return ptr;
  816. }
  817. template <int S>
  818. uint8* WriteRawLittleEndian(const void* data, int size, uint8* ptr);
  819. #ifndef PROTOBUF_LITTLE_ENDIAN
  820. uint8* WriteRawLittleEndian32(const void* data, int size, uint8* ptr);
  821. uint8* WriteRawLittleEndian64(const void* data, int size, uint8* ptr);
  822. #endif
  823. // These methods are for CodedOutputStream. Ideally they should be private
  824. // but to match current behavior of CodedOutputStream as close as possible
  825. // we allow it some functionality.
  826. public:
  827. uint8* SetInitialBuffer(void* data, int size) {
  828. auto ptr = static_cast<uint8*>(data);
  829. if (size > kSlopBytes) {
  830. end_ = ptr + size - kSlopBytes;
  831. buffer_end_ = nullptr;
  832. return ptr;
  833. } else {
  834. end_ = buffer_ + size;
  835. buffer_end_ = ptr;
  836. return buffer_;
  837. }
  838. }
  839. private:
  840. // Needed by CodedOutputStream HadError. HadError needs to flush the patch
  841. // buffers to ensure there is no error as of yet.
  842. uint8* FlushAndResetBuffer(uint8*);
  843. // The following functions mimick the old CodedOutputStream behavior as close
  844. // as possible. They flush the current state to the stream, behave as
  845. // the old CodedOutputStream and then return to normal operation.
  846. bool Skip(int count, uint8** pp);
  847. bool GetDirectBufferPointer(void** data, int* size, uint8** pp);
  848. uint8* GetDirectBufferForNBytesAndAdvance(int size, uint8** pp);
  849. friend class CodedOutputStream;
  850. };
  851. template <>
  852. inline uint8* EpsCopyOutputStream::WriteRawLittleEndian<1>(const void* data,
  853. int size,
  854. uint8* ptr) {
  855. return WriteRaw(data, size, ptr);
  856. }
  857. template <>
  858. inline uint8* EpsCopyOutputStream::WriteRawLittleEndian<4>(const void* data,
  859. int size,
  860. uint8* ptr) {
  861. #ifdef PROTOBUF_LITTLE_ENDIAN
  862. return WriteRaw(data, size, ptr);
  863. #else
  864. return WriteRawLittleEndian32(data, size, ptr);
  865. #endif
  866. }
  867. template <>
  868. inline uint8* EpsCopyOutputStream::WriteRawLittleEndian<8>(const void* data,
  869. int size,
  870. uint8* ptr) {
  871. #ifdef PROTOBUF_LITTLE_ENDIAN
  872. return WriteRaw(data, size, ptr);
  873. #else
  874. return WriteRawLittleEndian64(data, size, ptr);
  875. #endif
  876. }
  877. // Class which encodes and writes binary data which is composed of varint-
  878. // encoded integers and fixed-width pieces. Wraps a ZeroCopyOutputStream.
  879. // Most users will not need to deal with CodedOutputStream.
  880. //
  881. // Most methods of CodedOutputStream which return a bool return false if an
  882. // underlying I/O error occurs. Once such a failure occurs, the
  883. // CodedOutputStream is broken and is no longer useful. The Write* methods do
  884. // not return the stream status, but will invalidate the stream if an error
  885. // occurs. The client can probe HadError() to determine the status.
  886. //
  887. // Note that every method of CodedOutputStream which writes some data has
  888. // a corresponding static "ToArray" version. These versions write directly
  889. // to the provided buffer, returning a pointer past the last written byte.
  890. // They require that the buffer has sufficient capacity for the encoded data.
  891. // This allows an optimization where we check if an output stream has enough
  892. // space for an entire message before we start writing and, if there is, we
  893. // call only the ToArray methods to avoid doing bound checks for each
  894. // individual value.
  895. // i.e., in the example above:
  896. //
  897. // CodedOutputStream* coded_output = new CodedOutputStream(raw_output);
  898. // int magic_number = 1234;
  899. // char text[] = "Hello world!";
  900. //
  901. // int coded_size = sizeof(magic_number) +
  902. // CodedOutputStream::VarintSize32(strlen(text)) +
  903. // strlen(text);
  904. //
  905. // uint8* buffer =
  906. // coded_output->GetDirectBufferForNBytesAndAdvance(coded_size);
  907. // if (buffer != nullptr) {
  908. // // The output stream has enough space in the buffer: write directly to
  909. // // the array.
  910. // buffer = CodedOutputStream::WriteLittleEndian32ToArray(magic_number,
  911. // buffer);
  912. // buffer = CodedOutputStream::WriteVarint32ToArray(strlen(text), buffer);
  913. // buffer = CodedOutputStream::WriteRawToArray(text, strlen(text), buffer);
  914. // } else {
  915. // // Make bound-checked writes, which will ask the underlying stream for
  916. // // more space as needed.
  917. // coded_output->WriteLittleEndian32(magic_number);
  918. // coded_output->WriteVarint32(strlen(text));
  919. // coded_output->WriteRaw(text, strlen(text));
  920. // }
  921. //
  922. // delete coded_output;
  923. class PROTOBUF_EXPORT CodedOutputStream {
  924. public:
  925. // Create an CodedOutputStream that writes to the given ZeroCopyOutputStream.
  926. explicit CodedOutputStream(ZeroCopyOutputStream* stream)
  927. : CodedOutputStream(stream, true) {}
  928. CodedOutputStream(ZeroCopyOutputStream* stream, bool do_eager_refresh);
  929. // Destroy the CodedOutputStream and position the underlying
  930. // ZeroCopyOutputStream immediately after the last byte written.
  931. ~CodedOutputStream();
  932. // Returns true if there was an underlying I/O error since this object was
  933. // created. On should call Trim before this function in order to catch all
  934. // errors.
  935. bool HadError() {
  936. cur_ = impl_.FlushAndResetBuffer(cur_);
  937. GOOGLE_DCHECK(cur_);
  938. return impl_.HadError();
  939. }
  940. // Trims any unused space in the underlying buffer so that its size matches
  941. // the number of bytes written by this stream. The underlying buffer will
  942. // automatically be trimmed when this stream is destroyed; this call is only
  943. // necessary if the underlying buffer is accessed *before* the stream is
  944. // destroyed.
  945. void Trim() { cur_ = impl_.Trim(cur_); }
  946. // Skips a number of bytes, leaving the bytes unmodified in the underlying
  947. // buffer. Returns false if an underlying write error occurs. This is
  948. // mainly useful with GetDirectBufferPointer().
  949. // Note of caution, the skipped bytes may contain uninitialized data. The
  950. // caller must make sure that the skipped bytes are properly initialized,
  951. // otherwise you might leak bytes from your heap.
  952. bool Skip(int count) { return impl_.Skip(count, &cur_); }
  953. // Sets *data to point directly at the unwritten part of the
  954. // CodedOutputStream's underlying buffer, and *size to the size of that
  955. // buffer, but does not advance the stream's current position. This will
  956. // always either produce a non-empty buffer or return false. If the caller
  957. // writes any data to this buffer, it should then call Skip() to skip over
  958. // the consumed bytes. This may be useful for implementing external fast
  959. // serialization routines for types of data not covered by the
  960. // CodedOutputStream interface.
  961. bool GetDirectBufferPointer(void** data, int* size) {
  962. return impl_.GetDirectBufferPointer(data, size, &cur_);
  963. }
  964. // If there are at least "size" bytes available in the current buffer,
  965. // returns a pointer directly into the buffer and advances over these bytes.
  966. // The caller may then write directly into this buffer (e.g. using the
  967. // *ToArray static methods) rather than go through CodedOutputStream. If
  968. // there are not enough bytes available, returns NULL. The return pointer is
  969. // invalidated as soon as any other non-const method of CodedOutputStream
  970. // is called.
  971. inline uint8* GetDirectBufferForNBytesAndAdvance(int size) {
  972. return impl_.GetDirectBufferForNBytesAndAdvance(size, &cur_);
  973. }
  974. // Write raw bytes, copying them from the given buffer.
  975. void WriteRaw(const void* buffer, int size) {
  976. cur_ = impl_.WriteRaw(buffer, size, cur_);
  977. }
  978. // Like WriteRaw() but will try to write aliased data if aliasing is
  979. // turned on.
  980. void WriteRawMaybeAliased(const void* data, int size);
  981. // Like WriteRaw() but writing directly to the target array.
  982. // This is _not_ inlined, as the compiler often optimizes memcpy into inline
  983. // copy loops. Since this gets called by every field with string or bytes
  984. // type, inlining may lead to a significant amount of code bloat, with only a
  985. // minor performance gain.
  986. static uint8* WriteRawToArray(const void* buffer, int size, uint8* target);
  987. // Equivalent to WriteRaw(str.data(), str.size()).
  988. void WriteString(const std::string& str);
  989. // Like WriteString() but writing directly to the target array.
  990. static uint8* WriteStringToArray(const std::string& str, uint8* target);
  991. // Write the varint-encoded size of str followed by str.
  992. static uint8* WriteStringWithSizeToArray(const std::string& str,
  993. uint8* target);
  994. // Write a 32-bit little-endian integer.
  995. void WriteLittleEndian32(uint32 value) {
  996. cur_ = impl_.EnsureSpace(cur_);
  997. SetCur(WriteLittleEndian32ToArray(value, Cur()));
  998. }
  999. // Like WriteLittleEndian32() but writing directly to the target array.
  1000. static uint8* WriteLittleEndian32ToArray(uint32 value, uint8* target);
  1001. // Write a 64-bit little-endian integer.
  1002. void WriteLittleEndian64(uint64 value) {
  1003. cur_ = impl_.EnsureSpace(cur_);
  1004. SetCur(WriteLittleEndian64ToArray(value, Cur()));
  1005. }
  1006. // Like WriteLittleEndian64() but writing directly to the target array.
  1007. static uint8* WriteLittleEndian64ToArray(uint64 value, uint8* target);
  1008. // Write an unsigned integer with Varint encoding. Writing a 32-bit value
  1009. // is equivalent to casting it to uint64 and writing it as a 64-bit value,
  1010. // but may be more efficient.
  1011. void WriteVarint32(uint32 value);
  1012. // Like WriteVarint32() but writing directly to the target array.
  1013. static uint8* WriteVarint32ToArray(uint32 value, uint8* target);
  1014. // Write an unsigned integer with Varint encoding.
  1015. void WriteVarint64(uint64 value);
  1016. // Like WriteVarint64() but writing directly to the target array.
  1017. static uint8* WriteVarint64ToArray(uint64 value, uint8* target);
  1018. // Equivalent to WriteVarint32() except when the value is negative,
  1019. // in which case it must be sign-extended to a full 10 bytes.
  1020. void WriteVarint32SignExtended(int32 value);
  1021. // Like WriteVarint32SignExtended() but writing directly to the target array.
  1022. static uint8* WriteVarint32SignExtendedToArray(int32 value, uint8* target);
  1023. // This is identical to WriteVarint32(), but optimized for writing tags.
  1024. // In particular, if the input is a compile-time constant, this method
  1025. // compiles down to a couple instructions.
  1026. // Always inline because otherwise the aformentioned optimization can't work,
  1027. // but GCC by default doesn't want to inline this.
  1028. void WriteTag(uint32 value);
  1029. // Like WriteTag() but writing directly to the target array.
  1030. PROTOBUF_ALWAYS_INLINE
  1031. static uint8* WriteTagToArray(uint32 value, uint8* target);
  1032. // Returns the number of bytes needed to encode the given value as a varint.
  1033. static size_t VarintSize32(uint32 value);
  1034. // Returns the number of bytes needed to encode the given value as a varint.
  1035. static size_t VarintSize64(uint64 value);
  1036. // If negative, 10 bytes. Otheriwse, same as VarintSize32().
  1037. static size_t VarintSize32SignExtended(int32 value);
  1038. // Compile-time equivalent of VarintSize32().
  1039. template <uint32 Value>
  1040. struct StaticVarintSize32 {
  1041. static const size_t value =
  1042. (Value < (1 << 7))
  1043. ? 1
  1044. : (Value < (1 << 14))
  1045. ? 2
  1046. : (Value < (1 << 21)) ? 3 : (Value < (1 << 28)) ? 4 : 5;
  1047. };
  1048. // Returns the total number of bytes written since this object was created.
  1049. int ByteCount() const {
  1050. return static_cast<int>(impl_.ByteCount(cur_) - start_count_);
  1051. }
  1052. // Instructs the CodedOutputStream to allow the underlying
  1053. // ZeroCopyOutputStream to hold pointers to the original structure instead of
  1054. // copying, if it supports it (i.e. output->AllowsAliasing() is true). If the
  1055. // underlying stream does not support aliasing, then enabling it has no
  1056. // affect. For now, this only affects the behavior of
  1057. // WriteRawMaybeAliased().
  1058. //
  1059. // NOTE: It is caller's responsibility to ensure that the chunk of memory
  1060. // remains live until all of the data has been consumed from the stream.
  1061. void EnableAliasing(bool enabled) { impl_.EnableAliasing(enabled); }
  1062. // Indicate to the serializer whether the user wants derministic
  1063. // serialization. The default when this is not called comes from the global
  1064. // default, controlled by SetDefaultSerializationDeterministic.
  1065. //
  1066. // What deterministic serialization means is entirely up to the driver of the
  1067. // serialization process (i.e. the caller of methods like WriteVarint32). In
  1068. // the case of serializing a proto buffer message using one of the methods of
  1069. // MessageLite, this means that for a given binary equal messages will always
  1070. // be serialized to the same bytes. This implies:
  1071. //
  1072. // * Repeated serialization of a message will return the same bytes.
  1073. //
  1074. // * Different processes running the same binary (including on different
  1075. // machines) will serialize equal messages to the same bytes.
  1076. //
  1077. // Note that this is *not* canonical across languages. It is also unstable
  1078. // across different builds with intervening message definition changes, due to
  1079. // unknown fields. Users who need canonical serialization (e.g. persistent
  1080. // storage in a canonical form, fingerprinting) should define their own
  1081. // canonicalization specification and implement the serializer using
  1082. // reflection APIs rather than relying on this API.
  1083. void SetSerializationDeterministic(bool value) {
  1084. impl_.SetSerializationDeterministic(value);
  1085. }
  1086. // Return whether the user wants deterministic serialization. See above.
  1087. bool IsSerializationDeterministic() const {
  1088. return impl_.IsSerializationDeterministic();
  1089. }
  1090. static bool IsDefaultSerializationDeterministic() {
  1091. return default_serialization_deterministic_.load(
  1092. std::memory_order_relaxed) != 0;
  1093. }
  1094. template <typename Func>
  1095. void Serialize(const Func& func);
  1096. uint8* Cur() const { return cur_; }
  1097. void SetCur(uint8* ptr) { cur_ = ptr; }
  1098. EpsCopyOutputStream* EpsCopy() { return &impl_; }
  1099. private:
  1100. EpsCopyOutputStream impl_;
  1101. uint8* cur_;
  1102. int64 start_count_;
  1103. static std::atomic<bool> default_serialization_deterministic_;
  1104. // See above. Other projects may use "friend" to allow them to call this.
  1105. // After SetDefaultSerializationDeterministic() completes, all protocol
  1106. // buffer serializations will be deterministic by default. Thread safe.
  1107. // However, the meaning of "after" is subtle here: to be safe, each thread
  1108. // that wants deterministic serialization by default needs to call
  1109. // SetDefaultSerializationDeterministic() or ensure on its own that another
  1110. // thread has done so.
  1111. friend void internal::MapTestForceDeterministic();
  1112. static void SetDefaultSerializationDeterministic() {
  1113. default_serialization_deterministic_.store(true, std::memory_order_relaxed);
  1114. }
  1115. GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(CodedOutputStream);
  1116. };
  1117. // inline methods ====================================================
  1118. // The vast majority of varints are only one byte. These inline
  1119. // methods optimize for that case.
  1120. inline bool CodedInputStream::ReadVarint32(uint32* value) {
  1121. uint32 v = 0;
  1122. if (PROTOBUF_PREDICT_TRUE(buffer_ < buffer_end_)) {
  1123. v = *buffer_;
  1124. if (v < 0x80) {
  1125. *value = v;
  1126. Advance(1);
  1127. return true;
  1128. }
  1129. }
  1130. int64 result = ReadVarint32Fallback(v);
  1131. *value = static_cast<uint32>(result);
  1132. return result >= 0;
  1133. }
  1134. inline bool CodedInputStream::ReadVarint64(uint64* value) {
  1135. if (PROTOBUF_PREDICT_TRUE(buffer_ < buffer_end_) && *buffer_ < 0x80) {
  1136. *value = *buffer_;
  1137. Advance(1);
  1138. return true;
  1139. }
  1140. std::pair<uint64, bool> p = ReadVarint64Fallback();
  1141. *value = p.first;
  1142. return p.second;
  1143. }
  1144. inline bool CodedInputStream::ReadVarintSizeAsInt(int* value) {
  1145. if (PROTOBUF_PREDICT_TRUE(buffer_ < buffer_end_)) {
  1146. int v = *buffer_;
  1147. if (v < 0x80) {
  1148. *value = v;
  1149. Advance(1);
  1150. return true;
  1151. }
  1152. }
  1153. *value = ReadVarintSizeAsIntFallback();
  1154. return *value >= 0;
  1155. }
  1156. // static
  1157. inline const uint8* CodedInputStream::ReadLittleEndian32FromArray(
  1158. const uint8* buffer, uint32* value) {
  1159. #if defined(PROTOBUF_LITTLE_ENDIAN)
  1160. memcpy(value, buffer, sizeof(*value));
  1161. return buffer + sizeof(*value);
  1162. #else
  1163. *value = (static_cast<uint32>(buffer[0])) |
  1164. (static_cast<uint32>(buffer[1]) << 8) |
  1165. (static_cast<uint32>(buffer[2]) << 16) |
  1166. (static_cast<uint32>(buffer[3]) << 24);
  1167. return buffer + sizeof(*value);
  1168. #endif
  1169. }
  1170. // static
  1171. inline const uint8* CodedInputStream::ReadLittleEndian64FromArray(
  1172. const uint8* buffer, uint64* value) {
  1173. #if defined(PROTOBUF_LITTLE_ENDIAN)
  1174. memcpy(value, buffer, sizeof(*value));
  1175. return buffer + sizeof(*value);
  1176. #else
  1177. uint32 part0 = (static_cast<uint32>(buffer[0])) |
  1178. (static_cast<uint32>(buffer[1]) << 8) |
  1179. (static_cast<uint32>(buffer[2]) << 16) |
  1180. (static_cast<uint32>(buffer[3]) << 24);
  1181. uint32 part1 = (static_cast<uint32>(buffer[4])) |
  1182. (static_cast<uint32>(buffer[5]) << 8) |
  1183. (static_cast<uint32>(buffer[6]) << 16) |
  1184. (static_cast<uint32>(buffer[7]) << 24);
  1185. *value = static_cast<uint64>(part0) | (static_cast<uint64>(part1) << 32);
  1186. return buffer + sizeof(*value);
  1187. #endif
  1188. }
  1189. inline bool CodedInputStream::ReadLittleEndian32(uint32* value) {
  1190. #if defined(PROTOBUF_LITTLE_ENDIAN)
  1191. if (PROTOBUF_PREDICT_TRUE(BufferSize() >= static_cast<int>(sizeof(*value)))) {
  1192. buffer_ = ReadLittleEndian32FromArray(buffer_, value);
  1193. return true;
  1194. } else {
  1195. return ReadLittleEndian32Fallback(value);
  1196. }
  1197. #else
  1198. return ReadLittleEndian32Fallback(value);
  1199. #endif
  1200. }
  1201. inline bool CodedInputStream::ReadLittleEndian64(uint64* value) {
  1202. #if defined(PROTOBUF_LITTLE_ENDIAN)
  1203. if (PROTOBUF_PREDICT_TRUE(BufferSize() >= static_cast<int>(sizeof(*value)))) {
  1204. buffer_ = ReadLittleEndian64FromArray(buffer_, value);
  1205. return true;
  1206. } else {
  1207. return ReadLittleEndian64Fallback(value);
  1208. }
  1209. #else
  1210. return ReadLittleEndian64Fallback(value);
  1211. #endif
  1212. }
  1213. inline uint32 CodedInputStream::ReadTagNoLastTag() {
  1214. uint32 v = 0;
  1215. if (PROTOBUF_PREDICT_TRUE(buffer_ < buffer_end_)) {
  1216. v = *buffer_;
  1217. if (v < 0x80) {
  1218. Advance(1);
  1219. return v;
  1220. }
  1221. }
  1222. v = ReadTagFallback(v);
  1223. return v;
  1224. }
  1225. inline std::pair<uint32, bool> CodedInputStream::ReadTagWithCutoffNoLastTag(
  1226. uint32 cutoff) {
  1227. // In performance-sensitive code we can expect cutoff to be a compile-time
  1228. // constant, and things like "cutoff >= kMax1ByteVarint" to be evaluated at
  1229. // compile time.
  1230. uint32 first_byte_or_zero = 0;
  1231. if (PROTOBUF_PREDICT_TRUE(buffer_ < buffer_end_)) {
  1232. // Hot case: buffer_ non_empty, buffer_[0] in [1, 128).
  1233. // TODO(gpike): Is it worth rearranging this? E.g., if the number of fields
  1234. // is large enough then is it better to check for the two-byte case first?
  1235. first_byte_or_zero = buffer_[0];
  1236. if (static_cast<int8>(buffer_[0]) > 0) {
  1237. const uint32 kMax1ByteVarint = 0x7f;
  1238. uint32 tag = buffer_[0];
  1239. Advance(1);
  1240. return std::make_pair(tag, cutoff >= kMax1ByteVarint || tag <= cutoff);
  1241. }
  1242. // Other hot case: cutoff >= 0x80, buffer_ has at least two bytes available,
  1243. // and tag is two bytes. The latter is tested by bitwise-and-not of the
  1244. // first byte and the second byte.
  1245. if (cutoff >= 0x80 && PROTOBUF_PREDICT_TRUE(buffer_ + 1 < buffer_end_) &&
  1246. PROTOBUF_PREDICT_TRUE((buffer_[0] & ~buffer_[1]) >= 0x80)) {
  1247. const uint32 kMax2ByteVarint = (0x7f << 7) + 0x7f;
  1248. uint32 tag = (1u << 7) * buffer_[1] + (buffer_[0] - 0x80);
  1249. Advance(2);
  1250. // It might make sense to test for tag == 0 now, but it is so rare that
  1251. // that we don't bother. A varint-encoded 0 should be one byte unless
  1252. // the encoder lost its mind. The second part of the return value of
  1253. // this function is allowed to be either true or false if the tag is 0,
  1254. // so we don't have to check for tag == 0. We may need to check whether
  1255. // it exceeds cutoff.
  1256. bool at_or_below_cutoff = cutoff >= kMax2ByteVarint || tag <= cutoff;
  1257. return std::make_pair(tag, at_or_below_cutoff);
  1258. }
  1259. }
  1260. // Slow path
  1261. const uint32 tag = ReadTagFallback(first_byte_or_zero);
  1262. return std::make_pair(tag, static_cast<uint32>(tag - 1) < cutoff);
  1263. }
  1264. inline bool CodedInputStream::LastTagWas(uint32 expected) {
  1265. return last_tag_ == expected;
  1266. }
  1267. inline bool CodedInputStream::ConsumedEntireMessage() {
  1268. return legitimate_message_end_;
  1269. }
  1270. inline bool CodedInputStream::ExpectTag(uint32 expected) {
  1271. if (expected < (1 << 7)) {
  1272. if (PROTOBUF_PREDICT_TRUE(buffer_ < buffer_end_) &&
  1273. buffer_[0] == expected) {
  1274. Advance(1);
  1275. return true;
  1276. } else {
  1277. return false;
  1278. }
  1279. } else if (expected < (1 << 14)) {
  1280. if (PROTOBUF_PREDICT_TRUE(BufferSize() >= 2) &&
  1281. buffer_[0] == static_cast<uint8>(expected | 0x80) &&
  1282. buffer_[1] == static_cast<uint8>(expected >> 7)) {
  1283. Advance(2);
  1284. return true;
  1285. } else {
  1286. return false;
  1287. }
  1288. } else {
  1289. // Don't bother optimizing for larger values.
  1290. return false;
  1291. }
  1292. }
  1293. inline const uint8* CodedInputStream::ExpectTagFromArray(const uint8* buffer,
  1294. uint32 expected) {
  1295. if (expected < (1 << 7)) {
  1296. if (buffer[0] == expected) {
  1297. return buffer + 1;
  1298. }
  1299. } else if (expected < (1 << 14)) {
  1300. if (buffer[0] == static_cast<uint8>(expected | 0x80) &&
  1301. buffer[1] == static_cast<uint8>(expected >> 7)) {
  1302. return buffer + 2;
  1303. }
  1304. }
  1305. return nullptr;
  1306. }
  1307. inline void CodedInputStream::GetDirectBufferPointerInline(const void** data,
  1308. int* size) {
  1309. *data = buffer_;
  1310. *size = static_cast<int>(buffer_end_ - buffer_);
  1311. }
  1312. inline bool CodedInputStream::ExpectAtEnd() {
  1313. // If we are at a limit we know no more bytes can be read. Otherwise, it's
  1314. // hard to say without calling Refresh(), and we'd rather not do that.
  1315. if (buffer_ == buffer_end_ && ((buffer_size_after_limit_ != 0) ||
  1316. (total_bytes_read_ == current_limit_))) {
  1317. last_tag_ = 0; // Pretend we called ReadTag()...
  1318. legitimate_message_end_ = true; // ... and it hit EOF.
  1319. return true;
  1320. } else {
  1321. return false;
  1322. }
  1323. }
  1324. inline int CodedInputStream::CurrentPosition() const {
  1325. return total_bytes_read_ - (BufferSize() + buffer_size_after_limit_);
  1326. }
  1327. inline void CodedInputStream::Advance(int amount) { buffer_ += amount; }
  1328. inline void CodedInputStream::SetRecursionLimit(int limit) {
  1329. recursion_budget_ += limit - recursion_limit_;
  1330. recursion_limit_ = limit;
  1331. }
  1332. inline bool CodedInputStream::IncrementRecursionDepth() {
  1333. --recursion_budget_;
  1334. return recursion_budget_ >= 0;
  1335. }
  1336. inline void CodedInputStream::DecrementRecursionDepth() {
  1337. if (recursion_budget_ < recursion_limit_) ++recursion_budget_;
  1338. }
  1339. inline void CodedInputStream::UnsafeDecrementRecursionDepth() {
  1340. assert(recursion_budget_ < recursion_limit_);
  1341. ++recursion_budget_;
  1342. }
  1343. inline void CodedInputStream::SetExtensionRegistry(const DescriptorPool* pool,
  1344. MessageFactory* factory) {
  1345. extension_pool_ = pool;
  1346. extension_factory_ = factory;
  1347. }
  1348. inline const DescriptorPool* CodedInputStream::GetExtensionPool() {
  1349. return extension_pool_;
  1350. }
  1351. inline MessageFactory* CodedInputStream::GetExtensionFactory() {
  1352. return extension_factory_;
  1353. }
  1354. inline int CodedInputStream::BufferSize() const {
  1355. return static_cast<int>(buffer_end_ - buffer_);
  1356. }
  1357. inline CodedInputStream::CodedInputStream(ZeroCopyInputStream* input)
  1358. : buffer_(nullptr),
  1359. buffer_end_(nullptr),
  1360. input_(input),
  1361. total_bytes_read_(0),
  1362. overflow_bytes_(0),
  1363. last_tag_(0),
  1364. legitimate_message_end_(false),
  1365. aliasing_enabled_(false),
  1366. current_limit_(kint32max),
  1367. buffer_size_after_limit_(0),
  1368. total_bytes_limit_(kDefaultTotalBytesLimit),
  1369. recursion_budget_(default_recursion_limit_),
  1370. recursion_limit_(default_recursion_limit_),
  1371. extension_pool_(nullptr),
  1372. extension_factory_(nullptr) {
  1373. // Eagerly Refresh() so buffer space is immediately available.
  1374. Refresh();
  1375. }
  1376. inline CodedInputStream::CodedInputStream(const uint8* buffer, int size)
  1377. : buffer_(buffer),
  1378. buffer_end_(buffer + size),
  1379. input_(nullptr),
  1380. total_bytes_read_(size),
  1381. overflow_bytes_(0),
  1382. last_tag_(0),
  1383. legitimate_message_end_(false),
  1384. aliasing_enabled_(false),
  1385. current_limit_(size),
  1386. buffer_size_after_limit_(0),
  1387. total_bytes_limit_(kDefaultTotalBytesLimit),
  1388. recursion_budget_(default_recursion_limit_),
  1389. recursion_limit_(default_recursion_limit_),
  1390. extension_pool_(nullptr),
  1391. extension_factory_(nullptr) {
  1392. // Note that setting current_limit_ == size is important to prevent some
  1393. // code paths from trying to access input_ and segfaulting.
  1394. }
  1395. inline bool CodedInputStream::IsFlat() const { return input_ == nullptr; }
  1396. inline bool CodedInputStream::Skip(int count) {
  1397. if (count < 0) return false; // security: count is often user-supplied
  1398. const int original_buffer_size = BufferSize();
  1399. if (count <= original_buffer_size) {
  1400. // Just skipping within the current buffer. Easy.
  1401. Advance(count);
  1402. return true;
  1403. }
  1404. return SkipFallback(count, original_buffer_size);
  1405. }
  1406. inline uint8* CodedOutputStream::WriteVarint32ToArray(uint32 value,
  1407. uint8* target) {
  1408. return EpsCopyOutputStream::UnsafeVarint(value, target);
  1409. }
  1410. inline uint8* CodedOutputStream::WriteVarint64ToArray(uint64 value,
  1411. uint8* target) {
  1412. return EpsCopyOutputStream::UnsafeVarint(value, target);
  1413. }
  1414. inline void CodedOutputStream::WriteVarint32SignExtended(int32 value) {
  1415. WriteVarint64(static_cast<uint64>(value));
  1416. }
  1417. inline uint8* CodedOutputStream::WriteVarint32SignExtendedToArray(
  1418. int32 value, uint8* target) {
  1419. return WriteVarint64ToArray(static_cast<uint64>(value), target);
  1420. }
  1421. inline uint8* CodedOutputStream::WriteLittleEndian32ToArray(uint32 value,
  1422. uint8* target) {
  1423. #if defined(PROTOBUF_LITTLE_ENDIAN)
  1424. memcpy(target, &value, sizeof(value));
  1425. #else
  1426. target[0] = static_cast<uint8>(value);
  1427. target[1] = static_cast<uint8>(value >> 8);
  1428. target[2] = static_cast<uint8>(value >> 16);
  1429. target[3] = static_cast<uint8>(value >> 24);
  1430. #endif
  1431. return target + sizeof(value);
  1432. }
  1433. inline uint8* CodedOutputStream::WriteLittleEndian64ToArray(uint64 value,
  1434. uint8* target) {
  1435. #if defined(PROTOBUF_LITTLE_ENDIAN)
  1436. memcpy(target, &value, sizeof(value));
  1437. #else
  1438. uint32 part0 = static_cast<uint32>(value);
  1439. uint32 part1 = static_cast<uint32>(value >> 32);
  1440. target[0] = static_cast<uint8>(part0);
  1441. target[1] = static_cast<uint8>(part0 >> 8);
  1442. target[2] = static_cast<uint8>(part0 >> 16);
  1443. target[3] = static_cast<uint8>(part0 >> 24);
  1444. target[4] = static_cast<uint8>(part1);
  1445. target[5] = static_cast<uint8>(part1 >> 8);
  1446. target[6] = static_cast<uint8>(part1 >> 16);
  1447. target[7] = static_cast<uint8>(part1 >> 24);
  1448. #endif
  1449. return target + sizeof(value);
  1450. }
  1451. inline void CodedOutputStream::WriteVarint32(uint32 value) {
  1452. cur_ = impl_.EnsureSpace(cur_);
  1453. SetCur(WriteVarint32ToArray(value, Cur()));
  1454. }
  1455. inline void CodedOutputStream::WriteVarint64(uint64 value) {
  1456. cur_ = impl_.EnsureSpace(cur_);
  1457. SetCur(WriteVarint64ToArray(value, Cur()));
  1458. }
  1459. inline void CodedOutputStream::WriteTag(uint32 value) { WriteVarint32(value); }
  1460. inline uint8* CodedOutputStream::WriteTagToArray(uint32 value, uint8* target) {
  1461. return WriteVarint32ToArray(value, target);
  1462. }
  1463. inline size_t CodedOutputStream::VarintSize32(uint32 value) {
  1464. // This computes value == 0 ? 1 : floor(log2(value)) / 7 + 1
  1465. // Use an explicit multiplication to implement the divide of
  1466. // a number in the 1..31 range.
  1467. // Explicit OR 0x1 to avoid calling Bits::Log2FloorNonZero(0), which is
  1468. // undefined.
  1469. uint32 log2value = Bits::Log2FloorNonZero(value | 0x1);
  1470. return static_cast<size_t>((log2value * 9 + 73) / 64);
  1471. }
  1472. inline size_t CodedOutputStream::VarintSize64(uint64 value) {
  1473. // This computes value == 0 ? 1 : floor(log2(value)) / 7 + 1
  1474. // Use an explicit multiplication to implement the divide of
  1475. // a number in the 1..63 range.
  1476. // Explicit OR 0x1 to avoid calling Bits::Log2FloorNonZero(0), which is
  1477. // undefined.
  1478. uint32 log2value = Bits::Log2FloorNonZero64(value | 0x1);
  1479. return static_cast<size_t>((log2value * 9 + 73) / 64);
  1480. }
  1481. inline size_t CodedOutputStream::VarintSize32SignExtended(int32 value) {
  1482. if (value < 0) {
  1483. return 10; // TODO(kenton): Make this a symbolic constant.
  1484. } else {
  1485. return VarintSize32(static_cast<uint32>(value));
  1486. }
  1487. }
  1488. inline void CodedOutputStream::WriteString(const std::string& str) {
  1489. WriteRaw(str.data(), static_cast<int>(str.size()));
  1490. }
  1491. inline void CodedOutputStream::WriteRawMaybeAliased(const void* data,
  1492. int size) {
  1493. cur_ = impl_.WriteRawMaybeAliased(data, size, cur_);
  1494. }
  1495. inline uint8* CodedOutputStream::WriteRawToArray(const void* data, int size,
  1496. uint8* target) {
  1497. memcpy(target, data, size);
  1498. return target + size;
  1499. }
  1500. inline uint8* CodedOutputStream::WriteStringToArray(const std::string& str,
  1501. uint8* target) {
  1502. return WriteRawToArray(str.data(), static_cast<int>(str.size()), target);
  1503. }
  1504. } // namespace io
  1505. } // namespace protobuf
  1506. } // namespace google
  1507. #if defined(_MSC_VER) && _MSC_VER >= 1300 && !defined(__INTEL_COMPILER)
  1508. #pragma runtime_checks("c", restore)
  1509. #endif // _MSC_VER && !defined(__INTEL_COMPILER)
  1510. #include <google/protobuf/port_undef.inc>
  1511. #endif // GOOGLE_PROTOBUF_IO_CODED_STREAM_H__