1 // Copyright (C) 2003 Adam Megacz <adam@ibex.org> all rights reserved.
3 // You may modify, copy, and redistribute this code under the terms of
4 // the GNU Library Public License version 2.1, with the exception of
5 // the portion of clause 6a after the semicolon (aka the "obnoxious
11 // FEATURE: don't use a byte[] if we have a diskCache file
13 * Wraps around an InputStream, caching the stream in a byte[] as it
14 * is read and permitting multiple simultaneous readers
16 public class CachedInputStream {
18 boolean filling = false; ///< true iff some thread is blocked on us waiting for input
19 boolean eof = false; ///< true iff end of stream has been reached
20 byte[] cache = new byte[1024 * 128];
25 public CachedInputStream(InputStream is) { this(is, null); }
26 public CachedInputStream(InputStream is, File diskCache) {
28 this.diskCache = diskCache;
30 public InputStream getInputStream() throws IOException {
31 if (diskCache != null && diskCache.exists()) return new FileInputStream(diskCache);
32 return new SubStream();
35 public void grow(int newLength) {
36 if (newLength < cache.length) return;
37 byte[] newCache = new byte[cache.length + 2 * (newLength - cache.length)];
38 System.arraycopy(cache, 0, newCache, 0, size);
42 synchronized void fillCache(int howMuch) throws IOException {
43 if (filling) { try { wait(); } catch (InterruptedException e) { }; return; }
46 int ret = is.read(cache, size, howMuch);
49 // FIXME: probably a race here
50 if (diskCache != null && !diskCache.exists())
52 File cacheFile = new File(diskCache + ".incomplete");
53 FileOutputStream cacheFileStream = new FileOutputStream(cacheFile);
54 cacheFileStream.write(cache, 0, size);
55 cacheFileStream.close();
56 cacheFile.renameTo(diskCache);
57 } catch (IOException e) {
58 Log.info(this, "exception thrown while writing disk cache");
67 private class SubStream extends InputStream implements KnownLength {
69 public int available() { return Math.max(0, size - pos); }
70 public long skip(long n) throws IOException { pos += (int)n; return n; } // FEATURE: don't skip past EOF
71 public int getLength() { return eof ? size : is instanceof KnownLength ? ((KnownLength)is).getLength() : 0; }
72 public int read() throws IOException { // FEATURE: be smarter here
73 byte[] b = new byte[1];
74 int ret = read(b, 0, 1);
75 return ret == -1 ? -1 : b[0]&0xff;
77 public int read(byte[] b, int off, int len) throws IOException {
78 synchronized(CachedInputStream.this) {
79 while (pos >= size && !eof) fillCache(pos + len - size);
80 if (eof && pos == size) return -1;
81 int count = Math.min(size - pos, len);
82 System.arraycopy(cache, pos, b, off, count);