RepeatedField.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591
  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;
  34. using System.Collections.Generic;
  35. using System.IO;
  36. namespace Google.Protobuf.Collections
  37. {
  38. /// <summary>
  39. /// The contents of a repeated field: essentially, a collection with some extra
  40. /// restrictions (no null values) and capabilities (deep cloning).
  41. /// </summary>
  42. /// <remarks>
  43. /// This implementation does not generally prohibit the use of types which are not
  44. /// supported by Protocol Buffers but nor does it guarantee that all operations will work in such cases.
  45. /// </remarks>
  46. /// <typeparam name="T">The element type of the repeated field.</typeparam>
  47. public sealed class RepeatedField<T> : IList<T>, IList, IDeepCloneable<RepeatedField<T>>, IEquatable<RepeatedField<T>>
  48. {
  49. private static readonly T[] EmptyArray = new T[0];
  50. private const int MinArraySize = 8;
  51. private T[] array = EmptyArray;
  52. private int count = 0;
  53. /// <summary>
  54. /// Creates a deep clone of this repeated field.
  55. /// </summary>
  56. /// <remarks>
  57. /// If the field type is
  58. /// a message type, each element is also cloned; otherwise, it is
  59. /// assumed that the field type is primitive (including string and
  60. /// bytes, both of which are immutable) and so a simple copy is
  61. /// equivalent to a deep clone.
  62. /// </remarks>
  63. /// <returns>A deep clone of this repeated field.</returns>
  64. public RepeatedField<T> Clone()
  65. {
  66. RepeatedField<T> clone = new RepeatedField<T>();
  67. if (array != EmptyArray)
  68. {
  69. clone.array = (T[])array.Clone();
  70. IDeepCloneable<T>[] cloneableArray = clone.array as IDeepCloneable<T>[];
  71. if (cloneableArray != null)
  72. {
  73. for (int i = 0; i < count; i++)
  74. {
  75. clone.array[i] = cloneableArray[i].Clone();
  76. }
  77. }
  78. }
  79. clone.count = count;
  80. return clone;
  81. }
  82. /// <summary>
  83. /// Adds the entries from the given input stream, decoding them with the specified codec.
  84. /// </summary>
  85. /// <param name="input">The input stream to read from.</param>
  86. /// <param name="codec">The codec to use in order to read each entry.</param>
  87. public void AddEntriesFrom(CodedInputStream input, FieldCodec<T> codec)
  88. {
  89. // TODO: Inline some of the Add code, so we can avoid checking the size on every
  90. // iteration.
  91. uint tag = input.LastTag;
  92. var reader = codec.ValueReader;
  93. // Non-nullable value types can be packed or not.
  94. if (FieldCodec<T>.IsPackedRepeatedField(tag))
  95. {
  96. int length = input.ReadLength();
  97. if (length > 0)
  98. {
  99. int oldLimit = input.PushLimit(length);
  100. while (!input.ReachedLimit)
  101. {
  102. Add(reader(input));
  103. }
  104. input.PopLimit(oldLimit);
  105. }
  106. // Empty packed field. Odd, but valid - just ignore.
  107. }
  108. else
  109. {
  110. // Not packed... (possibly not packable)
  111. do
  112. {
  113. Add(reader(input));
  114. } while (input.MaybeConsumeTag(tag));
  115. }
  116. }
  117. /// <summary>
  118. /// Calculates the size of this collection based on the given codec.
  119. /// </summary>
  120. /// <param name="codec">The codec to use when encoding each field.</param>
  121. /// <returns>The number of bytes that would be written to a <see cref="CodedOutputStream"/> by <see cref="WriteTo"/>,
  122. /// using the same codec.</returns>
  123. public int CalculateSize(FieldCodec<T> codec)
  124. {
  125. if (count == 0)
  126. {
  127. return 0;
  128. }
  129. uint tag = codec.Tag;
  130. if (codec.PackedRepeatedField)
  131. {
  132. int dataSize = CalculatePackedDataSize(codec);
  133. return CodedOutputStream.ComputeRawVarint32Size(tag) +
  134. CodedOutputStream.ComputeLengthSize(dataSize) +
  135. dataSize;
  136. }
  137. else
  138. {
  139. var sizeCalculator = codec.ValueSizeCalculator;
  140. int size = count * CodedOutputStream.ComputeRawVarint32Size(tag);
  141. for (int i = 0; i < count; i++)
  142. {
  143. size += sizeCalculator(array[i]);
  144. }
  145. return size;
  146. }
  147. }
  148. private int CalculatePackedDataSize(FieldCodec<T> codec)
  149. {
  150. int fixedSize = codec.FixedSize;
  151. if (fixedSize == 0)
  152. {
  153. var calculator = codec.ValueSizeCalculator;
  154. int tmp = 0;
  155. for (int i = 0; i < count; i++)
  156. {
  157. tmp += calculator(array[i]);
  158. }
  159. return tmp;
  160. }
  161. else
  162. {
  163. return fixedSize * Count;
  164. }
  165. }
  166. /// <summary>
  167. /// Writes the contents of this collection to the given <see cref="CodedOutputStream"/>,
  168. /// encoding each value using the specified codec.
  169. /// </summary>
  170. /// <param name="output">The output stream to write to.</param>
  171. /// <param name="codec">The codec to use when encoding each value.</param>
  172. public void WriteTo(CodedOutputStream output, FieldCodec<T> codec)
  173. {
  174. if (count == 0)
  175. {
  176. return;
  177. }
  178. var writer = codec.ValueWriter;
  179. var tag = codec.Tag;
  180. if (codec.PackedRepeatedField)
  181. {
  182. // Packed primitive type
  183. uint size = (uint)CalculatePackedDataSize(codec);
  184. output.WriteTag(tag);
  185. output.WriteRawVarint32(size);
  186. for (int i = 0; i < count; i++)
  187. {
  188. writer(output, array[i]);
  189. }
  190. }
  191. else
  192. {
  193. // Not packed: a simple tag/value pair for each value.
  194. // Can't use codec.WriteTagAndValue, as that omits default values.
  195. for (int i = 0; i < count; i++)
  196. {
  197. output.WriteTag(tag);
  198. writer(output, array[i]);
  199. }
  200. }
  201. }
  202. private void EnsureSize(int size)
  203. {
  204. if (array.Length < size)
  205. {
  206. size = Math.Max(size, MinArraySize);
  207. int newSize = Math.Max(array.Length * 2, size);
  208. var tmp = new T[newSize];
  209. Array.Copy(array, 0, tmp, 0, array.Length);
  210. array = tmp;
  211. }
  212. }
  213. /// <summary>
  214. /// Adds the specified item to the collection.
  215. /// </summary>
  216. /// <param name="item">The item to add.</param>
  217. public void Add(T item)
  218. {
  219. ProtoPreconditions.CheckNotNullUnconstrained(item, nameof(item));
  220. EnsureSize(count + 1);
  221. array[count++] = item;
  222. }
  223. /// <summary>
  224. /// Removes all items from the collection.
  225. /// </summary>
  226. public void Clear()
  227. {
  228. array = EmptyArray;
  229. count = 0;
  230. }
  231. /// <summary>
  232. /// Determines whether this collection contains the given item.
  233. /// </summary>
  234. /// <param name="item">The item to find.</param>
  235. /// <returns><c>true</c> if this collection contains the given item; <c>false</c> otherwise.</returns>
  236. public bool Contains(T item)
  237. {
  238. return IndexOf(item) != -1;
  239. }
  240. /// <summary>
  241. /// Copies this collection to the given array.
  242. /// </summary>
  243. /// <param name="array">The array to copy to.</param>
  244. /// <param name="arrayIndex">The first index of the array to copy to.</param>
  245. public void CopyTo(T[] array, int arrayIndex)
  246. {
  247. Array.Copy(this.array, 0, array, arrayIndex, count);
  248. }
  249. /// <summary>
  250. /// Removes the specified item from the collection
  251. /// </summary>
  252. /// <param name="item">The item to remove.</param>
  253. /// <returns><c>true</c> if the item was found and removed; <c>false</c> otherwise.</returns>
  254. public bool Remove(T item)
  255. {
  256. int index = IndexOf(item);
  257. if (index == -1)
  258. {
  259. return false;
  260. }
  261. Array.Copy(array, index + 1, array, index, count - index - 1);
  262. count--;
  263. array[count] = default(T);
  264. return true;
  265. }
  266. /// <summary>
  267. /// Gets the number of elements contained in the collection.
  268. /// </summary>
  269. public int Count => count;
  270. /// <summary>
  271. /// Gets a value indicating whether the collection is read-only.
  272. /// </summary>
  273. public bool IsReadOnly => false;
  274. /// <summary>
  275. /// Adds all of the specified values into this collection.
  276. /// </summary>
  277. /// <param name="values">The values to add to this collection.</param>
  278. public void AddRange(IEnumerable<T> values)
  279. {
  280. ProtoPreconditions.CheckNotNull(values, nameof(values));
  281. // Optimization 1: If the collection we're adding is already a RepeatedField<T>,
  282. // we know the values are valid.
  283. var otherRepeatedField = values as RepeatedField<T>;
  284. if (otherRepeatedField != null)
  285. {
  286. EnsureSize(count + otherRepeatedField.count);
  287. Array.Copy(otherRepeatedField.array, 0, array, count, otherRepeatedField.count);
  288. count += otherRepeatedField.count;
  289. return;
  290. }
  291. // Optimization 2: The collection is an ICollection, so we can expand
  292. // just once and ask the collection to copy itself into the array.
  293. var collection = values as ICollection;
  294. if (collection != null)
  295. {
  296. var extraCount = collection.Count;
  297. // For reference types and nullable value types, we need to check that there are no nulls
  298. // present. (This isn't a thread-safe approach, but we don't advertise this is thread-safe.)
  299. // We expect the JITter to optimize this test to true/false, so it's effectively conditional
  300. // specialization.
  301. if (default(T) == null)
  302. {
  303. // TODO: Measure whether iterating once to check and then letting the collection copy
  304. // itself is faster or slower than iterating and adding as we go. For large
  305. // collections this will not be great in terms of cache usage... but the optimized
  306. // copy may be significantly faster than doing it one at a time.
  307. foreach (var item in collection)
  308. {
  309. if (item == null)
  310. {
  311. throw new ArgumentException("Sequence contained null element", nameof(values));
  312. }
  313. }
  314. }
  315. EnsureSize(count + extraCount);
  316. collection.CopyTo(array, count);
  317. count += extraCount;
  318. return;
  319. }
  320. // We *could* check for ICollection<T> as well, but very very few collections implement
  321. // ICollection<T> but not ICollection. (HashSet<T> does, for one...)
  322. // Fall back to a slower path of adding items one at a time.
  323. foreach (T item in values)
  324. {
  325. Add(item);
  326. }
  327. }
  328. /// <summary>
  329. /// Adds all of the specified values into this collection. This method is present to
  330. /// allow repeated fields to be constructed from queries within collection initializers.
  331. /// Within non-collection-initializer code, consider using the equivalent <see cref="AddRange"/>
  332. /// method instead for clarity.
  333. /// </summary>
  334. /// <param name="values">The values to add to this collection.</param>
  335. public void Add(IEnumerable<T> values)
  336. {
  337. AddRange(values);
  338. }
  339. /// <summary>
  340. /// Returns an enumerator that iterates through the collection.
  341. /// </summary>
  342. /// <returns>
  343. /// An enumerator that can be used to iterate through the collection.
  344. /// </returns>
  345. public IEnumerator<T> GetEnumerator()
  346. {
  347. for (int i = 0; i < count; i++)
  348. {
  349. yield return array[i];
  350. }
  351. }
  352. /// <summary>
  353. /// Determines whether the specified <see cref="System.Object" />, is equal to this instance.
  354. /// </summary>
  355. /// <param name="obj">The <see cref="System.Object" /> to compare with this instance.</param>
  356. /// <returns>
  357. /// <c>true</c> if the specified <see cref="System.Object" /> is equal to this instance; otherwise, <c>false</c>.
  358. /// </returns>
  359. public override bool Equals(object obj)
  360. {
  361. return Equals(obj as RepeatedField<T>);
  362. }
  363. /// <summary>
  364. /// Returns an enumerator that iterates through a collection.
  365. /// </summary>
  366. /// <returns>
  367. /// An <see cref="T:System.Collections.IEnumerator" /> object that can be used to iterate through the collection.
  368. /// </returns>
  369. IEnumerator IEnumerable.GetEnumerator()
  370. {
  371. return GetEnumerator();
  372. }
  373. /// <summary>
  374. /// Returns a hash code for this instance.
  375. /// </summary>
  376. /// <returns>
  377. /// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.
  378. /// </returns>
  379. public override int GetHashCode()
  380. {
  381. int hash = 0;
  382. for (int i = 0; i < count; i++)
  383. {
  384. hash = hash * 31 + array[i].GetHashCode();
  385. }
  386. return hash;
  387. }
  388. /// <summary>
  389. /// Compares this repeated field with another for equality.
  390. /// </summary>
  391. /// <param name="other">The repeated field to compare this with.</param>
  392. /// <returns><c>true</c> if <paramref name="other"/> refers to an equal repeated field; <c>false</c> otherwise.</returns>
  393. public bool Equals(RepeatedField<T> other)
  394. {
  395. if (ReferenceEquals(other, null))
  396. {
  397. return false;
  398. }
  399. if (ReferenceEquals(other, this))
  400. {
  401. return true;
  402. }
  403. if (other.Count != this.Count)
  404. {
  405. return false;
  406. }
  407. EqualityComparer<T> comparer = EqualityComparer<T>.Default;
  408. for (int i = 0; i < count; i++)
  409. {
  410. if (!comparer.Equals(array[i], other.array[i]))
  411. {
  412. return false;
  413. }
  414. }
  415. return true;
  416. }
  417. /// <summary>
  418. /// Returns the index of the given item within the collection, or -1 if the item is not
  419. /// present.
  420. /// </summary>
  421. /// <param name="item">The item to find in the collection.</param>
  422. /// <returns>The zero-based index of the item, or -1 if it is not found.</returns>
  423. public int IndexOf(T item)
  424. {
  425. ProtoPreconditions.CheckNotNullUnconstrained(item, nameof(item));
  426. EqualityComparer<T> comparer = EqualityComparer<T>.Default;
  427. for (int i = 0; i < count; i++)
  428. {
  429. if (comparer.Equals(array[i], item))
  430. {
  431. return i;
  432. }
  433. }
  434. return -1;
  435. }
  436. /// <summary>
  437. /// Inserts the given item at the specified index.
  438. /// </summary>
  439. /// <param name="index">The index at which to insert the item.</param>
  440. /// <param name="item">The item to insert.</param>
  441. public void Insert(int index, T item)
  442. {
  443. ProtoPreconditions.CheckNotNullUnconstrained(item, nameof(item));
  444. if (index < 0 || index > count)
  445. {
  446. throw new ArgumentOutOfRangeException(nameof(index));
  447. }
  448. EnsureSize(count + 1);
  449. Array.Copy(array, index, array, index + 1, count - index);
  450. array[index] = item;
  451. count++;
  452. }
  453. /// <summary>
  454. /// Removes the item at the given index.
  455. /// </summary>
  456. /// <param name="index">The zero-based index of the item to remove.</param>
  457. public void RemoveAt(int index)
  458. {
  459. if (index < 0 || index >= count)
  460. {
  461. throw new ArgumentOutOfRangeException(nameof(index));
  462. }
  463. Array.Copy(array, index + 1, array, index, count - index - 1);
  464. count--;
  465. array[count] = default(T);
  466. }
  467. /// <summary>
  468. /// Returns a string representation of this repeated field, in the same
  469. /// way as it would be represented by the default JSON formatter.
  470. /// </summary>
  471. public override string ToString()
  472. {
  473. var writer = new StringWriter();
  474. JsonFormatter.Default.WriteList(writer, this);
  475. return writer.ToString();
  476. }
  477. /// <summary>
  478. /// Gets or sets the item at the specified index.
  479. /// </summary>
  480. /// <value>
  481. /// The element at the specified index.
  482. /// </value>
  483. /// <param name="index">The zero-based index of the element to get or set.</param>
  484. /// <returns>The item at the specified index.</returns>
  485. public T this[int index]
  486. {
  487. get
  488. {
  489. if (index < 0 || index >= count)
  490. {
  491. throw new ArgumentOutOfRangeException(nameof(index));
  492. }
  493. return array[index];
  494. }
  495. set
  496. {
  497. if (index < 0 || index >= count)
  498. {
  499. throw new ArgumentOutOfRangeException(nameof(index));
  500. }
  501. ProtoPreconditions.CheckNotNullUnconstrained(value, nameof(value));
  502. array[index] = value;
  503. }
  504. }
  505. #region Explicit interface implementation for IList and ICollection.
  506. bool IList.IsFixedSize => false;
  507. void ICollection.CopyTo(Array array, int index)
  508. {
  509. Array.Copy(this.array, 0, array, index, count);
  510. }
  511. bool ICollection.IsSynchronized => false;
  512. object ICollection.SyncRoot => this;
  513. object IList.this[int index]
  514. {
  515. get { return this[index]; }
  516. set { this[index] = (T)value; }
  517. }
  518. int IList.Add(object value)
  519. {
  520. Add((T) value);
  521. return count - 1;
  522. }
  523. bool IList.Contains(object value)
  524. {
  525. return (value is T && Contains((T)value));
  526. }
  527. int IList.IndexOf(object value)
  528. {
  529. if (!(value is T))
  530. {
  531. return -1;
  532. }
  533. return IndexOf((T)value);
  534. }
  535. void IList.Insert(int index, object value)
  536. {
  537. Insert(index, (T) value);
  538. }
  539. void IList.Remove(object value)
  540. {
  541. if (!(value is T))
  542. {
  543. return;
  544. }
  545. Remove((T)value);
  546. }
  547. #endregion
  548. }
  549. }