UnknownFieldSet.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  1. #region Copyright notice and license
  2. // Protocol Buffers - Google's data interchange format
  3. // Copyright 2015 Google Inc. All rights reserved.
  4. // https://developers.google.com/protocol-buffers/
  5. //
  6. // Redistribution and use in source and binary forms, with or without
  7. // modification, are permitted provided that the following conditions are
  8. // met:
  9. //
  10. // * Redistributions of source code must retain the above copyright
  11. // notice, this list of conditions and the following disclaimer.
  12. // * Redistributions in binary form must reproduce the above
  13. // copyright notice, this list of conditions and the following disclaimer
  14. // in the documentation and/or other materials provided with the
  15. // distribution.
  16. // * Neither the name of Google Inc. nor the names of its
  17. // contributors may be used to endorse or promote products derived from
  18. // this software without specific prior written permission.
  19. //
  20. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  21. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  22. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  23. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  24. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  25. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  26. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  27. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  28. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  29. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  30. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  31. #endregion
  32. using System;
  33. using System.Collections.Generic;
  34. using System.IO;
  35. using Google.Protobuf.Reflection;
  36. namespace Google.Protobuf
  37. {
  38. /// <summary>
  39. /// Used to keep track of fields which were seen when parsing a protocol message
  40. /// but whose field numbers or types are unrecognized. This most frequently
  41. /// occurs when new fields are added to a message type and then messages containing
  42. /// those fields are read by old software that was built before the new types were
  43. /// added.
  44. ///
  45. /// Most users will never need to use this class directly.
  46. /// </summary>
  47. public sealed partial class UnknownFieldSet
  48. {
  49. private readonly IDictionary<int, UnknownField> fields;
  50. /// <summary>
  51. /// Creates a new UnknownFieldSet.
  52. /// </summary>
  53. internal UnknownFieldSet()
  54. {
  55. this.fields = new Dictionary<int, UnknownField>();
  56. }
  57. /// <summary>
  58. /// Checks whether or not the given field number is present in the set.
  59. /// </summary>
  60. internal bool HasField(int field)
  61. {
  62. return fields.ContainsKey(field);
  63. }
  64. /// <summary>
  65. /// Serializes the set and writes it to <paramref name="output"/>.
  66. /// </summary>
  67. public void WriteTo(CodedOutputStream output)
  68. {
  69. foreach (KeyValuePair<int, UnknownField> entry in fields)
  70. {
  71. entry.Value.WriteTo(entry.Key, output);
  72. }
  73. }
  74. /// <summary>
  75. /// Gets the number of bytes required to encode this set.
  76. /// </summary>
  77. public int CalculateSize()
  78. {
  79. int result = 0;
  80. foreach (KeyValuePair<int, UnknownField> entry in fields)
  81. {
  82. result += entry.Value.GetSerializedSize(entry.Key);
  83. }
  84. return result;
  85. }
  86. /// <summary>
  87. /// Checks if two unknown field sets are equal.
  88. /// </summary>
  89. public override bool Equals(object other)
  90. {
  91. if (ReferenceEquals(this, other))
  92. {
  93. return true;
  94. }
  95. UnknownFieldSet otherSet = other as UnknownFieldSet;
  96. IDictionary<int, UnknownField> otherFields = otherSet.fields;
  97. if (fields.Count != otherFields.Count)
  98. {
  99. return false;
  100. }
  101. foreach (KeyValuePair<int, UnknownField> leftEntry in fields)
  102. {
  103. UnknownField rightValue;
  104. if (!otherFields.TryGetValue(leftEntry.Key, out rightValue))
  105. {
  106. return false;
  107. }
  108. if (!leftEntry.Value.Equals(rightValue))
  109. {
  110. return false;
  111. }
  112. }
  113. return true;
  114. }
  115. /// <summary>
  116. /// Gets the unknown field set's hash code.
  117. /// </summary>
  118. public override int GetHashCode()
  119. {
  120. int ret = 1;
  121. foreach (KeyValuePair<int, UnknownField> field in fields)
  122. {
  123. // Use ^ here to make the field order irrelevant.
  124. int hash = field.Key.GetHashCode() ^ field.Value.GetHashCode();
  125. ret ^= hash;
  126. }
  127. return ret;
  128. }
  129. // Optimization: We keep around the last field that was
  130. // modified so that we can efficiently add to it multiple times in a
  131. // row (important when parsing an unknown repeated field).
  132. private int lastFieldNumber;
  133. private UnknownField lastField;
  134. private UnknownField GetOrAddField(int number)
  135. {
  136. if (lastField != null && number == lastFieldNumber)
  137. {
  138. return lastField;
  139. }
  140. if (number == 0)
  141. {
  142. return null;
  143. }
  144. UnknownField existing;
  145. if (fields.TryGetValue(number, out existing))
  146. {
  147. return existing;
  148. }
  149. lastField = new UnknownField();
  150. AddOrReplaceField(number, lastField);
  151. lastFieldNumber = number;
  152. return lastField;
  153. }
  154. /// <summary>
  155. /// Adds a field to the set. If a field with the same number already exists, it
  156. /// is replaced.
  157. /// </summary>
  158. internal UnknownFieldSet AddOrReplaceField(int number, UnknownField field)
  159. {
  160. if (number == 0)
  161. {
  162. throw new ArgumentOutOfRangeException("number", "Zero is not a valid field number.");
  163. }
  164. fields[number] = field;
  165. return this;
  166. }
  167. /// <summary>
  168. /// Parse a single field from <paramref name="input"/> and merge it
  169. /// into this set.
  170. /// </summary>
  171. /// <param name="input">The coded input stream containing the field</param>
  172. /// <returns>false if the tag is an "end group" tag, true otherwise</returns>
  173. private bool MergeFieldFrom(CodedInputStream input)
  174. {
  175. uint tag = input.LastTag;
  176. int number = WireFormat.GetTagFieldNumber(tag);
  177. switch (WireFormat.GetTagWireType(tag))
  178. {
  179. case WireFormat.WireType.Varint:
  180. {
  181. ulong uint64 = input.ReadUInt64();
  182. GetOrAddField(number).AddVarint(uint64);
  183. return true;
  184. }
  185. case WireFormat.WireType.Fixed32:
  186. {
  187. uint uint32 = input.ReadFixed32();
  188. GetOrAddField(number).AddFixed32(uint32);
  189. return true;
  190. }
  191. case WireFormat.WireType.Fixed64:
  192. {
  193. ulong uint64 = input.ReadFixed64();
  194. GetOrAddField(number).AddFixed64(uint64);
  195. return true;
  196. }
  197. case WireFormat.WireType.LengthDelimited:
  198. {
  199. ByteString bytes = input.ReadBytes();
  200. GetOrAddField(number).AddLengthDelimited(bytes);
  201. return true;
  202. }
  203. case WireFormat.WireType.StartGroup:
  204. {
  205. UnknownFieldSet set = new UnknownFieldSet();
  206. input.ReadGroup(number, set);
  207. GetOrAddField(number).AddGroup(set);
  208. return true;
  209. }
  210. case WireFormat.WireType.EndGroup:
  211. {
  212. return false;
  213. }
  214. default:
  215. throw InvalidProtocolBufferException.InvalidWireType();
  216. }
  217. }
  218. internal void MergeGroupFrom(CodedInputStream input)
  219. {
  220. while (true)
  221. {
  222. uint tag = input.ReadTag();
  223. if (tag == 0)
  224. {
  225. break;
  226. }
  227. if (!MergeFieldFrom(input))
  228. {
  229. break;
  230. }
  231. }
  232. }
  233. /// <summary>
  234. /// Create a new UnknownFieldSet if unknownFields is null.
  235. /// Parse a single field from <paramref name="input"/> and merge it
  236. /// into unknownFields. If <paramref name="input"/> is configured to discard unknown fields,
  237. /// <paramref name="unknownFields"/> will be returned as-is and the field will be skipped.
  238. /// </summary>
  239. /// <param name="unknownFields">The UnknownFieldSet which need to be merged</param>
  240. /// <param name="input">The coded input stream containing the field</param>
  241. /// <returns>The merged UnknownFieldSet</returns>
  242. public static UnknownFieldSet MergeFieldFrom(UnknownFieldSet unknownFields,
  243. CodedInputStream input)
  244. {
  245. if (input.DiscardUnknownFields)
  246. {
  247. input.SkipLastField();
  248. return unknownFields;
  249. }
  250. if (unknownFields == null)
  251. {
  252. unknownFields = new UnknownFieldSet();
  253. }
  254. if (!unknownFields.MergeFieldFrom(input))
  255. {
  256. throw new InvalidProtocolBufferException("Merge an unknown field of end-group tag, indicating that the corresponding start-group was missing."); // match the old code-gen
  257. }
  258. return unknownFields;
  259. }
  260. /// <summary>
  261. /// Merges the fields from <paramref name="other"/> into this set.
  262. /// If a field number exists in both sets, the values in <paramref name="other"/>
  263. /// will be appended to the values in this set.
  264. /// </summary>
  265. private UnknownFieldSet MergeFrom(UnknownFieldSet other)
  266. {
  267. if (other != null)
  268. {
  269. foreach (KeyValuePair<int, UnknownField> entry in other.fields)
  270. {
  271. MergeField(entry.Key, entry.Value);
  272. }
  273. }
  274. return this;
  275. }
  276. /// <summary>
  277. /// Created a new UnknownFieldSet to <paramref name="unknownFields"/> if
  278. /// needed and merges the fields from <paramref name="other"/> into the first set.
  279. /// If a field number exists in both sets, the values in <paramref name="other"/>
  280. /// will be appended to the values in this set.
  281. /// </summary>
  282. public static UnknownFieldSet MergeFrom(UnknownFieldSet unknownFields,
  283. UnknownFieldSet other)
  284. {
  285. if (other == null)
  286. {
  287. return unknownFields;
  288. }
  289. if (unknownFields == null)
  290. {
  291. unknownFields = new UnknownFieldSet();
  292. }
  293. unknownFields.MergeFrom(other);
  294. return unknownFields;
  295. }
  296. /// <summary>
  297. /// Adds a field to the unknown field set. If a field with the same
  298. /// number already exists, the two are merged.
  299. /// </summary>
  300. private UnknownFieldSet MergeField(int number, UnknownField field)
  301. {
  302. if (number == 0)
  303. {
  304. throw new ArgumentOutOfRangeException("number", "Zero is not a valid field number.");
  305. }
  306. if (HasField(number))
  307. {
  308. GetOrAddField(number).MergeFrom(field);
  309. }
  310. else
  311. {
  312. AddOrReplaceField(number, field);
  313. }
  314. return this;
  315. }
  316. /// <summary>
  317. /// Clone an unknown field set from <paramref name="other"/>.
  318. /// </summary>
  319. public static UnknownFieldSet Clone(UnknownFieldSet other)
  320. {
  321. if (other == null)
  322. {
  323. return null;
  324. }
  325. UnknownFieldSet unknownFields = new UnknownFieldSet();
  326. unknownFields.MergeFrom(other);
  327. return unknownFields;
  328. }
  329. }
  330. }