5 // Alexander Chebaturkin (chebaturkin@gmail.com)
7 // Copyright (C) 2011 Alexander Chebaturkin
9 // Permission is hereby granted, free of charge, to any person obtaining
10 // a copy of this software and associated documentation files (the
11 // "Software"), to deal in the Software without restriction, including
12 // without limitation the rights to use, copy, modify, merge, publish,
13 // distribute, sublicense, and/or sell copies of the Software, and to
14 // permit persons to whom the Software is furnished to do so, subject to
15 // the following conditions:
17 // The above copyright notice and this permission notice shall be
18 // included in all copies or substantial portions of the Software.
20 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
21 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
22 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
23 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
24 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
25 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
26 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
30 using System.Collections.Generic;
33 namespace Mono.CodeContracts.Static.DataStructures {
34 class ImmutableIntMap<T> : IImmutableIntMap<T> {
35 private readonly Dictionary<int, T> map = new Dictionary<int, T> ();
37 private ImmutableIntMap (Dictionary<int, T> map)
42 #region Implementation of IImm utableIntMap<T>
43 public T this [int key]
47 if (this.map == null || !this.map.ContainsKey (key))
50 return this.map [key];
60 return this.map.Values.First ();
64 public IEnumerable<T> Values
69 return Enumerable.Empty<T> ();
70 return this.map.Values;
74 public IEnumerable<int> Keys
79 return Enumerable.Empty<int> ();
90 return this.map.Count;
94 public T Lookup (int key)
98 return this.map [key];
101 public bool Contains (int key)
103 if (this.map == null)
105 return this.map.ContainsKey (key);
108 public IImmutableIntMap<T> Add (int key, T value)
110 if (this.map == null)
111 return new ImmutableIntMap<T> (new Dictionary<int, T> {{key, value}});
113 var newDict = new Dictionary<int, T> (this.map);
114 newDict [key] = value;
115 return new ImmutableIntMap<T> (newDict);
118 public IImmutableIntMap<T> Remove (int key)
120 if (this.map == null || !this.map.ContainsKey (key))
123 var newDict = new Dictionary<int, T> (this.map);
124 newDict.Remove (key);
125 return new ImmutableIntMap<T> (newDict);
128 public void Visit (Action<T> action)
130 foreach (T value in Values)
134 public void Visit (Action<int, T> action)
136 foreach (int key in Keys)
137 action (key, this [key]);
141 public static IImmutableIntMap<T> Empty ()
143 return new ImmutableIntMap<T> (null);