2 * Copyright (C) 2014, United States Government, as represented by the
3 * Administrator of the National Aeronautics and Space Administration.
6 * The Java Pathfinder core (jpf-core) platform is licensed under the
7 * Apache License, Version 2.0 (the "License"); you may not use this file except
8 * in compliance with the License. You may obtain a copy of the License at
10 * http://www.apache.org/licenses/LICENSE-2.0.
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
19 package gov.nasa.jpf.util;
21 import java.io.IOException;
22 import java.io.InputStream;
23 import java.util.Arrays;
25 public class AvailableBufferedInputStream extends InputStream
27 private static final boolean CLEAN = false;
28 static final int DEFAULT_BUFFER_SIZE = 16 * 1024; // Not private for testing purposes
30 private final InputStream m_input;
31 private final byte m_buffer[];
35 public AvailableBufferedInputStream(InputStream input)
37 this(input, DEFAULT_BUFFER_SIZE);
40 public AvailableBufferedInputStream(InputStream input, int bufferSize)
43 m_buffer = new byte[bufferSize];
46 throw new NullPointerException("input == null");
49 public int getBufferSize()
51 return(m_buffer.length);
55 public int read() throws IOException
62 return(m_input.read());
65 return(m_buffer[m_read++] & 0x00FF);
69 public int read(byte buffer[], int offset, int length) throws IOException
76 return(m_input.read(buffer, offset, length));
79 length = Math.min(length, m_end - m_read);
80 System.arraycopy(m_buffer, m_read, buffer, offset, length);
86 public int peek() throws IOException // Returns -1 if there is nothing to read.
96 return(m_buffer[m_read] & 0x00FF);
100 public int available() throws IOException
105 return(m_end - m_read);
108 public void unread(int data) throws IOException
112 if (m_end >= m_buffer.length)
113 throw new IOException("Internal buffer overflow");
115 System.arraycopy(m_buffer, m_read, m_buffer, m_buffer.length - m_end, m_end);
116 m_read = m_buffer.length - m_end;
117 m_end = m_buffer.length;
120 m_buffer[--m_read] = (byte) data;
123 private void fill() throws IOException
126 Arrays.fill(m_buffer, 0, m_buffer.length, (byte) 0);
129 m_end = m_input.available();
130 m_end = Math.max(m_end, 0);
132 if (m_end <= 0) // m_input.read(m_buffer, 0, 0) can be expensive. Don't waste time.
135 m_end = Math.min(m_end, m_buffer.length);
136 m_end = m_input.read(m_buffer, 0, m_end);
137 m_end = Math.max(m_end, 0); // Defend against a bug where m_input.available() returning > 0 and m_input.read() returning -1
141 public String toString() // For debugging purposes
143 return(new String(m_buffer, m_read, m_end - m_read));