|
2 | 2 | // Licensed under the MIT license. See LICENSE file in the project root for full license information.
|
3 | 3 |
|
4 | 4 |
|
| 5 | +using System; |
| 6 | +using System.Linq; |
5 | 7 | using System.Collections.Generic;
|
6 | 8 |
|
7 | 9 | namespace Microsoft.DebugEngineHost.VSCode
|
8 | 10 | {
|
9 | 11 | public sealed class HandleCollection<T>
|
10 | 12 | {
|
11 | 13 | private const int START_HANDLE = 1000;
|
12 |
| - private List<T> _collection = new List<T>(); |
13 | 14 |
|
14 |
| - public void Clear() |
| 15 | + private int _nextHandle; |
| 16 | + private Dictionary<int, T> _handleMap; |
| 17 | + |
| 18 | + public HandleCollection() |
| 19 | + { |
| 20 | + _nextHandle = START_HANDLE; |
| 21 | + _handleMap = new Dictionary<int, T>(); |
| 22 | + } |
| 23 | + |
| 24 | + public void Reset() |
15 | 25 | {
|
16 |
| - _collection.Clear(); |
| 26 | + _nextHandle = START_HANDLE; |
| 27 | + _handleMap.Clear(); |
17 | 28 | }
|
18 | 29 |
|
19 | 30 | public int Create(T value)
|
20 | 31 | {
|
21 |
| - _collection.Add(value); |
22 |
| - return _collection.Count + START_HANDLE - 1; |
| 32 | + var handle = _nextHandle++; |
| 33 | + _handleMap[handle] = value; |
| 34 | + return handle; |
23 | 35 | }
|
24 | 36 |
|
25 | 37 | public bool TryGet(int handle, out T value)
|
26 | 38 | {
|
27 |
| - if (handle < 0 || handle - START_HANDLE >= _collection.Count) |
| 39 | + if (_handleMap.TryGetValue(handle, out value)) |
28 | 40 | {
|
29 |
| - value = default; |
30 |
| - return false; |
| 41 | + return true; |
31 | 42 | }
|
32 |
| - |
33 |
| - value = _collection[handle - START_HANDLE]; |
34 |
| - return true; |
| 43 | + return false; |
35 | 44 | }
|
36 | 45 |
|
37 | 46 | public bool TryGetFirst(out T value)
|
38 | 47 | {
|
39 | 48 | if (IsEmpty)
|
40 | 49 | {
|
41 |
| - value = default; |
| 50 | + value = default(T); |
42 | 51 | return false;
|
43 | 52 | }
|
44 | 53 |
|
45 |
| - value = _collection[0]; |
46 |
| - return true; |
| 54 | + return TryGet(_handleMap.Keys.Min(), out value); |
47 | 55 | }
|
48 | 56 |
|
49 | 57 | public T this[int handle]
|
50 | 58 | {
|
51 | 59 | get
|
52 | 60 | {
|
53 |
| - return _collection[handle - START_HANDLE]; |
| 61 | + T value; |
| 62 | + if (!TryGet(handle, out value)) |
| 63 | + { |
| 64 | + throw new ArgumentOutOfRangeException(nameof(handle)); |
| 65 | + } |
| 66 | + |
| 67 | + return value; |
54 | 68 | }
|
55 | 69 | }
|
56 | 70 |
|
57 | 71 | public bool Remove(int handle)
|
58 | 72 | {
|
59 |
| - _collection.RemoveAt(handle - START_HANDLE); |
60 |
| - return true; |
| 73 | + return _handleMap.Remove(handle); |
61 | 74 | }
|
62 | 75 |
|
63 | 76 | public bool IsEmpty
|
64 | 77 | {
|
65 | 78 | get
|
66 | 79 | {
|
67 |
| - return _collection.Count == 0; |
| 80 | + return _handleMap.Count == 0; |
68 | 81 | }
|
69 | 82 | }
|
70 | 83 | }
|
|
0 commit comments