forked from Handlebars-Net/Handlebars.Net
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWeakCollection.cs
More file actions
87 lines (74 loc) · 2.63 KB
/
Copy pathWeakCollection.cs
File metadata and controls
87 lines (74 loc) · 2.63 KB
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
using System;
using System.Collections;
using System.Collections.Generic;
namespace HandlebarsDotNet.Collections
{
public class WeakCollection<T> : IEnumerable<T> where T : class
{
private readonly List<WeakReference<T>> _store = new List<WeakReference<T>>();
private int _firstAvailableIndex = 0;
public int Size => _store.Count;
public void Add(T value)
{
// Need a way to reset _firstAvailableIndex periodically
for (var index = _firstAvailableIndex; index < _store.Count; index++)
{
if (_store[index] == null)
{
_firstAvailableIndex = index + 1;
_store[index] = new WeakReference<T>(value);
return;
}
if (!_store[index].TryGetTarget(out _))
{
_firstAvailableIndex = index + 1;
_store[index].SetTarget(value);
return;
}
}
_store.Add(new WeakReference<T>(value));
_firstAvailableIndex = _store.Count;
}
public void Remove(T value)
{
for (var index = 0; index < _store.Count; index++)
{
if (_store[index] == null)
{
_firstAvailableIndex = Math.Min(_firstAvailableIndex, index);
continue;
}
if (!_store[index].TryGetTarget(out var target))
{
_firstAvailableIndex = Math.Min(_firstAvailableIndex, index);
continue;
}
if (target.Equals(value))
{
_store[index] = null;
_firstAvailableIndex = Math.Min(_firstAvailableIndex, index);
return;
}
}
}
public IEnumerator<T> GetEnumerator()
{
for (var index = 0; index < _store.Count; index++)
{
var reference = _store[index];
if (reference == null)
{
_firstAvailableIndex = Math.Min(_firstAvailableIndex, index);
continue;
}
if (!reference.TryGetTarget(out var target))
{
_firstAvailableIndex = Math.Min(_firstAvailableIndex, index);
continue;
}
yield return target;
}
}
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
}