Commit ecb6dd67 authored by Wastl's avatar Wastl

improve packing

parent a19e8826
......@@ -115,17 +115,18 @@ IN = parse('((())()())')
CAT = parse('(()()(()))')
DEF = parse('((()())())')
def pack(ob):
def pack(ob, debug=lambda x:None):
if len(ob) < 2: raise ObCodeError("Program %s containing less than two instructions can't be compressed" % ob)
big = pack_to_num(ob, 0L)
if len(ob) > 1:
while big & 1: big >>= 1
while big & 1: big >>= 1
big >>= 1
debug("Program number is %x" % big)
result = ""
while big:
char = big & 0xff
big >>= 8
if big: result = chr(char)+result
elif char & 0x80: result = chr(0x80)+chr(char)+result
elif char & 0x80: result = '\x80'+chr(char)+result
else: result = chr(char | 0x80)+result
return result
......@@ -153,6 +154,7 @@ def unpack(code):
elif had_one:
ob_stack.append(curr_ob)
curr_ob = []
curr_ob.append(Ob())
while ob_stack:
ob = Ob(curr_ob)
curr_ob = ob_stack.pop()
......@@ -294,22 +296,29 @@ Options:
if opt == '-p' or opt == '--pack': do_pack = True
elif opt == '-d' or opt == '--debug': debug = lambda x: sys.stderr.write(x+'\n')
elif opt == '-w' or opt == '--wimp' or opt == '--wimpy': wimp = True
elif opt == '-W' or opt == '--unwimp': unwimp = True
elif opt == '-W' or opt == '--unwimp':
wimp = True
unwimp = True
elif opt == '-e': code = val
elif opt == '-h' or opt == '-?' or opt == '--help': usage()
if code is None:
if args and args[0] != '-':
try:
with open(args[0]) as f: code = f.read()
except EnvironmentError as err: print >> sys.stderr, 'Error:', err.strerror
except EnvironmentError as err:
print >> sys.stderr, 'Error:', err.strerror
sys.exit(1)
else: code = sys.stdin.read()
if do_pack:
if is_packed(code): print unpack(code)
else:
code = pack(parse(code, wimp))
code = pack(parse(code, wimp), debug)
print >> sys.stderr, "Packed: %d bytes" % len(code)
sys.stdout.write(code)
elif unwimp:
if is_packed(code):
print >> sys.stderr, "Cannot unwimp packed program"
sys.exit(1)
code = str(parse(code, True))
print >> sys.stderr, "Size: %d bytes" % len(code)
print code
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment