Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 48 additions & 0 deletions Assets/FishNet/Runtime/Serializing/WriterPool.cs
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,14 @@ public static PooledWriter Retrieve(NetworkManager networkManager, int length)
PooledWriter result;
// There is already one pooled.
if (_lengthPool.TryGetValue(index, out stack) && stack.TryPop(out result))
{
if (stack.Count == 0)
_lengthPool.Remove(index);

result.Clear(networkManager);
}
// There is a larger writer pooled.
else if (TryPopLengthWriterAbove(index, out result))
{
result.Clear(networkManager);
}
Expand All @@ -107,6 +115,46 @@ public static PooledWriter Retrieve(NetworkManager networkManager, int length)
return result;
}

/// <summary>
/// Tries to pop the closest writer from a bucket above minimum index.
/// </summary>
private static bool TryPopLengthWriterAbove(int minimumIndex, out PooledWriter writer)
{
int foundIndex = int.MaxValue;
Stack<PooledWriter> foundStack = null;

foreach (KeyValuePair<int, Stack<PooledWriter>> entry in _lengthPool)
{
if (entry.Key <= minimumIndex)
continue;
if (entry.Value.Count == 0)
continue;
if (entry.Key < foundIndex)
{
foundIndex = entry.Key;
foundStack = entry.Value;
}
}

if (foundStack == null)
{
writer = null;
return false;
}

bool popped = foundStack.TryPop(out writer);
if (!popped)
{
writer = null;
return false;
}

if (foundStack.Count == 0)
_lengthPool.Remove(foundIndex);

return true;
}

/// <summary>
/// Returns a writer to the appropriate length pool.
/// Writers must be a minimum of 1000 bytes in length to be sorted by length.
Expand Down