Debian Codegraph @

rpython/rlib/buffer.py

raw symbols SCIP
1 """
2 Buffer protocol support.
3 """
4 from rpython.rtyper.lltypesystem import lltype, llmemory, rffi
5 from rpython.rtyper.lltypesystem.lloperation import llop
6 from rpython.rtyper.lltypesystem.rstr import STR, copy_string_to_raw
7 from rpython.rtyper.lltypesystem.rlist import LIST_OF
8 from rpython.rtyper.annlowlevel import llstr
9 from rpython.rlib.objectmodel import specialize, we_are_translated
10 from rpython.rlib import jit, rgc
11 from rpython.rlib.rgc import (resizable_list_supporting_raw_ptr,
12 nonmoving_raw_ptr_for_resizable_list,
13 ll_for_resizable_list)
14 from rpython.rlib.signature import signature
15 from rpython.rlib import types
16 from rpython.rlib import rawstorage
17
18 ALLOW_UNALIGNED_ACCESS = rawstorage.misaligned_is_fine
19
20 @specialize.ll()
21 def is_alignment_correct(TYPE, index):
22 if ALLOW_UNALIGNED_ACCESS:
23 return True
24 try:
25 rawstorage._check_alignment(TYPE, index)
26 except rawstorage.AlignmentError:
27 return False
28 else:
29 return True
30
31
32 class CannotRead(Exception):
33 """
34 Exception raised by Buffer.typed_read in case it is not possible to
35 accomplish the request. This might be because it is not supported by the
36 specific type of buffer, or because of alignment issues.
37 """
38
39 class CannotWrite(Exception):
40 """
41 Raised by Buffer.typed_write in case it is not possible to accomplish the
42 request
43 """
44
45 class Buffer(object):
46 """
47 Base class for buffers of bytes.
48
49 Most probably, you do NOT want to use this as a lone base class, but
50 either inherit from RawBuffer or GCBuffer, so that you automatically get
51 the proper implementation of typed_read and typed_write.
52 """
53 _attrs_ = ['readonly']
54 _immutable_ = True
55
56 def getlength(self):
57 """Return the size in bytes."""
58 raise NotImplementedError
59
60 def __len__(self):
61 res = self.getlength()
62 assert res >= 0
63 return res
64
65 def as_str(self):
66 "Returns an interp-level string with the whole content of the buffer."
67 # May be overridden.
68 return self.getslice(0, 1, self.getlength())
69
70 def getitem(self, index):
71 "Returns the index'th character in the buffer."
72 raise NotImplementedError # Must be overriden. No bounds checks.
73
74 def __getitem__(self, i):
75 return self.getitem(i)
76
77 def getslice(self, start, step, size):
78 # May be overridden. No bounds checks.
79 lst = ['\x00'] * size
80 for i in range(size):
81 lst[i] = self.getitem(start)
82 start += step
83 return ''.join(lst)
84
85 @signature(types.any(), types.int(), types.int(), returns=types.str())
86 def __getslice__(self, start, stop):
87 return self.getslice(start, 1, min(stop, self.getlength()) - start)
88
89 def setitem(self, index, char):
90 "Write a character into the buffer."
91 raise NotImplementedError # Must be overriden. No bounds checks.
92
93 def __setitem__(self, i, char):
94 return self.setitem(i, char)
95
96 def setslice(self, start, string):
97 # May be overridden. No bounds checks.
98 for i in range(len(string)):
99 self.setitem(start + i, string[i])
100
101 @jit.look_inside_iff(lambda self, index, count:
102 jit.isconstant(count) and count <= 8)
103 def setzeros(self, index, count):
104 for i in range(index, index + count):
105 self.setitem(i, '\x00')
106
107 @specialize.ll_and_arg(1)
108 def typed_read(self, TP, byte_offset):
109 """
110 Read the value of type TP starting at byte_offset. No bounds checks
111 """
112 raise CannotRead
113
114 @specialize.ll_and_arg(1)
115 def typed_write(self, TP, byte_offset, value):
116 """
117 Write the value of type TP at byte_offset. No bounds checks
118 """
119 raise CannotWrite
120
121 def get_raw_address(self):
122 msg = "cannot take the raw address of this buffer"
123 if not we_are_translated():
124 msg += " '%s'" % (self,)
125 raise ValueError(msg)
126
127
128 class RawBuffer(Buffer):
129 """
130 A buffer which is backed by a raw, non-movable memory area. It implementes
131 typed_read and typed_write in terms of get_raw_address(), llop.raw_load,
132 llop.raw_store.
133
134 NOTE: this assumes that get_raw_address() is cheap. Do not use this as a
135 base class if get_raw_address() is potentially costly, like for example if
136 you call rgc.nonmoving_raw_ptr_for_resizable_list
137 """
138 _immutable_ = True
139
140 @specialize.ll_and_arg(1)
141 def typed_read(self, TP, byte_offset):
142 """
143 Read the value of type TP starting at byte_offset. No bounds checks
144 """
145 if not is_alignment_correct(TP, byte_offset):
146 raise CannotRead
147 ptr = self.get_raw_address()
148 return llop.raw_load(TP, ptr, byte_offset)
149
150 @specialize.ll_and_arg(1)
151 def typed_write(self, TP, byte_offset, value):
152 """
153 Write the value of type TP at byte_offset. No bounds checks
154 """
155 if self.readonly or not is_alignment_correct(TP, byte_offset):
156 raise CannotWrite
157 ptr = self.get_raw_address()
158 value = lltype.cast_primitive(TP, value)
159 return llop.raw_store(lltype.Void, ptr, byte_offset, value)
160
161
162 class LLBuffer(RawBuffer):
163 _immutable_ = True
164
165 def __init__(self, raw_cdata, size):
166 self.raw_cdata = raw_cdata
167 self.size = size
168 self.readonly = False
169
170 def getlength(self):
171 return self.size
172
173 def getitem(self, index):
174 return self.raw_cdata[index]
175
176 def setitem(self, index, char):
177 self.raw_cdata[index] = char
178
179 def get_raw_address(self):
180 return self.raw_cdata
181
182 def getslice(self, start, step, size):
183 if step == 1:
184 return rffi.charpsize2str(rffi.ptradd(self.raw_cdata, start), size)
185 return RawBuffer.getslice(self, start, step, size)
186
187 def setslice(self, start, string):
188 raw_cdata = rffi.ptradd(self.raw_cdata, start)
189 copy_string_to_raw(llstr(string), raw_cdata, 0, len(string))
190
191
192 class RawByteBuffer(RawBuffer):
193 _immutable_ = True
194
195 def __init__(self, length):
196 self._length = length
197 self._buf = lltype.malloc(rffi.CCHARP.TO, length, flavor='raw', zero=True)
198 rgc.add_memory_pressure(length)
199 self.readonly = False
200
201 def getlength(self):
202 return self._length
203
204 def getitem(self, index):
205 return self._buf[index]
206
207 def getslice(self, start, step, size):
208 if step == 1:
209 return rffi.charpsize2str(rffi.ptradd(self._buf, start), size)
210 return Buffer.getslice(self, start, step, size)
211
212 def setitem(self, index, char):
213 self._buf[index] = char
214
215 def get_raw_address(self):
216 return self._buf
217
218 def __del__(self):
219 lltype.free(self._buf, flavor='raw')
220 self._buf = lltype.nullptr(rffi.CCHARP.TO)
221
222
223 class GCBuffer(Buffer):
224 """
225 Base class for a buffer which is backed by a GC-managed memory area. You
226 MUST also decorate the class with @GCBuffer.decorate: it implements
227 typed_read and typed_write in terms of llop.gc_load_indexed and
228 llop.gc_store_indexed.
229 """
230 _attrs_ = ['readonly', 'value']
231 _immutable_ = True
232
233 @staticmethod
234 def decorate(targetcls):
235 """
236 Create and attach specialized versions of typed_{read,write}. We need to
237 do this becase the JIT codewriters mandates that base_ofs is an
238 RPython constant.
239 """
240 if targetcls.__bases__ != (GCBuffer,):
241 raise ValueError("@GCBuffer.decorate should be used only on "
242 "GCBuffer subclasses")
243
244 base_ofs = targetcls._get_gc_data_offset()
245 scale_factor = llmemory.sizeof(lltype.Char)
246
247 @specialize.ll_and_arg(1)
248 def typed_read(self, TP, byte_offset):
249 if not is_alignment_correct(TP, byte_offset):
250 raise CannotRead
251 lldata = self._get_gc_data()
252 byte_offset += self._get_gc_data_extra_offset()
253 return llop.gc_load_indexed(TP, lldata, byte_offset,
254 scale_factor, base_ofs)
255
256 @specialize.ll_and_arg(1)
257 def typed_write(self, TP, byte_offset, value):
258 if self.readonly or not is_alignment_correct(TP, byte_offset):
259 raise CannotWrite
260 lldata = self._get_gc_data()
261 byte_offset += self._get_gc_data_extra_offset()
262 value = lltype.cast_primitive(TP, value)
263 return llop.gc_store_indexed(lltype.Void, lldata, byte_offset, value,
264 scale_factor, base_ofs)
265
266 targetcls.typed_read = typed_read
267 targetcls.typed_write = typed_write
268 return targetcls
269
270 @staticmethod
271 def _get_gc_data_offset(self):
272 raise NotImplementedError
273
274 def _get_gc_data_extra_offset(self):
275 return 0
276
277 def _get_gc_data(self):
278 raise NotImplementedError
279
280 @specialize.ll_and_arg(1)
281 def typed_read(self, TP, byte_offset):
282 raise NotImplementedError("You MUST decorate this class with "
283 "@GCBuffer.decorate")
284
285 @specialize.ll_and_arg(1)
286 def typed_write(self, TP, byte_offset, value):
287 raise NotImplementedError("You MUST decorate this class with "
288 "@GCBuffer.decorate")
289
290
291 def get_gc_data_for_list_of_chars(data):
292 ll_data = ll_for_resizable_list(data)
293 ll_items = ll_data.items
294 return lltype.cast_opaque_ptr(llmemory.GCREF, ll_items)
295
296 def get_gc_data_offset_for_list_of_chars():
297 LIST = LIST_OF(lltype.Char)
298 return llmemory.itemoffsetof(LIST.items.TO, 0)
299
300
301 @GCBuffer.decorate
302 class ByteBuffer(GCBuffer):
303 _immutable_ = True
304
305 def __init__(self, n):
306 self.data = resizable_list_supporting_raw_ptr(['\0'] * n)
307 self.readonly = False
308
309 def getlength(self):
310 return len(self.data)
311
312 def getitem(self, index):
313 return self.data[index]
314
315 def setitem(self, index, char):
316 self.data[index] = char
317
318 def getslice(self, start, step, size):
319 if step == 1:
320 assert start >= 0
321 assert size >= 0
322 if start == 0 and size == len(self.data):
323 return "".join(self.data)
324 return "".join(self.data[start:start + size])
325 return Buffer.getslice(self, start, step, size)
326
327 def get_raw_address(self):
328 return nonmoving_raw_ptr_for_resizable_list(self.data)
329
330 def _get_gc_data(self):
331 return get_gc_data_for_list_of_chars(self.data)
332
333 @staticmethod
334 def _get_gc_data_offset():
335 return get_gc_data_offset_for_list_of_chars()
336
337 def setslice(self, start, string):
338 # this could maybe be done with a memcopy, but at least make sure there
339 # is no virtual method call in the loop here!
340 data = self.data
341 for i in range(len(string)):
342 data[start + i] = string[i]
343
344 @GCBuffer.decorate
345 class StringBuffer(GCBuffer):
346 _attrs_ = ['readonly', 'value']
347 _immutable_ = True
348
349 def __init__(self, value):
350 assert value is not None
351 self.value = value
352 self.readonly = 1
353
354 def getlength(self):
355 return len(self.value)
356
357 def as_str(self):
358 return self.value
359
360 def getitem(self, index):
361 return self.value[index]
362
363 def getslice(self, start, step, size):
364 if size == 0:
365 return ""
366 if step == 1:
367 assert start >= 0
368 assert size >= 0
369 if start == 0 and size == len(self.value):
370 return self.value
371 return self.value[start:start + size]
372 return Buffer.getslice(self, start, step, size)
373
374 def get_raw_address(self):
375 from rpython.rtyper.lltypesystem import rffi
376 # may still raise ValueError on some GCs
377 return rffi.get_raw_address_of_string(self.value)
378
379 @staticmethod
380 def _get_gc_data_offset():
381 return (llmemory.offsetof(STR, 'chars') +
382 llmemory.itemoffsetof(STR.chars, 0))
383
384 def _get_gc_data(self):
385 lls = llstr(self.value)
386 return lltype.cast_opaque_ptr(llmemory.GCREF, lls)
387
388
389 class SubBuffer(Buffer):
390 _attrs_ = ['buffer', 'offset', 'size', 'readonly']
391 _immutable_ = True
392
393 @signature(types.any(), types.instance(Buffer), types.int(), types.int(),
394 returns=types.none())
395 def __init__(self, buffer, offset, size):
396 self.readonly = buffer.readonly
397 if isinstance(buffer, SubBuffer): # don't nest them
398 # we want a view (offset, size) over a view
399 # (buffer.offset, buffer.size) over buffer.buffer.
400 # Note that either '.size' can be -1 to mean 'up to the end'.
401 at_most = buffer.getlength() - offset
402 if size > at_most or size < 0:
403 if at_most < 0:
404 at_most = 0
405 size = at_most
406 offset += buffer.offset
407 buffer = buffer.buffer
408 #
409 self.buffer = buffer
410 self.offset = offset
411 self.size = size
412
413 def getlength(self):
414 at_most = self.buffer.getlength() - self.offset
415 if 0 <= self.size <= at_most:
416 return self.size
417 elif at_most >= 0:
418 return at_most
419 else:
420 return 0
421
422 def getitem(self, index):
423 return self.buffer.getitem(self.offset + index)
424
425 def getslice(self, start, step, size):
426 if size == 0:
427 # otherwise, adding self.offset might make them out of bounds
428 return ''
429 return self.buffer.getslice(self.offset + start, step, size)
430
431 def setitem(self, index, char):
432 self.buffer.setitem(self.offset + index, char)
433
434 def setslice(self, start, string):
435 if len(string) == 0:
436 # otherwise, adding self.offset might make 'start' out of bounds
437 return
438 self.buffer.setslice(self.offset + start, string)
439
440 def get_raw_address(self):
441 from rpython.rtyper.lltypesystem import rffi
442 ptr = self.buffer.get_raw_address()
443 return rffi.ptradd(ptr, self.offset)
444
445 @specialize.ll_and_arg(1)
446 def typed_read(self, TP, byte_offset):
447 return self.buffer.typed_read(TP, byte_offset + self.offset)
448
449 @specialize.ll_and_arg(1)
450 def typed_write(self, TP, byte_offset, value):
451 return self.buffer.typed_write(TP, byte_offset + self.offset, value)