001: package gnu.mapping;
002:
003: import java.io.CharArrayWriter;
004: import gnu.lists.*;
005:
006: /** A Format to print structured objects on streams.
007: * After JDK 1.1 comes out, this should be made compatible with
008: * java.text.Format. We will also encapulate formatting flags
009: * and pretty-printing here. */
010: // FIXME this class is deprecated - use DisplayFormat instead!
011: public class SFormat // extends gnu.text.ReportFormat
012: {
013: public String format(Object obj) {
014: CharArrayWriter wr = new CharArrayWriter();
015: format(obj, new OutPort(wr));
016: return wr.toString();
017: }
018:
019: public StringBuffer format(Object obj, StringBuffer buffer) {
020: /* FIXME - more efficient to use a "StringBufferWriter". */
021: CharArrayWriter wr = new CharArrayWriter();
022: format(obj, new OutPort(wr));
023: buffer.append(wr.toCharArray());
024: return buffer;
025: }
026:
027: public void format(Object obj, java.io.PrintWriter ps) {
028: print(obj, ps);
029: }
030:
031: public static boolean printReadable(java.io.Writer ps) {
032: return ps instanceof OutPort && ((OutPort) ps).printReadable;
033: }
034:
035: public static void print(Object obj, java.io.PrintWriter ps) {
036: if (obj instanceof Printable)
037: ((Printable) obj).print(ps);
038: else if (obj instanceof Boolean)
039: ps.print(((Boolean) obj).booleanValue() ? "#t" : "#f");
040: else if (obj == null)
041: ps.print("#!null");
042: else if (obj instanceof Object[]) {
043: Object[] arr = (Object[]) obj;
044: ps.print('[');
045: for (int i = 0; i < arr.length; i++) {
046: if (i > 0)
047: ps.print(' ');
048: print(arr[i], ps);
049: }
050: ps.print(']');
051: } else if (obj instanceof LList) {
052: ps.print('(');
053: boolean first = true;
054: while (obj instanceof Pair) {
055: if (!first)
056: ps.print(' ');
057: first = false;
058: Pair pair = (Pair) obj;
059: print(pair.car, ps);
060: obj = pair.cdr;
061: }
062: if (obj != LList.Empty) {
063: ps.print(" . ");
064: print(obj, ps);
065: }
066: ps.print(')');
067: } else if (obj instanceof CharSeq) {
068: if (printReadable(ps))
069: Strings.printQuoted((CharSeq) obj, ps, 0);
070: else
071: ps.print(obj);
072: } else if (obj instanceof SimpleVector) {
073: SimpleVector vec = (SimpleVector) obj;
074: String tag = vec.getTag();
075: int size = vec.size;
076: ps.print('#');
077: if (tag != null)
078: ps.print(tag);
079: ps.print('(');
080: for (int i = 0; i < size; i++) {
081: if (i > 0)
082: ps.print(' ');
083: print(vec.get(i), ps);
084: }
085: ps.print(')');
086: } else if (obj instanceof int[]) {
087: int[] arr = (int[]) obj;
088: ps.print('[');
089: for (int i = 0; i < arr.length; i++) {
090: if (i > 0)
091: ps.print(' ');
092: ps.print(arr[i]);
093: //ps.print ("#x"+Long.toString((long)arr[i] & 0xffffffffL, 16));
094: }
095: ps.print(']');
096: } else
097: ps.print(obj);
098: }
099:
100: }
|