1 28 29 package com.caucho.vfs; 30 31 import java.io.IOException ; 32 import java.io.OutputStream ; 33 34 public class MemoryStream extends StreamImpl { 35 private TempBuffer _head; 36 private TempBuffer _tail; 37 38 public Path getPath() { return new NullPath("temp:"); } 39 40 43 public boolean canWrite() 44 { 45 return true; 46 } 47 48 56 public void write(byte []buf, int offset, int length, boolean isEnd) 57 throws IOException 58 { 59 while (offset < length) { 60 if (_tail == null || _tail._length >= _tail._buf.length) 61 addBuffer(TempBuffer.allocate()); 62 63 int sublen = _tail._buf.length - _tail._length; 64 if (length - offset < sublen) 65 sublen = length - offset; 66 67 System.arraycopy(buf, offset, _tail._buf, _tail._length, sublen); 68 69 offset += sublen; 70 _tail._length += sublen; 71 } 72 } 73 74 private void addBuffer(TempBuffer buf) 75 { 76 buf._next = null; 77 buf._length = 0; 78 if (_tail != null) { 79 _tail._next = buf; 80 _tail = buf; 81 } else { 82 _tail = buf; 83 _head = buf; 84 } 85 _head._bufferCount++; 86 } 87 88 public void writeToStream(OutputStream os) throws IOException 89 { 90 for (TempBuffer node = _head; node != null; node = node._next) { 91 os.write(node._buf, 0, node._length); 92 } 93 } 94 95 public int getLength() 96 { 97 if (_tail == null) 98 return 0; 99 else 100 return (_head._bufferCount - 1) * _head._length + _tail._length; 101 } 102 103 public ReadStream openRead() 104 throws IOException 105 { 106 close(); 107 108 TempReadStream read = new TempReadStream(_head, getPath()); 109 read.setFreeWhenDone(false); 110 111 return new ReadStream(read); 112 } 113 114 public void destroy() 115 { 116 TempBuffer next; 117 118 for (; _head != null; _head = next) { 119 next = _head._next; 120 _head.free(_head); 121 } 122 123 _head = null; 124 _tail = null; 125 } 126 } 127 | Popular Tags |