MapField.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  1. #region Copyright notice and license
  2. // Protocol Buffers - Google's data interchange format
  3. // Copyright 2015 Google Inc. All rights reserved.
  4. // https://developers.google.com/protocol-buffers/
  5. //
  6. // Redistribution and use in source and binary forms, with or without
  7. // modification, are permitted provided that the following conditions are
  8. // met:
  9. //
  10. // * Redistributions of source code must retain the above copyright
  11. // notice, this list of conditions and the following disclaimer.
  12. // * Redistributions in binary form must reproduce the above
  13. // copyright notice, this list of conditions and the following disclaimer
  14. // in the documentation and/or other materials provided with the
  15. // distribution.
  16. // * Neither the name of Google Inc. nor the names of its
  17. // contributors may be used to endorse or promote products derived from
  18. // this software without specific prior written permission.
  19. //
  20. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  21. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  22. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  23. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  24. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  25. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  26. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  27. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  28. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  29. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  30. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  31. #endregion
  32. using System;
  33. using System.Collections;
  34. using System.Collections.Generic;
  35. using System.Linq;
  36. namespace Google.Protobuf.Collections
  37. {
  38. /// <summary>
  39. /// Representation of a map field in a Protocol Buffer message.
  40. /// </summary>
  41. /// <remarks>
  42. /// This implementation preserves insertion order for simplicity of testing
  43. /// code using maps fields. Overwriting an existing entry does not change the
  44. /// position of that entry within the map. Equality is not order-sensitive.
  45. /// For string keys, the equality comparison is provided by <see cref="StringComparer.Ordinal"/>.
  46. /// </remarks>
  47. /// <typeparam name="TKey">Key type in the map. Must be a type supported by Protocol Buffer map keys.</typeparam>
  48. /// <typeparam name="TValue">Value type in the map. Must be a type supported by Protocol Buffers.</typeparam>
  49. public sealed class MapField<TKey, TValue> : IDeepCloneable<MapField<TKey, TValue>>, IFreezable, IDictionary<TKey, TValue>, IEquatable<MapField<TKey, TValue>>
  50. {
  51. // TODO: Don't create the map/list until we have an entry. (Assume many maps will be empty.)
  52. private bool frozen;
  53. private readonly Dictionary<TKey, LinkedListNode<KeyValuePair<TKey, TValue>>> map =
  54. new Dictionary<TKey, LinkedListNode<KeyValuePair<TKey, TValue>>>();
  55. private readonly LinkedList<KeyValuePair<TKey, TValue>> list = new LinkedList<KeyValuePair<TKey, TValue>>();
  56. public MapField<TKey, TValue> Clone()
  57. {
  58. var clone = new MapField<TKey, TValue>();
  59. // Keys are never cloneable. Values might be.
  60. if (typeof(IDeepCloneable<TValue>).IsAssignableFrom(typeof(TValue)))
  61. {
  62. foreach (var pair in list)
  63. {
  64. clone.Add(pair.Key, pair.Value == null ? pair.Value : ((IDeepCloneable<TValue>) pair.Value).Clone());
  65. }
  66. }
  67. else
  68. {
  69. // Nothing is cloneable, so we don't need to worry.
  70. clone.Add(this);
  71. }
  72. return clone;
  73. }
  74. public void Add(TKey key, TValue value)
  75. {
  76. // Validation of arguments happens in ContainsKey and the indexer
  77. if (ContainsKey(key))
  78. {
  79. throw new ArgumentException("Key already exists in map", "key");
  80. }
  81. this[key] = value;
  82. }
  83. public bool ContainsKey(TKey key)
  84. {
  85. ThrowHelper.ThrowIfNull(key, "key");
  86. return map.ContainsKey(key);
  87. }
  88. public bool Remove(TKey key)
  89. {
  90. this.CheckMutable();
  91. ThrowHelper.ThrowIfNull(key, "key");
  92. LinkedListNode<KeyValuePair<TKey, TValue>> node;
  93. if (map.TryGetValue(key, out node))
  94. {
  95. map.Remove(key);
  96. node.List.Remove(node);
  97. return true;
  98. }
  99. else
  100. {
  101. return false;
  102. }
  103. }
  104. public bool TryGetValue(TKey key, out TValue value)
  105. {
  106. LinkedListNode<KeyValuePair<TKey, TValue>> node;
  107. if (map.TryGetValue(key, out node))
  108. {
  109. value = node.Value.Value;
  110. return true;
  111. }
  112. else
  113. {
  114. value = default(TValue);
  115. return false;
  116. }
  117. }
  118. public TValue this[TKey key]
  119. {
  120. get
  121. {
  122. ThrowHelper.ThrowIfNull(key, "key");
  123. TValue value;
  124. if (TryGetValue(key, out value))
  125. {
  126. return value;
  127. }
  128. throw new KeyNotFoundException();
  129. }
  130. set
  131. {
  132. ThrowHelper.ThrowIfNull(key, "key");
  133. if (value == null && (typeof(TValue) == typeof(ByteString) || typeof(TValue) == typeof(string)))
  134. {
  135. ThrowHelper.ThrowIfNull(value, "value");
  136. }
  137. this.CheckMutable();
  138. LinkedListNode<KeyValuePair<TKey, TValue>> node;
  139. var pair = new KeyValuePair<TKey, TValue>(key, value);
  140. if (map.TryGetValue(key, out node))
  141. {
  142. node.Value = pair;
  143. }
  144. else
  145. {
  146. node = list.AddLast(pair);
  147. map[key] = node;
  148. }
  149. }
  150. }
  151. // TODO: Make these views?
  152. public ICollection<TKey> Keys { get { return list.Select(t => t.Key).ToList(); } }
  153. public ICollection<TValue> Values { get { return list.Select(t => t.Value).ToList(); } }
  154. public void Add(IDictionary<TKey, TValue> entries)
  155. {
  156. ThrowHelper.ThrowIfNull(entries, "entries");
  157. foreach (var pair in entries)
  158. {
  159. Add(pair.Key, pair.Value);
  160. }
  161. }
  162. public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()
  163. {
  164. return list.GetEnumerator();
  165. }
  166. IEnumerator IEnumerable.GetEnumerator()
  167. {
  168. return GetEnumerator();
  169. }
  170. void ICollection<KeyValuePair<TKey, TValue>>.Add(KeyValuePair<TKey, TValue> item)
  171. {
  172. Add(item.Key, item.Value);
  173. }
  174. public void Clear()
  175. {
  176. this.CheckMutable();
  177. list.Clear();
  178. map.Clear();
  179. }
  180. bool ICollection<KeyValuePair<TKey, TValue>>.Contains(KeyValuePair<TKey, TValue> item)
  181. {
  182. TValue value;
  183. return TryGetValue(item.Key, out value)
  184. && EqualityComparer<TValue>.Default.Equals(item.Value, value);
  185. }
  186. void ICollection<KeyValuePair<TKey, TValue>>.CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex)
  187. {
  188. list.CopyTo(array, arrayIndex);
  189. }
  190. bool ICollection<KeyValuePair<TKey, TValue>>.Remove(KeyValuePair<TKey, TValue> item)
  191. {
  192. this.CheckMutable();
  193. if (item.Key == null)
  194. {
  195. throw new ArgumentException("Key is null", "item");
  196. }
  197. LinkedListNode<KeyValuePair<TKey, TValue>> node;
  198. if (map.TryGetValue(item.Key, out node) &&
  199. EqualityComparer<TValue>.Default.Equals(item.Value, node.Value.Value))
  200. {
  201. map.Remove(item.Key);
  202. node.List.Remove(node);
  203. return true;
  204. }
  205. else
  206. {
  207. return false;
  208. }
  209. }
  210. public int Count { get { return list.Count; } }
  211. public bool IsReadOnly { get { return frozen; } }
  212. public void Freeze()
  213. {
  214. if (IsFrozen)
  215. {
  216. return;
  217. }
  218. frozen = true;
  219. // Only values can be frozen, as all the key types are simple.
  220. // Everything can be done in-place, as we're just freezing objects.
  221. if (typeof(IFreezable).IsAssignableFrom(typeof(TValue)))
  222. {
  223. for (var node = list.First; node != null; node = node.Next)
  224. {
  225. var pair = node.Value;
  226. IFreezable freezableValue = pair.Value as IFreezable;
  227. if (freezableValue != null)
  228. {
  229. freezableValue.Freeze();
  230. }
  231. }
  232. }
  233. }
  234. public bool IsFrozen { get { return frozen; } }
  235. public override bool Equals(object other)
  236. {
  237. return Equals(other as MapField<TKey, TValue>);
  238. }
  239. public override int GetHashCode()
  240. {
  241. var valueComparer = EqualityComparer<TValue>.Default;
  242. int hash = 0;
  243. foreach (var pair in list)
  244. {
  245. hash ^= pair.Key.GetHashCode() * 31 + valueComparer.GetHashCode(pair.Value);
  246. }
  247. return hash;
  248. }
  249. public bool Equals(MapField<TKey, TValue> other)
  250. {
  251. if (other == null)
  252. {
  253. return false;
  254. }
  255. if (other == this)
  256. {
  257. return true;
  258. }
  259. if (other.Count != this.Count)
  260. {
  261. return false;
  262. }
  263. var valueComparer = EqualityComparer<TValue>.Default;
  264. foreach (var pair in this)
  265. {
  266. TValue value;
  267. if (!other.TryGetValue(pair.Key, out value))
  268. {
  269. return false;
  270. }
  271. if (!valueComparer.Equals(value, pair.Value))
  272. {
  273. return false;
  274. }
  275. }
  276. return true;
  277. }
  278. /// <summary>
  279. /// Adds entries to the map from the given stream.
  280. /// </summary>
  281. /// <remarks>
  282. /// It is assumed that the stream is initially positioned after the tag specified by the codec.
  283. /// This method will continue reading entries from the stream until the end is reached, or
  284. /// a different tag is encountered.
  285. /// </remarks>
  286. /// <param name="input">Stream to read from</param>
  287. /// <param name="codec">Codec describing how the key/value pairs are encoded</param>
  288. public void AddEntriesFrom(CodedInputStream input, Codec codec)
  289. {
  290. var adapter = new Codec.MessageAdapter(codec);
  291. do
  292. {
  293. adapter.Reset();
  294. input.ReadMessage(adapter);
  295. this[adapter.Key] = adapter.Value;
  296. } while (input.MaybeConsumeTag(codec.MapTag));
  297. }
  298. public void WriteTo(CodedOutputStream output, Codec codec)
  299. {
  300. var message = new Codec.MessageAdapter(codec);
  301. foreach (var entry in list)
  302. {
  303. message.Key = entry.Key;
  304. message.Value = entry.Value;
  305. output.WriteTag(codec.MapTag);
  306. output.WriteMessage(message);
  307. }
  308. }
  309. public int CalculateSize(Codec codec)
  310. {
  311. var message = new Codec.MessageAdapter(codec);
  312. int size = 0;
  313. foreach (var entry in list)
  314. {
  315. message.Key = entry.Key;
  316. message.Value = entry.Value;
  317. size += CodedOutputStream.ComputeRawVarint32Size(codec.MapTag);
  318. size += CodedOutputStream.ComputeMessageSize(message);
  319. }
  320. return size;
  321. }
  322. /// <summary>
  323. /// A codec for a specific map field. This contains all the information required to encoded and
  324. /// decode the nested messages.
  325. /// </summary>
  326. public sealed class Codec
  327. {
  328. private readonly FieldCodec<TKey> keyCodec;
  329. private readonly FieldCodec<TValue> valueCodec;
  330. private readonly uint mapTag;
  331. public Codec(FieldCodec<TKey> keyCodec, FieldCodec<TValue> valueCodec, uint mapTag)
  332. {
  333. this.keyCodec = keyCodec;
  334. this.valueCodec = valueCodec;
  335. this.mapTag = mapTag;
  336. }
  337. /// <summary>
  338. /// The tag used in the enclosing message to indicate map entries.
  339. /// </summary>
  340. internal uint MapTag { get { return mapTag; } }
  341. /// <summary>
  342. /// A mutable message class, used for parsing and serializing. This
  343. /// delegates the work to a codec, but implements the <see cref="IMessage"/> interface
  344. /// for interop with <see cref="CodedInputStream"/> and <see cref="CodedOutputStream"/>.
  345. /// This is nested inside Codec as it's tightly coupled to the associated codec,
  346. /// and it's simpler if it has direct access to all its fields.
  347. /// </summary>
  348. internal class MessageAdapter : IMessage
  349. {
  350. private readonly Codec codec;
  351. internal TKey Key { get; set; }
  352. internal TValue Value { get; set; }
  353. internal MessageAdapter(Codec codec)
  354. {
  355. this.codec = codec;
  356. }
  357. internal void Reset()
  358. {
  359. Key = codec.keyCodec.DefaultValue;
  360. Value = codec.valueCodec.DefaultValue;
  361. }
  362. public void MergeFrom(CodedInputStream input)
  363. {
  364. uint tag;
  365. while (input.ReadTag(out tag))
  366. {
  367. if (tag == 0)
  368. {
  369. throw InvalidProtocolBufferException.InvalidTag();
  370. }
  371. if (tag == codec.keyCodec.Tag)
  372. {
  373. Key = codec.keyCodec.Read(input);
  374. }
  375. else if (tag == codec.valueCodec.Tag)
  376. {
  377. Value = codec.valueCodec.Read(input);
  378. }
  379. else if (WireFormat.IsEndGroupTag(tag))
  380. {
  381. // TODO(jonskeet): Do we need this? (Given that we don't support groups...)
  382. return;
  383. }
  384. }
  385. }
  386. public void WriteTo(CodedOutputStream output)
  387. {
  388. codec.keyCodec.Write(output, Key);
  389. codec.valueCodec.Write(output, Value);
  390. }
  391. public int CalculateSize()
  392. {
  393. return codec.keyCodec.CalculateSize(Key) + codec.valueCodec.CalculateSize(Value);
  394. }
  395. }
  396. }
  397. }
  398. }