Back to home page

OSCL-LXR

 
 

    


0001 /*
0002  * Licensed to the Apache Software Foundation (ASF) under one or more
0003  * contributor license agreements.  See the NOTICE file distributed with
0004  * this work for additional information regarding copyright ownership.
0005  * The ASF licenses this file to You under the Apache License, Version 2.0
0006  * (the "License"); you may not use this file except in compliance with
0007  * the License.  You may obtain a copy of the License at
0008  *
0009  *    http://www.apache.org/licenses/LICENSE-2.0
0010  *
0011  * Unless required by applicable law or agreed to in writing, software
0012  * distributed under the License is distributed on an "AS IS" BASIS,
0013  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
0014  * See the License for the specific language governing permissions and
0015  * limitations under the License.
0016  */
0017 
0018 package org.apache.spark.network.buffer;
0019 
0020 import java.io.IOException;
0021 import java.io.InputStream;
0022 import java.nio.ByteBuffer;
0023 
0024 import io.netty.buffer.ByteBuf;
0025 import io.netty.buffer.ByteBufInputStream;
0026 import org.apache.commons.lang3.builder.ToStringBuilder;
0027 import org.apache.commons.lang3.builder.ToStringStyle;
0028 
0029 /**
0030  * A {@link ManagedBuffer} backed by a Netty {@link ByteBuf}.
0031  */
0032 public class NettyManagedBuffer extends ManagedBuffer {
0033   private final ByteBuf buf;
0034 
0035   public NettyManagedBuffer(ByteBuf buf) {
0036     this.buf = buf;
0037   }
0038 
0039   @Override
0040   public long size() {
0041     return buf.readableBytes();
0042   }
0043 
0044   @Override
0045   public ByteBuffer nioByteBuffer() throws IOException {
0046     return buf.nioBuffer();
0047   }
0048 
0049   @Override
0050   public InputStream createInputStream() throws IOException {
0051     return new ByteBufInputStream(buf);
0052   }
0053 
0054   @Override
0055   public ManagedBuffer retain() {
0056     buf.retain();
0057     return this;
0058   }
0059 
0060   @Override
0061   public ManagedBuffer release() {
0062     buf.release();
0063     return this;
0064   }
0065 
0066   @Override
0067   public Object convertToNetty() throws IOException {
0068     return buf.duplicate().retain();
0069   }
0070 
0071   @Override
0072   public String toString() {
0073     return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE)
0074       .append("buf", buf)
0075       .toString();
0076   }
0077 }