001/* 002 * Licensed to the Apache Software Foundation (ASF) under one 003 * or more contributor license agreements. See the NOTICE file 004 * distributed with this work for additional information 005 * regarding copyright ownership. The ASF licenses this file 006 * to you under the Apache License, Version 2.0 (the 007 * "License"); you may not use this file except in compliance 008 * with the License. You may obtain a copy of the License at 009 * 010 * http://www.apache.org/licenses/LICENSE-2.0 011 * 012 * Unless required by applicable law or agreed to in writing, 013 * software distributed under the License is distributed on an 014 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 015 * KIND, either express or implied. See the License for the 016 * specific language governing permissions and limitations 017 * under the License. 018 * 019 */ 020package org.apache.mina.core.buffer; 021 022import java.nio.ByteBuffer; 023import java.nio.ByteOrder; 024 025/** 026 * A simplistic {@link IoBufferAllocator} which simply allocates a new 027 * buffer every time. 028 * 029 * @author <a href="http://mina.apache.org">Apache MINA Project</a> 030 */ 031public class SimpleBufferAllocator implements IoBufferAllocator { 032 033 public IoBuffer allocate(int capacity, boolean direct) { 034 return wrap(allocateNioBuffer(capacity, direct)); 035 } 036 037 public ByteBuffer allocateNioBuffer(int capacity, boolean direct) { 038 ByteBuffer nioBuffer; 039 if (direct) { 040 nioBuffer = ByteBuffer.allocateDirect(capacity); 041 } else { 042 nioBuffer = ByteBuffer.allocate(capacity); 043 } 044 return nioBuffer; 045 } 046 047 public IoBuffer wrap(ByteBuffer nioBuffer) { 048 return new SimpleBuffer(nioBuffer); 049 } 050 051 public void dispose() { 052 // Do nothing 053 } 054 055 private class SimpleBuffer extends AbstractIoBuffer { 056 private ByteBuffer buf; 057 058 protected SimpleBuffer(ByteBuffer buf) { 059 super(SimpleBufferAllocator.this, buf.capacity()); 060 this.buf = buf; 061 buf.order(ByteOrder.BIG_ENDIAN); 062 } 063 064 protected SimpleBuffer(SimpleBuffer parent, ByteBuffer buf) { 065 super(parent); 066 this.buf = buf; 067 } 068 069 @Override 070 public ByteBuffer buf() { 071 return buf; 072 } 073 074 @Override 075 protected void buf(ByteBuffer buf) { 076 this.buf = buf; 077 } 078 079 @Override 080 protected IoBuffer duplicate0() { 081 return new SimpleBuffer(this, this.buf.duplicate()); 082 } 083 084 @Override 085 protected IoBuffer slice0() { 086 return new SimpleBuffer(this, this.buf.slice()); 087 } 088 089 @Override 090 protected IoBuffer asReadOnlyBuffer0() { 091 return new SimpleBuffer(this, this.buf.asReadOnlyBuffer()); 092 } 093 094 @Override 095 public byte[] array() { 096 return buf.array(); 097 } 098 099 @Override 100 public int arrayOffset() { 101 return buf.arrayOffset(); 102 } 103 104 @Override 105 public boolean hasArray() { 106 return buf.hasArray(); 107 } 108 109 @Override 110 public void free() { 111 // Do nothing 112 } 113 } 114}