RepeatedField.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521
  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 const int MinArraySize = 8;
  46. private bool frozen;
  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. public bool IsReadOnly { get { return IsFrozen; } }
  245. public void Add(RepeatedField<T> values)
  246. {
  247. if (values == null)
  248. {
  249. throw new ArgumentNullException("values");
  250. }
  251. this.CheckMutable();
  252. EnsureSize(count + values.count);
  253. // We know that all the values will be valid, because it's a RepeatedField.
  254. Array.Copy(values.array, 0, array, count, values.count);
  255. count += values.count;
  256. }
  257. public void Add(IEnumerable<T> values)
  258. {
  259. if (values == null)
  260. {
  261. throw new ArgumentNullException("values");
  262. }
  263. this.CheckMutable();
  264. // TODO: Check for ICollection and get the Count?
  265. foreach (T item in values)
  266. {
  267. Add(item);
  268. }
  269. }
  270. public RepeatedField<T>.Enumerator GetEnumerator()
  271. {
  272. return new Enumerator(this);
  273. }
  274. IEnumerator<T> IEnumerable<T>.GetEnumerator()
  275. {
  276. return GetEnumerator();
  277. }
  278. public override bool Equals(object obj)
  279. {
  280. return Equals(obj as RepeatedField<T>);
  281. }
  282. IEnumerator IEnumerable.GetEnumerator()
  283. {
  284. return GetEnumerator();
  285. }
  286. public override int GetHashCode()
  287. {
  288. int hash = 0;
  289. for (int i = 0; i < count; i++)
  290. {
  291. hash = hash * 31 + array[i].GetHashCode();
  292. }
  293. return hash;
  294. }
  295. public bool Equals(RepeatedField<T> other)
  296. {
  297. if (ReferenceEquals(other, null))
  298. {
  299. return false;
  300. }
  301. if (ReferenceEquals(other, this))
  302. {
  303. return true;
  304. }
  305. if (other.Count != this.Count)
  306. {
  307. return false;
  308. }
  309. // TODO(jonskeet): Does this box for enums?
  310. EqualityComparer<T> comparer = EqualityComparer<T>.Default;
  311. for (int i = 0; i < count; i++)
  312. {
  313. if (!comparer.Equals(array[i], other.array[i]))
  314. {
  315. return false;
  316. }
  317. }
  318. return true;
  319. }
  320. public int IndexOf(T item)
  321. {
  322. if (item == null)
  323. {
  324. throw new ArgumentNullException("item");
  325. }
  326. // TODO(jonskeet): Does this box for enums?
  327. EqualityComparer<T> comparer = EqualityComparer<T>.Default;
  328. for (int i = 0; i < count; i++)
  329. {
  330. if (comparer.Equals(array[i], item))
  331. {
  332. return i;
  333. }
  334. }
  335. return -1;
  336. }
  337. public void Insert(int index, T item)
  338. {
  339. if (item == null)
  340. {
  341. throw new ArgumentNullException("item");
  342. }
  343. if (index < 0 || index > count)
  344. {
  345. throw new ArgumentOutOfRangeException("index");
  346. }
  347. this.CheckMutable();
  348. EnsureSize(count + 1);
  349. Array.Copy(array, index, array, index + 1, count - index);
  350. array[index] = item;
  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. Array.Copy(this.array, 0, array, index, count);
  393. }
  394. bool ICollection.IsSynchronized { get { return false; } }
  395. object ICollection.SyncRoot { get { return this; } }
  396. object IList.this[int index]
  397. {
  398. get { return this[index]; }
  399. set { this[index] = (T)value; }
  400. }
  401. int IList.Add(object value)
  402. {
  403. Add((T) value);
  404. return count - 1;
  405. }
  406. bool IList.Contains(object value)
  407. {
  408. return (value is T && Contains((T)value));
  409. }
  410. int IList.IndexOf(object value)
  411. {
  412. if (!(value is T))
  413. {
  414. return -1;
  415. }
  416. return IndexOf((T)value);
  417. }
  418. void IList.Insert(int index, object value)
  419. {
  420. Insert(index, (T) value);
  421. }
  422. void IList.Remove(object value)
  423. {
  424. if (!(value is T))
  425. {
  426. return;
  427. }
  428. Remove((T)value);
  429. }
  430. #endregion
  431. public struct Enumerator : IEnumerator<T>
  432. {
  433. private int index;
  434. private readonly RepeatedField<T> field;
  435. public Enumerator(RepeatedField<T> field)
  436. {
  437. this.field = field;
  438. this.index = -1;
  439. }
  440. public bool MoveNext()
  441. {
  442. if (index + 1 >= field.Count)
  443. {
  444. index = field.Count;
  445. return false;
  446. }
  447. index++;
  448. return true;
  449. }
  450. public void Reset()
  451. {
  452. index = -1;
  453. }
  454. public T Current
  455. {
  456. get
  457. {
  458. if (index == -1 || index >= field.count)
  459. {
  460. throw new InvalidOperationException();
  461. }
  462. return field.array[index];
  463. }
  464. }
  465. object IEnumerator.Current
  466. {
  467. get { return Current; }
  468. }
  469. public void Dispose()
  470. {
  471. }
  472. }
  473. }
  474. }