1 module hunt.net.secure.conscrypt.AllocatedBuffer;
2 
3 import hunt.collection;
4 
5 /**
6  * A buffer that was allocated by a {@link BufferAllocator}.
7  */
8 abstract class AllocatedBuffer {
9     /**
10      * Returns the {@link ByteBuffer} that backs this buffer.
11      */
12     abstract ByteBuffer nioBuffer();
13 
14     /**
15      * Increases the reference count by {@code 1}.
16      */
17     abstract AllocatedBuffer retain();
18 
19     /**
20      * Decreases the reference count by {@code 1} and deallocates this object if the reference count
21      * reaches at {@code 0}.
22      *
23      * @return {@code true} if and only if the reference count became {@code 0} and this object has
24      * been deallocated
25      */
26     abstract AllocatedBuffer release();
27 
28     /**
29      * Creates a new {@link AllocatedBuffer} that is backed by the given {@link ByteBuffer}.
30      */
31     static AllocatedBuffer wrap(ByteBuffer buffer) {
32         // checkNotNull(buffer, "buffer");
33 
34         return new class AllocatedBuffer {
35 
36             override
37             ByteBuffer nioBuffer() {
38                 return buffer;
39             }
40 
41             override
42             AllocatedBuffer retain() {
43                 // Do nothing.
44                 return this;
45             }
46 
47             override
48             AllocatedBuffer release() {
49                 // Do nothing.
50                 return this;
51             }
52         };
53     }
54 }
55 
56 
57 
58 /**
59  * An object responsible for allocation of buffers. This is an extension point to enable buffer
60  * pooling within an application.
61  */
62 abstract class BufferAllocator {
63     private __gshared static BufferAllocator UNPOOLED;
64 
65     shared static this()
66     {
67         UNPOOLED = new class BufferAllocator {
68             override
69             AllocatedBuffer allocateDirectBuffer(int capacity) {
70                 return AllocatedBuffer.wrap(new HeapByteBuffer(capacity,capacity));
71                 // ByteBuffer.allocateDirect(capacity)
72             }
73         };        
74     }
75 
76     /**
77      * Returns an unpooled buffer allocator, which will create a new buffer for each request.
78      */
79     static BufferAllocator unpooled() {
80         return UNPOOLED;
81     }
82 
83     /**
84      * Allocates a direct (i.e. non-heap) buffer with the given capacity.
85      */
86     abstract AllocatedBuffer allocateDirectBuffer(int capacity);
87 }