forked from dotnet/runtime
-
Notifications
You must be signed in to change notification settings - Fork 0
/
KeysAndValuesFrozenDictionary.cs
50 lines (40 loc) · 1.97 KB
/
KeysAndValuesFrozenDictionary.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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
using System.Diagnostics;
namespace System.Collections.Frozen
{
/// <summary>Provides a base class for frozen dictionaries that store their keys and values in dedicated arrays.</summary>
internal abstract class KeysAndValuesFrozenDictionary<TKey, TValue> : FrozenDictionary<TKey, TValue>, IDictionary<TKey, TValue>
where TKey : notnull
{
private protected readonly FrozenHashTable _hashTable;
private protected readonly TKey[] _keys;
private protected readonly TValue[] _values;
protected KeysAndValuesFrozenDictionary(Dictionary<TKey, TValue> source, bool optimizeForReading = true) : base(source.Comparer)
{
Debug.Assert(source.Count != 0);
KeyValuePair<TKey, TValue>[] entries = new KeyValuePair<TKey, TValue>[source.Count];
((ICollection<KeyValuePair<TKey, TValue>>)source).CopyTo(entries, 0);
_keys = new TKey[entries.Length];
_values = new TValue[entries.Length];
_hashTable = FrozenHashTable.Create(
entries.Length,
index => Comparer.GetHashCode(entries[index].Key),
(destIndex, srcIndex) =>
{
_keys[destIndex] = entries[srcIndex].Key;
_values[destIndex] = entries[srcIndex].Value;
},
optimizeForReading);
}
/// <inheritdoc />
private protected sealed override TKey[] KeysCore => _keys;
/// <inheritdoc />
private protected sealed override TValue[] ValuesCore => _values;
/// <inheritdoc />
private protected sealed override Enumerator GetEnumeratorCore() => new Enumerator(_keys, _values);
/// <inheritdoc />
private protected sealed override int CountCore => _hashTable.Count;
}
}