Debian Codegraph @

rpython/rlib/rstruct/standardfmttable.py

raw symbols SCIP
1 """
2 The format table for standard sizes and alignments.
3 """
4
5 # Note: we follow Python 2.5 in being strict about the ranges of accepted
6 # values when packing.
7
8 import struct
9
10 from rpython.rlib.objectmodel import specialize
11 from rpython.rlib.rarithmetic import r_uint, r_longlong, r_ulonglong
12 from rpython.rlib.rstruct import ieee
13 from rpython.rlib.rstruct.error import StructError, StructOverflowError
14 from rpython.rlib.unroll import unrolling_iterable
15 from rpython.rlib.buffer import StringBuffer
16 from rpython.rlib import rarithmetic
17 from rpython.rlib.buffer import CannotRead, CannotWrite
18 from rpython.rtyper.lltypesystem import rffi
19
20 USE_FASTPATH = True # set to False by some tests
21 ALLOW_SLOWPATH = True # set to False by some tests
22 ALLOW_FASTPATH = True # set to False by some tests
23
24 native_is_bigendian = struct.pack("=i", 1) == struct.pack(">i", 1)
25 native_is_ieee754 = float.__getformat__('double').startswith('IEEE')
26
27 @specialize.memo()
28 def pack_fastpath(TYPE):
29 """
30 Create a fast path packer for TYPE. The packer returns True is it succeded
31 or False otherwise.
32 """
33 @specialize.argtype(0)
34 def do_pack_fastpath(fmtiter, value):
35 size = rffi.sizeof(TYPE)
36 if (not USE_FASTPATH or
37 fmtiter.bigendian != native_is_bigendian or
38 not native_is_ieee754):
39 raise CannotWrite
40 #
41 # typed_write() might raise CannotWrite
42 fmtiter.wbuf.typed_write(TYPE, fmtiter.pos, value)
43 if not ALLOW_FASTPATH:
44 # if we are here it means that typed_write did not raise, and thus
45 # the fast path was actually taken
46 raise ValueError("fastpath not allowed :(")
47 fmtiter.advance(size)
48 #
49 @specialize.argtype(0)
50 def do_pack_fastpath_maybe(fmtiter, value):
51 try:
52 do_pack_fastpath(fmtiter, value)
53 except CannotWrite:
54 if not ALLOW_SLOWPATH:
55 raise ValueError("fastpath not taken :(")
56 return False
57 else:
58 return True
59 #
60 return do_pack_fastpath_maybe
61
62 def pack_pad(fmtiter, count):
63 fmtiter.wbuf.setzeros(fmtiter.pos, count)
64 fmtiter.advance(count)
65
66 def pack_char(fmtiter):
67 string = fmtiter.accept_str_arg()
68 if len(string) != 1:
69 raise StructError("expected a string of length 1")
70 c = string[0] # string->char conversion for the annotator
71 fmtiter.wbuf.setitem(fmtiter.pos, c)
72 fmtiter.advance(1)
73
74 def pack_bool(fmtiter):
75 c = '\x01' if fmtiter.accept_bool_arg() else '\x00'
76 fmtiter.wbuf.setitem(fmtiter.pos, c)
77 fmtiter.advance(1)
78
79 def _pack_string(fmtiter, string, count):
80 pos = fmtiter.pos
81 if len(string) < count:
82 n = len(string)
83 fmtiter.wbuf.setslice(pos, string)
84 fmtiter.wbuf.setzeros(pos+n, count-n)
85 else:
86 assert count >= 0
87 fmtiter.wbuf.setslice(pos, string[:count])
88 fmtiter.advance(count)
89
90 def pack_string(fmtiter, count):
91 string = fmtiter.accept_str_arg()
92 _pack_string(fmtiter, string, count)
93
94 def pack_pascal(fmtiter, count):
95 string = fmtiter.accept_str_arg()
96 prefix = len(string)
97 if prefix >= count:
98 prefix = count - 1
99 if prefix < 0:
100 raise StructError("bad '0p' in struct format")
101 if prefix > 255:
102 prefix = 255
103 fmtiter.wbuf.setitem(fmtiter.pos, chr(prefix))
104 fmtiter.advance(1)
105 _pack_string(fmtiter, string, count-1)
106
107
108 def pack_halffloat(fmtiter):
109 size = 2
110 fl = fmtiter.accept_float_arg()
111 try:
112 result = ieee.pack_float(fmtiter.wbuf, fmtiter.pos,
113 fl, size, fmtiter.bigendian)
114 except OverflowError:
115 raise StructOverflowError("float too large for format 'e'")
116 else:
117 fmtiter.advance(size)
118 return result
119
120 def make_float_packer(TYPE):
121 size = rffi.sizeof(TYPE)
122 def packer(fmtiter):
123 fl = fmtiter.accept_float_arg()
124 if TYPE is not rffi.FLOAT and pack_fastpath(TYPE)(fmtiter, fl):
125 return
126 # slow path
127 try:
128 result = ieee.pack_float(fmtiter.wbuf, fmtiter.pos,
129 fl, size, fmtiter.bigendian)
130 except OverflowError:
131 assert size == 4
132 raise StructOverflowError("float too large for format 'f'")
133 else:
134 fmtiter.advance(size)
135 return result
136 return packer
137
138 # ____________________________________________________________
139
140 native_int_size = struct.calcsize("l")
141
142 def min_max_acc_method(size, signed):
143 if signed:
144 min = -(2 ** (8*size-1))
145 max = (2 ** (8*size-1)) - 1
146 if size <= native_int_size:
147 accept_method = 'accept_int_arg'
148 min = int(min)
149 max = int(max)
150 else:
151 accept_method = 'accept_longlong_arg'
152 min = r_longlong(min)
153 max = r_longlong(max)
154 else:
155 min = 0
156 max = (2 ** (8*size)) - 1
157 if size < native_int_size:
158 accept_method = 'accept_int_arg'
159 elif size == native_int_size:
160 accept_method = 'accept_uint_arg'
161 min = r_uint(min)
162 max = r_uint(max)
163 else:
164 accept_method = 'accept_ulonglong_arg'
165 min = r_ulonglong(min)
166 max = r_ulonglong(max)
167 return min, max, accept_method
168
169 def make_int_packer(size, signed, _memo={}):
170 key = size, signed
171 try:
172 return _memo[key]
173 except KeyError:
174 pass
175 min, max, accept_method = min_max_acc_method(size, signed)
176 if size > 1:
177 plural = "s"
178 else:
179 plural = ""
180 errormsg = "argument out of range for %d-byte%s integer format" % (size,
181 plural)
182 unroll_revrange_size = unrolling_iterable(range(size-1, -1, -1))
183 TYPE = get_rffi_int_type(size, signed)
184
185 def pack_int(fmtiter):
186 method = getattr(fmtiter, accept_method)
187 value = method()
188 if not min <= value <= max:
189 raise StructError(errormsg)
190 #
191 if pack_fastpath(TYPE)(fmtiter, value):
192 return
193 #
194 pos = fmtiter.pos + size - 1
195 if fmtiter.bigendian:
196 for i in unroll_revrange_size:
197 x = (value >> (8*i)) & 0xff
198 fmtiter.wbuf.setitem(pos-i, chr(x))
199 else:
200
201 for i in unroll_revrange_size:
202 fmtiter.wbuf.setitem(pos-i, chr(value & 0xff))
203 value >>= 8
204 fmtiter.advance(size)
205
206 _memo[key] = pack_int
207 return pack_int
208
209 # ____________________________________________________________
210
211
212 @specialize.memo()
213 def unpack_fastpath(TYPE):
214 @specialize.argtype(0)
215 def do_unpack_fastpath(fmtiter):
216 size = rffi.sizeof(TYPE)
217 buf, pos = fmtiter.get_buffer_and_pos()
218 if not USE_FASTPATH:
219 raise CannotRead
220 #
221 if not ALLOW_FASTPATH:
222 raise ValueError("fastpath not allowed :(")
223 # typed_read does not do any bound check, so we must call it only if
224 # we are sure there are at least "size" bytes to read
225 if fmtiter.can_advance(size):
226 result = buf.typed_read(TYPE, pos)
227 fmtiter.advance(size)
228 return result
229 else:
230 # this will raise StructError
231 fmtiter.advance(size)
232 assert False, 'fmtiter.advance should have raised!'
233 return do_unpack_fastpath
234
235 @specialize.argtype(0)
236 def unpack_pad(fmtiter, count):
237 fmtiter.read(count)
238
239 @specialize.argtype(0)
240 def unpack_char(fmtiter):
241 fmtiter.appendobj(fmtiter.read(1))
242
243 @specialize.argtype(0)
244 def unpack_bool(fmtiter):
245 c = ord(fmtiter.read(1)[0])
246 fmtiter.appendobj(bool(c))
247
248 @specialize.argtype(0)
249 def unpack_string(fmtiter, count):
250 fmtiter.appendobj(fmtiter.read(count))
251
252 @specialize.argtype(0)
253 def unpack_pascal(fmtiter, count):
254 if count == 0:
255 raise StructError("bad '0p' in struct format")
256 data = fmtiter.read(count)
257 end = 1 + ord(data[0])
258 if end > count:
259 end = count
260 fmtiter.appendobj(data[1:end])
261
262 @specialize.argtype(0)
263 def unpack_halffloat(fmtiter):
264 data = fmtiter.read(2)
265 fmtiter.appendobj(ieee.unpack_float(data, fmtiter.bigendian))
266
267 def make_ieee_unpacker(TYPE):
268 @specialize.argtype(0)
269 def unpack_ieee(fmtiter):
270 size = rffi.sizeof(TYPE)
271 if fmtiter.bigendian != native_is_bigendian or not native_is_ieee754:
272 # fallback to the very slow unpacking code in ieee.py
273 data = fmtiter.read(size)
274 fmtiter.appendobj(ieee.unpack_float(data, fmtiter.bigendian))
275 return
276 ## XXX check if the following code is still needed
277 ## if not str_storage_supported(TYPE):
278 ## # this happens e.g. on win32 and ARM32: we cannot read the string
279 ## # content as an array of doubles because it's not properly
280 ## # aligned. But we can read a longlong and convert to float
281 ## assert TYPE == rffi.DOUBLE
282 ## assert rffi.sizeof(TYPE) == 8
283 ## return unpack_longlong2float(fmtiter)
284 try:
285 # fast path
286 val = unpack_fastpath(TYPE)(fmtiter)
287 except CannotRead:
288 # slow path: we should arrive here only if we could not unpack
289 # because of alignment issues. So we copy the slice into a new
290 # string, which is guaranteed to be properly aligned, and read the
291 # float/double from there
292 input = fmtiter.read(size)
293 val = StringBuffer(input).typed_read(TYPE, 0)
294 fmtiter.appendobj(float(val))
295 return unpack_ieee
296
297 @specialize.argtype(0)
298 def unpack_longlong2float(fmtiter):
299 from rpython.rlib.rstruct.runpack import runpack
300 from rpython.rlib.longlong2float import longlong2float
301 s = fmtiter.read(8)
302 llval = runpack('q', s) # this is a bit recursive, I know
303 doubleval = longlong2float(llval)
304 fmtiter.appendobj(doubleval)
305
306
307 unpack_double = make_ieee_unpacker(rffi.DOUBLE)
308 unpack_float = make_ieee_unpacker(rffi.FLOAT)
309
310 # ____________________________________________________________
311
312 def get_rffi_int_type(size, signed):
313 for TYPE in rffi.platform.numbertype_to_rclass:
314 if (rffi.sizeof(TYPE) == size and
315 rarithmetic.is_signed_integer_type(TYPE) == signed):
316 return TYPE
317 raise KeyError("Cannot find an int type size=%d, signed=%d" % (size, signed))
318
319 def make_int_unpacker(size, signed, _memo={}):
320 try:
321 return _memo[size, signed]
322 except KeyError:
323 pass
324 if signed:
325 if size <= native_int_size:
326 inttype = int
327 else:
328 inttype = r_longlong
329 else:
330 if size < native_int_size:
331 inttype = int
332 elif size == native_int_size:
333 inttype = r_uint
334 else:
335 inttype = r_ulonglong
336 unroll_range_size = unrolling_iterable(range(size))
337 TYPE = get_rffi_int_type(size, signed)
338
339 @specialize.argtype(0)
340 def unpack_int_fastpath_maybe(fmtiter):
341 if fmtiter.bigendian != native_is_bigendian or not native_is_ieee754:
342 return False
343 try:
344 intvalue = unpack_fastpath(TYPE)(fmtiter)
345 except CannotRead:
346 return False
347 if not signed and size < native_int_size:
348 intvalue = rarithmetic.intmask(intvalue)
349 intvalue = inttype(intvalue)
350 fmtiter.appendobj(intvalue)
351 return True
352
353 @specialize.argtype(0)
354 def unpack_int(fmtiter):
355 if unpack_int_fastpath_maybe(fmtiter):
356 return
357 # slow path
358 if not ALLOW_SLOWPATH:
359 # we enter here only on some tests
360 raise ValueError("fastpath not taken :(")
361 intvalue = inttype(0)
362 s = fmtiter.read(size)
363 idx = 0
364 if fmtiter.bigendian:
365 for i in unroll_range_size:
366 x = ord(s[idx])
367 if signed and i == 0 and x >= 128:
368 x -= 256
369 intvalue <<= 8
370 intvalue |= inttype(x)
371 idx += 1
372 else:
373 for i in unroll_range_size:
374 x = ord(s[idx])
375 if signed and i == size - 1 and x >= 128:
376 x -= 256
377 intvalue |= inttype(x) << (8*i)
378 idx += 1
379 fmtiter.appendobj(intvalue)
380
381 _memo[size, signed] = unpack_int
382 return unpack_int
383
384 # ____________________________________________________________
385
386 standard_fmttable = {
387 'x':{ 'size' : 1, 'pack' : pack_pad, 'unpack' : unpack_pad,
388 'needcount' : True },
389 'c':{ 'size' : 1, 'pack' : pack_char, 'unpack' : unpack_char},
390 's':{ 'size' : 1, 'pack' : pack_string, 'unpack' : unpack_string,
391 'needcount' : True },
392 'p':{ 'size' : 1, 'pack' : pack_pascal, 'unpack' : unpack_pascal,
393 'needcount' : True },
394 'e':{ 'size' : 2, 'pack' : pack_halffloat,
395 'unpack' : unpack_halffloat},
396 'f':{ 'size' : 4, 'pack' : make_float_packer(rffi.FLOAT),
397 'unpack' : unpack_float},
398 'd':{ 'size' : 8, 'pack' : make_float_packer(rffi.DOUBLE),
399 'unpack' : unpack_double},
400 '?':{ 'size' : 1, 'pack' : pack_bool, 'unpack' : unpack_bool},
401 }
402
403 for c, size in [('b', 1), ('h', 2), ('i', 4), ('l', 4), ('q', 8)]:
404 standard_fmttable[c] = {'size': size,
405 'pack': make_int_packer(size, True),
406 'unpack': make_int_unpacker(size, True)}
407 standard_fmttable[c.upper()] = {'size': size,
408 'pack': make_int_packer(size, False),
409 'unpack': make_int_unpacker(size, False)}