1
from __future__ import unicode_literals
4
from rlp import SerializationError, utils
5
from rlp.sedes import big_endian_int, BigEndianInt
6
from rlp.utils import int_to_big_endian
14
single_bytes = ((n, utils.ascii_chr(n)) for n in range(1, 256))
16
random_integers = (256, 257, 4839, 849302, 483290432, 483290483290482039482039,
17
48930248348219540325894323584235894327865439258743754893066)
18
assert random_integers[-1] < 2**256
20
negative_ints = (-1, -100, -255, -256, -2342423)
24
for n in negative_ints:
25
with pytest.raises(SerializationError):
26
big_endian_int.serialize(n)
29
def test_serialization():
30
for n in random_integers:
31
serial = big_endian_int.serialize(n)
32
deserialized = big_endian_int.deserialize(serial)
33
assert deserialized == n
35
assert serial[0] != b'\x00' # is not checked
38
def test_single_byte():
39
for n, s in single_bytes:
40
serial = big_endian_int.serialize(n)
42
deserialized = big_endian_int.deserialize(serial)
43
assert deserialized == n
46
def test_valid_data():
47
for n, serial in valid_data:
48
serialized = big_endian_int.serialize(n)
49
deserialized = big_endian_int.deserialize(serial)
50
assert serialized == serial
51
assert deserialized == n
54
def test_fixedlength():
56
for i in (0, 1, 255, 256, 256**3, 256**4 - 1):
57
assert len(s.serialize(i)) == 4
58
assert s.deserialize(s.serialize(i)) == i
59
for i in (256**4, 256**4 + 1, 256**5, -1, -256, 'asdf'):
60
with pytest.raises(SerializationError):
68
"""Packs the lnum (which must be convertable to a long) into a
69
byte string 0 padded to a multiple of padmultiple bytes in size. 0
70
means no padding whatsoever, so that packing 0 result in an empty
71
string. The resulting byte string is the big-endian two's
72
complement representation of the passed in long."""
80
s = binascii.unhexlify(s)
86
PyLong_AsByteArray = ctypes.pythonapi._PyLong_AsByteArray
87
PyLong_AsByteArray.argtypes = [ctypes.py_object,
93
long_start = sys.maxint + 1
95
def packl_ctypes(lnum):
97
return int_to_big_endian(lnum)
98
a = ctypes.create_string_buffer(lnum.bit_length() // 8 + 1)
99
PyLong_AsByteArray(lnum, a, len(a), 0, 1)
100
return a.raw.lstrip(b'\0')
101
except AttributeError:
109
assert rc == int_to_big_endian(v)
111
assert r == int_to_big_endian(v)
118
for j in range(100000):
119
for i in random_integers:
121
print('packl elapsed {}'.format(time.time() - st))
124
for j in range(100000):
125
for i in random_integers:
127
print('ctypes elapsed {}'.format(time.time() - st))
130
for j in range(100000):
131
for i in random_integers:
133
print('py elapsed {}'.format(time.time() - st))
136
if __name__ == '__main__':