MapField.cs 33 KB

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