MapField.cs 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760
  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 Google.Protobuf.Reflection;
  33. using System;
  34. using System.Collections;
  35. using System.Collections.Generic;
  36. using System.IO;
  37. using System.Linq;
  38. using System.Text;
  39. using Google.Protobuf.Compatibility;
  40. namespace Google.Protobuf.Collections
  41. {
  42. /// <summary>
  43. /// Representation of a map field in a Protocol Buffer message.
  44. /// </summary>
  45. /// <typeparam name="TKey">Key type in the map. Must be a type supported by Protocol Buffer map keys.</typeparam>
  46. /// <typeparam name="TValue">Value type in the map. Must be a type supported by Protocol Buffers.</typeparam>
  47. /// <remarks>
  48. /// <para>
  49. /// This implementation preserves insertion order for simplicity of testing
  50. /// code using maps fields. Overwriting an existing entry does not change the
  51. /// position of that entry within the map. Equality is not order-sensitive.
  52. /// For string keys, the equality comparison is provided by <see cref="StringComparer.Ordinal" />.
  53. /// </para>
  54. /// <para>
  55. /// Null values are not permitted in the map, either for wrapper types or regular messages.
  56. /// If a map is deserialized from a data stream and the value is missing from an entry, a default value
  57. /// is created instead. For primitive types, that is the regular default value (0, the empty string and so
  58. /// on); for message types, an empty instance of the message is created, as if the map entry contained a 0-length
  59. /// encoded value for the field.
  60. /// </para>
  61. /// <para>
  62. /// This implementation does not generally prohibit the use of key/value types which are not
  63. /// supported by Protocol Buffers (e.g. using a key type of <code>byte</code>) but nor does it guarantee
  64. /// that all operations will work in such cases.
  65. /// </para>
  66. /// </remarks>
  67. public sealed class MapField<TKey, TValue> : IDeepCloneable<MapField<TKey, TValue>>, IDictionary<TKey, TValue>, IEquatable<MapField<TKey, TValue>>, IDictionary
  68. {
  69. // TODO: Don't create the map/list until we have an entry. (Assume many maps will be empty.)
  70. private readonly Dictionary<TKey, LinkedListNode<KeyValuePair<TKey, TValue>>> map =
  71. new Dictionary<TKey, LinkedListNode<KeyValuePair<TKey, TValue>>>();
  72. private readonly LinkedList<KeyValuePair<TKey, TValue>> list = new LinkedList<KeyValuePair<TKey, TValue>>();
  73. /// <summary>
  74. /// Creates a deep clone of this object.
  75. /// </summary>
  76. /// <returns>
  77. /// A deep clone of this object.
  78. /// </returns>
  79. public MapField<TKey, TValue> Clone()
  80. {
  81. var clone = new MapField<TKey, TValue>();
  82. // Keys are never cloneable. Values might be.
  83. if (typeof(IDeepCloneable<TValue>).IsAssignableFrom(typeof(TValue)))
  84. {
  85. foreach (var pair in list)
  86. {
  87. clone.Add(pair.Key, ((IDeepCloneable<TValue>)pair.Value).Clone());
  88. }
  89. }
  90. else
  91. {
  92. // Nothing is cloneable, so we don't need to worry.
  93. clone.Add(this);
  94. }
  95. return clone;
  96. }
  97. /// <summary>
  98. /// Adds the specified key/value pair to the map.
  99. /// </summary>
  100. /// <remarks>
  101. /// This operation fails if the key already exists in the map. To replace an existing entry, use the indexer.
  102. /// </remarks>
  103. /// <param name="key">The key to add</param>
  104. /// <param name="value">The value to add.</param>
  105. /// <exception cref="System.ArgumentException">The given key already exists in map.</exception>
  106. public void Add(TKey key, TValue value)
  107. {
  108. // Validation of arguments happens in ContainsKey and the indexer
  109. if (ContainsKey(key))
  110. {
  111. throw new ArgumentException("Key already exists in map", "key");
  112. }
  113. this[key] = value;
  114. }
  115. /// <summary>
  116. /// Determines whether the specified key is present in the map.
  117. /// </summary>
  118. /// <param name="key">The key to check.</param>
  119. /// <returns><c>true</c> if the map contains the given key; <c>false</c> otherwise.</returns>
  120. public bool ContainsKey(TKey key)
  121. {
  122. ProtoPreconditions.CheckNotNullUnconstrained(key, "key");
  123. return map.ContainsKey(key);
  124. }
  125. private bool ContainsValue(TValue value)
  126. {
  127. var comparer = EqualityComparer<TValue>.Default;
  128. return list.Any(pair => comparer.Equals(pair.Value, value));
  129. }
  130. /// <summary>
  131. /// Removes the entry identified by the given key from the map.
  132. /// </summary>
  133. /// <param name="key">The key indicating the entry to remove from the map.</param>
  134. /// <returns><c>true</c> if the map contained the given key before the entry was removed; <c>false</c> otherwise.</returns>
  135. public bool Remove(TKey key)
  136. {
  137. ProtoPreconditions.CheckNotNullUnconstrained(key, "key");
  138. LinkedListNode<KeyValuePair<TKey, TValue>> node;
  139. if (map.TryGetValue(key, out node))
  140. {
  141. map.Remove(key);
  142. node.List.Remove(node);
  143. return true;
  144. }
  145. else
  146. {
  147. return false;
  148. }
  149. }
  150. /// <summary>
  151. /// Gets the value associated with the specified key.
  152. /// </summary>
  153. /// <param name="key">The key whose value to get.</param>
  154. /// <param name="value">When this method returns, the value associated with the specified key, if the key is found;
  155. /// otherwise, the default value for the type of the <paramref name="value"/> parameter.
  156. /// This parameter is passed uninitialized.</param>
  157. /// <returns><c>true</c> if the map contains an element with the specified key; otherwise, <c>false</c>.</returns>
  158. public bool TryGetValue(TKey key, out TValue value)
  159. {
  160. LinkedListNode<KeyValuePair<TKey, TValue>> node;
  161. if (map.TryGetValue(key, out node))
  162. {
  163. value = node.Value.Value;
  164. return true;
  165. }
  166. else
  167. {
  168. value = default(TValue);
  169. return false;
  170. }
  171. }
  172. /// <summary>
  173. /// Gets or sets the value associated with the specified key.
  174. /// </summary>
  175. /// <param name="key">The key of the value to get or set.</param>
  176. /// <exception cref="KeyNotFoundException">The property is retrieved and key does not exist in the collection.</exception>
  177. /// <returns>The value associated with the specified key. If the specified key is not found,
  178. /// a get operation throws a <see cref="KeyNotFoundException"/>, and a set operation creates a new element with the specified key.</returns>
  179. public TValue this[TKey key]
  180. {
  181. get
  182. {
  183. ProtoPreconditions.CheckNotNullUnconstrained(key, "key");
  184. TValue value;
  185. if (TryGetValue(key, out value))
  186. {
  187. return value;
  188. }
  189. throw new KeyNotFoundException();
  190. }
  191. set
  192. {
  193. ProtoPreconditions.CheckNotNullUnconstrained(key, "key");
  194. // value == null check here is redundant, but avoids boxing.
  195. if (value == null)
  196. {
  197. ProtoPreconditions.CheckNotNullUnconstrained(value, "value");
  198. }
  199. LinkedListNode<KeyValuePair<TKey, TValue>> node;
  200. var pair = new KeyValuePair<TKey, TValue>(key, value);
  201. if (map.TryGetValue(key, out node))
  202. {
  203. node.Value = pair;
  204. }
  205. else
  206. {
  207. node = list.AddLast(pair);
  208. map[key] = node;
  209. }
  210. }
  211. }
  212. /// <summary>
  213. /// Gets a collection containing the keys in the map.
  214. /// </summary>
  215. public ICollection<TKey> Keys { get { return new MapView<TKey>(this, pair => pair.Key, ContainsKey); } }
  216. /// <summary>
  217. /// Gets a collection containing the values in the map.
  218. /// </summary>
  219. public ICollection<TValue> Values { get { return new MapView<TValue>(this, pair => pair.Value, ContainsValue); } }
  220. /// <summary>
  221. /// Adds the specified entries to the map. The keys and values are not automatically cloned.
  222. /// </summary>
  223. /// <param name="entries">The entries to add to the map.</param>
  224. public void Add(IDictionary<TKey, TValue> entries)
  225. {
  226. ProtoPreconditions.CheckNotNull(entries, "entries");
  227. foreach (var pair in entries)
  228. {
  229. Add(pair.Key, pair.Value);
  230. }
  231. }
  232. /// <summary>
  233. /// Returns an enumerator that iterates through the collection.
  234. /// </summary>
  235. /// <returns>
  236. /// An enumerator that can be used to iterate through the collection.
  237. /// </returns>
  238. public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()
  239. {
  240. return list.GetEnumerator();
  241. }
  242. /// <summary>
  243. /// Returns an enumerator that iterates through a collection.
  244. /// </summary>
  245. /// <returns>
  246. /// An <see cref="T:System.Collections.IEnumerator" /> object that can be used to iterate through the collection.
  247. /// </returns>
  248. IEnumerator IEnumerable.GetEnumerator()
  249. {
  250. return GetEnumerator();
  251. }
  252. /// <summary>
  253. /// Adds the specified item to the map.
  254. /// </summary>
  255. /// <param name="item">The item to add to the map.</param>
  256. void ICollection<KeyValuePair<TKey, TValue>>.Add(KeyValuePair<TKey, TValue> item)
  257. {
  258. Add(item.Key, item.Value);
  259. }
  260. /// <summary>
  261. /// Removes all items from the map.
  262. /// </summary>
  263. public void Clear()
  264. {
  265. list.Clear();
  266. map.Clear();
  267. }
  268. /// <summary>
  269. /// Determines whether map contains an entry equivalent to the given key/value pair.
  270. /// </summary>
  271. /// <param name="item">The key/value pair to find.</param>
  272. /// <returns></returns>
  273. bool ICollection<KeyValuePair<TKey, TValue>>.Contains(KeyValuePair<TKey, TValue> item)
  274. {
  275. TValue value;
  276. return TryGetValue(item.Key, out value)
  277. && EqualityComparer<TValue>.Default.Equals(item.Value, value);
  278. }
  279. /// <summary>
  280. /// Copies the key/value pairs in this map to an array.
  281. /// </summary>
  282. /// <param name="array">The array to copy the entries into.</param>
  283. /// <param name="arrayIndex">The index of the array at which to start copying values.</param>
  284. void ICollection<KeyValuePair<TKey, TValue>>.CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex)
  285. {
  286. list.CopyTo(array, arrayIndex);
  287. }
  288. /// <summary>
  289. /// Removes the specified key/value pair from the map.
  290. /// </summary>
  291. /// <remarks>Both the key and the value must be found for the entry to be removed.</remarks>
  292. /// <param name="item">The key/value pair to remove.</param>
  293. /// <returns><c>true</c> if the key/value pair was found and removed; <c>false</c> otherwise.</returns>
  294. bool ICollection<KeyValuePair<TKey, TValue>>.Remove(KeyValuePair<TKey, TValue> item)
  295. {
  296. if (item.Key == null)
  297. {
  298. throw new ArgumentException("Key is null", "item");
  299. }
  300. LinkedListNode<KeyValuePair<TKey, TValue>> node;
  301. if (map.TryGetValue(item.Key, out node) &&
  302. EqualityComparer<TValue>.Default.Equals(item.Value, node.Value.Value))
  303. {
  304. map.Remove(item.Key);
  305. node.List.Remove(node);
  306. return true;
  307. }
  308. else
  309. {
  310. return false;
  311. }
  312. }
  313. /// <summary>
  314. /// Gets the number of elements contained in the map.
  315. /// </summary>
  316. public int Count { get { return list.Count; } }
  317. /// <summary>
  318. /// Gets a value indicating whether the map is read-only.
  319. /// </summary>
  320. public bool IsReadOnly { get { return false; } }
  321. /// <summary>
  322. /// Determines whether the specified <see cref="System.Object" />, is equal to this instance.
  323. /// </summary>
  324. /// <param name="other">The <see cref="System.Object" /> to compare with this instance.</param>
  325. /// <returns>
  326. /// <c>true</c> if the specified <see cref="System.Object" /> is equal to this instance; otherwise, <c>false</c>.
  327. /// </returns>
  328. public override bool Equals(object other)
  329. {
  330. return Equals(other as MapField<TKey, TValue>);
  331. }
  332. /// <summary>
  333. /// Returns a hash code for this instance.
  334. /// </summary>
  335. /// <returns>
  336. /// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.
  337. /// </returns>
  338. public override int GetHashCode()
  339. {
  340. var valueComparer = EqualityComparer<TValue>.Default;
  341. int hash = 0;
  342. foreach (var pair in list)
  343. {
  344. hash ^= pair.Key.GetHashCode() * 31 + valueComparer.GetHashCode(pair.Value);
  345. }
  346. return hash;
  347. }
  348. /// <summary>
  349. /// Compares this map with another for equality.
  350. /// </summary>
  351. /// <remarks>
  352. /// The order of the key/value pairs in the maps is not deemed significant in this comparison.
  353. /// </remarks>
  354. /// <param name="other">The map to compare this with.</param>
  355. /// <returns><c>true</c> if <paramref name="other"/> refers to an equal map; <c>false</c> otherwise.</returns>
  356. public bool Equals(MapField<TKey, TValue> other)
  357. {
  358. if (other == null)
  359. {
  360. return false;
  361. }
  362. if (other == this)
  363. {
  364. return true;
  365. }
  366. if (other.Count != this.Count)
  367. {
  368. return false;
  369. }
  370. var valueComparer = EqualityComparer<TValue>.Default;
  371. foreach (var pair in this)
  372. {
  373. TValue value;
  374. if (!other.TryGetValue(pair.Key, out value))
  375. {
  376. return false;
  377. }
  378. if (!valueComparer.Equals(value, pair.Value))
  379. {
  380. return false;
  381. }
  382. }
  383. return true;
  384. }
  385. /// <summary>
  386. /// Adds entries to the map from the given stream.
  387. /// </summary>
  388. /// <remarks>
  389. /// It is assumed that the stream is initially positioned after the tag specified by the codec.
  390. /// This method will continue reading entries from the stream until the end is reached, or
  391. /// a different tag is encountered.
  392. /// </remarks>
  393. /// <param name="input">Stream to read from</param>
  394. /// <param name="codec">Codec describing how the key/value pairs are encoded</param>
  395. public void AddEntriesFrom(CodedInputStream input, Codec codec)
  396. {
  397. var adapter = new Codec.MessageAdapter(codec);
  398. do
  399. {
  400. adapter.Reset();
  401. input.ReadMessage(adapter);
  402. this[adapter.Key] = adapter.Value;
  403. } while (input.MaybeConsumeTag(codec.MapTag));
  404. }
  405. /// <summary>
  406. /// Writes the contents of this map to the given coded output stream, using the specified codec
  407. /// to encode each entry.
  408. /// </summary>
  409. /// <param name="output">The output stream to write to.</param>
  410. /// <param name="codec">The codec to use for each entry.</param>
  411. public void WriteTo(CodedOutputStream output, Codec codec)
  412. {
  413. var message = new Codec.MessageAdapter(codec);
  414. foreach (var entry in list)
  415. {
  416. message.Key = entry.Key;
  417. message.Value = entry.Value;
  418. output.WriteTag(codec.MapTag);
  419. output.WriteMessage(message);
  420. }
  421. }
  422. /// <summary>
  423. /// Calculates the size of this map based on the given entry codec.
  424. /// </summary>
  425. /// <param name="codec">The codec to use to encode each entry.</param>
  426. /// <returns></returns>
  427. public int CalculateSize(Codec codec)
  428. {
  429. if (Count == 0)
  430. {
  431. return 0;
  432. }
  433. var message = new Codec.MessageAdapter(codec);
  434. int size = 0;
  435. foreach (var entry in list)
  436. {
  437. message.Key = entry.Key;
  438. message.Value = entry.Value;
  439. size += CodedOutputStream.ComputeRawVarint32Size(codec.MapTag);
  440. size += CodedOutputStream.ComputeMessageSize(message);
  441. }
  442. return size;
  443. }
  444. /// <summary>
  445. /// Returns a string representation of this repeated field, in the same
  446. /// way as it would be represented by the default JSON formatter.
  447. /// </summary>
  448. public override string ToString()
  449. {
  450. var writer = new StringWriter();
  451. JsonFormatter.Default.WriteDictionary(writer, this);
  452. return writer.ToString();
  453. }
  454. #region IDictionary explicit interface implementation
  455. void IDictionary.Add(object key, object value)
  456. {
  457. Add((TKey)key, (TValue)value);
  458. }
  459. bool IDictionary.Contains(object key)
  460. {
  461. if (!(key is TKey))
  462. {
  463. return false;
  464. }
  465. return ContainsKey((TKey)key);
  466. }
  467. IDictionaryEnumerator IDictionary.GetEnumerator()
  468. {
  469. return new DictionaryEnumerator(GetEnumerator());
  470. }
  471. void IDictionary.Remove(object key)
  472. {
  473. ProtoPreconditions.CheckNotNull(key, "key");
  474. if (!(key is TKey))
  475. {
  476. return;
  477. }
  478. Remove((TKey)key);
  479. }
  480. void ICollection.CopyTo(Array array, int index)
  481. {
  482. // This is ugly and slow as heck, but with any luck it will never be used anyway.
  483. ICollection temp = this.Select(pair => new DictionaryEntry(pair.Key, pair.Value)).ToList();
  484. temp.CopyTo(array, index);
  485. }
  486. bool IDictionary.IsFixedSize { get { return false; } }
  487. ICollection IDictionary.Keys { get { return (ICollection)Keys; } }
  488. ICollection IDictionary.Values { get { return (ICollection)Values; } }
  489. bool ICollection.IsSynchronized { get { return false; } }
  490. object ICollection.SyncRoot { get { return this; } }
  491. object IDictionary.this[object key]
  492. {
  493. get
  494. {
  495. ProtoPreconditions.CheckNotNull(key, "key");
  496. if (!(key is TKey))
  497. {
  498. return null;
  499. }
  500. TValue value;
  501. TryGetValue((TKey)key, out value);
  502. return value;
  503. }
  504. set
  505. {
  506. this[(TKey)key] = (TValue)value;
  507. }
  508. }
  509. #endregion
  510. private class DictionaryEnumerator : IDictionaryEnumerator
  511. {
  512. private readonly IEnumerator<KeyValuePair<TKey, TValue>> enumerator;
  513. internal DictionaryEnumerator(IEnumerator<KeyValuePair<TKey, TValue>> enumerator)
  514. {
  515. this.enumerator = enumerator;
  516. }
  517. public bool MoveNext()
  518. {
  519. return enumerator.MoveNext();
  520. }
  521. public void Reset()
  522. {
  523. enumerator.Reset();
  524. }
  525. public object Current { get { return Entry; } }
  526. public DictionaryEntry Entry { get { return new DictionaryEntry(Key, Value); } }
  527. public object Key { get { return enumerator.Current.Key; } }
  528. public object Value { get { return enumerator.Current.Value; } }
  529. }
  530. /// <summary>
  531. /// A codec for a specific map field. This contains all the information required to encode and
  532. /// decode the nested messages.
  533. /// </summary>
  534. public sealed class Codec
  535. {
  536. private readonly FieldCodec<TKey> keyCodec;
  537. private readonly FieldCodec<TValue> valueCodec;
  538. private readonly uint mapTag;
  539. /// <summary>
  540. /// Creates a new entry codec based on a separate key codec and value codec,
  541. /// and the tag to use for each map entry.
  542. /// </summary>
  543. /// <param name="keyCodec">The key codec.</param>
  544. /// <param name="valueCodec">The value codec.</param>
  545. /// <param name="mapTag">The map tag to use to introduce each map entry.</param>
  546. public Codec(FieldCodec<TKey> keyCodec, FieldCodec<TValue> valueCodec, uint mapTag)
  547. {
  548. this.keyCodec = keyCodec;
  549. this.valueCodec = valueCodec;
  550. this.mapTag = mapTag;
  551. }
  552. /// <summary>
  553. /// The tag used in the enclosing message to indicate map entries.
  554. /// </summary>
  555. internal uint MapTag { get { return mapTag; } }
  556. /// <summary>
  557. /// A mutable message class, used for parsing and serializing. This
  558. /// delegates the work to a codec, but implements the <see cref="IMessage"/> interface
  559. /// for interop with <see cref="CodedInputStream"/> and <see cref="CodedOutputStream"/>.
  560. /// This is nested inside Codec as it's tightly coupled to the associated codec,
  561. /// and it's simpler if it has direct access to all its fields.
  562. /// </summary>
  563. internal class MessageAdapter : IMessage
  564. {
  565. private static readonly byte[] ZeroLengthMessageStreamData = new byte[] { 0 };
  566. private readonly Codec codec;
  567. internal TKey Key { get; set; }
  568. internal TValue Value { get; set; }
  569. internal MessageAdapter(Codec codec)
  570. {
  571. this.codec = codec;
  572. }
  573. internal void Reset()
  574. {
  575. Key = codec.keyCodec.DefaultValue;
  576. Value = codec.valueCodec.DefaultValue;
  577. }
  578. public void MergeFrom(CodedInputStream input)
  579. {
  580. uint tag;
  581. while ((tag = input.ReadTag()) != 0)
  582. {
  583. if (tag == codec.keyCodec.Tag)
  584. {
  585. Key = codec.keyCodec.Read(input);
  586. }
  587. else if (tag == codec.valueCodec.Tag)
  588. {
  589. Value = codec.valueCodec.Read(input);
  590. }
  591. else
  592. {
  593. input.SkipLastField();
  594. }
  595. }
  596. // Corner case: a map entry with a key but no value, where the value type is a message.
  597. // Read it as if we'd seen an input stream with no data (i.e. create a "default" message).
  598. if (Value == null)
  599. {
  600. Value = codec.valueCodec.Read(new CodedInputStream(ZeroLengthMessageStreamData));
  601. }
  602. }
  603. public void WriteTo(CodedOutputStream output)
  604. {
  605. codec.keyCodec.WriteTagAndValue(output, Key);
  606. codec.valueCodec.WriteTagAndValue(output, Value);
  607. }
  608. public int CalculateSize()
  609. {
  610. return codec.keyCodec.CalculateSizeWithTag(Key) + codec.valueCodec.CalculateSizeWithTag(Value);
  611. }
  612. MessageDescriptor IMessage.Descriptor { get { return null; } }
  613. }
  614. }
  615. private class MapView<T> : ICollection<T>, ICollection
  616. {
  617. private readonly MapField<TKey, TValue> parent;
  618. private readonly Func<KeyValuePair<TKey, TValue>, T> projection;
  619. private readonly Func<T, bool> containsCheck;
  620. internal MapView(
  621. MapField<TKey, TValue> parent,
  622. Func<KeyValuePair<TKey, TValue>, T> projection,
  623. Func<T, bool> containsCheck)
  624. {
  625. this.parent = parent;
  626. this.projection = projection;
  627. this.containsCheck = containsCheck;
  628. }
  629. public int Count { get { return parent.Count; } }
  630. public bool IsReadOnly { get { return true; } }
  631. public bool IsSynchronized { get { return false; } }
  632. public object SyncRoot { get { return parent; } }
  633. public void Add(T item)
  634. {
  635. throw new NotSupportedException();
  636. }
  637. public void Clear()
  638. {
  639. throw new NotSupportedException();
  640. }
  641. public bool Contains(T item)
  642. {
  643. return containsCheck(item);
  644. }
  645. public void CopyTo(T[] array, int arrayIndex)
  646. {
  647. if (arrayIndex < 0)
  648. {
  649. throw new ArgumentOutOfRangeException("arrayIndex");
  650. }
  651. if (arrayIndex + Count >= array.Length)
  652. {
  653. throw new ArgumentException("Not enough space in the array", "array");
  654. }
  655. foreach (var item in this)
  656. {
  657. array[arrayIndex++] = item;
  658. }
  659. }
  660. public IEnumerator<T> GetEnumerator()
  661. {
  662. return parent.list.Select(projection).GetEnumerator();
  663. }
  664. public bool Remove(T item)
  665. {
  666. throw new NotSupportedException();
  667. }
  668. IEnumerator IEnumerable.GetEnumerator()
  669. {
  670. return GetEnumerator();
  671. }
  672. public void CopyTo(Array array, int index)
  673. {
  674. if (index < 0)
  675. {
  676. throw new ArgumentOutOfRangeException("index");
  677. }
  678. if (index + Count >= array.Length)
  679. {
  680. throw new ArgumentException("Not enough space in the array", "array");
  681. }
  682. foreach (var item in this)
  683. {
  684. array.SetValue(item, index++);
  685. }
  686. }
  687. }
  688. }
  689. }