-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSafeBuffer.cs
90 lines (77 loc) · 2.04 KB
/
SafeBuffer.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
using System;
using System.Collections.Generic;
using System.IO;
using Common.ThreadSafeObjects;
namespace Networking
{
public class SafeBuffer
{
private static ThreadSafePool<SafeBuffer> bufferStack;
private static int _blockSize;
private static bool _autoGrowth;
private byte[] buffer;
private int offset, lenght;
private SafeBuffer(byte[] buffer)
{
this.buffer = buffer;
offset = 0;
lenght = buffer.Length;
}
public static void Init(int count, int blocksize, bool autoGrowth)
{
_autoGrowth = autoGrowth;
bufferStack = new ThreadSafePool<SafeBuffer>(count);
for (int i = 0; i < count; i++)
{
byte[] buf = new byte[blocksize];
bufferStack.Push(new SafeBuffer(buf));
}
}
public static SafeBuffer Get()
{
SafeBuffer safeBuffer;
if (!bufferStack.TryPop(out safeBuffer))
{
if (_autoGrowth)
{
byte[] buf = new byte[_blockSize];
bufferStack.Push(new SafeBuffer(buf));
}
else
{
throw new Exception("Buffers overrun!");
}
}
return safeBuffer;
}
public void Close()
{
bufferStack.Push(this);
}
public byte[] Buffer
{
get
{
return buffer;
}
}
public int Offset
{
get
{
return offset;
}
set
{
offset = value;
}
}
public int Lenght
{
get
{
return buffer.Length;
}
}
}
}