forked from Unity-Technologies/com.unity.netcode.gameobjects
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBitStreamPool.cs
More file actions
69 lines (62 loc) · 2.66 KB
/
Copy pathBitStreamPool.cs
File metadata and controls
69 lines (62 loc) · 2.66 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
using System;
using System.Collections.Generic;
using MLAPI.Logging;
namespace MLAPI.Serialization.Pooled
{
/// <summary>
/// Static class containing PooledBitStreams
/// </summary>
public static class BitStreamPool
{
private static byte createdStreams = 0;
private static readonly Queue<WeakReference> overflowStreams = new Queue<WeakReference>();
private static readonly Queue<PooledBitStream> streams = new Queue<PooledBitStream>();
/// <summary>
/// Retrieves an expandable PooledBitStream from the pool
/// </summary>
/// <returns>An expandable PooledBitStream</returns>
public static PooledBitStream GetStream()
{
if (overflowStreams.Count > 0)
{
if (LogHelper.CurrentLogLevel <= LogLevel.Developer) LogHelper.LogInfo("Retrieving PooledBitStream from overflow pool. Recent burst?");
WeakReference weakStream = null;
while (overflowStreams.Count > 0 && ((weakStream = overflowStreams.Dequeue()) == null || !weakStream.IsAlive)) ;
if (weakStream.IsAlive) return (PooledBitStream)weakStream.Target;
}
if (streams.Count == 0)
{
if (createdStreams == 254)
{
if (LogHelper.CurrentLogLevel <= LogLevel.Normal) LogHelper.LogWarning("255 streams have been created. Did you forget to dispose?");
}
else if (createdStreams < 255) createdStreams++;
return new PooledBitStream();
}
PooledBitStream stream = streams.Dequeue();
stream.SetLength(0);
stream.Position = 0;
return stream;
}
/// <summary>
/// Puts a PooledBitStream back into the pool
/// </summary>
/// <param name="stream">The stream to put in the pool</param>
public static void PutBackInPool(PooledBitStream stream)
{
if (streams.Count > 16)
{
//The user just created lots of streams without returning them in between.
//Streams are essentially byte array wrappers. This is valuable memory.
//Thus we put this stream as a weak reference incase of another burst
//But still leave it to GC
if (LogHelper.CurrentLogLevel <= LogLevel.Developer) LogHelper.LogInfo("Putting PooledBitStream into overflow pool. Did you forget to dispose?");
overflowStreams.Enqueue(new WeakReference(stream));
}
else
{
streams.Enqueue(stream);
}
}
}
}