KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > polyglot > lex > EscapedUnicodeReader


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