Debian Codegraph @

rpython/rlib/mutbuffer.py

raw symbols SCIP
1 from rpython.rtyper.lltypesystem import lltype, llmemory
2 from rpython.rtyper.lltypesystem.lloperation import llop
3 from rpython.rtyper.lltypesystem.rstr import STR, mallocstr
4 from rpython.rtyper.annlowlevel import llstr, hlstr
5 from rpython.rlib.objectmodel import specialize
6 from rpython.rlib.buffer import GCBuffer
7 from rpython.rlib import jit
8
9 @GCBuffer.decorate
10 class MutableStringBuffer(GCBuffer):
11 """
12 A writeable buffer to incrementally fill a string of a fixed size.
13
14 You can fill the string by calling setitem, setslice and typed_write, and
15 get the result by calling finish().
16
17 After you call finish(), you can no longer modify the buffer. There is no
18 check, you will probably get a segfault after translation.
19
20 You can call finish() only once.
21 """
22 _attrs_ = ['readonly', 'll_val', 'size']
23 _immutable_ = True
24
25 def __init__(self, size):
26 self.readonly = False
27 self.size = size
28 self.ll_val = mallocstr(size)
29
30 def getlength(self):
31 return self.size
32
33 def finish(self):
34 if not self.ll_val:
35 raise ValueError("Cannot call finish() twice")
36 result = hlstr(self.ll_val)
37 self.ll_val = lltype.nullptr(STR)
38 self.readonly = True
39 return result
40
41 def as_str(self):
42 raise ValueError('as_str() is not supported. Use finish() instead')
43
44 def _hlstr(self):
45 assert not we_are_translated() # debug only
46 return hlstr(self.ll_val)
47
48 def setitem(self, index, char):
49 self.ll_val.chars[index] = char
50
51 @staticmethod
52 def _get_gc_data_offset():
53 return (llmemory.offsetof(STR, 'chars') +
54 llmemory.itemoffsetof(STR.chars, 0))
55
56 def _get_gc_data(self):
57 return lltype.cast_opaque_ptr(llmemory.GCREF, self.ll_val)