-
-
Notifications
You must be signed in to change notification settings - Fork 451
Expand file tree
/
Copy pathPooledByteArray.cs
More file actions
78 lines (60 loc) · 1.59 KB
/
Copy pathPooledByteArray.cs
File metadata and controls
78 lines (60 loc) · 1.59 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
70
71
72
73
74
75
76
77
78
// Copyright Dirk Lemstra https://github.com/dlemstra/Magick.NET.
// Licensed under the Apache License, Version 2.0.
using System;
#if !NETSTANDARD2_0
using System.Buffers;
#endif
namespace ImageMagick;
internal sealed class PooledByteArray : IDisposable
{
#if !NETSTANDARD2_0
private static readonly ArrayPool<byte> _pool = ArrayPool<byte>.Create(1024 * 1024 * 64, 128);
private byte[] _bytes;
public PooledByteArray(int length)
=> _bytes = _pool.Rent(length);
public byte[] Data
=> _bytes;
public int Length
=> _bytes.Length;
public void Dispose()
{
if (_bytes == null)
return;
_pool.Return(_bytes);
_bytes = null!;
}
public void Resize(int length)
{
if (length <= _bytes.Length)
return;
var newBytes = _pool.Rent(length);
Buffer.BlockCopy(_bytes, 0, newBytes, 0, _bytes.Length);
_pool.Return(_bytes);
_bytes = newBytes;
}
public byte[] ToUnpooledArray(int length)
{
var result = new byte[length];
Buffer.BlockCopy(_bytes, 0, result, 0, length);
return result;
}
#else
private byte[] _bytes;
public PooledByteArray(int length)
=> _bytes = new byte[length];
public byte[] Data
=> _bytes;
public int Length
=> _bytes.Length;
public void Dispose()
{
}
public void Resize(int length)
=> Array.Resize(ref _bytes, length);
public byte[] ToUnpooledArray(int length)
{
Array.Resize(ref _bytes, length);
return _bytes;
}
#endif
}