~ubuntu-branches/debian/sid/pyrlp/sid

« back to all changes in this revision

Viewing changes to rlp/sedes/big_endian_int.py

  • Committer: Package Import Robot
  • Author(s): Ben Finney
  • Date: 2017-07-15 05:25:42 UTC
  • Revision ID: package-import@ubuntu.com-20170715052542-a20zzsypt1qfecq1
Tags: upstream-0.5.1
ImportĀ upstreamĀ versionĀ 0.5.1

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
from ..exceptions import DeserializationError, SerializationError
 
2
from ..utils import int_to_big_endian, big_endian_to_int, is_integer, ascii_chr
 
3
 
 
4
 
 
5
class BigEndianInt(object):
 
6
    """A sedes for big endian integers.
 
7
 
 
8
    :param l: the size of the serialized representation in bytes or `None` to
 
9
              use the shortest possible one
 
10
    """
 
11
 
 
12
    def __init__(self, l=None):
 
13
        self.l = l
 
14
 
 
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)
 
21
        if obj < 0:
 
22
            raise SerializationError('Cannot serialize negative integers', obj)
 
23
 
 
24
        if obj == 0:
 
25
            s = b''
 
26
        else:
 
27
            s = int_to_big_endian(obj)
 
28
 
 
29
        if self.l is not None:
 
30
            return b'\x00' * max(0, self.l - len(s)) + s
 
31
        else:
 
32
            return s
 
33
 
 
34
    def deserialize(self, serial):
 
35
        if self.l is not None and len(serial) != self.l:
 
36
            raise DeserializationError('Invalid serialization (wrong size)',
 
37
                                       serial)
 
38
        if self.l is None and len(serial) > 0 and serial[0:1] == ascii_chr(0):
 
39
            raise DeserializationError('Invalid serialization (not minimal '
 
40
                                       'length)', serial)
 
41
 
 
42
        serial = serial or b'\x00'
 
43
        return big_endian_to_int(serial)
 
44
 
 
45
big_endian_int = BigEndianInt()