1 21 22 package org.armedbear.j; 23 24 import java.io.Reader ; 25 26 public final class FastStringReader extends Reader 27 { 28 private final String s; 29 private final int length; 30 private int index; 31 private int mark; 32 33 public FastStringReader(String s) 34 { 35 this.s = s; 36 length = s.length(); 37 } 38 39 public final char readChar() 40 { 41 return index < length ? s.charAt(index++) : 0; 42 } 43 44 public final void unreadChar() 45 { 46 Debug.assertTrue(index > 0); 47 if (index > 0) 48 --index; 49 } 50 51 public int read() 52 { 53 return index < length ? s.charAt(index++) : -1; 54 } 55 56 public int read(char array[], int offset, int count) 57 { 58 if (offset < 0 || count < 0 || offset + count > array.length) 59 throw new IndexOutOfBoundsException (); 60 if (count == 0) 61 return 0; 62 final int actual = Math.min(count, length - index); 63 s.getChars(index, index + actual, array, offset); 64 index += actual; 65 return actual; 66 } 67 68 public String readToken() 71 { 72 skipWhitespace(); 73 if (index == length) 74 return ""; 75 char quoteChar = 0; 76 int begin = index; 77 char c = s.charAt(index++); 78 if (c == '"' || c == '\'') { 79 quoteChar = c; 80 ++begin; 81 } 82 while (index < length) { 83 c = s.charAt(index); 84 if (quoteChar != 0 && c == quoteChar) { 85 int end = index; 87 ++index; 89 return s.substring(begin, end); 90 } 91 if (quoteChar == 0 && Character.isWhitespace(c)) { 92 return s.substring(begin, index); 94 } else 95 ++index; 96 } 97 return s.substring(begin, index); 98 } 99 100 public String readLine() 101 { 102 final int limit = length; 103 if (index >= limit) 104 return null; 105 final int begin = index; 106 do { 107 switch (s.charAt(index)) { 108 case '\n': 109 return s.substring(begin, index++); 110 case '\r': { 111 final int end = index++; 112 if (index < limit && s.charAt(index) == '\n') 114 ++index; 115 return s.substring(begin, end); 116 } 117 } 119 } while (++index < limit); 120 return s.substring(begin, index); 121 } 122 123 public long skip(long count) 124 { 125 final long actual = Math.min(count, length - index); 126 index += actual; 127 return actual; 128 } 129 130 public boolean ready() 131 { 132 return true; 133 } 134 135 public boolean markSupported() 136 { 137 return true; 138 } 139 140 public void mark(int readAheadLimit) 141 { 142 if (readAheadLimit < 0) 143 throw new IllegalArgumentException ("Read-ahead limit < 0"); 144 mark = index; 145 } 146 147 public void reset() 148 { 149 index = mark; 150 } 151 152 public void close() {} 153 154 public final String remainder() 155 { 156 return s.substring(index); 157 } 158 159 public final void skipWhitespace() 160 { 161 while (index < length && Character.isWhitespace(s.charAt(index))) 162 ++index; 163 } 164 } 165 | Popular Tags |