Fixes for PushbackReader (which only can push back one char) and StringReader.

This commit is contained in:
Eric Scharff 2007-12-18 12:19:52 -07:00
parent 8b2577b77c
commit 6954c9c377
2 changed files with 22 additions and 27 deletions

View File

@ -2,13 +2,15 @@ package java.io;
public class PushbackReader extends Reader { public class PushbackReader extends Reader {
private final Reader in; private final Reader in;
private final char[] buffer; private char savedChar;
private int position; private boolean hasSavedChar;
private int limit;
public PushbackReader(Reader in, int bufferSize) { public PushbackReader(Reader in, int bufferSize) {
if (bufferSize > 1) {
throw new IllegalArgumentException(bufferSize + " > 1");
}
this.in = in; this.in = in;
this.buffer = new char[bufferSize]; this.hasSavedChar = false;
} }
public PushbackReader(Reader in) { public PushbackReader(Reader in) {
@ -17,29 +19,20 @@ public class PushbackReader extends Reader {
public int read(char[] b, int offset, int length) throws IOException { public int read(char[] b, int offset, int length) throws IOException {
int count = 0; int count = 0;
if (hasSavedChar && length > 0) {
if (position < limit) { length--;
int remaining = limit - position; b[offset++] = savedChar;
if (remaining > length) { hasSavedChar = false;
remaining = length; count = 1;
}
System.arraycopy(buffer, position, b, offset, remaining);
count += remaining;
position += remaining;
offset += remaining;
length -= remaining;
} }
if (length > 0) { if (length > 0) {
int c = in.read(b, offset, length); int c = in.read(b, offset, length);
if (c == -1) { if (c == -1) {
if (count == 0) { if (count == 0) {
count = -1; count = -1;
} }
} else { } else {
count += c; count += c;
} }
} }
@ -47,11 +40,13 @@ public class PushbackReader extends Reader {
} }
public void unread(char[] b, int offset, int length) throws IOException { public void unread(char[] b, int offset, int length) throws IOException {
if (position < length) { if (length != 1) {
throw new IOException(length + " not in [0," + position + "]"); throw new IOException("Can only push back 1 char, not " + length);
} else if (hasSavedChar) {
throw new IOException("Already have a saved char");
} else { } else {
System.arraycopy(buffer, position - length, b, offset, length); hasSavedChar = true;
position -= length; savedChar = b[offset];
} }
} }

View File

@ -15,7 +15,7 @@ public class StringReader extends Reader {
return -1; return -1;
} }
} }
in.getChars(position, length, b, offset); in.getChars(position, position+length, b, offset);
position += length; position += length;
return length; return length;
} }