-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathIndexedCollection.IndexOneToOne.cs
76 lines (64 loc) · 2.12 KB
/
IndexedCollection.IndexOneToOne.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
using System;
using System.Collections.Generic;
namespace IndexedCollection
{
public partial class IndexedCollection<TItem>
{
public class IndexOneToOne<TKey> : IIndex
{
private readonly Func<TItem, TKey> _selector;
private readonly IndexedCollection<TItem> _collection;
private readonly Dictionary<TKey, Entry> _dict =
new Dictionary<TKey, Entry>();
private readonly Buffer<(TKey key, bool set)> _backIndexes = new Buffer<(TKey, bool)>();
public IndexOneToOne(Func<TItem, TKey> selector, IndexedCollection<TItem> collection)
{
_selector = selector;
_collection = collection;
}
void IIndex.Add(Entry entry)
{
var key = _selector(entry.Item);
_dict.Add(key, entry);
_backIndexes.SetAtAndResize(entry.Index, (key, true));
}
void IIndex.Remove(Entry item)
{
var tuple = _backIndexes.Array[item.Index];
_dict.Remove(tuple.key);
_backIndexes.SetAtAndResize(item.Index, (default, false));
}
public Entry Get(TKey key)
{
return _dict[key];
}
public bool TryGet(TKey key, out Entry entry)
{
return _dict.TryGetValue(key, out entry);
}
public bool RemoveByKey(TKey key)
{
if(_dict.TryGetValue(key, out var entry))
{
_collection.Remove(entry);
return true;
}
return false;
}
void IIndex.Rebuild()
{
var indexer = (IIndex)this;
indexer.Clear();
foreach(var entry in _collection._values)
{
indexer.Add(entry);
}
}
void IIndex.Clear()
{
_dict.Clear();
_backIndexes.Clear();
}
}
}
}