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

See: RFC 1014

"""

import struct

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

11 12 13 14 15 16 17 18 19 20 21 22
# exceptions
class Error:
    """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):
23
        self.msg = msg
24
    def __repr__(self):
25
        return repr(self.msg)
26
    def __str__(self):
27
        return str(self.msg)
28 29 30 31 32 33


class ConversionError(Error):
    pass


34

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

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

    def reset(self):
42
        self.__buf = ''
43 44

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

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

    pack_int = pack_uint
    pack_enum = pack_int

    def pack_bool(self, x):
56 57
        if x: self.__buf = self.__buf + '\0\0\0\1'
        else: self.__buf = self.__buf + '\0\0\0\0'
58 59

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

    pack_hyper = pack_uhyper

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

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

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

    pack_fopaque = pack_fstring

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

    pack_opaque = pack_string
    pack_bytes = pack_string

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

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

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


111

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

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

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

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

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

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

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

    def unpack_uint(self):
136 137 138 139 140 141 142 143 144 145
        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
146 147

    def unpack_int(self):
148 149 150 151 152 153
        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]
154 155 156 157 158

    unpack_enum = unpack_int
    unpack_bool = unpack_int

    def unpack_uhyper(self):
159 160 161
        hi = self.unpack_uint()
        lo = self.unpack_uint()
        return long(hi)<<32 | lo
162 163

    def unpack_hyper(self):
164 165 166 167
        x = self.unpack_uhyper()
        if x >= 0x8000000000000000L:
            x = x - 0x10000000000000000L
        return x
168 169

    def unpack_float(self):
170 171 172 173 174 175
        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]
176

177
    def unpack_double(self):
178 179 180 181 182 183
        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]
184 185

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

    unpack_fopaque = unpack_fstring

    def unpack_string(self):
198 199
        n = self.unpack_uint()
        return self.unpack_fstring(n)
200 201 202 203 204

    unpack_opaque = unpack_string
    unpack_bytes = unpack_string

    def unpack_list(self, unpack_item):
205 206 207 208
        list = []
        while 1:
            x = self.unpack_uint()
            if x == 0: break
209
            if x != 1:
210 211 212 213
                raise ConversionError, '0 or 1 expected, got ' + `x`
            item = unpack_item()
            list.append(item)
        return list
214 215

    def unpack_farray(self, n, unpack_item):
216 217 218 219
        list = []
        for i in range(n):
            list.append(unpack_item())
        return list
220 221

    def unpack_array(self, unpack_item):
222 223
        n = self.unpack_uint()
        return self.unpack_farray(n, unpack_item)
224

225

226
# test suite
227
def _test():
228 229
    p = Packer()
    packtest = [
230 231 232 233 234 235 236 237 238 239
        (p.pack_uint,    (9,)),
        (p.pack_bool,    (None,)),
        (p.pack_bool,    ('hello',)),
        (p.pack_uhyper,  (45L,)),
        (p.pack_float,   (1.9,)),
        (p.pack_double,  (1.9,)),
        (p.pack_string,  ('hello world',)),
        (p.pack_list,    (range(5), p.pack_uint)),
        (p.pack_array,   (['what', 'is', 'hapnin', 'doctor'], p.pack_string)),
        ]
240 241 242
    succeedlist = [1] * len(packtest)
    count = 0
    for method, args in packtest:
243 244 245 246 247 248 249 250
        print 'pack test', count,
        try:
            apply(method, args)
            print 'succeeded'
        except ConversionError, var:
            print 'ConversionError:', var.msg
            succeedlist[count] = 0
        count = count + 1
251 252 253 254
    data = p.get_buffer()
    # now verify
    up = Unpacker(data)
    unpacktest = [
255 256 257 258 259 260 261 262 263 264 265
        (up.unpack_uint,   (), lambda x: x == 9),
        (up.unpack_bool,   (), lambda x: not x),
        (up.unpack_bool,   (), lambda x: x),
        (up.unpack_uhyper, (), lambda x: x == 45L),
        (up.unpack_float,  (), lambda x: 1.89 < x < 1.91),
        (up.unpack_double, (), lambda x: 1.89 < x < 1.91),
        (up.unpack_string, (), lambda x: x == 'hello world'),
        (up.unpack_list,   (up.unpack_uint,), lambda x: x == range(5)),
        (up.unpack_array,  (up.unpack_string,),
         lambda x: x == ['what', 'is', 'hapnin', 'doctor']),
        ]
266 267
    count = 0
    for method, args, pred in unpacktest:
268 269 270 271 272 273 274 275 276 277
        print 'unpack test', count,
        try:
            if succeedlist[count]:
                x = apply(method, args)
                print pred(x) and 'succeeded' or 'failed', ':', x
            else:
                print 'skipping'
        except ConversionError, var:
            print 'ConversionError:', var.msg
        count = count + 1
278

279

280
if __name__ == '__main__':
281
    _test()