1 /*
2  * Copyright 2016 The gRPC Authors
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 
17 package io.grpc.benchmarks;
18 
19 import io.grpc.Drainable;
20 import io.grpc.KnownLength;
21 import io.netty.buffer.ByteBuf;
22 import java.io.IOException;
23 import java.io.InputStream;
24 import java.io.OutputStream;
25 
26 /**
27  * A {@link Drainable} {@code InputStream} that reads an {@link ByteBuf}.
28  */
29 @SuppressWarnings("InputStreamSlowMultibyteRead") // doesn't matter if slow. It'll throw
30 public class ByteBufInputStream extends InputStream
31     implements Drainable, KnownLength {
32 
33   private ByteBuf buf;
34 
ByteBufInputStream(ByteBuf buf)35   ByteBufInputStream(ByteBuf buf) {
36     this.buf = buf;
37   }
38 
39   @Override
drainTo(OutputStream target)40   public int drainTo(OutputStream target) throws IOException {
41     int readableBytes = buf.readableBytes();
42     buf.readBytes(target, readableBytes);
43     buf = null;
44     return readableBytes;
45   }
46 
47   @Override
available()48   public int available() throws IOException {
49     if (buf != null) {
50       return buf.readableBytes();
51     }
52     return 0;
53   }
54 
55   @Override
read()56   public int read() throws IOException {
57     throw new UnsupportedOperationException();
58   }
59 }
60