01: /*
02: * Created on Feb 11, 2004
03: */
04: package uk.org.ponder.streamutil.read;
05:
06: import java.io.IOException;
07:
08: import uk.org.ponder.stringutil.CharWrap;
09: import uk.org.ponder.util.UniversalRuntimeException;
10:
11: /**
12: * The class
13: *
14: * @author Bosmon
15: */
16: public class LexUtil {
17: public static void expect(PushbackRIS lr, String toexpect) {
18: for (int i = 0; i < toexpect.length(); ++i) {
19: char c = lr.get();
20: if (c != toexpect.charAt(i))
21: throw new UniversalRuntimeException("Expected text "
22: + toexpect + " not found");
23: }
24: }
25:
26: public static void skipWhite(PushbackRIS lr) {
27: while (!lr.EOF()) {
28: char c = lr.get();
29: if (!Character.isWhitespace(c)) {
30: lr.unread(c);
31: break;
32: }
33: }
34: }
35:
36: public static String readString(PushbackRIS pbr, String delimiters) {
37: CharWrap togo = new CharWrap();
38: while (!pbr.EOF()) {
39: char c = pbr.get();
40: if (delimiters.indexOf(c) != -1) {
41: pbr.unread(c);
42: break;
43: }
44: togo.append(c);
45: }
46: return togo.toString();
47: }
48:
49: public static int readInt(PushbackRIS pbr) {
50: StringBuffer sb = new StringBuffer();
51: char c = pbr.get();
52: while (Character.isDigit(c)) {
53: sb.append(c);
54: c = pbr.get();
55: }
56: pbr.unread(c);
57: int togo = 0;
58: try {
59: togo = Integer.parseInt(sb.toString());
60: } catch (Exception e) {
61: throw UniversalRuntimeException.accumulate(e,
62: "Error reading integer: ");
63: }
64: return togo;
65: }
66:
67: public static double readDouble(PushbackRIS lr) {
68: StringBuffer sb = new StringBuffer();
69: char c = lr.get();
70: while (Character.isDigit(c) || c == '.' || c == 'e' || c == 'E'
71: || c == '+' || c == '-') {
72: sb.append(c);
73: c = lr.get();
74: }
75: lr.unread(c);
76: return Double.parseDouble(sb.toString());
77: }
78:
79: /**
80: * @param lr
81: */
82: public static void expectEmpty(PushbackRIS lr) {
83: skipWhite(lr);
84: if (!lr.EOF()) {
85: CharWrap unexpected = new CharWrap();
86: // TODO: this is rubbish! We cannot expect EOF until we actually read the
87: // char.
88: while (!lr.EOF()) {
89: char c = lr.get();
90: if (unexpected.size() < 32) {
91: unexpected.append(c);
92: }
93: }
94: throw new UniversalRuntimeException(
95: "Unexpected trailing data " + unexpected);
96: }
97: }
98: }
|