xdrlib.py 5.29 KB
Newer Older
1 2 3 4 5 6 7
"""Implements (a subset of) Sun XDR -- eXternal Data Representation.

See: RFC 1014

"""

import struct
8
from io import BytesIO
9

10 11
__all__ = ["Error", "Packer", "Unpacker", "ConversionError"]

12
# exceptions
13
class Error(Exception):
14 15 16 17 18 19 20 21 22 23
    """Exception class for this module. Use:

    except xdrlib.Error, var:
        # var has the Error instance for the exception

    Public ivars:
        msg -- contains the message

    """
    def __init__(self, msg):
24
        self.msg = msg
25
    def __repr__(self):
26
        return repr(self.msg)
27
    def __str__(self):
28
        return str(self.msg)
29 30 31 32 33 34


class ConversionError(Error):
    pass


35

36 37 38 39
class Packer:
    """Pack various data representations into a buffer."""

    def __init__(self):
40
        self.reset()
41 42

    def reset(self):
43
        self.__buf = BytesIO()
44 45

    def get_buffer(self):
46
        return self.__buf.getvalue()
47 48 49 50
    # backwards compatibility
    get_buf = get_buffer

    def pack_uint(self, x):
51
        self.__buf.write(struct.pack('>L', x))
52 53 54 55 56

    pack_int = pack_uint
    pack_enum = pack_int

    def pack_bool(self, x):
57 58
        if x: self.__buf.write(b'\0\0\0\1')
        else: self.__buf.write(b'\0\0\0\0')
59 60

    def pack_uhyper(self, x):
61 62
        self.pack_uint(x>>32 & 0xffffffff)
        self.pack_uint(x & 0xffffffff)
63 64 65 66

    pack_hyper = pack_uhyper

    def pack_float(self, x):
67
        try: self.__buf.write(struct.pack('>f', x))
68
        except struct.error as msg:
69
            raise ConversionError(msg)
70

71
    def pack_double(self, x):
72
        try: self.__buf.write(struct.pack('>d', x))
73
        except struct.error as msg:
74
            raise ConversionError(msg)
75 76

    def pack_fstring(self, n, s):
77
        if n < 0:
78
            raise ValueError('fstring size must be nonnegative')
79
        data = s[:n]
80
        n = ((n+3)//4)*4
81
        data = data + (n - len(data)) * b'\0'
82
        self.__buf.write(data)
83 84 85 86

    pack_fopaque = pack_fstring

    def pack_string(self, s):
87 88 89
        n = len(s)
        self.pack_uint(n)
        self.pack_fstring(n, s)
90 91 92 93 94

    pack_opaque = pack_string
    pack_bytes = pack_string

    def pack_list(self, list, pack_item):
95 96 97 98
        for item in list:
            self.pack_uint(1)
            pack_item(item)
        self.pack_uint(0)
99 100

    def pack_farray(self, n, list, pack_item):
101
        if len(list) != n:
102
            raise ValueError('wrong array size')
103 104
        for item in list:
            pack_item(item)
105 106

    def pack_array(self, list, pack_item):
107 108 109
        n = len(list)
        self.pack_uint(n)
        self.pack_farray(n, list, pack_item)
110 111


112

113 114 115 116
class Unpacker:
    """Unpacks various data representations from the given buffer."""

    def __init__(self, data):
117
        self.reset(data)
118 119

    def reset(self, data):
120 121
        self.__buf = data
        self.__pos = 0
122 123

    def get_position(self):
124
        return self.__pos
125 126

    def set_position(self, position):
127
        self.__pos = position
128

129
    def get_buffer(self):
130
        return self.__buf
131

132
    def done(self):
133 134
        if self.__pos < len(self.__buf):
            raise Error('unextracted data remains')
135 136

    def unpack_uint(self):
137 138 139 140 141 142 143 144 145 146
        i = self.__pos
        self.__pos = j = i+4
        data = self.__buf[i:j]
        if len(data) < 4:
            raise EOFError
        x = struct.unpack('>L', data)[0]
        try:
            return int(x)
        except OverflowError:
            return x
147 148

    def unpack_int(self):
149 150 151 152 153 154
        i = self.__pos
        self.__pos = j = i+4
        data = self.__buf[i:j]
        if len(data) < 4:
            raise EOFError
        return struct.unpack('>l', data)[0]
155 156

    unpack_enum = unpack_int
157 158 159

    def unpack_bool(self):
        return bool(self.unpack_int())
160 161

    def unpack_uhyper(self):
162 163
        hi = self.unpack_uint()
        lo = self.unpack_uint()
164
        return int(hi)<<32 | lo
165 166

    def unpack_hyper(self):
167
        x = self.unpack_uhyper()
168 169
        if x >= 0x8000000000000000:
            x = x - 0x10000000000000000
170
        return x
171 172

    def unpack_float(self):
173 174 175 176 177 178
        i = self.__pos
        self.__pos = j = i+4
        data = self.__buf[i:j]
        if len(data) < 4:
            raise EOFError
        return struct.unpack('>f', data)[0]
179

180
    def unpack_double(self):
181 182 183 184 185 186
        i = self.__pos
        self.__pos = j = i+8
        data = self.__buf[i:j]
        if len(data) < 8:
            raise EOFError
        return struct.unpack('>d', data)[0]
187 188

    def unpack_fstring(self, n):
189
        if n < 0:
190
            raise ValueError('fstring size must be nonnegative')
191
        i = self.__pos
192
        j = i + (n+3)//4*4
193 194 195 196
        if j > len(self.__buf):
            raise EOFError
        self.__pos = j
        return self.__buf[i:i+n]
197 198 199 200

    unpack_fopaque = unpack_fstring

    def unpack_string(self):
201 202
        n = self.unpack_uint()
        return self.unpack_fstring(n)
203 204 205 206 207

    unpack_opaque = unpack_string
    unpack_bytes = unpack_string

    def unpack_list(self, unpack_item):
208 209 210 211
        list = []
        while 1:
            x = self.unpack_uint()
            if x == 0: break
212
            if x != 1:
213
                raise ConversionError('0 or 1 expected, got %r' % (x,))
214 215 216
            item = unpack_item()
            list.append(item)
        return list
217 218

    def unpack_farray(self, n, unpack_item):
219 220 221 222
        list = []
        for i in range(n):
            list.append(unpack_item())
        return list
223 224

    def unpack_array(self, unpack_item):
225 226
        n = self.unpack_uint()
        return self.unpack_farray(n, unpack_item)