MapField.cs 28 KB

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