/
OrderedDictionary.cs
672 lines (599 loc) · 22.6 KB
/
OrderedDictionary.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
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.ComponentModel;
using System.Diagnostics;
using System.Runtime.Serialization;
namespace System.Collections.Specialized
{
/// <devdoc>
/// <para>
/// OrderedDictionary offers IDictionary syntax with ordering. Objects
/// added or inserted in an IOrderedDictionary must have both a key and an index, and
/// can be retrieved by either.
/// OrderedDictionary is used by the ParameterCollection because MSAccess relies on ordering of
/// parameters, while almost all other DBs do not. DataKeyArray also uses it so
/// DataKeys can be retrieved by either their name or their index.
///
/// OrderedDictionary implements IDeserializationCallback because it needs to have the
/// contained ArrayList and Hashtable deserialized before it tries to get its count and objects.
/// </para>
/// </devdoc>
[Serializable]
[System.Runtime.CompilerServices.TypeForwardedFrom("System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public class OrderedDictionary : IOrderedDictionary, ISerializable, IDeserializationCallback
{
private ArrayList? _objectsArray;
private Hashtable? _objectsTable;
private int _initialCapacity;
private IEqualityComparer? _comparer;
private bool _readOnly;
private readonly SerializationInfo? _siInfo; //A temporary variable which we need during deserialization.
private const string KeyComparerName = "KeyComparer"; // Do not rename (binary serialization)
private const string ArrayListName = "ArrayList"; // Do not rename (binary serialization)
private const string ReadOnlyName = "ReadOnly"; // Do not rename (binary serialization)
private const string InitCapacityName = "InitialCapacity"; // Do not rename (binary serialization)
public OrderedDictionary() : this(0)
{
}
public OrderedDictionary(int capacity) : this(capacity, null)
{
}
public OrderedDictionary(IEqualityComparer? comparer) : this(0, comparer)
{
}
public OrderedDictionary(int capacity, IEqualityComparer? comparer)
{
_initialCapacity = capacity;
_comparer = comparer;
}
private OrderedDictionary(OrderedDictionary dictionary)
{
Debug.Assert(dictionary != null);
_readOnly = true;
_objectsArray = dictionary._objectsArray;
_objectsTable = dictionary._objectsTable;
_comparer = dictionary._comparer;
_initialCapacity = dictionary._initialCapacity;
}
[Obsolete(Obsoletions.LegacyFormatterImplMessage, DiagnosticId = Obsoletions.LegacyFormatterImplDiagId, UrlFormat = Obsoletions.SharedUrlFormat)]
[EditorBrowsable(EditorBrowsableState.Never)]
protected OrderedDictionary(SerializationInfo info, StreamingContext context)
{
// We can't do anything with the keys and values until the entire graph has been deserialized
// and getting Counts and objects won't fail. For the time being, we'll just cache this.
// The graph is not valid until OnDeserialization has been called.
_siInfo = info;
}
/// <devdoc>
/// Gets the size of the table.
/// </devdoc>
public int Count
{
get
{
if (_objectsArray == null)
{
return 0;
}
return _objectsArray.Count;
}
}
/// <devdoc>
/// Indicates that the collection can grow.
/// </devdoc>
bool IDictionary.IsFixedSize
{
get
{
return _readOnly;
}
}
/// <devdoc>
/// Indicates that the collection is not read-only
/// </devdoc>
public bool IsReadOnly
{
get
{
return _readOnly;
}
}
/// <devdoc>
/// Indicates that this class is not synchronized
/// </devdoc>
bool ICollection.IsSynchronized
{
get
{
return false;
}
}
/// <devdoc>
/// Gets the collection of keys in the table in order.
/// </devdoc>
public ICollection Keys
{
get
{
ArrayList objectsArray = EnsureObjectsArray();
Hashtable objectsTable = EnsureObjectsTable();
return new OrderedDictionaryKeyValueCollection(objectsArray, objectsTable, _comparer);
}
}
private ArrayList EnsureObjectsArray() => _objectsArray ??= new ArrayList(_initialCapacity);
private Hashtable EnsureObjectsTable() => _objectsTable ??= new Hashtable(_initialCapacity, _comparer);
/// <devdoc>
/// The SyncRoot object. Not used because IsSynchronized is false
/// </devdoc>
object ICollection.SyncRoot => this;
/// <devdoc>
/// Gets or sets the object at the specified index
/// </devdoc>
public object? this[int index]
{
get
{
ArrayList objectsArray = EnsureObjectsArray();
return ((DictionaryEntry)objectsArray[index]!).Value;
}
set
{
if (_readOnly)
{
throw new NotSupportedException(SR.OrderedDictionary_ReadOnly);
}
if (_objectsArray == null || index < 0 || index >= _objectsArray.Count)
{
throw new ArgumentOutOfRangeException(nameof(index));
}
ArrayList objectsArray = EnsureObjectsArray();
Hashtable objectsTable = EnsureObjectsTable();
object key = ((DictionaryEntry)objectsArray[index]!).Key;
objectsArray[index] = new DictionaryEntry(key, value);
objectsTable[key] = value;
}
}
/// <devdoc>
/// Gets or sets the object with the specified key
/// </devdoc>
public object? this[object key]
{
get
{
if (_objectsTable == null)
{
return null;
}
return _objectsTable[key];
}
set
{
if (_readOnly)
{
throw new NotSupportedException(SR.OrderedDictionary_ReadOnly);
}
Hashtable objectsTable = EnsureObjectsTable();
if (objectsTable.Contains(key))
{
objectsTable[key] = value;
ArrayList objectsArray = EnsureObjectsArray();
objectsArray[IndexOfKey(key)] = new DictionaryEntry(key, value);
}
else
{
Add(key, value);
}
}
}
/// <devdoc>
/// Returns an arrayList of the values in the table
/// </devdoc>
public ICollection Values
{
get
{
ArrayList objectsArray = EnsureObjectsArray();
return new OrderedDictionaryKeyValueCollection(objectsArray);
}
}
/// <devdoc>
/// Adds a new entry to the table with the lowest-available index.
/// </devdoc>
public void Add(object key, object? value)
{
if (_readOnly)
{
throw new NotSupportedException(SR.OrderedDictionary_ReadOnly);
}
Hashtable objectsTable = EnsureObjectsTable();
ArrayList objectsArray = EnsureObjectsArray();
objectsTable.Add(key, value);
objectsArray.Add(new DictionaryEntry(key, value));
}
/// <devdoc>
/// Clears all elements in the table.
/// </devdoc>
public void Clear()
{
if (_readOnly)
{
throw new NotSupportedException(SR.OrderedDictionary_ReadOnly);
}
_objectsTable?.Clear();
_objectsArray?.Clear();
}
/// <devdoc>
/// Returns a readonly OrderedDictionary for the given OrderedDictionary.
/// </devdoc>
public OrderedDictionary AsReadOnly()
{
return new OrderedDictionary(this);
}
/// <devdoc>
/// Returns true if the key exists in the table, false otherwise.
/// </devdoc>
public bool Contains(object key)
{
ArgumentNullException.ThrowIfNull(key);
if (_objectsTable == null)
{
return false;
}
return _objectsTable.Contains(key);
}
/// <devdoc>
/// Copies the table to an array. This will not preserve order.
/// </devdoc>
public void CopyTo(Array array, int index)
{
Hashtable objectsTable = EnsureObjectsTable();
objectsTable.CopyTo(array, index);
}
private int IndexOfKey(object key)
{
if (_objectsArray == null)
{
return -1;
}
for (int i = 0; i < _objectsArray.Count; i++)
{
object o = ((DictionaryEntry)_objectsArray[i]!).Key;
if (_comparer != null)
{
if (_comparer.Equals(o, key))
{
return i;
}
}
else
{
if (o.Equals(key))
{
return i;
}
}
}
return -1;
}
/// <devdoc>
/// Inserts a new object at the given index with the given key.
/// </devdoc>
public void Insert(int index, object key, object? value)
{
if (_readOnly)
{
throw new NotSupportedException(SR.OrderedDictionary_ReadOnly);
}
ArgumentOutOfRangeException.ThrowIfGreaterThan(index, Count);
ArgumentOutOfRangeException.ThrowIfNegative(index);
Hashtable objectsTable = EnsureObjectsTable();
ArrayList objectsArray = EnsureObjectsArray();
objectsTable.Add(key, value);
objectsArray.Insert(index, new DictionaryEntry(key, value));
}
/// <devdoc>
/// Removes the entry at the given index.
/// </devdoc>
public void RemoveAt(int index)
{
if (_readOnly)
{
throw new NotSupportedException(SR.OrderedDictionary_ReadOnly);
}
ArgumentOutOfRangeException.ThrowIfGreaterThanOrEqual(index, Count);
ArgumentOutOfRangeException.ThrowIfNegative(index);
Hashtable objectsTable = EnsureObjectsTable();
ArrayList objectsArray = EnsureObjectsArray();
object key = ((DictionaryEntry)objectsArray[index]!).Key;
objectsArray.RemoveAt(index);
objectsTable.Remove(key);
}
/// <devdoc>
/// Removes the entry with the given key.
/// </devdoc>
public void Remove(object key)
{
if (_readOnly)
{
throw new NotSupportedException(SR.OrderedDictionary_ReadOnly);
}
ArgumentNullException.ThrowIfNull(key);
int index = IndexOfKey(key);
if (index < 0)
{
return;
}
Hashtable objectsTable = EnsureObjectsTable();
ArrayList objectsArray = EnsureObjectsArray();
objectsTable.Remove(key);
objectsArray.RemoveAt(index);
}
#region IDictionary implementation
public virtual IDictionaryEnumerator GetEnumerator()
{
ArrayList objectsArray = EnsureObjectsArray();
return new OrderedDictionaryEnumerator(objectsArray, OrderedDictionaryEnumerator.DictionaryEntry);
}
#endregion
#region IEnumerable implementation
IEnumerator IEnumerable.GetEnumerator()
{
ArrayList objectsArray = EnsureObjectsArray();
return new OrderedDictionaryEnumerator(objectsArray, OrderedDictionaryEnumerator.DictionaryEntry);
}
#endregion
#region ISerializable implementation
[Obsolete(Obsoletions.LegacyFormatterImplMessage, DiagnosticId = Obsoletions.LegacyFormatterImplDiagId, UrlFormat = Obsoletions.SharedUrlFormat)]
[EditorBrowsable(EditorBrowsableState.Never)]
public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
{
ArgumentNullException.ThrowIfNull(info);
info.AddValue(KeyComparerName, _comparer, typeof(IEqualityComparer));
info.AddValue(ReadOnlyName, _readOnly);
info.AddValue(InitCapacityName, _initialCapacity);
object[] serArray = new object[Count];
ArrayList objectsArray = EnsureObjectsArray();
objectsArray.CopyTo(serArray);
info.AddValue(ArrayListName, serArray);
}
#endregion
#region IDeserializationCallback implementation
void IDeserializationCallback.OnDeserialization(object? sender)
{
OnDeserialization(sender);
}
protected virtual void OnDeserialization(object? sender)
{
if (_siInfo == null)
{
throw new SerializationException(SR.Serialization_InvalidOnDeser);
}
_comparer = (IEqualityComparer?)_siInfo.GetValue(KeyComparerName, typeof(IEqualityComparer));
_readOnly = _siInfo.GetBoolean(ReadOnlyName);
_initialCapacity = _siInfo.GetInt32(InitCapacityName);
object[]? serArray = (object[]?)_siInfo.GetValue(ArrayListName, typeof(object[]));
if (serArray != null)
{
Hashtable objectsTable = EnsureObjectsTable();
ArrayList objectsArray = EnsureObjectsArray();
foreach (object o in serArray)
{
DictionaryEntry entry;
try
{
// DictionaryEntry is a value type, so it can only be casted.
entry = (DictionaryEntry)o;
}
catch
{
throw new SerializationException(SR.OrderedDictionary_SerializationMismatch);
}
objectsArray.Add(entry);
objectsTable.Add(entry.Key, entry.Value);
}
}
}
#endregion
/// <devdoc>
/// OrderedDictionaryEnumerator works just like any other IDictionaryEnumerator, but it retrieves DictionaryEntries
/// in the order by index.
/// </devdoc>
private sealed class OrderedDictionaryEnumerator : IDictionaryEnumerator
{
private readonly int _objectReturnType;
internal const int Keys = 1;
internal const int Values = 2;
internal const int DictionaryEntry = 3;
private readonly IEnumerator _arrayEnumerator;
internal OrderedDictionaryEnumerator(ArrayList array, int objectReturnType)
{
_arrayEnumerator = array.GetEnumerator();
_objectReturnType = objectReturnType;
}
/// <devdoc>
/// Retrieves the current DictionaryEntry. This is the same as Entry, but not strongly-typed.
/// </devdoc>
public object? Current
{
get
{
Debug.Assert(_arrayEnumerator.Current != null);
if (_objectReturnType == Keys)
{
return ((DictionaryEntry)_arrayEnumerator.Current).Key;
}
if (_objectReturnType == Values)
{
return ((DictionaryEntry)_arrayEnumerator.Current).Value;
}
return Entry;
}
}
/// <devdoc>
/// Retrieves the current DictionaryEntry
/// </devdoc>
public DictionaryEntry Entry
{
get
{
Debug.Assert(_arrayEnumerator.Current != null);
return new DictionaryEntry(((DictionaryEntry)_arrayEnumerator.Current).Key, ((DictionaryEntry)_arrayEnumerator.Current).Value);
}
}
/// <devdoc>
/// Retrieves the key of the current DictionaryEntry
/// </devdoc>
public object Key
{
get
{
Debug.Assert(_arrayEnumerator.Current != null);
return ((DictionaryEntry)_arrayEnumerator.Current).Key;
}
}
/// <devdoc>
/// Retrieves the value of the current DictionaryEntry
/// </devdoc>
public object? Value
{
get
{
Debug.Assert(_arrayEnumerator.Current != null);
return ((DictionaryEntry)_arrayEnumerator.Current).Value;
}
}
/// <devdoc>
/// Moves the enumerator pointer to the next member
/// </devdoc>
public bool MoveNext()
{
return _arrayEnumerator.MoveNext();
}
/// <devdoc>
/// Resets the enumerator pointer to the beginning.
/// </devdoc>
public void Reset()
{
_arrayEnumerator.Reset();
}
}
/// <devdoc>
/// OrderedDictionaryKeyValueCollection implements IList for the Values and Keys properties
/// that is "live"- it will reflect changes to the OrderedDictionary on the collection made after the getter
/// was called.
/// </devdoc>
private sealed class OrderedDictionaryKeyValueCollection : IList
{
private readonly ArrayList _objects;
private readonly Hashtable? _objectsTable;
private readonly IEqualityComparer? _comparer;
public OrderedDictionaryKeyValueCollection(ArrayList array, Hashtable objectsTable, IEqualityComparer? comparer)
{
_objects = array;
_objectsTable = objectsTable;
_comparer = comparer;
}
public OrderedDictionaryKeyValueCollection(ArrayList array)
{
_objects = array;
}
private bool IsKeys => _objectsTable is not null;
void ICollection.CopyTo(Array array, int index)
{
ArgumentNullException.ThrowIfNull(array);
ArgumentOutOfRangeException.ThrowIfNegative(index);
foreach (object? o in _objects)
{
Debug.Assert(o != null);
array.SetValue(IsKeys ? ((DictionaryEntry)o).Key : ((DictionaryEntry)o).Value, index);
index++;
}
}
int ICollection.Count => _objects.Count;
bool ICollection.IsSynchronized => false;
object ICollection.SyncRoot => _objects.SyncRoot;
IEnumerator IEnumerable.GetEnumerator()
{
return new OrderedDictionaryEnumerator(_objects, IsKeys ? OrderedDictionaryEnumerator.Keys : OrderedDictionaryEnumerator.Values);
}
bool IList.Contains(object? value)
{
if (IsKeys)
{
Debug.Assert(_objectsTable is not null);
return value != null && _objectsTable.ContainsKey(value);
}
foreach (object? o in _objects)
{
Debug.Assert(o != null);
if (object.Equals(((DictionaryEntry)o).Value, value))
{
return true;
}
}
return false;
}
int IList.IndexOf(object? value)
{
for (int i = 0; i < _objects.Count; i++)
{
if (IsKeys)
{
object entryKey = ((DictionaryEntry)_objects[i]!).Key;
if (_comparer != null)
{
if (_comparer.Equals(entryKey, value))
{
return i;
}
}
else if (entryKey.Equals(value))
{
return i;
}
}
else if (object.Equals(((DictionaryEntry)_objects[i]!).Value, value))
{
return i;
}
}
return -1;
}
bool IList.IsFixedSize => true;
bool IList.IsReadOnly => true;
object? IList.this[int index]
{
get
{
DictionaryEntry entry = (DictionaryEntry)_objects[index]!;
return IsKeys ? entry.Key : entry.Value;
}
set => throw new NotSupportedException(GetNotSupportedErrorMessage());
}
void IList.Insert(int index, object? value)
{
throw new NotSupportedException(GetNotSupportedErrorMessage());
}
void IList.Remove(object? value)
{
throw new NotSupportedException(GetNotSupportedErrorMessage());
}
void IList.RemoveAt(int index)
{
throw new NotSupportedException(GetNotSupportedErrorMessage());
}
int IList.Add(object? value)
{
throw new NotSupportedException(GetNotSupportedErrorMessage());
}
void IList.Clear()
{
throw new NotSupportedException(GetNotSupportedErrorMessage());
}
private string GetNotSupportedErrorMessage()
{
return IsKeys ? SR.NotSupported_KeyCollectionSet : SR.NotSupported_ValueCollectionSet;
}
}
}
}