001: /*
002: * Copyright (c) 1998-2008 Caucho Technology -- all rights reserved
003: *
004: * This file is part of Resin(R) Open Source
005: *
006: * Each copy or derived work must preserve the copyright notice and this
007: * notice unmodified.
008: *
009: * Resin Open Source is free software; you can redistribute it and/or modify
010: * it under the terms of the GNU General Public License as published by
011: * the Free Software Foundation; either version 2 of the License, or
012: * (at your option) any later version.
013: *
014: * Resin Open Source is distributed in the hope that it will be useful,
015: * but WITHOUT ANY WARRANTY; without even the implied warranty of
016: * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, or any warranty
017: * of NON-INFRINGEMENT. See the GNU General Public License for more
018: * details.
019: *
020: * You should have received a copy of the GNU General Public License
021: * along with Resin Open Source; if not, write to the
022: * Free SoftwareFoundation, Inc.
023: * 59 Temple Place, Suite 330
024: * Boston, MA 02111-1307 USA
025: *
026: * @author Scott Ferguson
027: */
028:
029: package com.caucho.vfs;
030:
031: import java.io.IOException;
032:
033: public class TempReadStream extends StreamImpl {
034: private TempBuffer _cursor;
035:
036: private int _offset;
037: private boolean _freeWhenDone = true;
038:
039: public TempReadStream(TempBuffer cursor) {
040: init(cursor);
041: }
042:
043: public TempReadStream() {
044: }
045:
046: public void init(TempBuffer cursor) {
047: _cursor = cursor;
048: _offset = 0;
049: _freeWhenDone = true;
050: }
051:
052: public void setFreeWhenDone(boolean free) {
053: _freeWhenDone = free;
054: }
055:
056: @Override
057: public boolean canRead() {
058: return true;
059: }
060:
061: // XXX: any way to make this automatically free?
062: @Override
063: public int read(byte[] buf, int offset, int length)
064: throws IOException {
065: if (_cursor == null)
066: return -1;
067:
068: int sublen = _cursor._length - _offset;
069:
070: if (length < sublen)
071: sublen = length;
072:
073: System.arraycopy(_cursor._buf, _offset, buf, offset, sublen);
074:
075: if (_cursor._length <= _offset + sublen) {
076: TempBuffer next = _cursor._next;
077:
078: if (_freeWhenDone) {
079: _cursor._next = null;
080: TempBuffer.free(_cursor);
081: _cursor = null;
082: }
083: _cursor = next;
084: _offset = 0;
085: } else
086: _offset += sublen;
087:
088: return sublen;
089: }
090:
091: @Override
092: public int getAvailable() throws IOException {
093: if (_cursor != null)
094: return _cursor._length - _offset;
095: else
096: return 0;
097: }
098:
099: @Override
100: public void close() throws IOException {
101: if (_freeWhenDone && _cursor != null)
102: TempBuffer.freeAll(_cursor);
103:
104: _cursor = null;
105: }
106:
107: @Override
108: public String toString() {
109: return "TempReadStream[]";
110: }
111: }
|