implement truncate and fstat better
[nestedvm.git] / src / org / ibex / nestedvm / util / Seekable.java
index 98f2c8e..51c7a39 100644 (file)
@@ -16,6 +16,18 @@ public abstract class Seekable {
         return n == -1 ? -1 : buf[0]&0xff;
     }
     
+    public int tryReadFully(byte[] buf, int off, int len) throws IOException {
+        int total = 0;
+        while(len > 0) {
+                int n = read(buf,off,len);
+                if(n == -1) break;
+                off += n;
+                len -= n;
+            total += n;
+        }
+        return total == 0 ? -1 : total;
+    }
+    
     public static class ByteArray extends Seekable {
         protected byte[] data;
         protected int pos;
@@ -54,15 +66,13 @@ public abstract class Seekable {
         private final RandomAccessFile raf;
         
         public File(String fileName) throws IOException { this(fileName,false); }
-        public File(String fileName, boolean writable) throws IOException { this(new java.io.File(fileName),writable); }    
+        public File(String fileName, boolean writable) throws IOException { this(new java.io.File(fileName),writable,false); }    
         
-        public File(java.io.File file, boolean writable) throws IOException {
-            raf = new RandomAccessFile(file,writable ? "rw" : "r");
+        public File(java.io.File file, boolean writable, boolean truncate) throws IOException {
+            String mode = writable ? "rw" : "r";
+            raf = truncate ? Platform.truncatedRandomAccessFile(file,mode) : new RandomAccessFile(file,mode);
         }
         
-        // NOTE: RandomAccessFile.setLength() is a Java2 function
-        public void setLength(int n) throws IOException { raf.setLength(n); }
-        
         public int read(byte[] buf, int offset, int length) throws IOException { return raf.read(buf,offset,length); }
         public int write(byte[] buf, int offset, int length) throws IOException { raf.write(buf,offset,length); return length; }
         public void seek(int pos) throws IOException{ raf.seek(pos); }