-
-
Notifications
You must be signed in to change notification settings - Fork 73
Expand file tree
/
Copy pathBuffer{T}.cs
More file actions
62 lines (50 loc) · 1.55 KB
/
Buffer{T}.cs
File metadata and controls
62 lines (50 loc) · 1.55 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
// Copyright (c) Six Labors.
// Licensed under the Six Labors Split License.
using System.Buffers;
using System.Runtime.CompilerServices;
namespace SixLabors.Fonts;
/// <summary>
/// An disposable buffer that is backed by an array pool.
/// </summary>
/// <typeparam name="T">The type of buffer element.</typeparam>
internal ref struct Buffer<T>
where T : unmanaged
{
private int length;
private readonly byte[] buffer;
private readonly Span<T> span;
private bool isDisposed;
public Buffer(int length)
{
Guard.MustBeGreaterThanOrEqualTo(length, 0, nameof(length));
int itemSizeBytes = Unsafe.SizeOf<T>();
int bufferSizeInBytes = length * itemSizeBytes;
this.buffer = ArrayPool<byte>.Shared.Rent(bufferSizeInBytes);
this.length = length;
using ByteMemoryManager<T> manager = new(this.buffer);
this.Memory = manager.Memory[..this.length];
this.span = this.Memory.Span;
this.isDisposed = false;
}
public Memory<T> Memory { get; }
public readonly Span<T> GetSpan()
{
if (this.buffer is null)
{
ThrowObjectDisposedException();
}
return this.span;
}
public void Dispose()
{
if (this.isDisposed)
{
return;
}
ArrayPool<byte>.Shared.Return(this.buffer);
this.length = 0;
this.isDisposed = true;
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static void ThrowObjectDisposedException() => throw new ObjectDisposedException("Buffer<T>");
}