xdrlib.py 5.38 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 9 10 11
try:
    from cStringIO import StringIO as _StringIO
except ImportError:
    from StringIO import StringIO as _StringIO
12

13 14
__all__ = ["Error", "Packer", "Unpacker", "ConversionError"]

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


class ConversionError(Error):
    pass


38

39 40 41 42
class Packer:
    """Pack various data representations into a buffer."""

    def __init__(self):
43
        self.reset()
44 45

    def reset(self):
46
        self.__buf = _StringIO()
47 48

    def get_buffer(self):
49
        return self.__buf.getvalue()
50 51 52 53
    # backwards compatibility
    get_buf = get_buffer

    def pack_uint(self, x):
54
        self.__buf.write(struct.pack('>L', x))
55 56 57 58 59

    pack_int = pack_uint
    pack_enum = pack_int

    def pack_bool(self, x):
60 61
        if x: self.__buf.write('\0\0\0\1')
        else: self.__buf.write('\0\0\0\0')
62 63

    def pack_uhyper(self, x):
64 65
        self.pack_uint(x>>32 & 0xffffffffL)
        self.pack_uint(x & 0xffffffffL)
66 67 68 69

    pack_hyper = pack_uhyper

    def pack_float(self, x):
70
        try: self.__buf.write(struct.pack('>f', x))
71 72
        except struct.error, msg:
            raise ConversionError, msg
73

74
    def pack_double(self, x):
75
        try: self.__buf.write(struct.pack('>d', x))
76 77
        except struct.error, msg:
            raise ConversionError, msg
78 79

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

    pack_fopaque = pack_fstring

    def pack_string(self, s):
90 91 92
        n = len(s)
        self.pack_uint(n)
        self.pack_fstring(n, s)
93 94 95 96 97

    pack_opaque = pack_string
    pack_bytes = pack_string

    def pack_list(self, list, pack_item):
98 99 100 101
        for item in list:
            self.pack_uint(1)
            pack_item(item)
        self.pack_uint(0)
102 103

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

    def pack_array(self, list, pack_item):
110 111 112
        n = len(list)
        self.pack_uint(n)
        self.pack_farray(n, list, pack_item)
113 114


115

116 117 118 119
class Unpacker:
    """Unpacks various data representations from the given buffer."""

    def __init__(self, data):
120
        self.reset(data)
121 122

    def reset(self, data):
123 124
        self.__buf = data
        self.__pos = 0
125 126

    def get_position(self):
127
        return self.__pos
128 129

    def set_position(self, position):
130
        self.__pos = position
131

132
    def get_buffer(self):
133
        return self.__buf
134

135
    def done(self):
136 137
        if self.__pos < len(self.__buf):
            raise Error('unextracted data remains')
138 139

    def unpack_uint(self):
140 141 142 143 144 145 146 147 148 149
        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
150 151

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

    unpack_enum = unpack_int
160 161 162

    def unpack_bool(self):
        return bool(self.unpack_int())
163 164

    def unpack_uhyper(self):
165 166 167
        hi = self.unpack_uint()
        lo = self.unpack_uint()
        return long(hi)<<32 | lo
168 169

    def unpack_hyper(self):
170 171 172 173
        x = self.unpack_uhyper()
        if x >= 0x8000000000000000L:
            x = x - 0x10000000000000000L
        return x
174 175

    def unpack_float(self):
176 177 178 179 180 181
        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]
182

183
    def unpack_double(self):
184 185 186 187 188 189
        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]
190 191

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

    unpack_fopaque = unpack_fstring

    def unpack_string(self):
204 205
        n = self.unpack_uint()
        return self.unpack_fstring(n)
206 207 208 209 210

    unpack_opaque = unpack_string
    unpack_bytes = unpack_string

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

    def unpack_farray(self, n, unpack_item):
222 223 224 225
        list = []
        for i in range(n):
            list.append(unpack_item())
        return list
226 227

    def unpack_array(self, unpack_item):
228 229
        n = self.unpack_uint()
        return self.unpack_farray(n, unpack_item)