-
Notifications
You must be signed in to change notification settings - Fork 46
Expand file tree
/
Copy pathBufferPool.cs
More file actions
47 lines (42 loc) · 1015 Bytes
/
Copy pathBufferPool.cs
File metadata and controls
47 lines (42 loc) · 1015 Bytes
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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace NetcodeIO.NET.Utils
{
/// <summary>
/// Helper methods for allocating temporary buffers
/// </summary>
public static class BufferPool
{
private static Dictionary<int, Queue<byte[]>> bufferPool = new Dictionary<int, Queue<byte[]>>();
/// <summary>
/// Retrieve a buffer of the given size
/// </summary>
public static byte[] GetBuffer(int size)
{
lock(bufferPool)
{
if (bufferPool.ContainsKey(size))
{
if (bufferPool[size].Count > 0)
return bufferPool[size].Dequeue();
}
}
return new byte[size];
}
/// <summary>
/// Return a buffer to the pool
/// </summary>
public static void ReturnBuffer(byte[] buffer)
{
lock(bufferPool)
{
if (!bufferPool.ContainsKey(buffer.Length))
bufferPool.Add(buffer.Length, new Queue<byte[]>());
System.Array.Clear(buffer, 0, buffer.Length);
bufferPool[buffer.Length].Enqueue(buffer);
}
}
}
}