01: /*
02: * Copyright (c) 1998-2008 Caucho Technology -- all rights reserved
03: *
04: * This file is part of Resin(R) Open Source
05: *
06: * Each copy or derived work must preserve the copyright notice and this
07: * notice unmodified.
08: *
09: * Resin Open Source is free software; you can redistribute it and/or modify
10: * it under the terms of the GNU General Public License as published by
11: * the Free Software Foundation; either version 2 of the License, or
12: * (at your option) any later version.
13: *
14: * Resin Open Source is distributed in the hope that it will be useful,
15: * but WITHOUT ANY WARRANTY; without even the implied warranty of
16: * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, or any warranty
17: * of NON-INFRINGEMENT. See the GNU General Public License for more
18: * details.
19: *
20: * You should have received a copy of the GNU General Public License
21: * along with Resin Open Source; if not, write to the
22: * Free SoftwareFoundation, Inc.
23: * 59 Temple Place, Suite 330
24: * Boston, MA 02111-1307 USA
25: *
26: * @author Scott Ferguson
27: */
28:
29: package com.caucho.vfs;
30:
31: import java.io.IOException;
32:
33: public class StringStream extends StreamImpl {
34: private String _string;
35: private int _length;
36: private int _index;
37:
38: StringStream(String string) {
39: // this.path = new NullPath("string");
40: _string = string;
41: _length = string.length();
42: _index = 0;
43: }
44:
45: public static ReadStream open(String string) {
46: StringStream ss = new StringStream(string);
47: return new ReadStream(ss);
48: }
49:
50: public Path getPath() {
51: return new StringPath(_string);
52: }
53:
54: public boolean canRead() {
55: return true;
56: }
57:
58: // XXX: encoding issues
59: public int read(byte[] buf, int offset, int length)
60: throws IOException {
61: int strlen = _length;
62:
63: int start = offset;
64: int end = offset + length;
65:
66: int index = _index;
67: for (; index < strlen && offset < end; index++) {
68: int ch = _string.charAt(index);
69:
70: if (ch < 0x80)
71: buf[offset++] = (byte) ch;
72: else if (ch < 0x800 && offset + 1 < end) {
73: buf[offset++] = (byte) (0xc0 | (ch >> 6));
74: buf[offset++] = (byte) (0x80 | (ch & 0x3f));
75: } else if (ch < 0x8000 && offset + 2 < end) {
76: buf[offset++] = (byte) (0xe0 | (ch >> 12));
77: buf[offset++] = (byte) (0x80 | ((ch >> 6) & 0x3f));
78: buf[offset++] = (byte) (0x80 | ((ch >> 6) & 0x3f));
79: } else if (offset == start) {
80: throw new IllegalStateException(
81: "buffer length is not large enough to decode UTF-8 data");
82: } else {
83: break;
84: }
85: }
86:
87: _index = index;
88:
89: return start < offset ? offset - start : -1;
90: }
91:
92: public int getAvailable() throws IOException {
93: return _length - _index;
94: }
95: }
|