01: /*
02: * <copyright>
03: *
04: * Copyright 1997-2004 BBNT Solutions, LLC
05: * under sponsorship of the Defense Advanced Research Projects
06: * Agency (DARPA).
07: *
08: * You can redistribute this software and/or modify it under the
09: * terms of the Cougaar Open Source License as published on the
10: * Cougaar Open Source Website (www.cougaar.org).
11: *
12: * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
13: * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
14: * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
15: * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
16: * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
17: * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
18: * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
19: * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
20: * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
21: * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
22: * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
23: *
24: * </copyright>
25: */
26:
27: package org.cougaar.util;
28:
29: import java.io.Externalizable;
30: import java.io.IOException;
31: import java.io.ObjectInput;
32: import java.io.ObjectOutput;
33:
34: /** A string wrapper which serializes the enclosed string more
35: * efficiently... maybe.
36: **/
37:
38: public class FastString implements Externalizable {
39: private transient String string;
40:
41: public FastString() {
42: }
43:
44: public FastString(String s) {
45: string = s;
46: }
47:
48: public String toString() {
49: return string;
50: }
51:
52: private static final int BUFSIZE = Short.MAX_VALUE;
53: private static final byte[] srcbuf = new byte[BUFSIZE];
54:
55: public final void readExternal(ObjectInput in) throws IOException {
56: int l = in.readShort();
57: synchronized (srcbuf) {
58: in.readFully(srcbuf, 0, l);
59:
60: string = new String(srcbuf, 0, l);
61: }
62:
63: // intern short strings
64: if (l < 18)
65: string = string.intern();
66: }
67:
68: private static final char[] dstbuf = new char[BUFSIZE];
69:
70: public final void writeExternal(ObjectOutput out)
71: throws IOException {
72: int l = string.length();
73: if (l > BUFSIZE)
74: throw new IOException(
75: "Attempt to serialize a FastString of length " + l
76: + " (limit is " + BUFSIZE + ").\n"
77: + " First 60 characters are \""
78: + string.substring(0, 60) + "...\"");
79: out.writeShort(l);
80: char[] dst = dstbuf; // localize the buffer reference
81: synchronized (dst) {
82: string.getChars(0, l, dst, 0);
83: for (int i = 0; i < l; i++) {
84: out.write(dst[i]); // upper bits ignored
85: }
86: }
87: }
88:
89: }
|