source: trunk/essentials/dev-lang/python/Demo/rpc/xdr.py@ 3393

Last change on this file since 3393 was 3225, checked in by bird, 19 years ago

Python 2.5

File size: 4.9 KB
Line 
1# Implement (a subset of) Sun XDR -- RFC1014.
2
3
4try:
5 import struct
6except ImportError:
7 struct = None
8
9
10Long = type(0L)
11
12
13class Packer:
14
15 def __init__(self):
16 self.reset()
17
18 def reset(self):
19 self.buf = ''
20
21 def get_buf(self):
22 return self.buf
23
24 def pack_uint(self, x):
25 self.buf = self.buf + \
26 (chr(int(x>>24 & 0xff)) + chr(int(x>>16 & 0xff)) + \
27 chr(int(x>>8 & 0xff)) + chr(int(x & 0xff)))
28 if struct and struct.pack('l', 1) == '\0\0\0\1':
29 def pack_uint(self, x):
30 if type(x) == Long:
31 x = int((x + 0x80000000L) % 0x100000000L \
32 - 0x80000000L)
33 self.buf = self.buf + struct.pack('l', x)
34
35 pack_int = pack_uint
36
37 pack_enum = pack_int
38
39 def pack_bool(self, x):
40 if x: self.buf = self.buf + '\0\0\0\1'
41 else: self.buf = self.buf + '\0\0\0\0'
42
43 def pack_uhyper(self, x):
44 self.pack_uint(int(x>>32 & 0xffffffff))
45 self.pack_uint(int(x & 0xffffffff))
46
47 pack_hyper = pack_uhyper
48
49 def pack_float(self, x):
50 # XXX
51 self.buf = self.buf + struct.pack('f', x)
52
53 def pack_double(self, x):
54 # XXX
55 self.buf = self.buf + struct.pack('d', x)
56
57 def pack_fstring(self, n, s):
58 if n < 0:
59 raise ValueError, 'fstring size must be nonnegative'
60 n = ((n+3)/4)*4
61 data = s[:n]
62 data = data + (n - len(data)) * '\0'
63 self.buf = self.buf + data
64
65 pack_fopaque = pack_fstring
66
67 def pack_string(self, s):
68 n = len(s)
69 self.pack_uint(n)
70 self.pack_fstring(n, s)
71
72 pack_opaque = pack_string
73
74 def pack_list(self, list, pack_item):
75 for item in list:
76 self.pack_uint(1)
77 pack_item(item)
78 self.pack_uint(0)
79
80 def pack_farray(self, n, list, pack_item):
81 if len(list) <> n:
82 raise ValueError, 'wrong array size'
83 for item in list:
84 pack_item(item)
85
86 def pack_array(self, list, pack_item):
87 n = len(list)
88 self.pack_uint(n)
89 self.pack_farray(n, list, pack_item)
90
91
92class Unpacker:
93
94 def __init__(self, data):