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