-
Notifications
You must be signed in to change notification settings - Fork 4k
/
ImmutableSegmentedDictionary`2.cs
390 lines (307 loc) · 15.4 KB
/
ImmutableSegmentedDictionary`2.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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics.CodeAnalysis;
namespace Microsoft.CodeAnalysis.Collections
{
/// <summary>
/// Represents a segmented dictionary that is immutable; meaning it cannot be changed once it is created.
/// </summary>
/// <remarks>
/// <para>There are different scenarios best for <see cref="ImmutableSegmentedDictionary{TKey, TValue}"/> and others
/// best for <see cref="ImmutableDictionary{TKey, TValue}"/>.</para>
///
/// <para>In general, <see cref="ImmutableSegmentedDictionary{TKey, TValue}"/> is applicable in scenarios most like
/// the scenarios where <see cref="ImmutableArray{T}"/> is applicable, and
/// <see cref="ImmutableDictionary{TKey, TValue}"/> is applicable in scenarios most like the scenarios where
/// <see cref="ImmutableList{T}"/> is applicable.</para>
///
/// <para>The following table summarizes the performance characteristics of
/// <see cref="ImmutableSegmentedDictionary{TKey, TValue}"/>:</para>
///
/// <list type="table">
/// <item>
/// <description>Operation</description>
/// <description><see cref="ImmutableSegmentedDictionary{TKey, TValue}"/> Complexity</description>
/// <description><see cref="ImmutableDictionary{TKey, TValue}"/> Complexity</description>
/// <description>Comments</description>
/// </item>
/// <item>
/// <description>Item</description>
/// <description>O(1)</description>
/// <description>O(log n)</description>
/// <description>Directly index into the underlying segmented dictionary</description>
/// </item>
/// <item>
/// <description>Add()</description>
/// <description>O(n)</description>
/// <description>O(log n)</description>
/// <description>Requires creating a new segmented dictionary</description>
/// </item>
/// </list>
///
/// <para>This type is backed by segmented arrays to avoid using the Large Object Heap without impacting algorithmic
/// complexity.</para>
/// </remarks>
/// <typeparam name="TKey">The type of the keys in the dictionary.</typeparam>
/// <typeparam name="TValue">The type of the values in the dictionary.</typeparam>
/// <devremarks>
/// <para>This type has a documented contract of being exactly one reference-type field in size. Our own
/// <see cref="RoslynImmutableInterlocked"/> class depends on it, as well as others externally.</para>
///
/// <para><strong>IMPORTANT NOTICE FOR MAINTAINERS AND REVIEWERS:</strong></para>
///
/// <para>This type should be thread-safe. As a struct, it cannot protect its own fields from being changed from one
/// thread while its members are executing on other threads because structs can change <em>in place</em> simply by
/// reassigning the field containing this struct. Therefore it is extremely important that <strong>⚠⚠ Every member
/// should only dereference <c>this</c> ONCE ⚠⚠</strong>. If a member needs to reference the
/// <see cref="_dictionary"/> field, that counts as a dereference of <c>this</c>. Calling other instance members
/// (properties or methods) also counts as dereferencing <c>this</c>. Any member that needs to use <c>this</c> more
/// than once must instead assign <c>this</c> to a local variable and use that for the rest of the code instead.
/// This effectively copies the one field in the struct to a local variable so that it is insulated from other
/// threads.</para>
/// </devremarks>
internal readonly partial struct ImmutableSegmentedDictionary<TKey, TValue> : IImmutableDictionary<TKey, TValue>, IDictionary<TKey, TValue>, IReadOnlyDictionary<TKey, TValue>, IDictionary, IEquatable<ImmutableSegmentedDictionary<TKey, TValue>>
where TKey : notnull
{
public static readonly ImmutableSegmentedDictionary<TKey, TValue> Empty = new(new SegmentedDictionary<TKey, TValue>());
private readonly SegmentedDictionary<TKey, TValue> _dictionary;
private ImmutableSegmentedDictionary(SegmentedDictionary<TKey, TValue> dictionary)
{
_dictionary = dictionary ?? throw new ArgumentNullException(nameof(dictionary));
}
public IEqualityComparer<TKey> KeyComparer => _dictionary.Comparer;
public int Count => _dictionary.Count;
public bool IsEmpty => _dictionary.Count == 0;
public bool IsDefault => _dictionary == null;
public bool IsDefaultOrEmpty => _dictionary?.Count is null or 0;
public KeyCollection Keys => new(this);
public ValueCollection Values => new(this);
ICollection<TKey> IDictionary<TKey, TValue>.Keys => Keys;
ICollection<TValue> IDictionary<TKey, TValue>.Values => Values;
IEnumerable<TKey> IReadOnlyDictionary<TKey, TValue>.Keys => Keys;
IEnumerable<TValue> IReadOnlyDictionary<TKey, TValue>.Values => Values;
bool ICollection<KeyValuePair<TKey, TValue>>.IsReadOnly => true;
ICollection IDictionary.Keys => Keys;
ICollection IDictionary.Values => Values;
bool IDictionary.IsReadOnly => true;
bool IDictionary.IsFixedSize => true;
object ICollection.SyncRoot => _dictionary;
bool ICollection.IsSynchronized => true;
public TValue this[TKey key] => _dictionary[key];
TValue IDictionary<TKey, TValue>.this[TKey key]
{
get => this[key];
set => throw new NotSupportedException();
}
object? IDictionary.this[object key]
{
get => ((IDictionary)_dictionary)[key];
set => throw new NotSupportedException();
}
public static bool operator ==(ImmutableSegmentedDictionary<TKey, TValue> left, ImmutableSegmentedDictionary<TKey, TValue> right)
=> left.Equals(right);
public static bool operator !=(ImmutableSegmentedDictionary<TKey, TValue> left, ImmutableSegmentedDictionary<TKey, TValue> right)
=> !left.Equals(right);
public static bool operator ==(ImmutableSegmentedDictionary<TKey, TValue>? left, ImmutableSegmentedDictionary<TKey, TValue>? right)
=> left.GetValueOrDefault().Equals(right.GetValueOrDefault());
public static bool operator !=(ImmutableSegmentedDictionary<TKey, TValue>? left, ImmutableSegmentedDictionary<TKey, TValue>? right)
=> !left.GetValueOrDefault().Equals(right.GetValueOrDefault());
public ImmutableSegmentedDictionary<TKey, TValue> Add(TKey key, TValue value)
{
var self = this;
if (self.Contains(new KeyValuePair<TKey, TValue>(key, value)))
return self;
var builder = ToValueBuilder();
builder.Add(key, value);
return builder.ToImmutable();
}
public ImmutableSegmentedDictionary<TKey, TValue> AddRange(IEnumerable<KeyValuePair<TKey, TValue>> pairs)
{
var self = this;
// Optimize the case of adding to an empty collection
if (self.IsEmpty && TryCastToImmutableSegmentedDictionary(pairs, out var other) && self.KeyComparer == other.KeyComparer)
{
return other;
}
var builder = ToValueBuilder();
builder.AddRange(pairs);
return builder.ToImmutable();
}
public ImmutableSegmentedDictionary<TKey, TValue> Clear()
{
var self = this;
if (self.IsEmpty)
{
return self;
}
return Empty.WithComparer(self.KeyComparer);
}
public bool Contains(KeyValuePair<TKey, TValue> pair)
{
return TryGetValue(pair.Key, out var value)
&& EqualityComparer<TValue>.Default.Equals(value, pair.Value);
}
public bool ContainsKey(TKey key)
=> _dictionary.ContainsKey(key);
public bool ContainsValue(TValue value)
=> _dictionary.ContainsValue(value);
public Enumerator GetEnumerator()
=> new(_dictionary, Enumerator.ReturnType.KeyValuePair);
public ImmutableSegmentedDictionary<TKey, TValue> Remove(TKey key)
{
var self = this;
if (!self._dictionary.ContainsKey(key))
return self;
var builder = ToValueBuilder();
builder.Remove(key);
return builder.ToImmutable();
}
public ImmutableSegmentedDictionary<TKey, TValue> RemoveRange(IEnumerable<TKey> keys)
{
if (keys is null)
throw new ArgumentNullException(nameof(keys));
var result = ToValueBuilder();
result.RemoveRange(keys);
return result.ToImmutable();
}
public ImmutableSegmentedDictionary<TKey, TValue> SetItem(TKey key, TValue value)
{
var self = this;
if (self.Contains(new KeyValuePair<TKey, TValue>(key, value)))
{
return self;
}
var builder = ToValueBuilder();
builder[key] = value;
return builder.ToImmutable();
}
public ImmutableSegmentedDictionary<TKey, TValue> SetItems(IEnumerable<KeyValuePair<TKey, TValue>> items)
{
if (items is null)
throw new ArgumentNullException(nameof(items));
var result = ToValueBuilder();
foreach (var item in items)
{
result[item.Key] = item.Value;
}
return result.ToImmutable();
}
public bool TryGetKey(TKey equalKey, out TKey actualKey)
{
var self = this;
foreach (var key in self.Keys)
{
if (self.KeyComparer.Equals(key, equalKey))
{
actualKey = key;
return true;
}
}
actualKey = equalKey;
return false;
}
#pragma warning disable CS8767 // Nullability of reference types in type of parameter doesn't match implicitly implemented member (possibly because of nullability attributes).
public bool TryGetValue(TKey key, [MaybeNullWhen(false)] out TValue value)
#pragma warning restore CS8767 // Nullability of reference types in type of parameter doesn't match implicitly implemented member (possibly because of nullability attributes).
=> _dictionary.TryGetValue(key, out value);
public ImmutableSegmentedDictionary<TKey, TValue> WithComparer(IEqualityComparer<TKey>? keyComparer)
{
keyComparer ??= EqualityComparer<TKey>.Default;
var self = this;
if (self.KeyComparer == keyComparer)
{
// Don't need to reconstruct the dictionary because the key comparer is the same
return self;
}
else if (self.IsEmpty)
{
if (keyComparer == Empty.KeyComparer)
{
return Empty;
}
else
{
return new ImmutableSegmentedDictionary<TKey, TValue>(new SegmentedDictionary<TKey, TValue>(keyComparer));
}
}
else
{
return ImmutableSegmentedDictionary.CreateRange(keyComparer, self);
}
}
public Builder ToBuilder()
=> new(this);
private ValueBuilder ToValueBuilder()
=> new(this);
public override int GetHashCode()
=> _dictionary?.GetHashCode() ?? 0;
public override bool Equals(object? obj)
{
return obj is ImmutableSegmentedDictionary<TKey, TValue> other
&& Equals(other);
}
public bool Equals(ImmutableSegmentedDictionary<TKey, TValue> other)
=> _dictionary == other._dictionary;
IImmutableDictionary<TKey, TValue> IImmutableDictionary<TKey, TValue>.Clear()
=> Clear();
IImmutableDictionary<TKey, TValue> IImmutableDictionary<TKey, TValue>.Add(TKey key, TValue value)
=> Add(key, value);
IImmutableDictionary<TKey, TValue> IImmutableDictionary<TKey, TValue>.AddRange(IEnumerable<KeyValuePair<TKey, TValue>> pairs)
=> AddRange(pairs);
IImmutableDictionary<TKey, TValue> IImmutableDictionary<TKey, TValue>.SetItem(TKey key, TValue value)
=> SetItem(key, value);
IImmutableDictionary<TKey, TValue> IImmutableDictionary<TKey, TValue>.SetItems(IEnumerable<KeyValuePair<TKey, TValue>> items)
=> SetItems(items);
IImmutableDictionary<TKey, TValue> IImmutableDictionary<TKey, TValue>.RemoveRange(IEnumerable<TKey> keys)
=> RemoveRange(keys);
IImmutableDictionary<TKey, TValue> IImmutableDictionary<TKey, TValue>.Remove(TKey key) => Remove(key);
IEnumerator<KeyValuePair<TKey, TValue>> IEnumerable<KeyValuePair<TKey, TValue>>.GetEnumerator()
=> new Enumerator(_dictionary, Enumerator.ReturnType.KeyValuePair);
IDictionaryEnumerator IDictionary.GetEnumerator()
=> new Enumerator(_dictionary, Enumerator.ReturnType.DictionaryEntry);
IEnumerator IEnumerable.GetEnumerator()
=> new Enumerator(_dictionary, Enumerator.ReturnType.KeyValuePair);
void ICollection<KeyValuePair<TKey, TValue>>.CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex)
=> ((ICollection<KeyValuePair<TKey, TValue>>)_dictionary).CopyTo(array, arrayIndex);
bool IDictionary.Contains(object key)
=> ((IDictionary)_dictionary).Contains(key);
void ICollection.CopyTo(Array array, int index)
=> ((ICollection)_dictionary).CopyTo(array, index);
void IDictionary<TKey, TValue>.Add(TKey key, TValue value)
=> throw new NotSupportedException();
bool IDictionary<TKey, TValue>.Remove(TKey key)
=> throw new NotSupportedException();
void ICollection<KeyValuePair<TKey, TValue>>.Add(KeyValuePair<TKey, TValue> item)
=> throw new NotSupportedException();
void ICollection<KeyValuePair<TKey, TValue>>.Clear()
=> throw new NotSupportedException();
bool ICollection<KeyValuePair<TKey, TValue>>.Remove(KeyValuePair<TKey, TValue> item)
=> throw new NotSupportedException();
void IDictionary.Add(object key, object? value)
=> throw new NotSupportedException();
void IDictionary.Clear()
=> throw new NotSupportedException();
void IDictionary.Remove(object key)
=> throw new NotSupportedException();
private static bool TryCastToImmutableSegmentedDictionary(IEnumerable<KeyValuePair<TKey, TValue>> pairs, out ImmutableSegmentedDictionary<TKey, TValue> other)
{
if (pairs is ImmutableSegmentedDictionary<TKey, TValue> dictionary)
{
other = dictionary;
return true;
}
if (pairs is ImmutableSegmentedDictionary<TKey, TValue>.Builder builder)
{
other = builder.ToImmutable();
return true;
}
other = default;
return false;
}
}
}