1 28 29 package HTTPClient; 30 31 32 import java.io.IOException ; 33 import java.io.InputStream ; 34 import java.io.FilterInputStream ; 35 36 37 47 48 69 70 final class ExtBufferedInputStream extends FilterInputStream 71 { 72 77 protected byte buf[]; 78 79 85 protected int count; 86 87 94 protected int pos; 95 96 105 protected int markpos = -1; 106 107 116 protected int marklimit; 117 118 125 public ExtBufferedInputStream(InputStream in) 126 { 127 this(in, 2048); 128 } 129 130 138 public ExtBufferedInputStream(InputStream in, int size) 139 { 140 super(in); 141 buf = new byte[size]; 142 } 143 144 151 private void fill() throws IOException 152 { 153 if (markpos < 0) 154 pos = 0; 155 else if (pos >= buf.length) 156 { 157 if (markpos > 0) 158 { 159 int sz = pos - markpos; 160 System.arraycopy(buf, markpos, buf, 0, sz); 161 pos = sz; 162 markpos = 0; 163 } 164 else if (buf.length >= marklimit) 165 { 166 markpos = -1; 167 pos = 0; 168 } 169 else 170 { 171 int nsz = pos * 2; 172 if (nsz > marklimit) 173 nsz = marklimit; 174 byte nbuf[] = new byte[nsz]; 175 System.arraycopy(buf, 0, nbuf, 0, pos); 176 buf = nbuf; 177 } 178 } 179 count = pos; int n = in.read(buf, pos, buf.length - pos); 181 count = n <= 0 ? pos : n + pos; 182 } 183 184 205 public synchronized int read() throws IOException 206 { 207 if (pos >= count) 208 { 209 fill(); 210 if (pos >= count) 211 return -1; 212 } 213 return buf[pos++] & 0xff; 214 } 215 216 240 public synchronized int read(byte b[], int off, int len) throws IOException 241 { 242 int avail = count - pos; 243 if (avail <= 0) 244 { 245 249 if (len >= buf.length && markpos < 0) 250 return in.read(b, off, len); 251 252 fill(); 253 avail = count - pos; 254 if (avail <= 0) 255 return -1; 256 } 257 int cnt = (avail < len) ? avail : len; 258 System.arraycopy(buf, pos, b, off, cnt); 259 pos += cnt; 260 return cnt; 261 } 262 263 284 public synchronized long skip(long n) throws IOException 285 { 286 if (n < 0) 287 return 0; 288 289 long avail = count - pos; 290 291 if (avail >= n) 292 { 293 pos += n; 294 return n; 295 } 296 297 pos += avail; 298 return avail + in.skip(n - avail); 299 } 300 301 318 public synchronized int available() throws IOException 319 { 320 return (count - pos) + in.available(); 321 } 322 323 338 public synchronized void mark(int readlimit) 339 { 340 marklimit = readlimit; 341 markpos = pos; 342 } 343 344 363 public synchronized void reset() throws IOException 364 { 365 if (markpos < 0) 366 throw new IOException ("Resetting to invalid mark"); 367 pos = markpos; 368 } 369 370 383 public boolean markSupported() 384 { 385 return true; 386 } 387 388 389 399 int pastEnd(byte[] search, int[] search_cmp) 400 { 401 int idx = Util.findStr(search, search_cmp, buf, markpos, pos); 402 if (idx == -1) 403 markpos = pos - search.length; 404 else 405 { 406 markpos = idx + search.length; 407 idx = pos - markpos; 408 } 409 410 return idx; 411 } 412 413 414 417 void initMark() 418 { 419 mark(buf.length); 420 } 421 } 422 | Popular Tags |