-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathStackBuffer.cs
76 lines (63 loc) · 1.55 KB
/
StackBuffer.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
/***
* StackBuffer
*
* A character buffer allocated on the stack
*
*/
using System;
namespace Performance
{
public ref struct StackBuffer
{
private Span<char> _buffer;
private int _index;
public StackBuffer(Span<char> charBuffer)
{
_buffer = charBuffer;
_index = 0;
}
public void Clear()
{
_index = 0;
}
public int Count => _index;
public int Length => _index;
public char this[int index]
{
get => _buffer[index];
set => _buffer[index] = value;
}
public void Append(char c)
{
_buffer[_index++] = c;
}
public void Append(string s)
{
for (var i = 0; i < s.Length; i++) _buffer[_index++] = s[i];
}
public void Append(char c, int count)
{
while (count-- > 0)
_buffer[_index++] = c;
}
public void Append(StackBuffer sourceBuffer)
{
for (var i = 0; i < sourceBuffer.Count; i++) _buffer[_index++] = sourceBuffer[i];
}
/// <summary>
/// Reverses the characters inplace
/// </summary>
public void Reverse()
{
int start = 0, end = Count - 1;
while (start < end)
{
var temp = _buffer[start];
_buffer[start] = _buffer[end];
_buffer[end] = temp;
start++;
end--;
}
}
}
}