01: package gnu.mapping;
02:
03: import gnu.lists.Consumer;
04: import java.io.PrintWriter;
05:
06: /**
07: * Similar to CharArrayWriter.
08: */
09:
10: public class CharArrayOutPort extends OutPort {
11: public CharArrayOutPort() {
12: super (null, false, CharArrayInPort.stringPath);
13: }
14:
15: public int length() {
16: return bout.bufferFillPointer;
17: }
18:
19: public void setLength(int length) {
20: bout.bufferFillPointer = length;
21: }
22:
23: public void reset() {
24: bout.bufferFillPointer = 0;
25: }
26:
27: /** Returns the written data as a freshly copied {@code char} array. */
28: public char[] toCharArray() {
29: int length = bout.bufferFillPointer;
30: char[] result = new char[length];
31: System.arraycopy(bout.buffer, 0, result, 0, length);
32: return result;
33: }
34:
35: /** Do nothing.
36: * This allows access to the buffer after the port is closed.
37: * Not clear whether this is a good or bad idea, but it matches
38: * ByteArrayOutputStream, CharArrayWriter, and StringWriter.
39: */
40: public void close() {
41: }
42:
43: /** No point in registering this port with a WriterManager. */
44: protected boolean closeOnExit() {
45: return false;
46: }
47:
48: /** Returns the written data as a new {@code String}. */
49: public String toString() {
50: return new String(bout.buffer, 0, bout.bufferFillPointer);
51: }
52:
53: /** Returns a substring of the written data as a new {@code String}.
54: * Equivalent to {@code toString().substring(beginIndex, endIndex)}
55: * but more efficient.
56: */
57: public String toSubString(int beginIndex, int endIndex) {
58: if (endIndex > bout.bufferFillPointer)
59: throw new IndexOutOfBoundsException();
60: return new String(bout.buffer, beginIndex, endIndex
61: - beginIndex);
62: }
63:
64: /** Returns a substring of the written data as a new {@code String}.
65: * Equivalent to {@code toString().substring(beginIndex)}
66: * but more efficient.
67: */
68: public String toSubString(int beginIndex) {
69: return new String(bout.buffer, beginIndex,
70: bout.bufferFillPointer - beginIndex);
71: }
72:
73: public void writeTo(Consumer out) {
74: out.write(bout.buffer, 0, bout.bufferFillPointer);
75: }
76:
77: public void writeTo(int start, int count, Consumer out) {
78: out.write(bout.buffer, start, count);
79: }
80: }
|