Home | History | Annotate | Download | only in conscrypt
      1 /*
      2  *  Licensed to the Apache Software Foundation (ASF) under one or more
      3  *  contributor license agreements.  See the NOTICE file distributed with
      4  *  this work for additional information regarding copyright ownership.
      5  *  The ASF licenses this file to You under the Apache License, Version 2.0
      6  *  (the "License"); you may not use this file except in compliance with
      7  *  the License.  You may obtain a copy of the License at
      8  *
      9  *     http://www.apache.org/licenses/LICENSE-2.0
     10  *
     11  *  Unless required by applicable law or agreed to in writing, software
     12  *  distributed under the License is distributed on an "AS IS" BASIS,
     13  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     14  *  See the License for the specific language governing permissions and
     15  *  limitations under the License.
     16  */
     17 
     18 package org.conscrypt;
     19 
     20 import java.io.IOException;
     21 import java.nio.ByteBuffer;
     22 
     23 /**
     24  * This is a wrapper input stream for ByteBuffer data source.
     25  * Among with the read functionality it provides info
     26  * about number of cunsumed bytes from the source ByteBuffer.
     27  * The source ByteBuffer object can be reseted.
     28  * So one instance of this wrapper can be reused for several
     29  * ByteBuffer data sources.
     30  */
     31 public class SSLBufferedInput extends SSLInputStream {
     32 
     33     private ByteBuffer in;
     34     private int bytik;
     35     private int consumed = 0;
     36 
     37     /**
     38      * Constructor
     39      */
     40     protected SSLBufferedInput() {}
     41 
     42     /**
     43      * Sets the buffer as a data source
     44      */
     45     protected void setSourceBuffer(ByteBuffer in) {
     46         consumed = 0;
     47         this.in = in;
     48     }
     49 
     50     @Override
     51     public int available() throws IOException {
     52         // in assumption that the buffer has been set
     53         return in.remaining();
     54     }
     55 
     56     /**
     57      * Returns the number of consumed bytes.
     58      */
     59     protected int consumed() {
     60         return consumed;
     61     }
     62 
     63     /**
     64      * Reads the following byte value. If there are no bytes in the source
     65      * buffer, method throws java.nio.BufferUnderflowException.
     66      */
     67     @Override
     68     public int read() throws IOException {
     69         // TODO: implement optimized read(int)
     70         // and read(byte[], int, int) methods
     71         bytik = in.get() & 0x00FF;
     72         consumed ++;
     73         return bytik;
     74     }
     75 }
     76