1 21 package com.db4o.io; 22 23 import java.io.*; 24 25 import com.db4o.foundation.*; 26 27 45 public class MemoryIoAdapter extends IoAdapter{ 46 47 private byte[] _bytes; 48 private int _length; 49 private int _seekPos; 50 51 private Hashtable4 _memoryFiles; 52 private int _growBy; 53 54 public MemoryIoAdapter(){ 55 _memoryFiles = new Hashtable4(); 56 _growBy = 10000; 57 } 58 59 private MemoryIoAdapter(MemoryIoAdapter adapter, byte[] bytes){ 60 _bytes = bytes; 61 _length = bytes.length; 62 _growBy = adapter._growBy; 63 } 64 65 private MemoryIoAdapter(MemoryIoAdapter adapter, int initialLength){ 66 this(adapter, new byte[initialLength]); 67 } 68 69 75 public void put(String name, byte[] bytes){ 76 if(bytes == null){ 77 bytes = new byte[0]; 78 } 79 _memoryFiles.put(name, new MemoryIoAdapter(this,bytes)); 80 } 81 82 87 public byte[] get(String name){ 88 MemoryIoAdapter mia = (MemoryIoAdapter)_memoryFiles.get(name); 89 if(mia == null){ 90 return null; 91 } 92 return mia._bytes; 93 } 94 95 103 public void growBy(int length){ 104 if(length < 1){ 105 length = 1; 106 } 107 _growBy = length; 108 } 109 110 113 public void close() throws IOException { 114 } 116 117 public void delete(String path) { 118 _memoryFiles.remove(path); 119 } 120 121 124 public boolean exists(String path){ 125 MemoryIoAdapter mia = (MemoryIoAdapter)_memoryFiles.get(path); 126 if(mia == null){ 127 return false; 128 } 129 return mia._length > 0; 130 } 131 132 133 136 public long getLength() throws IOException { 137 return _length; 138 } 139 140 143 public IoAdapter open(String path, boolean lockFile, long initialLength) throws IOException { 144 MemoryIoAdapter mia = (MemoryIoAdapter)_memoryFiles.get(path); 145 if(mia == null){ 146 mia = new MemoryIoAdapter(this, (int)initialLength); 147 _memoryFiles.put( path, mia); 148 } 149 return mia; 150 } 151 152 155 public int read(byte[] bytes, int length) throws IOException { 156 System.arraycopy(_bytes, _seekPos, bytes, 0, length); 157 _seekPos += length; 158 return length; 159 } 160 161 164 public void seek(long pos) throws IOException { 165 _seekPos = (int)pos; 166 } 167 168 171 public void sync() throws IOException { 172 } 173 174 177 public void write(byte[] buffer, int length) throws IOException { 178 if(_seekPos + length > _bytes.length){ 179 int growBy = _growBy; 180 if(_seekPos + length > growBy){ 181 growBy = _seekPos + length; 182 } 183 byte[] temp = new byte[_bytes.length + growBy]; 184 System.arraycopy(_bytes, 0, temp, 0, _length); 185 _bytes = temp; 186 } 187 System.arraycopy(buffer, 0, _bytes, _seekPos, length); 188 _seekPos += length; 189 if(_seekPos > _length){ 190 _length = _seekPos; 191 } 192 } 193 194 } 195 | Popular Tags |