1
0
mirror of https://git.teknik.io/Teknikode/Teknik.git synced 2023-08-02 14:16:22 +02:00
Teknik/Utilities/PooledArray.cs

65 lines
1.4 KiB
C#
Raw Permalink Normal View History

2022-05-28 08:03:57 +02:00
using System;
using System.Buffers;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Teknik.Utilities
{
public class PooledArray : IDisposable
{
private static ArrayPool<byte> _arrayPool = ArrayPool<byte>.Create();
public byte[] Array { get; private set; }
public readonly int Length;
2022-05-28 08:03:57 +02:00
public PooledArray(int size)
{
Array = _arrayPool.Rent(size);
Length = size;
2022-05-28 08:03:57 +02:00
}
2022-05-28 20:00:15 +02:00
public PooledArray(byte[] array)
{
2022-05-29 23:21:24 +02:00
Length = array.Length;
2022-05-28 20:00:15 +02:00
Array = _arrayPool.Rent(array.Length);
array.CopyTo(Array, 0);
2022-05-29 23:21:24 +02:00
}
public PooledArray(PooledArray array)
{
Length = array.Length;
2022-05-29 23:21:24 +02:00
Array = _arrayPool.Rent(array.Length);
array.CopyTo(Array);
2022-05-28 20:00:15 +02:00
}
2022-05-29 06:56:41 +02:00
public void CopyTo(byte[] destination)
{
System.Array.Copy(Array, destination, Length);
}
public byte[] ToArray()
{
return Array.Take(Length).ToArray();
}
2022-05-28 08:03:57 +02:00
public void Dispose()
{
2022-05-29 23:21:24 +02:00
Dispose(true);
// Suppress finalization.
GC.SuppressFinalize(this);
}
public void Dispose(bool disposing)
{
if (disposing)
{
_arrayPool.Return(Array);
}
2022-05-28 08:03:57 +02:00
}
}
}