RepeatedField.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526
  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. namespace Google.Protobuf.Collections
  36. {
  37. /// <summary>
  38. /// The contents of a repeated field: essentially, a collection with some extra
  39. /// restrictions (no null values) and capabilities (deep cloning and freezing).
  40. /// </summary>
  41. /// <typeparam name="T">The element type of the repeated field.</typeparam>
  42. public sealed class RepeatedField<T> : IList<T>, IList, IDeepCloneable<RepeatedField<T>>, IEquatable<RepeatedField<T>>, IFreezable
  43. {
  44. private static readonly T[] EmptyArray = new T[0];
  45. private bool frozen;
  46. private const int MinArraySize = 8;
  47. private T[] array = EmptyArray;
  48. private int count = 0;
  49. /// <summary>
  50. /// Creates a deep clone of this repeated field.
  51. /// </summary>
  52. /// <remarks>
  53. /// If the field type is
  54. /// a message type, each element is also cloned; otherwise, it is
  55. /// assumed that the field type is primitive (including string and
  56. /// bytes, both of which are immutable) and so a simple copy is
  57. /// equivalent to a deep clone.
  58. /// </remarks>
  59. /// <returns>A deep clone of this repeated field.</returns>
  60. public RepeatedField<T> Clone()
  61. {
  62. RepeatedField<T> clone = new RepeatedField<T>();
  63. // Clone is implicitly *not* frozen, even if this object is.
  64. if (array != EmptyArray)
  65. {
  66. clone.array = (T[])array.Clone();
  67. IDeepCloneable<T>[] cloneableArray = clone.array as IDeepCloneable<T>[];
  68. if (cloneableArray != null)
  69. {
  70. for (int i = 0; i < count; i++)
  71. {
  72. clone.array[i] = cloneableArray[i].Clone();
  73. }
  74. }
  75. }
  76. clone.count = count;
  77. return clone;
  78. }
  79. public void AddEntriesFrom(CodedInputStream input, FieldCodec<T> codec)
  80. {
  81. // TODO: Inline some of the Add code, so we can avoid checking the size on every
  82. // iteration and the mutability.
  83. uint tag = input.LastTag;
  84. var reader = codec.ValueReader;
  85. // Value types can be packed or not.
  86. if (typeof(T).IsValueType && WireFormat.GetTagWireType(tag) == WireFormat.WireType.LengthDelimited)
  87. {
  88. int length = input.ReadLength();
  89. if (length > 0)
  90. {
  91. int oldLimit = input.PushLimit(length);
  92. while (!input.ReachedLimit)
  93. {
  94. Add(reader(input));
  95. }
  96. input.PopLimit(oldLimit);
  97. }
  98. // Empty packed field. Odd, but valid - just ignore.
  99. }
  100. else
  101. {
  102. // Not packed... (possibly not packable)
  103. do
  104. {
  105. Add(reader(input));
  106. } while (input.MaybeConsumeTag(tag));
  107. }
  108. }
  109. public int CalculateSize(FieldCodec<T> codec)
  110. {
  111. if (count == 0)
  112. {
  113. return 0;
  114. }
  115. uint tag = codec.Tag;
  116. if (typeof(T).IsValueType && WireFormat.GetTagWireType(tag) == WireFormat.WireType.LengthDelimited)
  117. {
  118. int dataSize = CalculatePackedDataSize(codec);
  119. return CodedOutputStream.ComputeRawVarint32Size(tag) +
  120. CodedOutputStream.ComputeRawVarint32Size((uint)dataSize) +
  121. dataSize;
  122. }
  123. else
  124. {
  125. var sizeCalculator = codec.ValueSizeCalculator;
  126. int size = count * CodedOutputStream.ComputeRawVarint32Size(tag);
  127. for (int i = 0; i < count; i++)
  128. {
  129. size += sizeCalculator(array[i]);
  130. }
  131. return size;
  132. }
  133. }
  134. private int CalculatePackedDataSize(FieldCodec<T> codec)
  135. {
  136. int fixedSize = codec.FixedSize;
  137. if (fixedSize == 0)
  138. {
  139. var calculator = codec.ValueSizeCalculator;
  140. int tmp = 0;
  141. for (int i = 0; i < count; i++)
  142. {
  143. tmp += calculator(array[i]);
  144. }
  145. return tmp;
  146. }
  147. else
  148. {
  149. return fixedSize * Count;
  150. }
  151. }
  152. public void WriteTo(CodedOutputStream output, FieldCodec<T> codec)
  153. {
  154. if (count == 0)
  155. {
  156. return;
  157. }
  158. var writer = codec.ValueWriter;
  159. var tag = codec.Tag;
  160. if (typeof(T).IsValueType && WireFormat.GetTagWireType(tag) == WireFormat.WireType.LengthDelimited)
  161. {
  162. // Packed primitive type
  163. uint size = (uint)CalculatePackedDataSize(codec);
  164. output.WriteTag(tag);
  165. output.WriteRawVarint32(size);
  166. for (int i = 0; i < count; i++)
  167. {
  168. writer(output, array[i]);
  169. }
  170. }
  171. else
  172. {
  173. // Not packed: a simple tag/value pair for each value.
  174. // Can't use codec.WriteTagAndValue, as that omits default values.
  175. for (int i = 0; i < count; i++)
  176. {
  177. output.WriteTag(tag);
  178. writer(output, array[i]);
  179. }
  180. }
  181. }
  182. public bool IsFrozen { get { return frozen; } }
  183. public void Freeze()
  184. {
  185. frozen = true;
  186. IFreezable[] freezableArray = array as IFreezable[];
  187. if (freezableArray != null)
  188. {
  189. for (int i = 0; i < count; i++)
  190. {
  191. freezableArray[i].Freeze();
  192. }
  193. }
  194. }
  195. private void EnsureSize(int size)
  196. {
  197. if (array.Length < size)
  198. {
  199. size = Math.Max(size, MinArraySize);
  200. int newSize = Math.Max(array.Length * 2, size);
  201. var tmp = new T[newSize];
  202. Array.Copy(array, 0, tmp, 0, array.Length);
  203. array = tmp;
  204. }
  205. }
  206. public void Add(T item)
  207. {
  208. if (item == null)
  209. {
  210. throw new ArgumentNullException("item");
  211. }
  212. this.CheckMutable();
  213. EnsureSize(count + 1);
  214. array[count++] = item;
  215. }
  216. public void Clear()
  217. {
  218. this.CheckMutable();
  219. array = EmptyArray;
  220. count = 0;
  221. }
  222. public bool Contains(T item)
  223. {
  224. return IndexOf(item) != -1;
  225. }
  226. public void CopyTo(T[] array, int arrayIndex)
  227. {
  228. Array.Copy(this.array, 0, array, arrayIndex, count);
  229. }
  230. public bool Remove(T item)
  231. {
  232. this.CheckMutable();
  233. int index = IndexOf(item);
  234. if (index == -1)
  235. {
  236. return false;
  237. }
  238. Array.Copy(array, index + 1, array, index, count - index - 1);
  239. count--;
  240. array[count] = default(T);
  241. return true;
  242. }
  243. public int Count { get { return count; } }
  244. // TODO(jonskeet): If we implement freezing, make this reflect it.
  245. public bool IsReadOnly { get { return IsFrozen; } }
  246. public void Add(RepeatedField<T> values)
  247. {
  248. if (values == null)
  249. {
  250. throw new ArgumentNullException("values");
  251. }
  252. this.CheckMutable();
  253. EnsureSize(count + values.count);
  254. // We know that all the values will be valid, because it's a RepeatedField.
  255. Array.Copy(values.array, 0, array, count, values.count);
  256. count += values.count;
  257. }
  258. public void Add(IEnumerable<T> values)
  259. {
  260. if (values == null)
  261. {
  262. throw new ArgumentNullException("values");
  263. }
  264. this.CheckMutable();
  265. // TODO: Check for ICollection and get the Count?
  266. foreach (T item in values)
  267. {
  268. Add(item);
  269. }
  270. }
  271. public RepeatedField<T>.Enumerator GetEnumerator()
  272. {
  273. return new Enumerator(this);
  274. }
  275. IEnumerator<T> IEnumerable<T>.GetEnumerator()
  276. {
  277. return GetEnumerator();
  278. }
  279. public override bool Equals(object obj)
  280. {
  281. return Equals(obj as RepeatedField<T>);
  282. }
  283. IEnumerator IEnumerable.GetEnumerator()
  284. {
  285. return GetEnumerator();
  286. }
  287. public override int GetHashCode()
  288. {
  289. int hash = 0;
  290. for (int i = 0; i < count; i++)
  291. {
  292. hash = hash * 31 + array[i].GetHashCode();
  293. }
  294. return hash;
  295. }
  296. public bool Equals(RepeatedField<T> other)
  297. {
  298. if (ReferenceEquals(other, null))
  299. {
  300. return false;
  301. }
  302. if (ReferenceEquals(other, this))
  303. {
  304. return true;
  305. }
  306. if (other.Count != this.Count)
  307. {
  308. return false;
  309. }
  310. // TODO(jonskeet): Does this box for enums?
  311. EqualityComparer<T> comparer = EqualityComparer<T>.Default;
  312. for (int i = 0; i < count; i++)
  313. {
  314. if (!comparer.Equals(array[i], other.array[i]))
  315. {
  316. return false;
  317. }
  318. }
  319. return true;
  320. }
  321. public int IndexOf(T item)
  322. {
  323. if (item == null)
  324. {
  325. throw new ArgumentNullException("item");
  326. }
  327. // TODO(jonskeet): Does this box for enums?
  328. EqualityComparer<T> comparer = EqualityComparer<T>.Default;
  329. for (int i = 0; i < count; i++)
  330. {
  331. if (comparer.Equals(array[i], item))
  332. {
  333. return i;
  334. }
  335. }
  336. return -1;
  337. }
  338. public void Insert(int index, T item)
  339. {
  340. if (item == null)
  341. {
  342. throw new ArgumentNullException("item");
  343. }
  344. if (index < 0 || index > count)
  345. {
  346. throw new ArgumentOutOfRangeException("index");
  347. }
  348. this.CheckMutable();
  349. EnsureSize(count + 1);
  350. Array.Copy(array, index, array, index + 1, count - index);
  351. count++;
  352. }
  353. public void RemoveAt(int index)
  354. {
  355. if (index < 0 || index >= count)
  356. {
  357. throw new ArgumentOutOfRangeException("index");
  358. }
  359. this.CheckMutable();
  360. Array.Copy(array, index + 1, array, index, count - index - 1);
  361. count--;
  362. array[count] = default(T);
  363. }
  364. public T this[int index]
  365. {
  366. get
  367. {
  368. if (index < 0 || index >= count)
  369. {
  370. throw new ArgumentOutOfRangeException("index");
  371. }
  372. return array[index];
  373. }
  374. set
  375. {
  376. if (index < 0 || index >= count)
  377. {
  378. throw new ArgumentOutOfRangeException("index");
  379. }
  380. this.CheckMutable();
  381. if (value == null)
  382. {
  383. throw new ArgumentNullException("value");
  384. }
  385. array[index] = value;
  386. }
  387. }
  388. #region Explicit interface implementation for IList and ICollection.
  389. bool IList.IsFixedSize { get { return IsFrozen; } }
  390. void ICollection.CopyTo(Array array, int index)
  391. {
  392. ThrowHelper.ThrowIfNull(array, "array");
  393. T[] strongArray = array as T[];
  394. if (strongArray == null)
  395. {
  396. throw new ArgumentException("Array is of incorrect type", "array");
  397. }
  398. CopyTo(strongArray, index);
  399. }
  400. bool ICollection.IsSynchronized { get { return false; } }
  401. object ICollection.SyncRoot { get { return null; } }
  402. object IList.this[int index]
  403. {
  404. get { return this[index]; }
  405. set { this[index] = (T)value; }
  406. }
  407. int IList.Add(object value)
  408. {
  409. Add((T) value);
  410. return count - 1;
  411. }
  412. bool IList.Contains(object value)
  413. {
  414. return (value is T && Contains((T)value));
  415. }
  416. int IList.IndexOf(object value)
  417. {
  418. if (!(value is T))
  419. {
  420. return -1;
  421. }
  422. return IndexOf((T)value);
  423. }
  424. void IList.Insert(int index, object value)
  425. {
  426. Insert(index, (T) value);
  427. }
  428. void IList.Remove(object value)
  429. {
  430. if (!(value is T))
  431. {
  432. return;
  433. }
  434. Remove((T)value);
  435. }
  436. #endregion
  437. public struct Enumerator : IEnumerator<T>
  438. {
  439. private int index;
  440. private readonly RepeatedField<T> field;
  441. public Enumerator(RepeatedField<T> field)
  442. {
  443. this.field = field;
  444. this.index = -1;
  445. }
  446. public bool MoveNext()
  447. {
  448. if (index + 1 >= field.Count)
  449. {
  450. return false;
  451. }
  452. index++;
  453. return true;
  454. }
  455. public void Reset()
  456. {
  457. index = -1;
  458. }
  459. public T Current
  460. {
  461. get
  462. {
  463. if (index == -1 || index >= field.count)
  464. {
  465. throw new InvalidOperationException();
  466. }
  467. return field.array[index];
  468. }
  469. }
  470. object IEnumerator.Current
  471. {
  472. get { return Current; }
  473. }
  474. public void Dispose()
  475. {
  476. }
  477. }
  478. }
  479. }