Debian Codegraph @

rpython/rtyper/lltypesystem/rbytearray.py

raw symbols SCIP
1
2 from rpython.rtyper.rbytearray import AbstractByteArrayRepr
3 from rpython.rtyper.lltypesystem import lltype, rstr
4 from rpython.rtyper.debug import ll_assert
5
6 BYTEARRAY = lltype.GcForwardReference()
7
8 def mallocbytearray(size):
9 return lltype.malloc(BYTEARRAY, size)
10
11 _, _, copy_bytearray_contents, _ = rstr._new_copy_contents_fun(BYTEARRAY, BYTEARRAY,
12 lltype.Char,
13 'bytearray')
14 _, _, copy_bytearray_contents_from_str, _ = rstr._new_copy_contents_fun(rstr.STR,
15 BYTEARRAY,
16 lltype.Char,
17 'bytearray_from_str')
18
19 def _empty_bytearray():
20 return empty
21
22 BYTEARRAY.become(lltype.GcStruct('rpy_bytearray',
23 ('chars', lltype.Array(lltype.Char)), adtmeths={
24 'malloc' : lltype.staticAdtMethod(mallocbytearray),
25 'copy_contents' : lltype.staticAdtMethod(copy_bytearray_contents),
26 'copy_contents_from_str': lltype.staticAdtMethod(
27 copy_bytearray_contents_from_str),
28 'length': rstr.LLHelpers.ll_length,
29 'empty': lltype.staticAdtMethod(_empty_bytearray),
30 }))
31
32 empty = lltype.malloc(BYTEARRAY, 0, immortal=True)
33
34 class LLHelpers(rstr.LLHelpers):
35 @classmethod
36 def ll_strsetitem(cls, s, i, item):
37 if i < 0:
38 i += s.length()
39 cls.ll_strsetitem_nonneg(s, i, item)
40
41 @staticmethod
42 def ll_strsetitem_nonneg(s, i, item):
43 chars = s.chars
44 ll_assert(i >= 0, "negative str getitem index")
45 ll_assert(i < len(chars), "str getitem index out of bound")
46 chars[i] = chr(item)
47
48 @staticmethod
49 def ll_stritem_nonneg(s, i):
50 return ord(rstr.LLHelpers.ll_stritem_nonneg(s, i))
51
52 class ByteArrayRepr(AbstractByteArrayRepr):
53 lowleveltype = lltype.Ptr(BYTEARRAY)
54
55 def __init__(self, *args):
56 AbstractByteArrayRepr.__init__(self, *args)
57 self.ll = LLHelpers
58 self.repr = self
59
60 def convert_const(self, value):
61 if value is None:
62 return lltype.nullptr(BYTEARRAY)
63 p = lltype.malloc(BYTEARRAY, len(value))
64 for i, c in enumerate(value):
65 p.chars[i] = chr(c)
66 return p
67
68 def ll_str(self, ll_b):
69 from rpython.rtyper.lltypesystem.rstr import mallocstr, STR
70 if ll_b:
71 lgt = ll_b.length()
72 ll_s = mallocstr(lgt)
73 for i in range(lgt):
74 ll_s.chars[i] = ll_b.chars[i]
75 return ll_s
76 else:
77 return lltype.nullptr(STR)
78
79 bytearray_repr = ByteArrayRepr()
80
81 def hlbytearray(ll_b):
82 b = bytearray()
83 for i in range(ll_b.length()):
84 b.append(ll_b.chars[i])
85 return b