1 32 package com.imagero.uio; 33 34 import com.imagero.uio.buffer.Buffer; 35 import com.imagero.uio.buffer.BufferManager; 36 import com.imagero.uio.buffer.DefaultBufferManager; 37 38 import java.io.EOFException ; 39 import java.io.IOException ; 40 41 47 public class RandomAccessBufferRO extends AbstractRandomAccessRO { 48 49 protected BufferManager bufferManager; 50 int dataIndex; 51 int fp; 52 byte[] buf; 53 54 59 public RandomAccessBufferRO(Buffer[] ds, int byteOrder) throws IOException { 60 this(new DefaultBufferManager(ds), byteOrder); 61 } 62 63 70 public RandomAccessBufferRO(BufferManager sourceManager, int byteOrder) throws IOException { 71 this.bufferManager = sourceManager; 72 this.buf = sourceManager.getData(0); 73 _setByteOrder(byteOrder); 74 } 75 76 public BufferManager getBufferManager() { 77 return bufferManager; 78 } 79 80 86 public int read() throws IOException { 87 if(fp < buf.length) { 88 return buf[fp++] & 0xFF; 89 } 90 else { 91 nextArray(); 92 if(buf == null || buf.length == 0) { 93 return -1; 94 } 95 return buf[fp++] & 0xFF; 96 } 97 } 98 99 protected boolean nextArray() throws IOException { 100 try { 102 this.buf = bufferManager.getData(++dataIndex); 103 this.fp = 0; 104 if(buf.length == 0) { 105 return false; 106 } 107 return true; 108 } 109 catch(IOException ex) { 110 this.buf = null; 111 this.fp = 0; 112 throw ex; 114 } 115 } 116 117 public long getFilePointer() throws IOException { 118 return bufferManager.getDataStart(dataIndex) + fp; 119 } 120 121 128 public void seek(long pos) throws IOException { 129 if(pos < 0) { 130 throw new IOException ("" + pos); 131 } 132 133 this.dataIndex = bufferManager.getIndex((int) pos); 134 this.buf = bufferManager.getData(dataIndex); 135 this.fp = (int) (pos - bufferManager.getDataStart(dataIndex)); 136 } 137 138 143 public long length() { 144 return bufferManager.getLength(); 145 } 146 147 public int read(byte[] b) throws IOException { 148 return read(b, 0, b.length); 149 } 150 151 public int read(byte[] b, int off, int length) throws IOException { 152 int read = 0; 153 int _off = off; 154 int _length = length; 155 156 while(read < _length) { 157 int len = readBytes(b, _off, _length); 158 if(len == -1) { 159 if(!nextArray()) { 160 return read > 0 ? read : -1; 161 } 162 } 163 else { 164 read += len; 165 fp += len; 166 _off += len; 167 _length -= len; 168 } 169 } 170 171 return read; 172 } 173 174 private int readBytes(byte[] b, int off, int length) { 175 if(buf == null) { 176 return -1; 177 } 178 int len = Math.min(length, buf.length - fp); 179 if(len <= 0) { 180 return -1; 181 } 182 System.arraycopy(buf, fp, b, off, len); 183 return len; 184 } 185 186 public void close() { 187 bufferManager.close(); 188 } 189 190 public int skip(int n) throws IOException { 191 return skipBytes(n); 192 } 193 194 protected int _read() throws IOException { 195 int a = read(); 196 if(a < 0) { 197 throw new EOFException (); 198 } 199 return a; 200 } 201 } 202 | Popular Tags |