From 5c00456ae53ef02c957c2b0dbf8bf3a6e3602211 Mon Sep 17 00:00:00 2001 From: Daira Hopwood Date: Sat, 21 Jul 2018 14:13:20 +0100 Subject: [PATCH] Add more conversion utility functions. Signed-off-by: Daira Hopwood --- sapling_utils.py | 38 +++++++++++++++++++++++++++++++++++--- 1 file changed, 35 insertions(+), 3 deletions(-) diff --git a/sapling_utils.py b/sapling_utils.py index 8324109..ed9dcdb 100644 --- a/sapling_utils.py +++ b/sapling_utils.py @@ -10,26 +10,58 @@ def i2lebsp(l, x): def leos2ip(S): return int.from_bytes(S, byteorder='little') +def beos2ip(S): + return int.from_bytes(S, byteorder='big') + # This should be equivalent to LEBS2OSP(I2LEBSP(l, x)) def i2leosp(l, x): return x.to_bytes(cldiv(l, 8), byteorder='little') -def ledna(bits): +# This should be equivalent to BEBS2OSP(I2BEBSP(l, x)) +def i2beosp(l, x): + return x.to_bytes(cldiv(l, 8), byteorder='big') + +def bebs2ip(bits): ret = 0 - for b in bits[::-1]: + for b in bits: ret = ret * 2 if b: ret += 1 return ret +def lebs2ip(bits): + return bebs2ip(bits[::-1]) + +def i2bebsp(m, x): + assert 0 <= x and x < (1 << m) + return [(x >> (m-1-i)) & 1 for i in range(m)] + def lebs2osp(bits): l = len(bits) bits = bits + [0] * (8 * cldiv(l, 8) - l) - return bytes([ledna(bits[i:i + 8]) for i in range(0, len(bits), 8)]) + return bytes([lebs2ip(bits[i:i + 8]) for i in range(0, len(bits), 8)]) def leos2bsp(buf): return sum([[(c >> i) & 1 for i in range(8)] for c in buf], []) +def bebs2osp(bits, m=None): + l = len(bits) + bits = [0] * (8 * cldiv(l, 8) - l) + bits + return bytes([bebs2ip(bits[i:i + 8]) for i in range(0, len(bits), 8)]) + +def beos2bsp(buf): + return sum([[(c >> (7-i)) & 1 for i in range(8)] for c in buf], []) assert i2leosp(5, 7) == lebs2osp(i2lebsp(5, 7)) assert i2leosp(32, 1234567890) == lebs2osp(i2lebsp(32, 1234567890)) + +assert i2beosp(5, 7) == bebs2osp(i2bebsp(5, 7)) +assert i2beosp(32, 1234567890) == bebs2osp(i2bebsp(32, 1234567890)) + +assert bebs2ip(i2bebsp(5, 7)) == 7 +try: + i2bebsp(3, 12) +except AssertionError: + pass +else: + raise AssertionError("invalid input not caught by i2bebsp")