forked from lucasmeijer/UnityDictionary
-
Notifications
You must be signed in to change notification settings - Fork 0
/
UnityDictionary.cs
465 lines (382 loc) · 12 KB
/
UnityDictionary.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
using System.Collections;
using System.Runtime.Serialization;
using UnityEngine;
using System.Collections.Generic;
using System;
[Serializable]
public class UnityDictionary<TKey,TValue> : IDictionary<TKey, TValue>, IDictionary
{
[SerializeField]
private List<TKey> _keys = new List<TKey>();
[SerializeField]
private List<TValue> _values = new List<TValue>();
private int _version = 0;
public UnityDictionary()
{
}
public UnityDictionary(int capacity)
{
_keys.Capacity = capacity;
_values.Capacity = capacity;
}
// _cache maps keys to list indices; this allows us to do stuff
// like Remove() as O(1), instead of O(n)
private Dictionary<TKey, int> _cache;
public bool ContainsKey(TKey key)
{
BuildCacheIfNeeded();
return _cache.ContainsKey(key);
}
public void Add(TKey key, TValue value)
{
BuildCacheIfNeeded();
// Add to the cache before adding to the key/value lists
// That way, duplicate or null keys get caught before we
// modify anything permanently.
_cache.Add(key, _keys.Count);
_keys.Add(key);
_values.Add(value);
++_version;
}
public bool Remove(TKey key)
{
BuildCacheIfNeeded();
int index;
if (!_cache.TryGetValue(key, out index))
return false;
RemoveAt(index);
return true;
}
// Private method for removing the key/value pair at a particular index
// This should never be public; dictionaries aren't supposed to have any
// ordering on their elements, so the idea of an element at a particular
// index isn't valid in the outside world. That we're using indexable
// lists for storing keys/values is an implementation detail.
private void RemoveAt(int index)
{
if (_cache != null) _cache.Remove(_keys[index]);
if(_keys.Count > 1)
{
// Copy the final key/value into this index and update the cache if it exists
_keys[index] = _keys[_keys.Count - 1];
_values[index] = _values[_values.Count - 1];
if(_cache != null) _cache[_keys[index]] = index;
}
// Truncate the lists
_keys.RemoveAt(_keys.Count - 1);
_values.RemoveAt(_values.Count - 1);
++_version;
}
public bool TryGetValue(TKey key, out TValue value)
{
BuildCacheIfNeeded();
int index;
if(!_cache.TryGetValue(key, out index))
{
value = default(TValue);
return false;
}
value = _values[index];
return true;
}
TValue IDictionary<TKey, TValue>.this[TKey key]
{
get { return this[key]; }
set { this[key] = value; }
}
public TValue this[TKey key]
{
get
{
BuildCacheIfNeeded();
return _values[_cache[key]];
}
set
{
BuildCacheIfNeeded();
int index;
if (!_cache.TryGetValue(key, out index))
{
// This key isn't presently in the dictionary, so add it
Add(key, value);
}
else
{
// The key is already in the dictionary, just update it
_values[index] = value;
++_version;
}
}
}
public ICollection<TKey> Keys
{
get { return new ReadOnlyListWrapper<TKey>(_keys); }
}
public ICollection<TValue> Values
{
get { return new ReadOnlyListWrapper<TValue>(_values); }
}
ICollection IDictionary.Keys
{
get { return new ReadOnlyListWrapper<TKey>(_keys); }
}
ICollection IDictionary.Values
{
get { return new ReadOnlyListWrapper<TValue>(_values); }
}
void BuildCacheIfNeeded()
{
if(_cache == null) BuildCache();
}
void BuildCache()
{
_cache = new Dictionary<TKey,int>();
for (int i=0; i!=_keys.Count; i++)
{
_cache.Add(_keys[i], i);
}
}
#region Implementation of IEnumerable
private class Enumerator : IEnumerator<KeyValuePair<TKey, TValue>>, IDictionaryEnumerator
{
public void Dispose() { }
private int _index = -1;
private readonly UnityDictionary<TKey, TValue> _dict;
private readonly int _initialVersion;
public Enumerator(UnityDictionary<TKey, TValue> dict)
{
_dict = dict;
_initialVersion = dict._version;
Reset();
}
#region Implementation of IEnumerator
public bool MoveNext()
{
if(_dict._version != _initialVersion)
throw new InvalidOperationException("The dictionary was modified while enumerating.");
++_index;
return _index < _dict.Count;
}
public void Reset()
{
_index = -1;
}
public KeyValuePair<TKey, TValue> Current
{
get {
if (_dict._version != _initialVersion)
throw new InvalidOperationException("The dictionary was modified while enumerating.");
if(_index < 0 || _index >= _dict.Count) throw new InvalidOperationException();
return new KeyValuePair<TKey, TValue>(_dict._keys[_index], _dict._values[_index]);
}
}
object IEnumerator.Current
{
get { return Current; }
}
#endregion
#region Implementation of IDictionaryEnumerator
public object Key
{
get { return Current.Key; }
}
public object Value
{
get { return Current.Value; }
}
public DictionaryEntry Entry
{
get { return new DictionaryEntry(Current.Key, Current.Value); }
}
#endregion
}
[Serializable]
private class NonGenericEnumerator : IDictionaryEnumerator
{
private readonly Enumerator _e;
public NonGenericEnumerator(Enumerator e) { _e = e; }
// Map .Current to .Entry for the sake of old nongeneric clients that don't
// are expecting DictionaryEntry instead of KeyValuePair<TKey, TValue>
public object Current { get { return Entry; } }
public bool MoveNext() { return _e.MoveNext(); }
public void Reset() { _e.Reset(); }
public DictionaryEntry Entry { get { return _e.Entry; } }
public object Key { get { return _e.Current.Key; } }
public object Value { get { return _e.Current.Value; } }
}
public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()
{
return new Enumerator(this);
}
public void Remove(object key)
{
if(key == null) throw new ArgumentNullException("key");
BuildCacheIfNeeded();
if (!((IDictionary)_cache).Contains(key))
return;
int index = (int) ((IDictionary) _cache)[key];
RemoveAt(index);
}
object IDictionary.this[object key]
{
get {
if (key == null) throw new ArgumentNullException("key");
BuildCacheIfNeeded();
if (!((IDictionary)_cache).Contains(key)) return null;
int index = (int) ((IDictionary) _cache)[key];
return _values[index];
}
set {
if (key == null) throw new ArgumentNullException("key");
BuildCacheIfNeeded();
if (!((IDictionary)_cache).Contains(key))
{
Add(key, value);
}
else
{
TValue tV = ConvertObjectValHelper<TValue>(value);
int index = (int)((IDictionary)_cache)[key];
_values[index] = tV;
++_version;
}
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
IDictionaryEnumerator IDictionary.GetEnumerator()
{
return new NonGenericEnumerator(new Enumerator(this));
}
#endregion
#region Implementation of ICollection<KeyValuePair<TKey,TValue>>
public void Add(KeyValuePair<TKey, TValue> item)
{
Add(item.Key, item.Value);
}
public bool Contains(object key)
{
if(key == null)
throw new ArgumentNullException("key");
BuildCacheIfNeeded();
return ((IDictionary) _cache).Contains(key);
}
private static T ConvertObjectValHelper<T>(object obj)
{
T result;
try
{
if (obj != null)
result = (T)obj;
else if (!typeof(T).IsValueType)
result = default(T);
else
throw new ArgumentException();
}
catch (InvalidCastException)
{
throw new ArgumentException(string.Format("The value \"{0}\" is not of type \"{1}\" and cannot be used in this generic collection.", obj, typeof(T).FullName));
}
return result;
}
public void Add(object key, object value)
{
if(key == null) throw new ArgumentNullException("key");
TKey tK = ConvertObjectValHelper<TKey>(key);
TValue tV = ConvertObjectValHelper<TValue>(value);
Add(tK, tV);
}
public void Clear()
{
_keys.Clear();
_values.Clear();
if (_cache == null)
_cache = new Dictionary<TKey, int>();
else
_cache.Clear();
++_version;
}
public bool Contains(KeyValuePair<TKey, TValue> item)
{
BuildCacheIfNeeded();
int index;
if (!_cache.TryGetValue(item.Key, out index))
return false;
return EqualityComparer<TValue>.Default.Equals(_values[index], item.Value);
}
public void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex)
{
if(array == null)
throw new ArgumentNullException("array");
if(arrayIndex < 0)
throw new ArgumentOutOfRangeException("arrayIndex");
if(array.Length - arrayIndex < Count)
throw new ArgumentException("The provided array is too small.");
for(int i = 0; i < _keys.Count; ++i, ++arrayIndex)
{
array[arrayIndex] = new KeyValuePair<TKey, TValue>(_keys[i], _values[i]);
}
}
public bool Remove(KeyValuePair<TKey, TValue> item)
{
BuildCacheIfNeeded();
int index;
if (!_cache.TryGetValue(item.Key, out index))
return false;
if (!EqualityComparer<TValue>.Default.Equals(_values[index], item.Value))
return false;
RemoveAt(index);
return true;
}
public void CopyTo(Array array, int index)
{
if (array == null)
throw new ArgumentNullException("array");
if (index < 0)
throw new ArgumentOutOfRangeException("index");
if (array.Length - index < Count)
throw new ArgumentException("The provided array is too small.");
if(!(array is KeyValuePair<TKey, TValue>[]) && !(array is DictionaryEntry[]) && !(array is object[]))
throw new ArgumentException("The array is not of the appropriate type.");
if(array is DictionaryEntry[])
{
for (int i = 0; i < _keys.Count; ++i, ++index)
{
array.SetValue(new DictionaryEntry(_keys[i], _values[i]), index);
}
}
else
{
for (int i = 0; i < _keys.Count; ++i, ++index)
{
array.SetValue(new KeyValuePair<TKey, TValue>(_keys[i], _values[i]), index);
}
}
}
public int Count
{
get { return _keys.Count; }
}
public object SyncRoot
{
get { return this; }
}
public bool IsSynchronized
{
get { return false; }
}
public bool IsReadOnly
{
get { return false; }
}
public bool IsFixedSize
{
get { return false; }
}
#endregion
}
//Unfortunately, Unity currently doesn't serialize UnityDictionary<int,string>, but it will serialize a dummy subclass of that.
[Serializable]
public class UnityDictionaryIntString : UnityDictionary<int,string> {}