Home | History | Annotate | Download | only in conscrypt
      1 /*
      2  * Copyright 2017 The Android Open Source Project
      3  *
      4  * Licensed under the Apache License, Version 2.0 (the "License");
      5  * you may not use this file except in compliance with the License.
      6  * You may obtain a copy of the License at
      7  *
      8  *      http://www.apache.org/licenses/LICENSE-2.0
      9  *
     10  * Unless required by applicable law or agreed to in writing, software
     11  * distributed under the License is distributed on an "AS IS" BASIS,
     12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     13  * See the License for the specific language governing permissions and
     14  * limitations under the License.
     15  */
     16 package org.conscrypt;
     17 
     18 import io.netty.buffer.ByteBuf;
     19 import io.netty.buffer.ByteBufAllocator;
     20 import io.netty.buffer.PooledByteBufAllocator;
     21 import java.nio.ByteBuffer;
     22 
     23 /**
     24  * A {@link BufferAllocator} that is backed by a Netty buffer pool.
     25  */
     26 final class NettyBufferAllocator extends BufferAllocator {
     27     private static final ByteBufAllocator alloc = PooledByteBufAllocator.DEFAULT;
     28     private static final NettyBufferAllocator instance = new NettyBufferAllocator();
     29 
     30     static NettyBufferAllocator getInstance() {
     31         return instance;
     32     }
     33 
     34     private NettyBufferAllocator() {}
     35 
     36     @Override
     37     public AllocatedBuffer allocateDirectBuffer(int capacity) {
     38         return new ByteBufAdapter(alloc.directBuffer(capacity));
     39     }
     40 
     41     private static final class ByteBufAdapter extends AllocatedBuffer {
     42         private final ByteBuf nettyBuffer;
     43         private final ByteBuffer buffer;
     44 
     45         private ByteBufAdapter(ByteBuf nettyBuffer) {
     46             this.nettyBuffer = nettyBuffer;
     47             this.buffer = nettyBuffer.nioBuffer(0, nettyBuffer.capacity());
     48         }
     49 
     50         @Override
     51         public ByteBuffer nioBuffer() {
     52             return buffer;
     53         }
     54 
     55         @Override
     56         public AllocatedBuffer retain() {
     57             nettyBuffer.retain();
     58             return this;
     59         }
     60 
     61         @Override
     62         public AllocatedBuffer release() {
     63             nettyBuffer.release();
     64             return this;
     65         }
     66     }
     67 }
     68