This repository has been archived by the owner on Aug 2, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 346
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
64 additions
and
1 deletion.
There are no files selected for viewing
62 changes: 62 additions & 0 deletions
62
src/System.Buffers.Experimental/System/Buffers/AutoBufferPool.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,62 @@ | ||
using System.Collections.Concurrent; | ||
|
||
namespace System.Buffers | ||
{ | ||
public class AutoBufferPool | ||
{ | ||
private readonly static AutoBufferPool s_shared = new AutoBufferPool(); | ||
public static AutoBufferPool Shared => s_shared; | ||
|
||
private ConcurrentQueue<AutoPooledMemory> _pool = new ConcurrentQueue<AutoPooledMemory>(); | ||
|
||
public OwnedMemory<byte> Rent(int minimumBufferSize) | ||
{ | ||
var array = ArrayPool<byte>.Shared.Rent(minimumBufferSize); | ||
|
||
AutoPooledMemory memory; | ||
if (!_pool.TryDequeue(out memory)) | ||
{ | ||
memory = new AutoPooledMemory(array, this); | ||
} | ||
else | ||
{ | ||
memory.Initalize(array); | ||
} | ||
|
||
return memory; | ||
} | ||
|
||
private void Return(AutoPooledMemory memory) | ||
{ | ||
_pool.Enqueue(memory); | ||
} | ||
|
||
private class AutoPooledMemory : OwnedMemory<byte> | ||
{ | ||
private AutoBufferPool _pool; | ||
|
||
public AutoPooledMemory(byte[] array, AutoBufferPool pool) : base(array, 0, array.Length) | ||
{ | ||
_pool = pool; | ||
} | ||
|
||
public void Initalize(byte[] array) | ||
{ | ||
base.Initialize(array, 0, array.Length); | ||
} | ||
|
||
protected override void Dispose(bool disposing) | ||
{ | ||
// Return Array to pool before clear | ||
ArrayPool<byte>.Shared.Return(Array); | ||
base.Dispose(disposing); | ||
} | ||
|
||
protected override void DisposeComplete() | ||
{ | ||
// Disposal complete, no init/clear race - return AutoPooledMemory to pool | ||
_pool.Return(this); | ||
} | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters