1
+ // Licensed to the .NET Foundation under one or more agreements.
2
+ // The .NET Foundation licenses this file to you under the MIT license.
3
+ // See the LICENSE file in the project root for more information.
4
+
5
+ using System . Buffers ;
6
+ using System . Threading . Tasks ;
7
+ using Xunit ;
8
+
9
+ namespace System . IO . Pipelines . Tests
10
+ {
11
+ public class DisposeTrackingBufferPool : TestMemoryPool
12
+ {
13
+ public int DisposedBlocks { get ; set ; }
14
+ public int CurrentlyRentedBlocks { get ; set ; }
15
+
16
+ public override IMemoryOwner < byte > Rent ( int size )
17
+ {
18
+ return new DisposeTrackingMemoryManager ( new byte [ size ] , this ) ;
19
+ }
20
+
21
+ protected override void Dispose ( bool disposing )
22
+ {
23
+ }
24
+
25
+ private class DisposeTrackingMemoryManager : MemoryManager < byte >
26
+ {
27
+ private byte [ ] _array ;
28
+
29
+ private readonly DisposeTrackingBufferPool _bufferPool ;
30
+
31
+ public DisposeTrackingMemoryManager ( byte [ ] array , DisposeTrackingBufferPool bufferPool )
32
+ {
33
+ _array = array ;
34
+ _bufferPool = bufferPool ;
35
+ _bufferPool . CurrentlyRentedBlocks ++ ;
36
+ }
37
+
38
+ public override Memory < byte > Memory => CreateMemory ( _array . Length ) ;
39
+
40
+ public bool IsDisposed => _array == null ;
41
+
42
+ public override MemoryHandle Pin ( int elementIndex = 0 )
43
+ {
44
+ throw new NotImplementedException ( ) ;
45
+ }
46
+
47
+ public override void Unpin ( )
48
+ {
49
+ throw new NotImplementedException ( ) ;
50
+ }
51
+
52
+ protected override bool TryGetArray ( out ArraySegment < byte > segment )
53
+ {
54
+ if ( IsDisposed )
55
+ throw new ObjectDisposedException ( nameof ( DisposeTrackingBufferPool ) ) ;
56
+ segment = new ArraySegment < byte > ( _array ) ;
57
+ return true ;
58
+ }
59
+
60
+ protected override void Dispose ( bool disposing )
61
+ {
62
+ _bufferPool . DisposedBlocks ++ ;
63
+ _bufferPool . CurrentlyRentedBlocks -- ;
64
+
65
+ _array = null ;
66
+ }
67
+
68
+ public override Span < byte > GetSpan ( )
69
+ {
70
+ if ( IsDisposed )
71
+ throw new ObjectDisposedException ( nameof ( DisposeTrackingBufferPool ) ) ;
72
+ return _array ;
73
+ }
74
+ }
75
+ }
76
+ }
0 commit comments