start of new file
[IRC.git] / Robust / src / Lex / EscapedUnicodeReader.java
1 package Lex;
2
3 import java.io.Reader;
4 import java.io.FilterReader;
5 import java.io.IOException;
6
7 public class EscapedUnicodeReader extends FilterReader {
8
9   int pushback=-1;
10   boolean isEvenSlash = true;
11
12   public EscapedUnicodeReader(Reader in) {
13     super(in);
14   }
15   public int read() throws IOException {
16     int r = (pushback==-1)?in.read():pushback; pushback=-1;
17     
18     if (r!='\\') {
19       isEvenSlash=true;
20       return r;
21     } else { // found a backslash;
22       if (!isEvenSlash) { // Only even slashes are eligible unicode escapes.
23         isEvenSlash=true;
24         return r;
25       }
26       
27       // Check for the trailing u.
28       pushback=in.read();
29       if (pushback!='u') {
30         isEvenSlash=false;
31         return '\\';
32       }
33
34       // OK, we've found backslash-u.  
35       // Reset pushback and snarf up all trailing u's.
36       pushback=-1;
37       while((r=in.read())=='u')
38         ;
39       // Now we should find 4 hex digits. 
40       // If we don't, we can raise bloody hell.
41       int val=0;
42       for (int i=0; i<4; i++, r=in.read()) {
43         int d=Character.digit((char)r, 16);
44         if (r<0 || d<0)
45           throw new Error("Invalid unicode escape character.");
46         val = (val*16) + d;
47       }
48       // yeah, we made it.
49       pushback = r;
50       isEvenSlash=true;
51       return val;
52     }
53   }
54   // synthesize array read from single-character read.
55   public int read(char cbuf[], int off, int len) throws IOException {
56     for (int i=0; i<len; i++) {
57       int c = read();
58       if (c==-1) return (i==0)?-1:i; // end of stream reached.
59       else cbuf[i+off] = (char) c;
60     }
61     return len;
62   }
63
64   public boolean markSupported() { return false; }
65
66   public boolean ready() throws IOException {
67     if (pushback!=-1) return true;
68     else return in.ready();
69   }
70 }