1
from ..exceptions import DeserializationError, SerializationError
2
from ..utils import int_to_big_endian, big_endian_to_int, is_integer, ascii_chr
5
class BigEndianInt(object):
6
"""A sedes for big endian integers.
8
:param l: the size of the serialized representation in bytes or `None` to
9
use the shortest possible one
12
def __init__(self, l=None):
15
def serialize(self, obj):
16
if not is_integer(obj):
17
raise SerializationError('Can only serialize integers', obj)
18
if self.l is not None and obj >= 256**self.l:
19
raise SerializationError('Integer too large (does not fit in {} '
20
'bytes)'.format(self.l), obj)
22
raise SerializationError('Cannot serialize negative integers', obj)
27
s = int_to_big_endian(obj)
29
if self.l is not None:
30
return b'\x00' * max(0, self.l - len(s)) + s
34
def deserialize(self, serial):
35
if self.l is not None and len(serial) != self.l:
36
raise DeserializationError('Invalid serialization (wrong size)',
38
if self.l is None and len(serial) > 0 and serial[0:1] == ascii_chr(0):
39
raise DeserializationError('Invalid serialization (not minimal '
42
serial = serial or b'\x00'
43
return big_endian_to_int(serial)
45
big_endian_int = BigEndianInt()