Debian Codegraph @

pypy/module/cpyext/bytesobject.py

raw symbols SCIP
1 from pypy.interpreter.error import oefmt
2 from rpython.rtyper.lltypesystem import rffi, lltype
3 from pypy.module.cpyext.api import (
4 cpython_api, cpython_struct, bootstrap_function, build_type_checkers_flags,
5 PyVarObjectFields, Py_ssize_t, CONST_STRING, CANNOT_FAIL, slot_function,
6 PyVarObject)
7 from pypy.module.cpyext.pyerrors import PyErr_BadArgument
8 from pypy.module.cpyext.pyobject import (
9 PyObject, PyObjectP, decref, make_ref, from_ref, track_reference,
10 make_typedescr, get_typedescr, as_pyobj, get_w_obj_and_decref,
11 pyobj_has_w_obj)
12 from pypy.objspace.std.bytesobject import W_BytesObject, _convert_from_buffer_or_iterable
13
14 ##
15 ## Implementation of PyBytesObject
16 ## ================================
17 ##
18 ## PyBytesObject has its own ob_sval buffer, so we have two copies of a string;
19 ## one in the PyBytesObject returned from various C-API functions and another
20 ## in the corresponding RPython object.
21 ##
22 ## The following calls can create a PyBytesObject without a correspoinding
23 ## RPython object:
24 ##
25 ## PyBytes_FromStringAndSize(NULL, n) / PyString_FromStringAndSize(NULL, n)
26 ##
27 ## In the PyBytesObject returned, the ob_sval buffer may be modified as
28 ## long as the freshly allocated PyBytesObject is not "forced" via a call
29 ## to any of the more sophisticated C-API functions.
30 ##
31 ## Care has been taken in implementing the functions below, so that
32 ## if they are called with a non-forced PyBytesObject, they will not
33 ## unintentionally force the creation of a RPython object. As long as only these
34 ## are used, the ob_sval buffer is still modifiable:
35 ##
36 ## PyBytes_AsString / PyString_AsString
37 ## PyBytes_AS_STRING / PyString_AS_STRING
38 ## PyBytes_AsStringAndSize / PyString_AsStringAndSize
39 ## PyBytes_Size / PyString_Size
40 ## PyBytes_Resize / PyString_Resize
41 ## _PyBytes_Resize / _PyString_Resize (raises if called with a forced object)
42 ##
43 ## - There could be an (expensive!) check in from_ref() that the buffer still
44 ## corresponds to the pypy gc-managed string,
45 ##
46
47 PyBytesObjectStruct = lltype.ForwardReference()
48 PyBytesObject = lltype.Ptr(PyBytesObjectStruct)
49 PyBytesObjectFields = PyVarObjectFields + \
50 (("ob_shash", rffi.LONG), ("ob_sstate", rffi.INT), ("ob_sval", rffi.CArray(lltype.Char)))
51 cpython_struct("PyBytesObject", PyBytesObjectFields, PyBytesObjectStruct)
52
53 @bootstrap_function
54 def init_bytesobject(space):
55 "Type description of PyBytesObject"
56 make_typedescr(space.w_bytes.layout.typedef,
57 basestruct=PyBytesObject.TO,
58 attach=bytes_attach,
59 dealloc=bytes_dealloc,
60 realize=bytes_realize)
61
62 PyBytes_Check, PyBytes_CheckExact = build_type_checkers_flags("Bytes", "w_bytes")
63
64 def new_empty_str(space, length):
65 """
66 Allocate a PyBytesObject and its ob_sval, but without a corresponding
67 interpreter object. The ob_sval may be mutated, until bytes_realize() is
68 called. Refcount of the result is 1.
69 """
70 typedescr = get_typedescr(space.w_bytes.layout.typedef)
71 py_obj = typedescr.allocate(space, space.w_bytes, length)
72 py_str = rffi.cast(PyBytesObject, py_obj)
73 py_str.c_ob_shash = -1
74 py_str.c_ob_sstate = rffi.cast(rffi.INT, 0) # SSTATE_NOT_INTERNED
75 return py_str
76
77 def bytes_attach(space, py_obj, w_obj, w_userdata=None):
78 """
79 Copy RPython string object contents to a PyBytesObject. The
80 c_ob_sval must not be modified.
81 """
82 py_str = rffi.cast(PyBytesObject, py_obj)
83 s = space.bytes_w(w_obj)
84 len_s = len(s)
85 ob_size = rffi.cast(PyVarObject, py_str).c_ob_size
86 if ob_size < len_s:
87 raise oefmt(space.w_ValueError,
88 "bytes_attach called on object with ob_size %d but trying to store %d",
89 ob_size, len_s)
90 with rffi.scoped_nonmovingbuffer(s) as s_ptr:
91 const_s_ptr = rffi.cast(rffi.CONST_VOIDP, s_ptr)
92 rffi.c_memcpy(py_str.c_ob_sval, const_s_ptr, len_s)
93 py_str.c_ob_sval[len_s] = '\0'
94 # if py_obj has a tp_hash, this will try to call it, but the objects are
95 # not fully linked yet
96 #py_str.c_ob_shash = space.hash_w(w_obj)
97 py_str.c_ob_shash = space.hash_w(space.newbytes(s))
98 py_str.c_ob_sstate = rffi.cast(rffi.INT, 1) # SSTATE_INTERNED_MORTAL
99
100 def bytes_realize(space, py_obj):
101 """
102 Creates the string in the interpreter. The PyBytesObject ob_sval must not
103 be modified after this call.
104 """
105 py_str = rffi.cast(PyBytesObject, py_obj)
106 ob_size = rffi.cast(PyVarObject, py_str).c_ob_size
107 s = rffi.charpsize2str(py_str.c_ob_sval, ob_size)
108 w_type = from_ref(space, rffi.cast(PyObject, py_obj.c_ob_type))
109 w_obj = space.allocate_instance(W_BytesObject, w_type)
110 w_obj.__init__(s)
111 # if py_obj has a tp_hash, this will try to call it but the object is
112 # not realized yet
113 py_str.c_ob_shash = space.hash_w(space.newbytes(s))
114 py_str.c_ob_sstate = rffi.cast(rffi.INT, 1) # SSTATE_INTERNED_MORTAL
115 track_reference(space, py_obj, w_obj)
116 return w_obj
117
118 @slot_function([PyObject], lltype.Void)
119 def bytes_dealloc(space, py_obj):
120 """Frees allocated PyBytesObject resources.
121 """
122 from pypy.module.cpyext.object import _dealloc
123 _dealloc(space, py_obj)
124
125 #_______________________________________________________________________
126
127 @cpython_api([CONST_STRING, Py_ssize_t], PyObject, result_is_ll=True)
128 def PyBytes_FromStringAndSize(space, char_p, length):
129 if char_p:
130 s = rffi.charpsize2str(char_p, length)
131 return make_ref(space, space.newbytes(s))
132 else:
133 return rffi.cast(PyObject, new_empty_str(space, length))
134
135 @cpython_api([CONST_STRING], PyObject)
136 def PyBytes_FromString(space, char_p):
137 s = rffi.charp2str(char_p)
138 return space.newbytes(s)
139
140 @cpython_api([PyObject], rffi.CCHARP, error=0)
141 def PyBytes_AsString(space, ref):
142 return _PyBytes_AsString(space, ref)
143
144 def _PyBytes_AsString(space, ref):
145 if from_ref(space, rffi.cast(PyObject, ref.c_ob_type)) is space.w_bytes:
146 pass # typecheck returned "ok" without forcing 'ref' at all
147 elif not PyBytes_Check(space, ref): # otherwise, use the alternate way
148 raise oefmt(space.w_TypeError,
149 "expected bytes, %T found", from_ref(space, ref))
150 ref_str = rffi.cast(PyBytesObject, ref)
151 return ref_str.c_ob_sval
152
153 @cpython_api([rffi.VOIDP], rffi.CCHARP, error=0)
154 def PyBytes_AS_STRING(space, void_ref):
155 ref = rffi.cast(PyObject, void_ref)
156 # if no w_str is associated with this ref,
157 # return the c-level ptr as RW
158 if not pyobj_has_w_obj(ref):
159 py_str = rffi.cast(PyBytesObject, ref)
160 return py_str.c_ob_sval
161 return _PyBytes_AsString(space, ref)
162
163 @cpython_api([PyObject, rffi.CCHARPP, rffi.CArrayPtr(Py_ssize_t)], rffi.INT_real, error=-1)
164 def PyBytes_AsStringAndSize(space, ref, data, length):
165 if not PyBytes_Check(space, ref):
166 raise oefmt(space.w_TypeError,
167 "expected bytes, %T found", from_ref(space, ref))
168 ref_str = rffi.cast(PyBytesObject, ref)
169 data[0] = ref_str.c_ob_sval
170 ob_size = rffi.cast(PyVarObject, ref_str).c_ob_size
171 if length:
172 length[0] = ob_size
173 else:
174 i = 0
175 while ref_str.c_ob_sval[i] != '\0':
176 i += 1
177 if i != ob_size:
178 raise oefmt(space.w_TypeError,
179 "expected string without null bytes")
180 return 0
181
182 @cpython_api([PyObject], Py_ssize_t, error=-1)
183 def PyBytes_Size(space, ref):
184 if from_ref(space, rffi.cast(PyObject, ref.c_ob_type)) is space.w_bytes:
185 ref = rffi.cast(PyVarObject, ref)
186 return ref.c_ob_size
187 else:
188 w_obj = from_ref(space, ref)
189 return space.len_w(w_obj)
190
191 @cpython_api([PyObjectP, Py_ssize_t], rffi.INT_real, error=-1)
192 def _PyBytes_Resize(space, ref, newsize):
193 """A way to resize a string object even though it is "immutable". Only use this to
194 build up a brand new string object; don't use this if the string may already be
195 known in other parts of the code. It is an error to call this function if the
196 refcount on the input string object is not one. Pass the address of an existing
197 string object as an lvalue (it may be written into), and the new size desired.
198 On success, *string holds the resized string object and 0 is returned;
199 the address in *string may differ from its input value. If the reallocation
200 fails, the original string object at *string is deallocated, *string is
201 set to NULL, a memory exception is set, and -1 is returned.
202 """
203 # XXX always create a new string so far
204 if pyobj_has_w_obj(ref[0]):
205 raise oefmt(space.w_SystemError,
206 "_PyBytes_Resize called on already created string")
207 py_str = rffi.cast(PyBytesObject, ref[0])
208 try:
209 py_newstr = new_empty_str(space, newsize)
210 except MemoryError:
211 decref(space, ref[0])
212 ref[0] = lltype.nullptr(PyObject.TO)
213 raise
214 to_cp = newsize
215 oldsize = rffi.cast(PyVarObject, py_str).c_ob_size
216 if oldsize < newsize:
217 to_cp = oldsize
218 for i in range(to_cp):
219 py_newstr.c_ob_sval[i] = py_str.c_ob_sval[i]
220 decref(space, ref[0])
221 ref[0] = rffi.cast(PyObject, py_newstr)
222 return 0
223
224 @cpython_api([PyObject, PyObject], rffi.INT, error=CANNOT_FAIL)
225 def _PyBytes_Eq(space, w_str1, w_str2):
226 return space.eq_w(w_str1, w_str2)
227
228 @cpython_api([PyObjectP, PyObject], lltype.Void, error=None)
229 def PyBytes_Concat(space, ref, w_newpart):
230 """Create a new string object in *string containing the contents of newpart
231 appended to string; the caller will own the new reference. The reference to
232 the old value of string will be stolen. If the new string cannot be created,
233 the old reference to string will still be discarded and the value of
234 *string will be set to NULL; the appropriate exception will be set."""
235
236 old = ref[0]
237 if not old:
238 return
239
240 ref[0] = lltype.nullptr(PyObject.TO)
241 w_str = get_w_obj_and_decref(space, old)
242 if w_newpart is not None and PyBytes_Check(space, old):
243 # XXX: should use buffer protocol
244 w_newstr = space.add(w_str, w_newpart)
245 ref[0] = make_ref(space, w_newstr)
246
247 @cpython_api([PyObjectP, PyObject], lltype.Void, error=None)
248 def PyBytes_ConcatAndDel(space, ref, newpart):
249 """Create a new string object in *string containing the contents of newpart
250 appended to string. This version decrements the reference count of newpart."""
251 try:
252 PyBytes_Concat(space, ref, newpart)
253 finally:
254 decref(space, newpart)
255
256 @cpython_api([PyObject, PyObject], PyObject)
257 def _PyBytes_Join(space, w_sep, w_seq):
258 return space.call_method(w_sep, 'join', w_seq)
259
260 @cpython_api([PyObject], PyObject)
261 def PyBytes_FromObject(space, w_obj):
262 """Return the bytes representation of object obj that implements
263 the buffer protocol."""
264 if space.is_w(space.type(w_obj), space.w_bytes):
265 return w_obj
266 if space.isinstance_w(w_obj, space.w_bytes):
267 return space.newbytes(space.bytes_w(w_obj))
268 return space.newbytes(_convert_from_buffer_or_iterable(space, w_obj))