1dc0b0dbbdadebf31a3cc0699ac0cc4447a8a1ee
[nestedvm.git] / src / org / xwt / mips / util / SeekableInputStream.java
1 package org.xwt.mips.util;
2
3 import java.io.*;
4
5 public class SeekableInputStream implements SeekableData {
6     private byte[] buffer = new byte[4096];
7     private int bytesRead = 0;
8     private boolean eof = false;
9     private int pos;
10     private InputStream is;
11     
12     public SeekableInputStream(InputStream is) { this.is = is; }
13     
14     public int read(byte[] outbuf, int off, int len) throws IOException {
15         if(pos >= bytesRead && !eof) readTo(pos + 1);
16         len = Math.min(len,bytesRead-pos);
17         if(len <= 0) return -1;
18         System.arraycopy(buffer,pos,outbuf,off,len);
19         pos += len;
20         return len;
21     }
22     
23     private void readTo(int target) throws IOException {
24         if(target >= buffer.length) {
25             byte[] buf2 = new byte[Math.max(buffer.length+Math.min(buffer.length,65536),target)];
26             System.arraycopy(buffer,0,buf2,0,bytesRead);
27             buffer = buf2;
28         }
29         while(bytesRead < target) {
30             int n = is.read(buffer,bytesRead,buffer.length-bytesRead);
31             if(n == -1) {
32                 eof = true;
33                 break;
34             }
35             bytesRead += n;
36         }
37     }
38     
39     public int length() throws IOException {
40         while(!eof) readTo(bytesRead+4096);
41         return bytesRead;
42     }
43         
44     public int write(byte[] buf, int off, int len) throws IOException { throw new IOException("read-only"); }
45     public void seek(int pos) { this.pos = pos; }
46     public int pos() { return pos; }
47     public void close() throws IOException { is.close(); }
48 }