1 11 package org.eclipse.swt.internal.image; 12 13 14 import java.io.*; 15 16 final class LEDataInputStream extends InputStream { 17 int position; 18 InputStream in; 19 20 23 protected byte[] buf; 24 25 30 protected int pos; 31 32 33 public LEDataInputStream(InputStream input) { 34 this(input, 512); 35 } 36 37 public LEDataInputStream(InputStream input, int bufferSize) { 38 this.in = input; 39 if (bufferSize > 0) { 40 buf = new byte[bufferSize]; 41 pos = bufferSize; 42 } 43 else throw new IllegalArgumentException (); 44 } 45 46 public void close() throws IOException { 47 buf = null; 48 if (in != null) { 49 in.close(); 50 in = null; 51 } 52 } 53 54 57 public int getPosition() { 58 return position; 59 } 60 61 64 public int available() throws IOException { 65 if (buf == null) throw new IOException(); 66 return (buf.length - pos) + in.available(); 67 } 68 69 72 public int read() throws IOException { 73 if (buf == null) throw new IOException(); 74 if (pos < buf.length) { 75 position++; 76 return (buf[pos++] & 0xFF); 77 } 78 int c = in.read(); 79 if (c != -1) position++; 80 return c; 81 } 82 83 87 public int read(byte b[], int off, int len) throws IOException { 88 int read = 0, count; 89 while (read != len && (count = readData(b, off, len - read)) != -1) { 90 off += count; 91 read += count; 92 } 93 position += read; 94 if (read == 0 && read != len) return -1; 95 return read; 96 } 97 98 115 private int readData(byte[] buffer, int offset, int length) throws IOException { 116 if (buf == null) throw new IOException(); 117 if (offset < 0 || offset > buffer.length || 118 length < 0 || (length > buffer.length - offset)) { 119 throw new ArrayIndexOutOfBoundsException (); 120 } 121 122 int cacheCopied = 0; 123 int newOffset = offset; 124 125 int available = buf.length - pos; 127 if (available > 0) { 128 cacheCopied = (available >= length) ? length : available; 129 System.arraycopy(buf, pos, buffer, newOffset, cacheCopied); 130 newOffset += cacheCopied; 131 pos += cacheCopied; 132 } 133 134 if (cacheCopied == length) return length; 136 137 int inCopied = in.read(buffer, newOffset, length - cacheCopied); 138 139 if (inCopied > 0) return inCopied + cacheCopied; 140 if (cacheCopied == 0) return inCopied; 141 return cacheCopied; 142 } 143 144 148 public int readInt() throws IOException { 149 byte[] buf = new byte[4]; 150 read(buf); 151 return ((((((buf[3] & 0xFF) << 24) | 152 (buf[2] & 0xFF)) << 16) | 153 (buf[1] & 0xFF)) << 8) | 154 (buf[0] & 0xFF); 155 } 156 157 161 public short readShort() throws IOException { 162 byte[] buf = new byte[2]; 163 read(buf); 164 return (short)(((buf[1] & 0xFF) << 8) | (buf[0] & 0xFF)); 165 } 166 167 179 public void unread(byte[] b) throws IOException { 180 int length = b.length; 181 if (length > pos) throw new IOException(); 182 position -= length; 183 pos -= length; 184 System.arraycopy(b, 0, buf, pos, length); 185 } 186 } 187 | Popular Tags |