1 29 30 package com.caucho.vfs; 31 32 import com.caucho.util.FreeList; 33 34 import java.io.IOException ; 35 36 39 public class TempBuffer { 40 private static FreeList<TempBuffer> _freeList = new FreeList<TempBuffer>(32); 41 public static final int SIZE = 16 * 1024; 42 43 TempBuffer _next; 44 final byte []_buf; 45 int _offset; 46 int _length; 47 int _bufferCount; 48 49 52 public TempBuffer(int size) 53 { 54 _buf = new byte[size]; 55 } 56 57 60 public static TempBuffer allocate() 61 { 62 TempBuffer next = _freeList.allocate(); 63 64 if (next == null) 65 return new TempBuffer(SIZE); 66 67 next._next = null; 68 69 next._offset = 0; 70 next._length = 0; 71 next._bufferCount = 0; 72 73 return next; 74 } 75 76 79 public void clear() 80 { 81 _next = null; 82 83 _offset = 0; 84 _length = 0; 85 _bufferCount = 0; 86 } 87 88 91 public final byte []getBuffer() 92 { 93 return _buf; 94 } 95 96 99 public final int getLength() 100 { 101 return _length; 102 } 103 104 107 public final void setLength(int length) 108 { 109 _length = length; 110 } 111 112 public final int getCapacity() 113 { 114 return _buf.length; 115 } 116 117 public int getAvailable() 118 { 119 return _buf.length - _length; 120 } 121 122 public final TempBuffer getNext() 123 { 124 return _next; 125 } 126 127 public final void setNext(TempBuffer next) 128 { 129 _next = next; 130 } 131 132 public int write(byte []buf, int offset, int length) 133 { 134 byte []thisBuf = _buf; 135 int thisLength = _length; 136 137 if (thisBuf.length - thisLength < length) 138 length = thisBuf.length - thisLength; 139 140 System.arraycopy(buf, offset, thisBuf, thisLength, length); 141 142 _length = thisLength + length; 143 144 return length; 145 } 146 147 public static TempBuffer copyFromStream(ReadStream is) 148 throws IOException 149 { 150 TempBuffer head = TempBuffer.allocate(); 151 TempBuffer tail = head; 152 int len; 153 154 while ((len = is.readAll(tail._buf, 0, tail._buf.length)) == tail._buf.length) { 155 TempBuffer buf = TempBuffer.allocate(); 156 tail._length = len; 157 tail._next = buf; 158 tail = buf; 159 } 160 161 if (len == 0 && head == tail) 162 return null; else if (len == 0) { 164 for (TempBuffer ptr = head; ptr.getNext() != null; ptr = ptr.getNext()) { 165 TempBuffer next = ptr.getNext(); 166 167 if (next.getNext() == null) { 168 TempBuffer.free(next); 169 ptr._next = null; 170 } 171 } 172 } 173 else 174 tail._length = len; 175 176 return head; 177 } 178 179 182 public static void free(TempBuffer buf) 183 { 184 buf._next = null; 185 186 if (buf._buf.length == SIZE) 187 _freeList.free(buf); 188 } 189 190 public static void freeAll(TempBuffer buf) 191 { 192 while (buf != null) { 193 TempBuffer next = buf._next; 194 buf._next = null; 195 if (buf._buf.length == SIZE) 196 _freeList.free(buf); 197 buf = next; 198 } 199 } 200 } 201 | Popular Tags |