MapField.cs 29 KB

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