1 18 package org.apache.batik.ext.awt.image.codec; 19 20 import java.io.IOException ; 21 import java.io.InputStream ; 22 import java.util.Vector ; 23 24 37 public final class MemoryCacheSeekableStream extends SeekableStream { 38 39 40 private InputStream src; 41 42 43 private long pointer = 0; 44 45 46 private static final int SECTOR_SHIFT = 9; 47 48 49 private static final int SECTOR_SIZE = 1 << SECTOR_SHIFT; 50 51 52 private static final int SECTOR_MASK = SECTOR_SIZE - 1; 53 54 55 private Vector data = new Vector (); 56 57 58 int sectors = 0; 59 60 61 int length = 0; 62 63 64 boolean foundEOS = false; 65 66 71 public MemoryCacheSeekableStream(InputStream src) { 72 this.src = src; 73 } 74 75 81 private long readUntil(long pos) throws IOException { 82 if (pos < length) { 84 return pos; 85 } 86 if (foundEOS) { 88 return length; 89 } 90 91 int sector = (int)(pos >> SECTOR_SHIFT); 92 93 int startSector = length >> SECTOR_SHIFT; 95 96 for (int i = startSector; i <= sector; i++) { 98 byte[] buf = new byte[SECTOR_SIZE]; 99 data.addElement(buf); 100 101 int len = SECTOR_SIZE; 103 int off = 0; 104 while (len > 0) { 105 int nbytes = src.read(buf, off, len); 106 if (nbytes == -1) { 108 foundEOS = true; 109 return length; 110 } 111 off += nbytes; 112 len -= nbytes; 113 114 length += nbytes; 116 } 117 } 118 119 return length; 120 } 121 122 127 public boolean canSeekBackwards() { 128 return true; 129 } 130 131 137 public long getFilePointer() { 138 return pointer; 139 } 140 141 151 public void seek(long pos) throws IOException { 152 if (pos < 0) { 153 throw new IOException (PropertyUtil.getString("MemoryCacheSeekableStream0")); 154 } 155 pointer = pos; 156 } 157 158 169 public int read() throws IOException { 170 long next = pointer + 1; 171 long pos = readUntil(next); 172 if (pos >= next) { 173 byte[] buf = 174 (byte[])data.elementAt((int)(pointer >> SECTOR_SHIFT)); 175 return buf[(int)(pointer++ & SECTOR_MASK)] & 0xff; 176 } else { 177 return -1; 178 } 179 } 180 181 228 public int read(byte[] b, int off, int len) throws IOException { 229 if (b == null) { 230 throw new NullPointerException (); 231 } 232 if ((off < 0) || (len < 0) || (off + len > b.length)) { 233 throw new IndexOutOfBoundsException (); 234 } 235 if (len == 0) { 236 return 0; 237 } 238 239 long pos = readUntil(pointer + len); 240 if (pos <= pointer) { 242 return -1; 243 } 244 245 byte[] buf = (byte[])data.elementAt((int)(pointer >> SECTOR_SHIFT)); 246 int nbytes = Math.min(len, SECTOR_SIZE - (int)(pointer & SECTOR_MASK)); 247 System.arraycopy(buf, (int)(pointer & SECTOR_MASK), 248 b, off, nbytes); 249 pointer += nbytes; 250 return nbytes; 251 } 252 } 253 | Popular Tags |