use fmt; use strings; // TODO: docs export type Node = struct { left: nullable *Node, right: nullable *Node, data: Leaf, length: size, }; // TODO: docs fn node_new() Node = Node { left = null, right = null, data = leaf_new(), length = 0: size, }; // TODO: docs fn node_close(node: *Node) void = { match (node.left) { case null => void; case let left: *Node => node_close(left); }; match (node.right) { case null => void; case let right: *Node => node_close(right); }; leaf_close(&node.data); }; // Caller must free return value. Do not free the passed string or else the // internal buffer will become invalid. fn node_fromstr(string: str) Node = Node { left = null, right = null, data = leaf_fromstr(string), length = 0: size, }; //fn strtonode(data: str) Node = { // return data; //}; // //fn nodetorope(node: *Node) Rope = { // return Rope { // left = node, // right = null, // length = node_length(node) // }; //}; // //fn node_length(node: *Node) size = { // return match (*node) { // case let leaf: str => yield len(leaf); // case let rope: Rope => yield rope_length(&rope); // }; //}; // TODO: docs fn print_node(node: *const Node) void = { fmt::print(strings::fromrunes(node.data.buf))!; }; // TODO: docs fn print_tree(node: nullable *const Node) void = { match (node) { case null => void; case let good: *const Node => { print_tree(good.left); fmt::print(strings::fromrunes(good.data.buf))!; print_tree(good.right); }; }; }; // TODO: docs fn node_length(node: nullable *const Node) size = match (node) { case null => yield 0: size; case let good: *const Node => yield if (good.data.length == 0) { yield node_length(good.left) + node_length(good.right); } else { yield good.data.length; }; }; fn node_index(node: nullable *const Node, idx: size) (rune | indexerror) = { yield match (node) { case null => yield indexerror; case let good: *const Node => yield if (idx < good.length && !(good.left is null)) { yield node_index(good.left, idx); } else if (good.left is null) { yield leaf_at(&good.data, idx); } else { yield node_index(good.right, idx - good.length); }; }; };