#!/usr/bin/env python import sys class Node(object): def __init__(self, left_child = None, right_child = None, value = None): self.left_child = left_child self.right_child = right_child self.value = value def leaf_P(self): return self.left_child is None and self.right_child is None def __repr__(self): return "Node(value=%r, left_child=\n%r, right_child=\n%r)" % (self.value, self.left_child, self.right_child) def add_coding(root, binary, value): if binary == "": root.value = value return root digit = int(binary[0]) # 0 or 1. if digit == 0: if root.left_child is None: root.left_child = Node() return add_coding(root.left_child, binary[1 : ], value) else: assert(digit == 1) if root.right_child is None: root.right_child = Node() return add_coding(root.right_child, binary[1 : ], value) def decode(root, input_bits): if input_bits == "": return root, "" digit = int(input_bits[0]) # 0 or 1. if digit == 0: if root.left_child is not None: return decode(root.left_child, input_bits[1 : ]) else: return root, input_bits else: assert(digit == 1) if root.right_child is not None: return decode(root.right_child, input_bits[1 : ]) else: return root, input_bits return root, input_bits def parse_RFC804(input_file): for line in input_file.readlines(): line = line.strip() if not line.startswith("0") and not line.startswith("1"): continue cells = [item for item in line.replace("\t", " ").split(" ") if item != ""] code, bit_length, value = cells value = int(value) bit_length = int(bit_length) yield code, bit_length, value def generate_Pascal_Node(name, root): if root.left_child is not None: left_child_name = "%s0" % name generate_Pascal_Node(left_child_name, root.left_child) left_child_name = "@%s" % left_child_name else: left_child_name = "nil" if root.right_child is not None: right_child_name = "%s1" % name generate_Pascal_Node(right_child_name, root.right_child) right_child_name = "@%s" % right_child_name else: right_child_name = "nil" print """ %s : TNode = (value: %s; left_child: %s; right_child: %s);""" % (name, root.value or "cValueNil", left_child_name, right_child_name) if __name__ == "__main__": root = Node() which = sys.argv[1] or "White" for code, bit_length, value in parse_RFC804(file(which, "rt")): add_coding(root, code, value) add_coding(root, "000000000001", "cValueEOL") # EOL. # test: for code, bit_length, value in parse_RFC804(file(which, "rt")): node, remaining_input = decode(root, code) assert(remaining_input == "") assert(node.value == value) assert(node.left_child is None) assert(node.right_child is None) generate_Pascal_Node("f%sNode" % which, root)