Added a peekable reader.
authorFredrik Tolf <fredrik@dolda2000.com>
Sun, 15 Nov 2009 06:49:25 +0000 (07:49 +0100)
committerFredrik Tolf <fredrik@dolda2000.com>
Sun, 15 Nov 2009 06:49:25 +0000 (07:49 +0100)
src/dolda/jsvc/next/PeekReader.java [new file with mode: 0644]

diff --git a/src/dolda/jsvc/next/PeekReader.java b/src/dolda/jsvc/next/PeekReader.java
new file mode 100644 (file)
index 0000000..1c3fce5
--- /dev/null
@@ -0,0 +1,61 @@
+package dolda.jsvc.next;
+
+import java.io.*;
+
+public class PeekReader extends Reader {
+    private final Reader back;
+    private boolean p = false;
+    private int la;
+       
+    public PeekReader(Reader back) {
+       this.back = back;
+    }
+       
+    public void close() throws IOException {
+       back.close();
+    }
+       
+    public int read() throws IOException {
+       if(p) {
+           p = false;
+           return(la);
+       } else {
+           return(back.read());
+       }
+    }
+       
+    public int read(char[] b, int off, int len) throws IOException {
+       int r = 0;
+       while(r < len) {
+           int c = read();
+           if(c < 0)
+               return(r);
+           b[off + r++] = (char)c;
+       }
+       return(r);
+    }
+       
+    public boolean ready() throws IOException {
+       if(p)
+           return(true);
+       return(back.ready());
+    }
+    
+    protected boolean whitespace(char c) {
+       return(Character.isWhitespace(c));
+    }
+
+    public int peek(boolean skipws) throws IOException {
+       if(p)
+           return(la);
+       do {
+           la = back.read();
+           p = true;
+       } while(skipws && (la >= 0) && whitespace((char)la));
+       return(la);
+    }
+    
+    public int peek() throws IOException {
+       return(peek(false));
+    }
+}