诸暨麻将添加redis
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.
 
 
 
 
 
 

539 строки
24 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. // Authors: wink@google.com (Wink Saville),
  31. // kenton@google.com (Kenton Varda)
  32. // Based on original Protocol Buffers design by
  33. // Sanjay Ghemawat, Jeff Dean, and others.
  34. //
  35. // Defines MessageLite, the abstract interface implemented by all (lite
  36. // and non-lite) protocol message objects.
  37. #ifndef GOOGLE_PROTOBUF_MESSAGE_LITE_H__
  38. #define GOOGLE_PROTOBUF_MESSAGE_LITE_H__
  39. #include <climits>
  40. #include <string>
  41. #include <google/protobuf/stubs/common.h>
  42. #include <google/protobuf/stubs/logging.h>
  43. #include <google/protobuf/io/coded_stream.h>
  44. #include <google/protobuf/arena.h>
  45. #include <google/protobuf/stubs/once.h>
  46. #include <google/protobuf/port.h>
  47. #include <google/protobuf/stubs/strutil.h>
  48. #include <google/protobuf/port_def.inc>
  49. #ifdef SWIG
  50. #error "You cannot SWIG proto headers"
  51. #endif
  52. namespace google {
  53. namespace protobuf {
  54. template <typename T>
  55. class RepeatedPtrField;
  56. namespace io {
  57. class CodedInputStream;
  58. class CodedOutputStream;
  59. class ZeroCopyInputStream;
  60. class ZeroCopyOutputStream;
  61. } // namespace io
  62. namespace internal {
  63. // See parse_context.h for explanation
  64. class ParseContext;
  65. class RepeatedPtrFieldBase;
  66. class WireFormatLite;
  67. class WeakFieldMap;
  68. // We compute sizes as size_t but cache them as int. This function converts a
  69. // computed size to a cached size. Since we don't proceed with serialization
  70. // if the total size was > INT_MAX, it is not important what this function
  71. // returns for inputs > INT_MAX. However this case should not error or
  72. // GOOGLE_CHECK-fail, because the full size_t resolution is still returned from
  73. // ByteSizeLong() and checked against INT_MAX; we can catch the overflow
  74. // there.
  75. inline int ToCachedSize(size_t size) { return static_cast<int>(size); }
  76. // We mainly calculate sizes in terms of size_t, but some functions that
  77. // compute sizes return "int". These int sizes are expected to always be
  78. // positive. This function is more efficient than casting an int to size_t
  79. // directly on 64-bit platforms because it avoids making the compiler emit a
  80. // sign extending instruction, which we don't want and don't want to pay for.
  81. inline size_t FromIntSize(int size) {
  82. // Convert to unsigned before widening so sign extension is not necessary.
  83. return static_cast<unsigned int>(size);
  84. }
  85. // For cases where a legacy function returns an integer size. We GOOGLE_DCHECK()
  86. // that the conversion will fit within an integer; if this is false then we
  87. // are losing information.
  88. inline int ToIntSize(size_t size) {
  89. GOOGLE_DCHECK_LE(size, static_cast<size_t>(INT_MAX));
  90. return static_cast<int>(size);
  91. }
  92. // This type wraps a variable whose constructor and destructor are explicitly
  93. // called. It is particularly useful for a global variable, without its
  94. // constructor and destructor run on start and end of the program lifetime.
  95. // This circumvents the initial construction order fiasco, while keeping
  96. // the address of the empty string a compile time constant.
  97. //
  98. // Pay special attention to the initialization state of the object.
  99. // 1. The object is "uninitialized" to begin with.
  100. // 2. Call Construct() or DefaultConstruct() only if the object is
  101. // uninitialized. After the call, the object becomes "initialized".
  102. // 3. Call get() and get_mutable() only if the object is initialized.
  103. // 4. Call Destruct() only if the object is initialized.
  104. // After the call, the object becomes uninitialized.
  105. template <typename T>
  106. class ExplicitlyConstructed {
  107. public:
  108. void DefaultConstruct() { new (&union_) T(); }
  109. template <typename... Args>
  110. void Construct(Args&&... args) {
  111. new (&union_) T(std::forward<Args>(args)...);
  112. }
  113. void Destruct() { get_mutable()->~T(); }
  114. constexpr const T& get() const { return reinterpret_cast<const T&>(union_); }
  115. T* get_mutable() { return reinterpret_cast<T*>(&union_); }
  116. private:
  117. // Prefer c++14 aligned_storage, but for compatibility this will do.
  118. union AlignedUnion {
  119. char space[sizeof(T)];
  120. int64 align_to_int64;
  121. void* align_to_ptr;
  122. } union_;
  123. };
  124. // Default empty string object. Don't use this directly. Instead, call
  125. // GetEmptyString() to get the reference.
  126. PROTOBUF_EXPORT extern ExplicitlyConstructed<std::string>
  127. fixed_address_empty_string;
  128. PROTOBUF_EXPORT inline const std::string& GetEmptyStringAlreadyInited() {
  129. return fixed_address_empty_string.get();
  130. }
  131. PROTOBUF_EXPORT size_t StringSpaceUsedExcludingSelfLong(const std::string& str);
  132. } // namespace internal
  133. // Interface to light weight protocol messages.
  134. //
  135. // This interface is implemented by all protocol message objects. Non-lite
  136. // messages additionally implement the Message interface, which is a
  137. // subclass of MessageLite. Use MessageLite instead when you only need
  138. // the subset of features which it supports -- namely, nothing that uses
  139. // descriptors or reflection. You can instruct the protocol compiler
  140. // to generate classes which implement only MessageLite, not the full
  141. // Message interface, by adding the following line to the .proto file:
  142. //
  143. // option optimize_for = LITE_RUNTIME;
  144. //
  145. // This is particularly useful on resource-constrained systems where
  146. // the full protocol buffers runtime library is too big.
  147. //
  148. // Note that on non-constrained systems (e.g. servers) when you need
  149. // to link in lots of protocol definitions, a better way to reduce
  150. // total code footprint is to use optimize_for = CODE_SIZE. This
  151. // will make the generated code smaller while still supporting all the
  152. // same features (at the expense of speed). optimize_for = LITE_RUNTIME
  153. // is best when you only have a small number of message types linked
  154. // into your binary, in which case the size of the protocol buffers
  155. // runtime itself is the biggest problem.
  156. class PROTOBUF_EXPORT MessageLite {
  157. public:
  158. inline MessageLite() {}
  159. virtual ~MessageLite() {}
  160. // Basic Operations ------------------------------------------------
  161. // Get the name of this message type, e.g. "foo.bar.BazProto".
  162. virtual std::string GetTypeName() const = 0;
  163. // Construct a new instance of the same type. Ownership is passed to the
  164. // caller.
  165. virtual MessageLite* New() const = 0;
  166. // Construct a new instance on the arena. Ownership is passed to the caller
  167. // if arena is a NULL. Default implementation for backwards compatibility.
  168. virtual MessageLite* New(Arena* arena) const;
  169. // Get the arena, if any, associated with this message. Virtual method
  170. // required for generic operations but most arena-related operations should
  171. // use the GetArenaNoVirtual() generated-code method. Default implementation
  172. // to reduce code size by avoiding the need for per-type implementations
  173. // when types do not implement arena support.
  174. virtual Arena* GetArena() const { return NULL; }
  175. // Get a pointer that may be equal to this message's arena, or may not be.
  176. // If the value returned by this method is equal to some arena pointer, then
  177. // this message is on that arena; however, if this message is on some arena,
  178. // this method may or may not return that arena's pointer. As a tradeoff,
  179. // this method may be more efficient than GetArena(). The intent is to allow
  180. // underlying representations that use e.g. tagged pointers to sometimes
  181. // store the arena pointer directly, and sometimes in a more indirect way,
  182. // and allow a fastpath comparison against the arena pointer when it's easy
  183. // to obtain.
  184. virtual void* GetMaybeArenaPointer() const { return GetArena(); }
  185. // Clear all fields of the message and set them to their default values.
  186. // Clear() avoids freeing memory, assuming that any memory allocated
  187. // to hold parts of the message will be needed again to hold the next
  188. // message. If you actually want to free the memory used by a Message,
  189. // you must delete it.
  190. virtual void Clear() = 0;
  191. // Quickly check if all required fields have values set.
  192. virtual bool IsInitialized() const = 0;
  193. // This is not implemented for Lite messages -- it just returns "(cannot
  194. // determine missing fields for lite message)". However, it is implemented
  195. // for full messages. See message.h.
  196. virtual std::string InitializationErrorString() const;
  197. // If |other| is the exact same class as this, calls MergeFrom(). Otherwise,
  198. // results are undefined (probably crash).
  199. virtual void CheckTypeAndMergeFrom(const MessageLite& other) = 0;
  200. // These methods return a human-readable summary of the message. Note that
  201. // since the MessageLite interface does not support reflection, there is very
  202. // little information that these methods can provide. They are shadowed by
  203. // methods of the same name on the Message interface which provide much more
  204. // information. The methods here are intended primarily to facilitate code
  205. // reuse for logic that needs to interoperate with both full and lite protos.
  206. //
  207. // The format of the returned string is subject to change, so please do not
  208. // assume it will remain stable over time.
  209. std::string DebugString() const;
  210. std::string ShortDebugString() const { return DebugString(); }
  211. // MessageLite::DebugString is already Utf8 Safe. This is to add compatibility
  212. // with Message.
  213. std::string Utf8DebugString() const { return DebugString(); }
  214. // Parsing ---------------------------------------------------------
  215. // Methods for parsing in protocol buffer format. Most of these are
  216. // just simple wrappers around MergeFromCodedStream(). Clear() will be
  217. // called before merging the input.
  218. // Fill the message with a protocol buffer parsed from the given input
  219. // stream. Returns false on a read error or if the input is in the wrong
  220. // format. A successful return does not indicate the entire input is
  221. // consumed, ensure you call ConsumedEntireMessage() to check that if
  222. // applicable.
  223. bool ParseFromCodedStream(io::CodedInputStream* input);
  224. // Like ParseFromCodedStream(), but accepts messages that are missing
  225. // required fields.
  226. bool ParsePartialFromCodedStream(io::CodedInputStream* input);
  227. // Read a protocol buffer from the given zero-copy input stream. If
  228. // successful, the entire input will be consumed.
  229. bool ParseFromZeroCopyStream(io::ZeroCopyInputStream* input);
  230. // Like ParseFromZeroCopyStream(), but accepts messages that are missing
  231. // required fields.
  232. bool ParsePartialFromZeroCopyStream(io::ZeroCopyInputStream* input);
  233. // Parse a protocol buffer from a file descriptor. If successful, the entire
  234. // input will be consumed.
  235. bool ParseFromFileDescriptor(int file_descriptor);
  236. // Like ParseFromFileDescriptor(), but accepts messages that are missing
  237. // required fields.
  238. bool ParsePartialFromFileDescriptor(int file_descriptor);
  239. // Parse a protocol buffer from a C++ istream. If successful, the entire
  240. // input will be consumed.
  241. bool ParseFromIstream(std::istream* input);
  242. // Like ParseFromIstream(), but accepts messages that are missing
  243. // required fields.
  244. bool ParsePartialFromIstream(std::istream* input);
  245. // Read a protocol buffer from the given zero-copy input stream, expecting
  246. // the message to be exactly "size" bytes long. If successful, exactly
  247. // this many bytes will have been consumed from the input.
  248. bool MergePartialFromBoundedZeroCopyStream(io::ZeroCopyInputStream* input,
  249. int size);
  250. // Like ParseFromBoundedZeroCopyStream(), but accepts messages that are
  251. // missing required fields.
  252. bool MergeFromBoundedZeroCopyStream(io::ZeroCopyInputStream* input, int size);
  253. bool ParseFromBoundedZeroCopyStream(io::ZeroCopyInputStream* input, int size);
  254. // Like ParseFromBoundedZeroCopyStream(), but accepts messages that are
  255. // missing required fields.
  256. bool ParsePartialFromBoundedZeroCopyStream(io::ZeroCopyInputStream* input,
  257. int size);
  258. // Parses a protocol buffer contained in a string. Returns true on success.
  259. // This function takes a string in the (non-human-readable) binary wire
  260. // format, matching the encoding output by MessageLite::SerializeToString().
  261. // If you'd like to convert a human-readable string into a protocol buffer
  262. // object, see google::protobuf::TextFormat::ParseFromString().
  263. bool ParseFromString(const std::string& data);
  264. // Like ParseFromString(), but accepts messages that are missing
  265. // required fields.
  266. bool ParsePartialFromString(const std::string& data);
  267. // Parse a protocol buffer contained in an array of bytes.
  268. bool ParseFromArray(const void* data, int size);
  269. // Like ParseFromArray(), but accepts messages that are missing
  270. // required fields.
  271. bool ParsePartialFromArray(const void* data, int size);
  272. // Reads a protocol buffer from the stream and merges it into this
  273. // Message. Singular fields read from the what is
  274. // already in the Message and repeated fields are appended to those
  275. // already present.
  276. //
  277. // It is the responsibility of the caller to call input->LastTagWas()
  278. // (for groups) or input->ConsumedEntireMessage() (for non-groups) after
  279. // this returns to verify that the message's end was delimited correctly.
  280. //
  281. // ParseFromCodedStream() is implemented as Clear() followed by
  282. // MergeFromCodedStream().
  283. bool MergeFromCodedStream(io::CodedInputStream* input);
  284. // Like MergeFromCodedStream(), but succeeds even if required fields are
  285. // missing in the input.
  286. //
  287. // MergeFromCodedStream() is just implemented as MergePartialFromCodedStream()
  288. // followed by IsInitialized().
  289. bool MergePartialFromCodedStream(io::CodedInputStream* input);
  290. // Merge a protocol buffer contained in a string.
  291. bool MergeFromString(const std::string& data);
  292. // Serialization ---------------------------------------------------
  293. // Methods for serializing in protocol buffer format. Most of these
  294. // are just simple wrappers around ByteSize() and SerializeWithCachedSizes().
  295. // Write a protocol buffer of this message to the given output. Returns
  296. // false on a write error. If the message is missing required fields,
  297. // this may GOOGLE_CHECK-fail.
  298. bool SerializeToCodedStream(io::CodedOutputStream* output) const;
  299. // Like SerializeToCodedStream(), but allows missing required fields.
  300. bool SerializePartialToCodedStream(io::CodedOutputStream* output) const;
  301. // Write the message to the given zero-copy output stream. All required
  302. // fields must be set.
  303. bool SerializeToZeroCopyStream(io::ZeroCopyOutputStream* output) const;
  304. // Like SerializeToZeroCopyStream(), but allows missing required fields.
  305. bool SerializePartialToZeroCopyStream(io::ZeroCopyOutputStream* output) const;
  306. // Serialize the message and store it in the given string. All required
  307. // fields must be set.
  308. bool SerializeToString(std::string* output) const;
  309. // Like SerializeToString(), but allows missing required fields.
  310. bool SerializePartialToString(std::string* output) const;
  311. // Serialize the message and store it in the given byte array. All required
  312. // fields must be set.
  313. bool SerializeToArray(void* data, int size) const;
  314. // Like SerializeToArray(), but allows missing required fields.
  315. bool SerializePartialToArray(void* data, int size) const;
  316. // Make a string encoding the message. Is equivalent to calling
  317. // SerializeToString() on a string and using that. Returns the empty
  318. // string if SerializeToString() would have returned an error.
  319. // Note: If you intend to generate many such strings, you may
  320. // reduce heap fragmentation by instead re-using the same string
  321. // object with calls to SerializeToString().
  322. std::string SerializeAsString() const;
  323. // Like SerializeAsString(), but allows missing required fields.
  324. std::string SerializePartialAsString() const;
  325. // Serialize the message and write it to the given file descriptor. All
  326. // required fields must be set.
  327. bool SerializeToFileDescriptor(int file_descriptor) const;
  328. // Like SerializeToFileDescriptor(), but allows missing required fields.
  329. bool SerializePartialToFileDescriptor(int file_descriptor) const;
  330. // Serialize the message and write it to the given C++ ostream. All
  331. // required fields must be set.
  332. bool SerializeToOstream(std::ostream* output) const;
  333. // Like SerializeToOstream(), but allows missing required fields.
  334. bool SerializePartialToOstream(std::ostream* output) const;
  335. // Like SerializeToString(), but appends to the data to the string's
  336. // existing contents. All required fields must be set.
  337. bool AppendToString(std::string* output) const;
  338. // Like AppendToString(), but allows missing required fields.
  339. bool AppendPartialToString(std::string* output) const;
  340. // Computes the serialized size of the message. This recursively calls
  341. // ByteSizeLong() on all embedded messages.
  342. //
  343. // ByteSizeLong() is generally linear in the number of fields defined for the
  344. // proto.
  345. virtual size_t ByteSizeLong() const = 0;
  346. // Legacy ByteSize() API.
  347. PROTOBUF_DEPRECATED_MSG("Please use ByteSizeLong() instead")
  348. int ByteSize() const { return internal::ToIntSize(ByteSizeLong()); }
  349. // Serializes the message without recomputing the size. The message must not
  350. // have changed since the last call to ByteSize(), and the value returned by
  351. // ByteSize must be non-negative. Otherwise the results are undefined.
  352. void SerializeWithCachedSizes(io::CodedOutputStream* output) const {
  353. output->SetCur(InternalSerializeWithCachedSizesToArray(output->Cur(),
  354. output->EpsCopy()));
  355. }
  356. // Functions below here are not part of the public interface. It isn't
  357. // enforced, but they should be treated as private, and will be private
  358. // at some future time. Unfortunately the implementation of the "friend"
  359. // keyword in GCC is broken at the moment, but we expect it will be fixed.
  360. // Like SerializeWithCachedSizes, but writes directly to *target, returning
  361. // a pointer to the byte immediately after the last byte written. "target"
  362. // must point at a byte array of at least ByteSize() bytes. Whether to use
  363. // deterministic serialization, e.g., maps in sorted order, is determined by
  364. // CodedOutputStream::IsDefaultSerializationDeterministic().
  365. uint8* SerializeWithCachedSizesToArray(uint8* target) const;
  366. // Returns the result of the last call to ByteSize(). An embedded message's
  367. // size is needed both to serialize it (because embedded messages are
  368. // length-delimited) and to compute the outer message's size. Caching
  369. // the size avoids computing it multiple times.
  370. //
  371. // ByteSize() does not automatically use the cached size when available
  372. // because this would require invalidating it every time the message was
  373. // modified, which would be too hard and expensive. (E.g. if a deeply-nested
  374. // sub-message is changed, all of its parents' cached sizes would need to be
  375. // invalidated, which is too much work for an otherwise inlined setter
  376. // method.)
  377. virtual int GetCachedSize() const = 0;
  378. virtual const char* _InternalParse(const char* ptr,
  379. internal::ParseContext* ctx) {
  380. return nullptr;
  381. }
  382. protected:
  383. template <typename T>
  384. static T* CreateMaybeMessage(Arena* arena) {
  385. return Arena::CreateMaybeMessage<T>(arena);
  386. }
  387. public:
  388. enum ParseFlags {
  389. kMerge = 0,
  390. kParse = 1,
  391. kMergePartial = 2,
  392. kParsePartial = 3,
  393. kMergeWithAliasing = 4,
  394. kParseWithAliasing = 5,
  395. kMergePartialWithAliasing = 6,
  396. kParsePartialWithAliasing = 7
  397. };
  398. template <ParseFlags flags, typename T>
  399. bool ParseFrom(const T& input);
  400. // Fast path when conditions match (ie. non-deterministic)
  401. // uint8* InternalSerializeWithCachedSizesToArray(uint8* ptr) const;
  402. virtual uint8* InternalSerializeWithCachedSizesToArray(
  403. uint8* ptr, io::EpsCopyOutputStream* stream) const = 0;
  404. private:
  405. // TODO(gerbens) make this a pure abstract function
  406. virtual const void* InternalGetTable() const { return NULL; }
  407. friend class internal::WireFormatLite;
  408. friend class Message;
  409. friend class internal::WeakFieldMap;
  410. bool IsInitializedWithErrors() const {
  411. if (IsInitialized()) return true;
  412. LogInitializationErrorMessage();
  413. return false;
  414. }
  415. void LogInitializationErrorMessage() const;
  416. GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MessageLite);
  417. };
  418. namespace internal {
  419. template <bool alias>
  420. bool MergePartialFromImpl(StringPiece input, MessageLite* msg);
  421. extern template bool MergePartialFromImpl<false>(StringPiece input,
  422. MessageLite* msg);
  423. extern template bool MergePartialFromImpl<true>(StringPiece input,
  424. MessageLite* msg);
  425. template <bool alias>
  426. bool MergePartialFromImpl(io::ZeroCopyInputStream* input, MessageLite* msg);
  427. extern template bool MergePartialFromImpl<false>(io::ZeroCopyInputStream* input,
  428. MessageLite* msg);
  429. extern template bool MergePartialFromImpl<true>(io::ZeroCopyInputStream* input,
  430. MessageLite* msg);
  431. struct BoundedZCIS {
  432. io::ZeroCopyInputStream* zcis;
  433. int limit;
  434. };
  435. template <bool alias>
  436. bool MergePartialFromImpl(BoundedZCIS input, MessageLite* msg);
  437. extern template bool MergePartialFromImpl<false>(BoundedZCIS input,
  438. MessageLite* msg);
  439. extern template bool MergePartialFromImpl<true>(BoundedZCIS input,
  440. MessageLite* msg);
  441. template <typename T>
  442. struct SourceWrapper;
  443. template <bool alias, typename T>
  444. bool MergePartialFromImpl(const SourceWrapper<T>& input, MessageLite* msg) {
  445. return input.template MergePartialInto<alias>(msg);
  446. }
  447. } // namespace internal
  448. template <MessageLite::ParseFlags flags, typename T>
  449. bool MessageLite::ParseFrom(const T& input) {
  450. if (flags & kParse) Clear();
  451. constexpr bool alias = flags & kMergeWithAliasing;
  452. bool res = internal::MergePartialFromImpl<alias>(input, this);
  453. return res && ((flags & kMergePartial) || IsInitializedWithErrors());
  454. }
  455. } // namespace protobuf
  456. } // namespace google
  457. #include <google/protobuf/port_undef.inc>
  458. #endif // GOOGLE_PROTOBUF_MESSAGE_LITE_H__