forked from PowerShell/PSReadLine
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHistoryQueue.cs
More file actions
127 lines (111 loc) · 3.31 KB
/
Copy pathHistoryQueue.cs
File metadata and controls
127 lines (111 loc) · 3.31 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
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
/********************************************************************++
Copyright (c) Microsoft Corporation. All rights reserved.
--********************************************************************/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
namespace Microsoft.PowerShell
{
[ExcludeFromCodeCoverage]
internal sealed class QueueDebugView<T>
{
private readonly HistoryQueue<T> _queue;
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
public T[] Items => this._queue.ToArray();
public QueueDebugView(HistoryQueue<T> queue)
{
this._queue = queue ?? throw new ArgumentNullException(nameof(queue));
}
}
[DebuggerDisplay("Count = {" + nameof(Count) + "}")]
[DebuggerTypeProxy(typeof(QueueDebugView<>))]
internal class HistoryQueue<T>
{
private readonly T[] _array;
private int _head;
private int _tail;
public HistoryQueue(int capacity)
{
Debug.Assert(capacity > 0);
_array = new T[capacity];
_head = _tail = Count = 0;
}
public void Clear()
{
for (int i = 0; i < Count; i++)
{
this[i] = default(T);
}
_head = _tail = Count = 0;
}
public bool Contains(T item)
{
return IndexOf(item) != -1;
}
public int Count { get; private set; }
public int IndexOf(T item)
{
// REVIEW: should we use case insensitive here?
var eqComparer = EqualityComparer<T>.Default;
for (int i = 0; i < Count; i++)
{
if (eqComparer.Equals(this[i], item))
{
return i;
}
}
return -1;
}
public void Enqueue(T item)
{
if (Count == _array.Length)
{
Dequeue();
}
_array[_tail] = item;
_tail = (_tail + 1) % _array.Length;
Count += 1;
}
public T Dequeue()
{
Debug.Assert(Count > 0);
T obj = _array[_head];
_array[_head] = default(T);
_head = (_head + 1) % _array.Length;
Count -= 1;
return obj;
}
public T[] ToArray()
{
var result = new T[Count];
if (Count > 0)
{
if (_head < _tail)
{
Array.Copy(_array, _head, result, 0, Count);
}
else
{
Array.Copy(_array, _head, result, 0, _array.Length - _head);
Array.Copy(_array, 0, result, _array.Length - _head, _tail);
}
}
return result;
}
[ExcludeFromCodeCoverage]
public T this[int index]
{
get
{
Debug.Assert(index >= 0 && index < Count);
return _array[(_head + index) % _array.Length];
}
set
{
Debug.Assert(index >= 0 && index < Count);
_array[(_head + index) % _array.Length] = value;
}
}
}
}