1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package org.apache.mina.common;
21
22 import java.nio.ByteOrder;
23
24 import org.apache.mina.common.support.BaseByteBuffer;
25
26
27
28
29
30
31
32
33 public class SimpleByteBufferAllocator implements ByteBufferAllocator {
34 private static final int MINIMUM_CAPACITY = 1;
35
36 public SimpleByteBufferAllocator() {
37 }
38
39 public ByteBuffer allocate(int capacity, boolean direct) {
40 java.nio.ByteBuffer nioBuffer;
41 if (direct) {
42 nioBuffer = java.nio.ByteBuffer.allocateDirect(capacity);
43 } else {
44 nioBuffer = java.nio.ByteBuffer.allocate(capacity);
45 }
46 return new SimpleByteBuffer(nioBuffer);
47 }
48
49 public ByteBuffer wrap(java.nio.ByteBuffer nioBuffer) {
50 return new SimpleByteBuffer(nioBuffer);
51 }
52
53 public void dispose() {
54 }
55
56 private static class SimpleByteBuffer extends BaseByteBuffer {
57 private java.nio.ByteBuffer buf;
58
59 private int refCount = 1;
60
61 protected SimpleByteBuffer(java.nio.ByteBuffer buf) {
62 this.buf = buf;
63 buf.order(ByteOrder.BIG_ENDIAN);
64 refCount = 1;
65 }
66
67 public synchronized void acquire() {
68 if (refCount <= 0) {
69 throw new IllegalStateException("Already released buffer.");
70 }
71
72 refCount++;
73 }
74
75 public void release() {
76 synchronized (this) {
77 if (refCount <= 0) {
78 refCount = 0;
79 throw new IllegalStateException(
80 "Already released buffer. You released the buffer too many times.");
81 }
82
83 refCount--;
84 if (refCount > 0) {
85 return;
86 }
87 }
88 }
89
90 public java.nio.ByteBuffer buf() {
91 return buf;
92 }
93
94 public boolean isPooled() {
95 return false;
96 }
97
98 public void setPooled(boolean pooled) {
99 }
100
101 protected void capacity0(int requestedCapacity) {
102 int newCapacity = MINIMUM_CAPACITY;
103 while (newCapacity < requestedCapacity) {
104 newCapacity <<= 1;
105 }
106
107 java.nio.ByteBuffer oldBuf = this.buf;
108 java.nio.ByteBuffer newBuf;
109 if (isDirect()) {
110 newBuf = java.nio.ByteBuffer.allocateDirect(newCapacity);
111 } else {
112 newBuf = java.nio.ByteBuffer.allocate(newCapacity);
113 }
114
115 newBuf.clear();
116 oldBuf.clear();
117 newBuf.put(oldBuf);
118 this.buf = newBuf;
119 }
120
121 public ByteBuffer duplicate() {
122 return new SimpleByteBuffer(this.buf.duplicate());
123 }
124
125 public ByteBuffer slice() {
126 return new SimpleByteBuffer(this.buf.slice());
127 }
128
129 public ByteBuffer asReadOnlyBuffer() {
130 return new SimpleByteBuffer(this.buf.asReadOnlyBuffer());
131 }
132
133 public byte[] array() {
134 return buf.array();
135 }
136
137 public int arrayOffset() {
138 return buf.arrayOffset();
139 }
140 }
141 }