Exemplo n.º 1
0
 /**
  * Gives string representation of a tree, parametrized by how to represent each position. It does
  * a preorder traversal, giving a newline and some indentation before each node, then represents
  * each node as specified. It can print a tree which is at most 100 levels deep.
  *
  * @param t tree to stringify
  * @param pts how to stringify each position
  * @throws IndexOutOfBoundsException if the tree is more then 100 levels deep
  * @return the string representation of t
  */
 public static String stringfor(InspectableTree t, PositionToString pts) {
   if (spaces == null) {
     spaces = new byte[200]; // tree can't be more than 100 levels deep
     for (int i = 0; i < 200; ++i) spaces[i] = (byte) ' ';
   }
   // the 4 below was generated entirely at random
   ByteArrayOutputStream bstr = new ByteArrayOutputStream(t.size() * 4);
   DataOutputStream ostr = new DataOutputStream(bstr);
   writeNodeAndChildren(t.root(), pts, ostr, t, 0, 2);
   return bstr.toString();
 }
Exemplo n.º 2
0
 /**
  * Recursively dumps a byte representation of a subtree onto a stream. Used by stringfor( InspTree
  * ). Publicly available in case you want to stringify a subtree and really think this way is less
  * work than doing it yourself. You'll want to make sure the "spaces" static variable is
  * initialized first :)
  *
  * @param subtreeRoot root of subtree to represent
  * @param pts way to stringify each position
  * @param ostream stream on which to represent the subtree
  * @param t tree, so children(.) can be called
  * @param indentation number of spaces to indent this level
  * @param indentation_increment amount by which indentation will be increased before writing
  *     children
  */
 public static void writeNodeAndChildren(
     Position subtreeRoot,
     PositionToString pts,
     DataOutputStream ostream,
     InspectableTree t,
     int indentation,
     int indentation_increment) {
   try {
     // indent, then write the subtreeRoot
     ostream.write(spaces, 0, indentation);
     ostream.writeBytes(pts.stringfor(subtreeRoot));
     ostream.writeBytes("\n");
   } catch (java.io.IOException e) {
     System.err.println("\nAn I/O error occurred: " + e);
     return;
   }
   PositionIterator pp = t.children(subtreeRoot);
   // recur on all children
   while (pp.hasNext())
     writeNodeAndChildren(
         pp.nextPosition(),
         pts,
         ostream,
         t,
         indentation + indentation_increment,
         indentation_increment);
 }