1 package gnu.text; 2 import java.io.*; 3 4 8 9 public class QueueReader extends Reader 10 { 11 char[] buffer; 12 int readAheadLimit; 13 int mark; int pos; int limit; boolean EOFseen; 17 18 public QueueReader () 19 { 20 } 21 22 public boolean markSupported () { return true; } 23 24 public synchronized void mark(int readAheadLimit) 25 { 26 this.readAheadLimit = readAheadLimit; 27 mark = pos; 28 } 29 30 public synchronized void reset () 31 { 32 if (readAheadLimit > 0) 33 pos = mark; 34 } 35 36 void resize (int len) 37 { 38 int cur_size = limit - pos; 39 if (readAheadLimit > 0 && pos - mark <= readAheadLimit) 40 cur_size = limit - mark; 41 else 42 mark = pos; 43 char[] new_buffer = (buffer.length < cur_size + len 44 ? new char[2 * cur_size + len] 45 : buffer); 46 System.arraycopy(buffer, mark, new_buffer, 0, cur_size); 47 buffer = new_buffer; 48 pos -= mark; 49 mark = 0; 50 limit = cur_size; 51 } 52 53 public void append (String str) 54 { 55 append (str.toCharArray()); 56 } 57 58 public void append(char[] chars) 59 { 60 append(chars, 0, chars.length); 61 } 62 63 public synchronized void append(char[] chars, int off, int len) 64 { 65 if (buffer == null) 66 buffer = new char[100+len]; 67 else if (buffer.length < limit + len) 68 resize(len); 69 System.arraycopy(chars, off, buffer, limit, len); 70 limit += len; 71 notifyAll(); 72 } 73 74 public synchronized void append(char ch) 75 { 76 if (buffer == null) 77 buffer = new char[100]; 78 else if (buffer.length <= limit) 79 resize(1); 80 buffer[limit++] = ch; 81 notifyAll(); 82 } 83 84 85 public synchronized void appendEOF () 86 { 87 EOFseen = true; 88 } 89 90 public synchronized boolean ready () 91 { 92 return pos < limit || EOFseen; 93 } 94 95 public synchronized int read () 96 { 97 while (pos >= limit) 98 { 99 if (EOFseen) 100 return -1; 101 try 102 { 103 wait(); 104 } 105 catch (java.lang.InterruptedException ex) 106 { 107 } 108 } 109 char ch = buffer[pos++]; 110 return ch; 111 } 112 113 public synchronized int read (char[] cbuf, int off, int len) 114 { 115 if (len == 0) 116 return 0; 117 while (pos >= limit) 118 { 119 if (EOFseen) 120 return -1; 121 try 122 { 123 wait(); 124 } 125 catch (java.lang.InterruptedException ex) 126 { 127 } 128 } 129 int avail = limit - pos; 130 if (len > avail) 131 len = avail; 132 System.arraycopy (buffer, pos, cbuf, off, len); 133 pos += len; 134 return len; 135 } 136 137 public synchronized void close () 138 { 139 pos = 0; 140 limit = 0; 141 mark = 0; 142 EOFseen = true; 143 buffer = null; 144 } 145 } 146 | Popular Tags |