-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathBytePool.cs
More file actions
100 lines (82 loc) · 2.3 KB
/
BytePool.cs
File metadata and controls
100 lines (82 loc) · 2.3 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
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BytePool
{
// for ease of use, there's a global pool
static private BytePool _Global;
static public BytePool Global
{
get {
if ( _Global == null )
_Global = new BytePool();
return _Global;
}
}
public int MaxPoolSize = 10;
public int TotalAllocatedBytes { get { return FreeBytes + UsedBytes; } }
public int TotalAllocatedArrays { get { return FreeArrays.Count + UsedArrays.Count; } }
public int FreeBytes { get { return CountBytes( FreeArrays ); } }
public int UsedBytes { get { return CountBytes( UsedArrays ); } }
public bool IsFull { get { return UsedArrays.Count >= MaxPoolSize; } }
static public int CountBytes(List<byte[]> Arrays)
{
var Total = 0;
foreach ( var Array in Arrays )
Total += Array.Length;
return Total;
}
List<byte[]> FreeArrays = new List<byte[]>();
List<byte[]> UsedArrays = new List<byte[]>();
void TrimArrays()
{
FreeArrays.Clear();
}
public byte[] Alloc(byte[] CopyThisArray,bool AllowBiggerSize=false)
{
var NewArray = Alloc( CopyThisArray.Length, AllowBiggerSize );
CopyThisArray.CopyTo( NewArray, 0 );
return NewArray;
}
public byte[] Alloc(int Size,bool AllowBiggerSize=false)
{
lock(FreeArrays)
{
// find free array that fits
for ( int i=0; i<FreeArrays.Count; i++ )
{
var Array = FreeArrays[i];
if ( Array.Length < Size )
continue;
if ( !AllowBiggerSize && Array.Length > Size )
continue;
// this fits!
FreeArrays.RemoveAt(i);
UsedArrays.Add(Array);
return Array;
}
// not allowed to allocate more
if ( TotalAllocatedArrays >= MaxPoolSize )
TrimArrays();
if ( TotalAllocatedArrays >= MaxPoolSize )
throw new System.Exception("Byte pool full " + TotalAllocatedArrays + "/" + MaxPoolSize );
// allocate a new array
var NewArray = new byte[Size];
UsedArrays.Add( NewArray );
return NewArray;
}
}
public void Release(byte[] ReleasedBuffer)
{
lock(FreeArrays)
{
if (!UsedArrays.Remove (ReleasedBuffer)) {
Debug.LogError ("Tried to remove ByteBuffer (" + ReleasedBuffer.Length + ") from pool that does not belong");
return;
}
// move out of used arrays
// gr: more error checking plz!
FreeArrays.Add(ReleasedBuffer);
}
}
};