| 4 | import java.io.Reader; |
| 5 | |
| 6 | public class CircularCharBuffer implements CharStream { |
| 7 | private static final int DEFAULT_BUFFER_SIZE = 2048; |
| 8 | private Reader in; |
| 9 | private char[] buf; |
| 10 | private int readPos = 0; |
| 11 | private int writePos = 0; |
| 12 | private int available = 0; |
| 13 | private boolean eof = false; |
| 14 | |
| 15 | public CircularCharBuffer(Reader in) throws IOException { |
| 16 | this(in, DEFAULT_BUFFER_SIZE); |
| 17 | } |
| 18 | |
| 19 | public CircularCharBuffer(Reader in, int bufferSize) throws IOException { |
| 20 | this.in = in; |
| 21 | this.buf = new char[bufferSize]; |
| 22 | fill(); |
| 23 | } |
| 24 | |
| 25 | public int available() { |
| 26 | return this.available; |
| 27 | } |
| 28 | |
| 29 | private void fill() throws IOException { |
| 30 | int len = 0; |
| 31 | |
| 32 | if (this.writePos == this.readPos && available > 0) { |
| 33 | return; |
| 34 | } |
| 35 | |
| 36 | if (this.writePos >= this.readPos) { |
| 37 | len = this.buf.length - this.writePos; |
| 38 | } else { |
| 39 | len = this.readPos - this.writePos; |
| 40 | } |
| 41 | |
| 42 | int amountRead = this.in.read(this.buf, this.writePos, len); |
| 43 | |
| 44 | if (amountRead < 0) { |
| 45 | this.eof = true; |
| 46 | return; |
| 47 | } |
| 48 | |
| 49 | this.available += amountRead; |
| 50 | this.writePos = (this.writePos + amountRead) % this.buf.length; |
| 51 | } |
| 52 | |
| 53 | public int peek() throws IOException { |
| 54 | return peek(1); |
| 55 | } |
| 56 | |
| 57 | public int peek(int pos) throws IOException { |
| 58 | if (available() < pos) { |
| 59 | fill(); |
| 60 | } |
| 61 | if (available() < pos) { |
| 62 | return -1; |
| 63 | } |
nothing calls this directly
no outgoing calls
no test coverage detected