Debian Codegraph @

pypy/module/cpyext/unicodeobject.py

raw symbols SCIP
1 from rpython.rtyper.lltypesystem import rffi, lltype
2 from rpython.rlib import rstring
3 from rpython.rlib.rarithmetic import widen, r_uint, r_uint32, intmask
4 from rpython.rlib import rstring, rutf8
5 from rpython.tool.sourcetools import func_renamer
6
7 from pypy.interpreter.error import OperationError, oefmt
8 from pypy.interpreter.buffer import BufferInterfaceNotFound
9 from pypy.interpreter.unicodehelper import (
10 wcharpsize2utf8, str_decode_utf_16_helper, str_decode_utf_32_helper,
11 unicode_encode_decimal, utf8_encode_utf_16_helper, BYTEORDER,
12 utf8_encode_utf_32_helper, str_decode_latin_1, utf8_encode_latin_1,
13 utf8_encode_raw_unicode_escape, str_decode_raw_unicode_escape)
14 from pypy.objspace.std.unicodeobject import unicodedb
15 from pypy.module.cpyext.api import (
16 CANNOT_FAIL, Py_ssize_t, cpython_api,
17 bootstrap_function, CONST_STRING, INTP_real, Py_TPFLAGS_UNICODE_SUBCLASS,
18 CONST_WSTRING, Py_CLEANUP_SUPPORTED, slot_function, cts, parse_dir,
19 PyTypeObjectPtr, PyVarObject, PY_SSIZE_T_MAX)
20 from pypy.module.cpyext.pyerrors import PyErr_BadArgument, PyErr_BadInternalCall
21 from pypy.module.cpyext.pyobject import (
22 PyObject, PyObjectP, decref, make_ref, from_ref, track_reference,
23 make_typedescr, get_typedescr, as_pyobj, pyobj_has_w_obj, BaseCpyTypedescr,
24 incref, decref)
25 from pypy.module.cpyext.bytesobject import PyBytes_Check, PyBytes_FromObject
26 from pypy.module.cpyext.pyfile import pyos_fspath
27 from pypy.module._codecs.interp_codecs import (
28 CodecState, latin_1_decode, utf_16_decode, utf_32_decode)
29 from pypy.module.cpyext.state import State
30 from pypy.objspace.std import unicodeobject
31 from rpython.rlib.debug import fatalerror
32 import sys
33
34 ## See comment in bytesobject.py.
35
36 cts.parse_header(parse_dir / 'cpyext_unicodeobject.h')
37 PyUnicodeObject = cts.gettype('PyUnicodeObject*')
38 Py_UNICODE = cts.gettype('Py_UNICODE')
39 Py_UCS4 = cts.gettype('Py_UCS4')
40 INT_realP = lltype.Ptr(lltype.Array(rffi.INT_real, hints={'nolength': True}))
41
42 @bootstrap_function
43 def init_unicodeobject(space):
44 make_typedescr(space.w_unicode.layout.typedef,
45 basestruct=PyUnicodeObject.TO,
46 attach=unicode_attach,
47 alloc=unicode_alloc,
48 dealloc=unicode_dealloc,
49 realize=unicode_realize)
50
51 # Buffer for the default encoding (used by PyUnicode_GetDefaultEncoding)
52 DEFAULT_ENCODING_SIZE = 100
53 default_encoding = lltype.malloc(rffi.CCHARP.TO, DEFAULT_ENCODING_SIZE,
54 flavor='raw', zero=True)
55
56 WCHAR_KIND = 0
57 _1BYTE_KIND = 1
58 _2BYTE_KIND = 2
59 _4BYTE_KIND = 4
60
61 kind_to_name = {
62 0: 'WCHAR_KIND',
63 1: '_1BYTE_KIND',
64 2: '_2BYTE_KIND',
65 4: '_4BYTE_KIND',
66 }
67
68 def pyunicode_check(ref):
69 return (widen(ref.c_ob_type.c_tp_flags) & Py_TPFLAGS_UNICODE_SUBCLASS) != 0
70
71 # Backward compatibility: in PyPy7.3.4 this function became a C macro. But
72 # since we do not change the API, we need to export this function from the
73 # dll/so. This requires giving the mangled name here and special casing it in
74 # mangle_name from api.py
75 @cts.decl("int PyPyUnicode_Check(void * obj)", error=CANNOT_FAIL)
76 def PyUnicode_Check(space, ref):
77 if not ref:
78 return False
79 ref = rffi.cast(PyObject, ref)
80 return pyunicode_check(ref)
81
82 # Backward compatibility: in PyPy7.3.4 this function became a C macro. But
83 # since we do not change the API, we need to also export this function from the
84 # dll/so. This requires giving the mangled name here and special casing it in
85 # mangle_name from api.py
86 @cts.decl("int PyPyUnicode_CheckExact(void * obj)", error=CANNOT_FAIL)
87 def PyUnicode_CheckExact(space, ref):
88 if not ref:
89 return False
90 w_obj = from_ref(space, rffi.cast(PyObject, ref))
91 w_obj_type = space.type(w_obj)
92 return space.is_w(w_obj_type, space.w_unicode)
93
94 def new_empty_unicode(space, length):
95 """
96 Allocate a PyUnicodeObject and its buffer, but without a corresponding
97 interpreter object. The buffer may be mutated, until unicode_realize() is
98 called. Refcount of the result is 1.
99 """
100 typedescr = get_typedescr(space.w_unicode.layout.typedef)
101 py_obj = typedescr.allocate(space, space.w_unicode, itemcount=length)
102
103 buflen = length + 1
104 set_wsize(py_obj, length)
105 set_wbuffer(py_obj,
106 lltype.malloc(
107 rffi.CWCHARP.TO, buflen, flavor='raw', zero=True,
108 add_memory_pressure=True))
109 return py_obj
110
111 def unicode_attach(space, py_obj, w_obj, w_userdata=None):
112 "Fills a newly allocated PyUnicodeObject with a unicode string"
113 value = space.utf8_w(w_obj)
114 length = space.len_w(w_obj)
115 set_wsize(py_obj, length)
116 set_wbuffer(py_obj, lltype.nullptr(rffi.CWCHARP.TO))
117 _readify(space, py_obj, value)
118
119 def unicode_realize(space, py_obj):
120 """
121 Creates the unicode in the interpreter. The PyUnicodeObject buffer must not
122 be modified after this call. Can raise in wcharpsize2utf8
123 """
124 if not get_wbuffer(py_obj):
125 data = cts.cast('char *', get_data(py_obj))
126 size = get_len(py_obj)
127 kind = get_kind(py_obj)
128 value = rffi.charpsize2str(data, size * kind)
129 state = space.fromcache(CodecState)
130 eh = state.decode_error_handler
131 w_value = space.newbytes(value)
132 if kind == _1BYTE_KIND:
133 s_utf8, lgt, _ = str_decode_latin_1(space, value, w_value, 'strict', True, eh)
134 elif kind == _2BYTE_KIND:
135 decoded = str_decode_utf_16_helper(space, value, w_value, 'strict', True, eh,
136 byteorder=BYTEORDER)
137 s_utf8, lgt = decoded[:2]
138 elif kind == _4BYTE_KIND:
139 decoded = str_decode_utf_32_helper(space, value, w_value, 'strict',
140 True, eh,
141 byteorder=BYTEORDER)
142 s_utf8, lgt = decoded[:2]
143 else:
144 assert False
145 else:
146 lgt = get_wsize(py_obj)
147 s_utf8 = wcharpsize2utf8(space, get_wbuffer(py_obj), lgt)
148
149 w_type = from_ref(space, rffi.cast(PyObject, py_obj.c_ob_type))
150 w_obj = space.allocate_instance(unicodeobject.W_UnicodeObject, w_type)
151 w_obj.__init__(s_utf8, lgt)
152 track_reference(space, py_obj, w_obj)
153 return w_obj
154
155 def unicode_alloc(typedescr, space, w_type, itemcount):
156 if not w_type is space.w_unicode:
157 # subclass, will not use compact format, so no need for extra space
158 return BaseCpyTypedescr.allocate(typedescr, space, w_type, 1)
159 # This could be optimized: PyUnicodeObject is 80 bytes, PyASCIIObject
160 # is 48. In any case, leave room for a NULL char. Also override the
161 # tp_itemsize since we use the compact form
162 return BaseCpyTypedescr.allocate(typedescr, space, w_type, itemcount + 1,
163 itemsize=1)
164
165 @slot_function([PyObject], lltype.Void)
166 def unicode_dealloc(space, py_obj):
167 if has_wbuffer_memory(py_obj):
168 lltype.free(get_wbuffer(py_obj), flavor="raw")
169 if has_utf8_memory(py_obj):
170 lltype.free(get_utf8(py_obj), flavor="raw")
171 from pypy.module.cpyext.object import _dealloc
172 _dealloc(space, py_obj)
173
174 def has_wbuffer_memory(py_obj):
175 ptr = get_wbuffer(py_obj)
176 if not ptr:
177 return False
178 elif not get_ready(py_obj):
179 return True
180 else:
181 return cts.cast('void *', ptr) != get_data(py_obj)
182
183 def get_compact_ascii(py_obj):
184 a = get_ascii(py_obj)
185 if not a:
186 return False
187 return True
188
189 def has_utf8_memory(py_obj):
190 if get_compact_ascii(py_obj):
191 return False
192 utf8 = get_utf8(py_obj)
193 return bool(utf8) and cts.cast('void *', utf8) != get_data(py_obj)
194
195 def get_len(py_obj):
196 py_obj = cts.cast('PyASCIIObject*', py_obj)
197 return py_obj.c_length
198
199 def set_len(py_obj, n):
200 py_obj = cts.cast('PyASCIIObject*', py_obj)
201 py_obj.c_length = n
202
203 def get_state(py_obj):
204 py_obj = cts.cast('PyASCIIObject*', py_obj)
205 return py_obj.c_state
206
207 def get_kind(py_obj):
208 return rffi.getintfield(get_state(py_obj), 'c_kind')
209
210 def set_kind(py_obj, value):
211 get_state(py_obj).c_kind = cts.cast('unsigned char', value)
212
213 def get_ascii(py_obj):
214 return rffi.getintfield(get_state(py_obj), 'c_ascii')
215
216 def set_ascii(py_obj, value):
217 get_state(py_obj).c_ascii = cts.cast('unsigned char', value)
218
219 def get_ready(py_obj):
220 return rffi.getintfield(get_state(py_obj), 'c_ready')
221
222 def set_ready(py_obj, value):
223 get_state(py_obj).c_ready = cts.cast('unsigned char', value)
224
225 def get_wbuffer(py_obj):
226 py_obj = cts.cast('PyASCIIObject*', py_obj)
227 return py_obj.c_wstr
228
229 def set_wbuffer(py_obj, wbuf):
230 py_obj = cts.cast('PyASCIIObject*', py_obj)
231 py_obj.c_wstr = wbuf
232
233 def get_utf8_len(py_obj):
234 py_obj = cts.cast('PyCompactUnicodeObject*', py_obj)
235 return py_obj.c_utf8_length
236
237 def set_utf8_len(py_obj, n):
238 py_obj = cts.cast('PyCompactUnicodeObject*', py_obj)
239 py_obj.c_utf8_length = n
240
241 def get_utf8(py_obj):
242 py_obj = cts.cast('PyCompactUnicodeObject*', py_obj)
243 return py_obj.c_utf8
244
245 def set_utf8(py_obj, buf):
246 py_obj = cts.cast('PyCompactUnicodeObject*', py_obj)
247 py_obj.c_utf8 = buf
248
249 def get_wsize(py_obj):
250 py_obj = cts.cast('PyCompactUnicodeObject*', py_obj)
251 return py_obj.c_wstr_length
252
253 def set_wsize(py_obj, value):
254 py_obj = cts.cast('PyCompactUnicodeObject*', py_obj)
255 py_obj.c_wstr_length = value
256
257 def get_data(py_obj):
258 if get_compact(py_obj):
259 if get_ascii(py_obj):
260 PyASCIIObject = cts.gettype('PyASCIIObject')
261 struct_size = rffi.sizeof(PyASCIIObject)
262 else:
263 PyCompactUnicodeObject = cts.gettype('PyCompactUnicodeObject')
264 struct_size = rffi.sizeof(PyCompactUnicodeObject)
265 data = rffi.ptradd(rffi.cast(rffi.CCHARP, py_obj), struct_size)
266 return cts.cast('void *', data)
267 py_obj = cts.cast('PyUnicodeObject*', py_obj)
268 return py_obj.c_data
269
270 def set_data_compact(py_obj, p_data, size):
271 if get_ascii(py_obj):
272 PyASCIIObject = cts.gettype('PyASCIIObject')
273 struct_size = rffi.sizeof(PyASCIIObject)
274 else:
275 PyCompactUnicodeObject = cts.gettype('PyCompactUnicodeObject')
276 struct_size = rffi.sizeof(PyCompactUnicodeObject)
277 data = rffi.ptradd(rffi.cast(rffi.CCHARP, py_obj), struct_size)
278 for i in range(size):
279 data[i] = p_data[i]
280 data[size] = '\x00'
281
282 def set_data(py_obj, p_data):
283 py_obj = cts.cast('PyUnicodeObject*', py_obj)
284 py_obj.c_data = p_data
285
286 def get_compact(py_obj):
287 return rffi.getintfield(get_state(py_obj), 'c_compact')
288
289 def set_compact(py_obj, value):
290 get_state(py_obj).c_compact = cts.cast('unsigned char', value)
291
292
293 @cpython_api([Py_UCS4], rffi.INT_real, error=CANNOT_FAIL)
294 def _PyUnicode_IsAlpha(space, ch):
295 """Return 1 or 0 depending on whether ch is an alphabetic character."""
296 ch = rffi.cast(lltype.Signed, ch)
297 if ch >= rutf8.MAXUNICODE:
298 return 0
299 return unicodedb.isalpha(ch)
300
301 @cpython_api([Py_UCS4], rffi.INT_real, error=CANNOT_FAIL)
302 def _PyUnicode_IsDecimalDigit(space, ch):
303 """Return 1 or 0 depending on whether ch is a decimal character."""
304 ch = rffi.cast(lltype.Signed, ch)
305 if ch >= rutf8.MAXUNICODE:
306 return 0
307 return unicodedb.isdecimal(ch)
308
309 @cpython_api([Py_UCS4], rffi.INT_real, error=CANNOT_FAIL)
310 def _PyUnicode_IsDigit(space, ch):
311 """Return 1 or 0 depending on whether ch is a digit character."""
312 ch = rffi.cast(lltype.Signed, ch)
313 if ch >= rutf8.MAXUNICODE:
314 return 0
315 return unicodedb.isdigit(ch)
316
317 @cpython_api([Py_UCS4], rffi.INT_real, error=CANNOT_FAIL)
318 def _PyUnicode_IsNumeric(space, ch):
319 """Return 1 or 0 depending on whether ch is a numeric character."""
320 ch = rffi.cast(lltype.Signed, ch)
321 if ch >= rutf8.MAXUNICODE:
322 return 0
323 return unicodedb.isnumeric(ch)
324
325 @cpython_api([Py_UCS4], rffi.INT_real, error=CANNOT_FAIL)
326 def _PyUnicode_IsLowercase(space, ch):
327 """Return 1 or 0 depending on whether ch is a lowercase character."""
328 ch = rffi.cast(lltype.Signed, ch)
329 if ch >= rutf8.MAXUNICODE:
330 return 0
331 return unicodedb.islower(ch)
332
333 @cpython_api([Py_UCS4], rffi.INT_real, error=CANNOT_FAIL)
334 def _PyUnicode_IsUppercase(space, ch):
335 """Return 1 or 0 depending on whether ch is an uppercase character."""
336 ch = rffi.cast(lltype.Signed, ch)
337 if ch >= rutf8.MAXUNICODE:
338 return 0
339 return unicodedb.isupper(ch)
340
341 @cpython_api([Py_UCS4], rffi.INT_real, error=CANNOT_FAIL)
342 def _PyUnicode_IsTitlecase(space, ch):
343 """Return 1 or 0 depending on whether ch is a titlecase character."""
344 ch = rffi.cast(lltype.Signed, ch)
345 if ch >= rutf8.MAXUNICODE:
346 return 0
347 return unicodedb.istitle(ch)
348
349 @cpython_api([Py_UCS4], rffi.INT_real, error=CANNOT_FAIL)
350 def _PyUnicode_IsPrintable(space, ch):
351 """Return 1 or 0 depending on whether ch is a printable character."""
352 ch = rffi.cast(lltype.Signed, ch)
353 if ch >= rutf8.MAXUNICODE:
354 return 0
355 return unicodedb.isprintable(ch)
356
357
358 @cpython_api([Py_UCS4], Py_UCS4, error=CANNOT_FAIL)
359 def _PyUnicode_ToLowercase(space, ch):
360 """Return the character ch converted to lower case."""
361 val = rffi.cast(lltype.Signed, ch)
362 if val >= rutf8.MAXUNICODE:
363 return ch
364 return r_uint32(unicodedb.tolower(val))
365
366 @cpython_api([Py_UCS4], Py_UCS4, error=CANNOT_FAIL)
367 def _PyUnicode_ToUppercase(space, ch):
368 """Return the character ch converted to upper case."""
369 val = rffi.cast(lltype.Signed, ch)
370 if val >= rutf8.MAXUNICODE:
371 return ch
372 return r_uint32(unicodedb.toupper(val))
373
374 @cpython_api([Py_UCS4], Py_UCS4, error=CANNOT_FAIL)
375 def _PyUnicode_ToTitlecase(space, ch):
376 """Return the character ch converted to title case."""
377 val = rffi.cast(lltype.Signed, ch)
378 if val >= rutf8.MAXUNICODE:
379 return ch
380 return r_uint32(unicodedb.totitle(val))
381
382 @cpython_api([Py_UCS4], rffi.INT_real, error=CANNOT_FAIL)
383 def _PyUnicode_ToDecimalDigit(space, ch):
384 """Return the character ch converted to a decimal positive integer. Return
385 -1 if this is not possible. This macro does not raise exceptions."""
386 val = rffi.cast(lltype.Signed, ch)
387 if val >= rutf8.MAXUNICODE:
388 return -1
389 try:
390 return unicodedb.decimal(val)
391 except KeyError:
392 return -1
393
394 @cpython_api([Py_UCS4], rffi.INT_real, error=CANNOT_FAIL)
395 def _PyUnicode_ToDigit(space, ch):
396 """Return the character ch converted to a single digit integer. Return -1 if
397 this is not possible. This macro does not raise exceptions."""
398 ch = rffi.cast(lltype.Signed, ch)
399 if ch >= rutf8.MAXUNICODE:
400 return -1
401 try:
402 return unicodedb.digit(ch)
403 except KeyError:
404 return -1
405
406 @cpython_api([], Py_UNICODE, error=CANNOT_FAIL)
407 def PyUnicode_GetMax(space):
408 """Get the maximum ordinal for a Unicode character."""
409 from rpython.rlib import runicode, rutf8
410 return runicode.UNICHR(rutf8.MAXUNICODE)
411
412 @cts.decl("int _PyUnicode_Ready(PyObject *unicode)", error=-1)
413 def _PyUnicode_Ready(space, py_obj):
414 # conversion from pyobj to space.w_unicode can fail,
415 # so create the rpython object here and not in the api wrapper
416 kind = get_kind(py_obj)
417 if kind == WCHAR_KIND:
418 w_obj = from_ref(space, rffi.cast(PyObject, py_obj))
419 else:
420 s = kind_to_name.get(kind, "INVALID")
421 raise oefmt(space.w_ValueError,
422 "converting %s PyUnicodeObject not supported yet", s)
423 return _readify(space, py_obj, space.utf8_w(w_obj))
424
425 def _readify(space, py_obj, value):
426 PyUnicode_Type = rffi.cast(cts.gettype('PyTypeObject*'),
427 make_ref(space, space.w_unicode))
428 maxchar = 0
429 for c in rutf8.Utf8StringIterator(value):
430 if c > maxchar:
431 maxchar = c
432 if maxchar > rutf8.MAXUNICODE:
433 raise oefmt(space.w_ValueError,
434 "Character U+%s is not in range [U+0000; U+10ffff]",
435 '%x' % maxchar)
436 use_compact = (py_obj.c_ob_type == PyUnicode_Type)
437 if maxchar < 256:
438 # Do this before the compact format overwrites the
439 # PyCompactUnicodeObject.c_wstr_length
440 alloc_len = get_wsize(py_obj)
441 if use_compact:
442 pyvarobj = rffi.cast(PyVarObject, py_obj)
443 itemcount = pyvarobj.c_ob_size
444 set_compact(py_obj, 1)
445 set_len(py_obj, alloc_len)
446 set_kind(py_obj, _1BYTE_KIND)
447 set_utf8(py_obj, cts.cast('char *', 0))
448 set_utf8_len(py_obj, 0)
449 if maxchar < 128:
450 set_ascii(py_obj, 1)
451 if use_compact:
452 set_data_compact(py_obj, value, len(value))
453 else:
454 ucs1_data = cts.cast('void *', rffi.str2charp(value))
455 set_data(py_obj, ucs1_data)
456 set_utf8(py_obj, cts.cast('char *', get_data(py_obj)))
457 set_utf8_len(py_obj, get_wsize(py_obj))
458 else:
459 set_ascii(py_obj, 0)
460 # re-encode as latin-1
461 w_value = space.newtext(value)
462 value = utf8_encode_latin_1(space, value, w_value, 'strict', None)
463 if use_compact:
464 set_data_compact(py_obj, value, len(value))
465 else:
466 ucs1_data = cts.cast('void *', rffi.str2charp(value))
467 set_data(py_obj, ucs1_data)
468 elif maxchar < 65536:
469 ucs2_data = cts.cast('void *', 0)
470 if rffi.sizeof(lltype.UniChar) == 2:
471 ucs2_data = cts.cast('void *', get_wbuffer(py_obj))
472 if not ucs2_data:
473 w_value = space.newtext(value)
474 ucs2_str = utf8_encode_utf_16_helper(
475 space, value, w_value, 'strict',
476 byteorder=BYTEORDER)
477 ucs2_data = cts.cast('void *', rffi.str2charp(ucs2_str))
478 if rffi.sizeof(lltype.UniChar) == 2:
479 set_wbuffer(py_obj, cts.cast('wchar_t *', ucs2_data))
480 set_data(py_obj, ucs2_data)
481 set_len(py_obj, get_wsize(py_obj))
482 set_kind(py_obj, _2BYTE_KIND)
483 set_utf8(py_obj, cts.cast('char *', 0))
484 set_utf8_len(py_obj, 0)
485 else:
486 ucs4_data = cts.cast('void *', 0)
487 if rffi.sizeof(lltype.UniChar) == 4:
488 ucs4_data = cts.cast('void *', get_wbuffer(py_obj))
489 if not ucs4_data:
490 w_value = space.newtext(value)
491 ucs4_str = utf8_encode_utf_32_helper(
492 space, value, w_value, 'strict',
493 byteorder=BYTEORDER)
494 ucs4_data = cts.cast('void *', rffi.str2charp(ucs4_str))
495 if rffi.sizeof(lltype.UniChar) == 4:
496 set_wbuffer(py_obj, cts.cast('wchar_t *', ucs4_data))
497 set_data(py_obj, ucs4_data)
498 set_len(py_obj, get_wsize(py_obj))
499 set_kind(py_obj, _4BYTE_KIND)
500 set_utf8(py_obj, cts.cast('char *', 0))
501 set_utf8_len(py_obj, 0)
502 set_ready(py_obj, 1)
503 return 0
504
505 @cts.decl("""PyObject* PyUnicode_FromKindAndData(
506 int kind, const void *buffer, Py_ssize_t size)""")
507 def PyUnicode_FromKindAndData(space, kind, data, size):
508 if size < 0:
509 raise oefmt(space.w_ValueError, "size must be positive")
510 data = cts.cast('char *', data)
511 kind = widen(kind)
512 if kind == _1BYTE_KIND:
513 value = rffi.charpsize2str(data, size)
514 w_res = latin_1_decode(space, value, w_final=space.w_False)
515 elif kind == _2BYTE_KIND:
516 value = rffi.charpsize2str(data, 2 * size)
517 w_res = utf_16_decode(space, value, errors='surrogatepass',
518 w_final=space.w_False)
519 elif kind == _4BYTE_KIND:
520 value = rffi.charpsize2str(data, 4 * size)
521 state = space.fromcache(CodecState)
522 eh = state.decode_error_handler
523 w_value = space.newbytes(value)
524 result, length, pos, _ = str_decode_utf_32_helper(space, value, w_value,
525 'surrogatpass', True, eh,
526 byteorder=BYTEORDER,
527 allow_surrogates=True)
528 return space.newutf8(result, length)
529 else:
530 raise oefmt(space.w_SystemError, "invalid kind")
531 return space.unpackiterable(w_res)[0]
532
533 @cts.decl("Py_UNICODE * PyUnicode_AsUnicodeAndSize(PyObject *unicode, Py_ssize_t *size)")
534 def PyUnicode_AsUnicodeAndSize(space, ref, psize):
535 """Return a read-only pointer to the Unicode object's internal Py_UNICODE
536 buffer, NULL if unicode is not a Unicode object."""
537 if not pyunicode_check(ref):
538 raise oefmt(space.w_TypeError, "expected unicode object")
539 ret = get_maybe_create_wbuffer(space, ref)
540 if psize:
541 psize[0] = get_len(ref)
542 return ret
543
544 def get_maybe_create_wbuffer(space, ref):
545 if not get_wbuffer(ref):
546 # compact ascii for instance
547 w_unicode = from_ref(space, rffi.cast(PyObject, ref))
548 u = space.utf8_w(w_unicode)
549 lgt = space.len_w(w_unicode)
550 if rffi.sizeof(lltype.UniChar) == 2:
551 # Handle surrogates
552 wbuf = rffi.utf82wcharp_ex(u, lgt)
553 else:
554 wbuf = rffi.utf82wcharp(u, lgt)
555 if lgt != get_len(ref):
556 raise oefmt(space.w_SystemError, "inconsistent length")
557 set_wbuffer(ref, wbuf)
558 if not get_compact_ascii(ref):
559 set_wsize(ref, lgt)
560 return get_wbuffer(ref)
561
562 @cts.decl("char * PyUnicode_AsUTF8AndSize(PyObject *unicode, Py_ssize_t *psize)")
563 def PyUnicode_AsUTF8AndSize(space, ref, psize):
564 if not pyunicode_check(ref):
565 # PyUnicode_Check failed
566 PyErr_BadArgument(space)
567 if not get_ready(ref):
568 res = _PyUnicode_Ready(space, ref)
569
570 if get_compact_ascii(ref):
571 if psize:
572 psize[0] = get_len(ref)
573 return cts.cast('char *', get_data(ref))
574 ret = get_utf8(ref)
575 if not ret:
576 # Happens the first time through for compact, non-ascii
577 # Copy unicode buffer
578 w_unicode = from_ref(space, ref)
579 w_encoded = unicodeobject.encode_object(space, w_unicode, "utf-8",
580 "strict")
581 s = space.bytes_w(w_encoded)
582 set_utf8(ref, rffi.str2charp(s))
583 set_utf8_len(ref, len(s))
584 ret = get_utf8(ref)
585 if psize:
586 psize[0] = get_utf8_len(ref)
587 return ret
588
589 @cts.decl("char * PyUnicode_AsUTF8(PyObject *unicode)")
590 def PyUnicode_AsUTF8(space, ref):
591 return PyUnicode_AsUTF8AndSize(space, ref, cts.cast('Py_ssize_t *', 0))
592
593 @cpython_api([PyObject, rffi.CWCHARP, Py_ssize_t], Py_ssize_t, error=-1)
594 def PyUnicode_AsWideChar(space, ref, buf, size):
595 """Copy the Unicode object contents into the wchar_t buffer w. At most
596 size wchar_t characters are copied (excluding a possibly trailing
597 0-termination character). Return the number of wchar_t characters
598 copied or -1 in case of an error. Note that the resulting wchar_t
599 string may or may not be 0-terminated. It is the responsibility of the caller
600 to make sure that the wchar_t string is 0-terminated in case this is
601 required by the application."""
602 c_buffer = get_maybe_create_wbuffer(space, ref)
603 c_length = get_len(ref)
604
605 # If possible, try to copy the 0-termination as well
606 if size > c_length:
607 size = c_length + 1
608
609 i = 0
610 while i < size:
611 buf[i] = c_buffer[i]
612 i += 1
613
614 if size > c_length:
615 return c_length
616 else:
617 return size
618
619 @cpython_api([], rffi.CCHARP, error=CANNOT_FAIL)
620 def PyUnicode_GetDefaultEncoding(space):
621 """Returns the currently active default encoding."""
622 if default_encoding[0] == '\x00':
623 encoding = unicodeobject.getdefaultencoding(space)
624 i = 0
625 while i < len(encoding) and i < DEFAULT_ENCODING_SIZE:
626 default_encoding[i] = encoding[i]
627 i += 1
628 return default_encoding
629
630 def _unicode_as_encoded_object(space, pyobj, llencoding, llerrors):
631 if not pyunicode_check(pyobj):
632 PyErr_BadArgument(space)
633
634 encoding = errors = None
635 if llencoding:
636 encoding = rffi.charp2str(llencoding)
637 if llerrors:
638 errors = rffi.charp2str(llerrors)
639 w_unicode = from_ref(space, pyobj)
640 return unicodeobject.encode_object(space, w_unicode, encoding, errors)
641
642 @cpython_api([PyObject, CONST_STRING, CONST_STRING], PyObject)
643 def PyUnicode_AsEncodedObject(space, pyobj, llencoding, llerrors):
644 """Encode a Unicode object and return the result as Python object.
645 encoding and errors have the same meaning as the parameters of the same name
646 in the Unicode encode() method. The codec to be used is looked up using
647 the Python codec registry. Return NULL if an exception was raised by the
648 codec."""
649 return _unicode_as_encoded_object(space, pyobj, llencoding, llerrors)
650
651 @cpython_api([PyObject, CONST_STRING, CONST_STRING], PyObject)
652 def PyUnicode_AsEncodedString(space, pyref, llencoding, llerrors):
653 """Encode a Unicode object and return the result as Python string object.
654 encoding and errors have the same meaning as the parameters of the same name
655 in the Unicode encode() method. The codec to be used is looked up using
656 the Python codec registry. Return NULL if an exception was raised by the
657 codec."""
658 w_str = _unicode_as_encoded_object(space, pyref, llencoding, llerrors)
659 if not PyBytes_Check(space, w_str):
660 raise oefmt(space.w_TypeError,
661 "encoder did not return a bytes object")
662 return w_str
663
664 @cpython_api([PyObject], PyObject)
665 def PyUnicode_AsUnicodeEscapeString(space, pyobj):
666 """Encode a Unicode object using Unicode-Escape and return the result as Python
667 string object. Error handling is "strict". Return NULL if an exception was
668 raised by the codec."""
669 if not pyunicode_check(pyobj):
670 PyErr_BadArgument(space)
671
672 w_unicode = from_ref(space, pyobj)
673 return unicodeobject.encode_object(space, w_unicode, 'unicode-escape', 'strict')
674
675 @cpython_api([CONST_WSTRING, Py_ssize_t], PyObject, result_is_ll=True)
676 def PyUnicode_FromUnicode(space, wchar_p, length):
677 """Create a legacy (non-compact) Unicode Object from the Py_UNICODE
678 buffer wchar_p of the given size. wchar_p may be NULL which causes the
679 contents to be undefined. It is the user's responsibility to fill in
680 the needed data. The buffer is copied into the data field of the
681 PyUnicodeObject. If the buffer is not NULL, the return value might be a
682 shared object. Therefore, modification of the resulting Unicode object
683 is only allowed when u is NULL."""
684 if length < 0:
685 length = 0
686 if wchar_p:
687 s = wcharpsize2utf8(space, wchar_p, length)
688 # XXX this is for windows, since wchar_p is in utf16 so length may not
689 # be codepoints. This could be pushed into the windows branch of
690 # wcharpsize2utf8
691 length = rutf8.codepoints_in_utf8(s)
692 return make_ref(space, space.newutf8(s, length))
693 else:
694 return new_empty_unicode(space, length)
695
696 @cpython_api([CONST_STRING, Py_ssize_t, CONST_STRING, CONST_STRING], PyObject)
697 def PyUnicode_Decode(space, s, size, encoding, errors):
698 """Create a Unicode object by decoding size bytes of the encoded string s.
699 encoding and errors have the same meaning as the parameters of the same name
700 in the unicode() built-in function. The codec to be used is looked up
701 using the Python codec registry. Return NULL if an exception was raised by
702 the codec."""
703 return _pyunicode_decode(space, rffi.charpsize2str(s, size),
704 encoding, errors)
705
706 def _pyunicode_decode(space, s, encoding, errors):
707 if encoding:
708 w_encoding = space.newtext(rffi.charp2str(encoding))
709 else:
710 # python 3.4 changed to this from defaultencoding
711 w_encoding = space.newtext('utf-8')
712 w_str = space.newbytes(s)
713 if errors:
714 w_errors = space.newtext(rffi.charp2str(errors))
715 else:
716 w_errors = None
717 return space.call_method(w_str, 'decode', w_encoding, w_errors)
718
719 @cpython_api([PyObject], PyObject)
720 def PyUnicode_FromObject(space, w_obj):
721 """Copy an instance of a Unicode subtype to a new true Unicode object if
722 necessary. If obj is already a true Unicode object (not a subtype), return
723 the reference with incremented refcount.
724
725 Objects other than Unicode or its subtypes will cause a TypeError.
726 """
727 return pyunicode_fromobject(space, w_obj)
728
729 def pyunicode_fromobject(space, w_obj):
730 if space.is_w(space.type(w_obj), space.w_unicode):
731 return w_obj
732 elif space.isinstance_w(w_obj, space.w_unicode):
733 return space.call_function(space.w_unicode, w_obj)
734 else:
735 raise oefmt(space.w_TypeError,
736 "Can't convert '%T' object to str implicitly", w_obj)
737
738 @cpython_api([PyObject, CONST_STRING, CONST_STRING], PyObject)
739 def PyUnicode_FromEncodedObject(space, w_obj, encoding, errors):
740 """Coerce an encoded object obj to an Unicode object and return a reference with
741 incremented refcount.
742
743 String and other char buffer compatible objects are decoded according to the
744 given encoding and using the error handling defined by errors. Both can be
745 NULL to have the interface use the default values (see the next section for
746 details).
747
748 All other objects, including Unicode objects, cause a TypeError to be
749 set."""
750 if space.isinstance_w(w_obj, space.w_bytes):
751 s = space.bytes_w(w_obj)
752 if not s:
753 return space.newtext('')
754 elif space.isinstance_w(w_obj, space.w_unicode):
755 raise oefmt(space.w_TypeError, "decoding str is not supported")
756 elif space.isinstance_w(w_obj, space.w_bytearray): # Python 2.x specific
757 raise oefmt(space.w_TypeError, "decoding bytearray is not supported")
758 else:
759 s = space.charbuf_w(w_obj)
760 return _pyunicode_decode(space, s, encoding, errors)
761
762
763 @cpython_api([PyObject, CONST_STRING], PyObject)
764 def PyUnicode_EncodeLocale(space, w_obj, errors):
765 from pypy.module._codecs.locale import utf8_encode_locale
766 if errors:
767 s = rffi.charp2str(errors)
768 else:
769 s = 'strict'
770 if not s in ('strict', 'surrogateescape'):
771 raise oefmt(space.w_ValueError, "only 'strict' and 'surrogateescape' "
772 "error handlers are supported, not '%s'", s)
773 utf8 = space.utf8_w(w_obj)
774 ulen = space.len_w(w_obj)
775 return space.newbytes(utf8_encode_locale(utf8, ulen, s))
776
777 @cpython_api([CONST_STRING, CONST_STRING], PyObject)
778 def PyUnicode_DecodeLocale(space, obj, errors):
779 from pypy.module._codecs.locale import str_decode_locale
780 if errors:
781 s = rffi.charp2str(errors)
782 else:
783 s = 'strict'
784 if not s in ('strict', 'surrogateescape'):
785 raise oefmt(space.w_ValueError, "only 'strict' and 'surrogateescape' "
786 "error handlers are supported, not '%s'", s)
787 utf8 = rffi.charp2str(obj)
788 return space.newtext(*str_decode_locale(utf8, s))
789
790 @cpython_api([CONST_STRING, Py_ssize_t, CONST_STRING], PyObject)
791 def PyUnicode_DecodeLocaleAndSize(space, obj, length, errors):
792 from pypy.module._codecs.locale import str_decode_locale
793 if errors:
794 s = rffi.charp2str(errors)
795 else:
796 s = 'strict'
797 if not s in ('strict', 'surrogateescape'):
798 raise oefmt(space.w_ValueError, "only 'strict' and 'surrogateescape' "
799 "error handlers are supported, not '%s'", s)
800 utf8 = rffi.charpsize2str(obj, length)
801 return space.newtext(*str_decode_locale(utf8, s))
802
803 @cpython_api([PyObject, PyObjectP], rffi.INT_real, error=0)
804 def PyUnicode_FSConverter(space, w_obj, result):
805 """ParseTuple converter: encode str objects to bytes using
806 PyUnicode_EncodeFSDefault(); bytes objects are output as-is.
807 result must be a PyBytesObject* which must be released when it is
808 no longer used.
809 """
810 if not w_obj:
811 # Implement ParseTuple cleanup support
812 decref(space, result[0])
813 return 1
814 w_path = pyos_fspath(space, w_obj)
815 if space.isinstance_w(w_path, space.w_bytes):
816 w_output = w_path
817 else:
818 w_output = space.fsencode(w_path)
819
820 if not space.isinstance_w(w_output, space.w_bytes):
821 raise oefmt(space.w_TypeError, "encoder failed to return bytes")
822 data = space.bytes0_w(w_output) # Check for NUL bytes
823 result[0] = make_ref(space, w_output)
824 return Py_CLEANUP_SUPPORTED
825
826
827 @cpython_api([PyObject, PyObjectP], rffi.INT_real, error=0)
828 def PyUnicode_FSDecoder(space, w_obj, result):
829 """ParseTuple converter: decode bytes objects to str using
830 PyUnicode_DecodeFSDefaultAndSize(); str objects are output
831 as-is. result must be a PyUnicodeObject* which must be released
832 when it is no longer used.
833 """
834 if not w_obj:
835 # Implement ParseTuple cleanup support
836 decref(space, result[0])
837 return 1
838 if space.isinstance_w(w_obj, space.w_unicode):
839 w_output = w_obj
840 elif space.isinstance_w(w_obj, space.w_bytes):
841 w_output = space.fsdecode(w_obj)
842 else:
843 allowed_types = "string, bytes or os.PathLike"
844 try:
845 space._try_buffer_w(w_obj, space.BUF_FULL_RO)
846 except BufferInterfaceNotFound:
847 w_fspath_method = space.lookup(w_obj, '__fspath__')
848 if w_fspath_method:
849 w_result = space.get_and_call_function(w_fspath_method, w_obj)
850 if space.isinstance_w(w_result, space.w_unicode):
851 w_output = w_result
852 elif space.isinstance_w(w_result, space.w_bytes):
853 w_output = space.fsdecode(w_result)
854 else:
855 raise oefmt(space.w_TypeError,
856 "expected %S.__fspath__() to return str or bytes, not %T",
857 w_obj, w_result)
858 else:
859 raise oefmt(
860 space.w_TypeError,
861 "path should be %s, not %T",
862 allowed_types, w_obj)
863 else:
864 tp = space.type(w_obj).name
865 space.warn(space.newtext(
866 "path should be %s, not %s" % (allowed_types, tp,)),
867 space.w_DeprecationWarning)
868 buffer = space.buffer_w(w_obj, space.BUF_FULL_RO)
869 w_output = space.fsdecode(space.newbytes(buffer.as_str()))
870 if not space.isinstance_w(w_output, space.w_unicode):
871 raise oefmt(space.w_TypeError, "decoder failed to return unicode")
872 data = space.utf8_0_w(w_output) # Check for NUL bytes
873 result[0] = make_ref(space, w_output)
874 return Py_CLEANUP_SUPPORTED
875
876
877 @cpython_api([CONST_STRING, Py_ssize_t], PyObject)
878 def PyUnicode_DecodeFSDefaultAndSize(space, s, size):
879 """Decode a string using Py_FileSystemDefaultEncoding and the
880 'surrogateescape' error handler, or 'strict' on Windows.
881
882 If Py_FileSystemDefaultEncoding is not set, fall back to the
883 locale encoding.
884
885 Use 'strict' error handler on Windows."""
886 w_bytes = space.newbytes(rffi.charpsize2str(s, size))
887 return space.fsdecode(w_bytes)
888
889
890 @cpython_api([CONST_STRING], PyObject)
891 def PyUnicode_DecodeFSDefault(space, s):
892 """Decode a null-terminated string using Py_FileSystemDefaultEncoding
893 and the 'surrogateescape' error handler, or 'strict' on Windows.
894
895 If Py_FileSystemDefaultEncoding is not set, fall back to the
896 locale encoding.
897
898 Use PyUnicode_DecodeFSDefaultAndSize() if you know the string length.
899
900 Use 'strict' error handler on Windows."""
901 w_bytes = space.newbytes(rffi.charp2str(s))
902 return space.fsdecode(w_bytes)
903
904
905 @cpython_api([PyObject], PyObject)
906 def PyUnicode_EncodeFSDefault(space, w_unicode):
907 """Encode a Unicode object to Py_FileSystemDefaultEncoding with the
908 'surrogateescape' error handler, or 'strict' on Windows, and return
909 bytes. Note that the resulting bytes object may contain
910 null bytes.
911
912 If Py_FileSystemDefaultEncoding is not set, fall back to the
913 locale encoding.
914 """
915 return space.fsencode(w_unicode)
916
917
918 @cpython_api([CONST_STRING], PyObject)
919 def PyUnicode_FromString(space, s):
920 """Create a Unicode object from an UTF-8 encoded null-terminated char buffer"""
921 w_str = space.newbytes(rffi.charp2str(s))
922 return space.call_method(w_str, 'decode', space.newtext("utf-8"))
923
924 @cpython_api([PyObjectP], lltype.Void)
925 def PyUnicode_InternInPlace(space, string):
926 """Intern the argument *string in place. The argument must be the address
927 of a pointer variable pointing to a Python unicode string object. If there
928 is an existing interned string that is the same as *string, it sets *string
929 to it (decrementing the reference count of the old string object and
930 incrementing the reference count of the interned string object), otherwise
931 it leaves *string alone and interns it (incrementing its reference count).
932 (Clarification: even though there is a lot of talk about reference counts,
933 think of this function as reference-count-neutral; you own the object after
934 the call if and only if you owned it before the call.)"""
935 w_str = from_ref(space, string[0])
936 w_str = space.new_interned_w_str(w_str)
937 decref(space, string[0])
938 string[0] = make_ref(space, w_str)
939
940 @cpython_api([CONST_STRING], PyObject)
941 def PyUnicode_InternFromString(space, s):
942 """A combination of PyUnicode_FromString() and
943 PyUnicode_InternInPlace(), returning either a new unicode string
944 object that has been interned, or a new ("owned") reference to an
945 earlier interned string object with the same value.
946 """
947 w_str = space.newtext(rffi.charp2str(s))
948 return space.new_interned_w_str(w_str)
949
950 @cpython_api([CONST_STRING, Py_ssize_t], PyObject, result_is_ll=True)
951 def PyUnicode_FromStringAndSize(space, s, size):
952 """Create a Unicode Object from the char buffer u. The bytes will be
953 interpreted as being UTF-8 encoded. u may also be NULL which causes the
954 contents to be undefined. It is the user's responsibility to fill in the
955 needed data. The buffer is copied into the new object. If the buffer is not
956 NULL, the return value might be a shared object. Therefore, modification of
957 the resulting Unicode object is only allowed when u is NULL."""
958 if s:
959 return make_ref(space, PyUnicode_DecodeUTF8(
960 space, s, size, lltype.nullptr(rffi.CCHARP.TO)))
961 else:
962 return new_empty_unicode(space, size)
963
964 @cpython_api([rffi.INT_real], PyObject)
965 def PyUnicode_FromOrdinal(space, ordinal):
966 """Create a Unicode Object from the given Unicode code point ordinal.
967
968 The ordinal must be in range(0x10000) on narrow Python builds
969 (UCS2), and range(0x110000) on wide builds (UCS4). A ValueError is
970 raised in case it is not."""
971 w_ordinal = space.newint(rffi.cast(lltype.Signed, ordinal))
972 return space.call_function(space.builtin.get('chr'), w_ordinal)
973
974 @cpython_api([PyObjectP, Py_ssize_t], rffi.INT_real, error=-1)
975 def PyUnicode_Resize(space, ref, newsize):
976 # XXX always create a new string so far
977 py_obj = ref[0]
978 if not get_wbuffer(py_obj):
979 raise oefmt(space.w_SystemError,
980 "PyUnicode_Resize called on already created string")
981 try:
982 py_newuni = new_empty_unicode(space, newsize)
983 except MemoryError:
984 decref(space, ref[0])
985 ref[0] = lltype.nullptr(PyObject.TO)
986 raise
987 to_cp = newsize
988 oldsize = get_wsize(py_obj)
989 if oldsize < newsize:
990 to_cp = oldsize
991 for i in range(to_cp):
992 get_wbuffer(py_newuni)[i] = get_wbuffer(py_obj)[i]
993 decref(space, ref[0])
994 ref[0] = rffi.cast(PyObject, py_newuni)
995 return 0
996
997 def make_conversion_functions(suffix, encoding, only_for_asstring=False):
998 @cpython_api([PyObject], PyObject)
999 @func_renamer('PyUnicode_As%sString' % suffix)
1000 def PyUnicode_AsXXXString(space, pyobj):
1001 """Encode a Unicode object and return the result as Python
1002 string object. Error handling is "strict". Return NULL if an
1003 exception was raised by the codec."""
1004 if not pyunicode_check(pyobj):
1005 PyErr_BadArgument(space)
1006 w_unicode = from_ref(space, pyobj)
1007 return unicodeobject.encode_object(space, w_unicode, encoding, "strict")
1008 globals()['PyUnicode_As%sString' % suffix] = PyUnicode_AsXXXString
1009
1010 if only_for_asstring:
1011 return
1012
1013 @cpython_api([CONST_STRING, Py_ssize_t, CONST_STRING], PyObject)
1014 @func_renamer('PyUnicode_Decode%s' % suffix)
1015 def PyUnicode_DecodeXXX(space, s, size, errors):
1016 """Create a Unicode object by decoding size bytes of the
1017 encoded string s. Return NULL if an exception was raised by
1018 the codec.
1019 """
1020 w_s = space.newbytes(rffi.charpsize2str(s, size))
1021 if errors:
1022 w_errors = space.newtext(rffi.charp2str(errors))
1023 else:
1024 w_errors = None
1025 return space.call_method(w_s, 'decode', space.newtext(encoding), w_errors)
1026 globals()['PyUnicode_Decode%s' % suffix] = PyUnicode_DecodeXXX
1027
1028 @cpython_api([CONST_WSTRING, Py_ssize_t, CONST_STRING], PyObject)
1029 @func_renamer('PyUnicode_Encode%s' % suffix)
1030 def PyUnicode_EncodeXXX(space, s, size, errors):
1031 """Encode the Py_UNICODE buffer of the given size and return a
1032 Python string object. Return NULL if an exception was raised
1033 by the codec."""
1034 if size < 0:
1035 size = 0
1036 u = wcharpsize2utf8(space, s, size)
1037 w_u = space.newutf8(u, size)
1038 if errors:
1039 w_errors = space.newtext(rffi.charp2str(errors))
1040 else:
1041 w_errors = None
1042 return space.call_method(w_u, 'encode', space.newtext(encoding), w_errors)
1043 globals()['PyUnicode_Encode%s' % suffix] = PyUnicode_EncodeXXX
1044
1045 make_conversion_functions('UTF8', 'utf-8')
1046 make_conversion_functions('UTF16', 'utf-16', only_for_asstring=True)
1047 make_conversion_functions('UTF32', 'utf-32', only_for_asstring=True)
1048 make_conversion_functions('ASCII', 'ascii')
1049 make_conversion_functions('Latin1', 'latin-1')
1050 if sys.platform == 'win32':
1051 from pypy.module._codecs.interp_codecs import code_page_encode
1052 make_conversion_functions('MBCS', 'mbcs')
1053
1054 @cpython_api([rffi.INT_real, PyObject, CONST_STRING], PyObject)
1055 def PyUnicode_EncodeCodePage(space, code_page, w_obj, errors):
1056 if errors:
1057 errors = rffi.charp2str(errors)
1058 else:
1059 errors = None
1060 res = code_page_encode(space, widen(code_page), w_obj, errors)
1061 return space.listview(res)[0]
1062
1063 @cpython_api([CONST_STRING, Py_ssize_t, CONST_STRING, INTP_real], PyObject)
1064 def PyUnicode_DecodeUTF16(space, s, size, llerrors, pbyteorder):
1065 """Decode length bytes from a UTF-16 encoded buffer string and return the
1066 corresponding Unicode object. errors (if non-NULL) defines the error
1067 handling. It defaults to "strict".
1068
1069 If byteorder is non-NULL, the decoder starts decoding using the given byte
1070 order:
1071
1072 *byteorder == -1: little endian
1073 *byteorder == 0: native order
1074 *byteorder == 1: big endian
1075
1076 If *byteorder is zero, and the first two bytes of the input data are a
1077 byte order mark (BOM), the decoder switches to this byte order and the BOM is
1078 not copied into the resulting Unicode string. If *byteorder is -1 or
1079 1, any byte order mark is copied to the output (where it will result in
1080 either a \ufeff or a \ufffe character).
1081
1082 After completion, *byteorder is set to the current byte order at the end
1083 of input data.
1084
1085 If byteorder is NULL, the codec starts in native order mode.
1086
1087 Return NULL if an exception was raised by the codec."""
1088
1089 string = rffi.charpsize2str(s, size)
1090
1091 if pbyteorder is not None:
1092 llbyteorder = rffi.cast(lltype.Signed, pbyteorder[0])
1093 if llbyteorder < 0:
1094 byteorder = "little"
1095 elif llbyteorder > 0:
1096 byteorder = "big"
1097 else:
1098 byteorder = "native"
1099 else:
1100 byteorder = "native"
1101
1102 if llerrors:
1103 errors = rffi.charp2str(llerrors)
1104 else:
1105 errors = 'strict'
1106
1107 state = space.fromcache(CodecState)
1108 w_string = space.newbytes(string)
1109 result, length, pos, bo = str_decode_utf_16_helper(
1110 space, string, w_string, errors, True, state.decode_error_handler,
1111 byteorder=byteorder)
1112 if pbyteorder is not None:
1113 pbyteorder[0] = rffi.cast(rffi.INT_real, bo)
1114 return space.newutf8(result, length)
1115
1116 @cpython_api([CONST_STRING, Py_ssize_t, CONST_STRING, INTP_real], PyObject)
1117 def PyUnicode_DecodeUTF32(space, s, size, llerrors, pbyteorder):
1118 """Decode length bytes from a UTF-32 encoded buffer string and
1119 return the corresponding Unicode object. errors (if non-NULL)
1120 defines the error handling. It defaults to "strict".
1121
1122 If byteorder is non-NULL, the decoder starts decoding using the
1123 given byte order:
1124 *byteorder == -1: little endian
1125 *byteorder == 0: native order
1126 *byteorder == 1: big endian
1127
1128 If *byteorder is zero, and the first four bytes of the input data
1129 are a byte order mark (BOM), the decoder switches to this byte
1130 order and the BOM is not copied into the resulting Unicode string.
1131 If *byteorder is -1 or 1, any byte order mark is copied to the
1132 output.
1133
1134 After completion, *byteorder is set to the current byte order at
1135 the end of input data.
1136
1137 In a narrow build codepoints outside the BMP will be decoded as
1138 surrogate pairs.
1139
1140 If byteorder is NULL, the codec starts in native order mode.
1141
1142 Return NULL if an exception was raised by the codec.
1143 """
1144 string = rffi.charpsize2str(s, size)
1145
1146 if pbyteorder:
1147 llbyteorder = rffi.cast(lltype.Signed, pbyteorder[0])
1148 if llbyteorder < 0:
1149 byteorder = "little"
1150 elif llbyteorder > 0:
1151 byteorder = "big"
1152 else:
1153 byteorder = "native"
1154 else:
1155 byteorder = "native"
1156
1157 if llerrors:
1158 errors = rffi.charp2str(llerrors)
1159 else:
1160 errors = 'strict'
1161
1162 state = space.fromcache(CodecState)
1163 w_string = space.newbytes(string)
1164 result, length, pos, bo = str_decode_utf_32_helper(
1165 space, string, w_string, errors, True, state.decode_error_handler,
1166 byteorder=byteorder)
1167 if pbyteorder is not None:
1168 pbyteorder[0] = rffi.cast(rffi.INT_real, bo)
1169 return space.newutf8(result, length)
1170
1171 @cpython_api([rffi.CWCHARP, Py_ssize_t, rffi.CCHARP, CONST_STRING],
1172 rffi.INT_real, error=-1)
1173 def PyUnicode_EncodeDecimal(space, s, length, output, llerrors):
1174 """Takes a Unicode string holding a decimal value and writes it
1175 into an output buffer using standard ASCII digit codes.
1176
1177 The output buffer has to provide at least length+1 bytes of
1178 storage area. The output string is 0-terminated.
1179
1180 The encoder converts whitespace to ' ', decimal characters to
1181 their corresponding ASCII digit and all other Latin-1 characters
1182 except \0 as-is. Characters outside this range (Unicode ordinals
1183 1-256) are treated as errors. This includes embedded NULL bytes.
1184
1185 Returns 0 on success, -1 on failure.
1186 """
1187 u = wcharpsize2utf8(space, s, length)
1188 if llerrors:
1189 errors = rffi.charp2str(llerrors)
1190 else:
1191 errors = None
1192 state = space.fromcache(CodecState)
1193 w_u = space.newtext(u)
1194 result = unicode_encode_decimal(space, u, w_u, errors, state.encode_error_handler)
1195 i = len(result)
1196 output[i] = '\0'
1197 i -= 1
1198 while i >= 0:
1199 output[i] = result[i]
1200 i -= 1
1201 return 0
1202
1203 @cpython_api([rffi.CArrayPtr(Py_UNICODE), Py_ssize_t], PyObject)
1204 def PyUnicode_TransformDecimalToASCII(space, s, size):
1205 """Create a Unicode object by replacing all decimal digits in
1206 Py_UNICODE buffer of the given size by ASCII digits 0--9
1207 according to their decimal value. Return NULL if an exception
1208 occurs."""
1209 result = rutf8.Utf8StringBuilder(size)
1210 for i in range(size):
1211 ch = s[i]
1212 ordch = ord(ch)
1213 if ordch > 127:
1214 decimal = _PyUnicode_ToDecimalDigit(space, ordch)
1215 decimal = rffi.cast(lltype.Signed, decimal)
1216 if decimal >= 0:
1217 ordch = ord('0') + decimal
1218 result.append_code(ordch)
1219 u = result.build()
1220 return space.newtext(u, result.getlength())
1221
1222 @cpython_api([PyObject, PyObject], rffi.INT_real, error=-2)
1223 def PyUnicode_Compare(space, w_left, w_right):
1224 """Compare two strings and return -1, 0, 1 for less than, equal, and greater
1225 than, respectively."""
1226 if space.is_true(space.lt(w_left, w_right)):
1227 return -1
1228 if space.is_true(space.lt(w_right, w_left)):
1229 return 1
1230 return 0
1231
1232 @cpython_api([PyObject, PyObject], PyObject)
1233 def PyUnicode_Concat(space, w_left, w_right):
1234 """Concat two strings giving a new Unicode string."""
1235 return space.add(w_left, w_right)
1236
1237 @cpython_api([PyObject, CONST_STRING], rffi.INT_real, error=CANNOT_FAIL)
1238 def _PyUnicode_EqualToASCIIString(space, w_uni, string):
1239 """Test whether a unicode is equal to ASCII string. Return 1 if true,
1240 0 otherwise. The right argument must be ASCII-encoded string.
1241 Any error occurs inside will be cleared before return."""
1242 utf8 = space.utf8_w(w_uni)
1243 lgt = space.len_w(w_uni)
1244 i = 0
1245 # Compare Unicode string and source character set string
1246 for ch in rutf8.Utf8StringIterator(utf8):
1247 if string[i] == '\0':
1248 break
1249 s = ord(string[i])
1250 if ch != s:
1251 if ch != s:
1252 return 0
1253 i += 1
1254 if i < lgt:
1255 return 0 # uni is longer
1256 if string[i] != '\0':
1257 return 0 # str is longer
1258 return 1
1259
1260 @cpython_api([PyObject, PyObject], rffi.INT_real, error=CANNOT_FAIL)
1261 def _PyUnicode_EQ(space, w_aa, w_bb):
1262 if not space.isinstance_w(w_aa, space.w_unicode) or not space.isinstance_w(w_bb, space.w_unicode):
1263 raise oefmt(space.w_TypeError, "_PyUnicode_EQ(aa, bb) must be called with two str instances")
1264 aa = space.utf8_w(w_aa)
1265 la = space.len_w(w_aa)
1266 bb = space.utf8_w(w_bb)
1267 lb = space.len_w(w_bb)
1268 if la != lb:
1269 return 0
1270 if la == 0:
1271 return 1
1272 if aa == bb:
1273 return 1
1274 return 0
1275 @cpython_api([PyObject, CONST_STRING], rffi.INT_real, error=CANNOT_FAIL)
1276 def PyUnicode_CompareWithASCIIString(space, w_uni, string):
1277 """Compare a unicode object, uni, with string and return -1, 0, 1 for less
1278 than, equal, and greater than, respectively. It is best to pass only
1279 ASCII-encoded strings, but the function interprets the input string as
1280 ISO-8859-1 if it contains non-ASCII characters."""
1281 utf8 = space.utf8_w(w_uni)
1282 lgt = space.len_w(w_uni)
1283 i = 0
1284 # Compare Unicode string and source character set string
1285 for ch in rutf8.Utf8StringIterator(utf8):
1286 if string[i] == '\0':
1287 break
1288 s = ord(string[i])
1289 if ch != s:
1290 if ch < s:
1291 return -1
1292 else:
1293 return 1
1294 i += 1
1295 if i < lgt:
1296 return 1 # uni is longer
1297 if string[i] != '\0':
1298 return -1 # str is longer
1299 return 0
1300
1301
1302 @cpython_api([rffi.CWCHARP, rffi.CWCHARP, Py_ssize_t], lltype.Void)
1303 def Py_UNICODE_COPY(space, target, source, length):
1304 """Roughly equivalent to memcpy() only the base size is Py_UNICODE
1305 copies sizeof(Py_UNICODE) * length bytes from source to target"""
1306 for i in range(0, length):
1307 target[i] = source[i]
1308
1309 @cpython_api([PyObject, PyObject], PyObject)
1310 def PyUnicode_Format(space, w_format, w_args):
1311 """Return a new string object from format and args; this is analogous to
1312 format % args. The args argument must be a tuple."""
1313 return space.mod(w_format, w_args)
1314
1315 @cpython_api([PyObject, PyObject], PyObject)
1316 def PyUnicode_Join(space, w_sep, w_seq):
1317 """Join a sequence of strings using the given separator and return
1318 the resulting Unicode string."""
1319 return space.call_method(w_sep, 'join', w_seq)
1320
1321 @cpython_api([PyObject, PyObject, PyObject, Py_ssize_t], PyObject)
1322 def PyUnicode_Replace(space, w_str, w_substr, w_replstr, maxcount):
1323 """Replace at most maxcount occurrences of substr in str with replstr and
1324 return the resulting Unicode object. maxcount == -1 means replace all
1325 occurrences."""
1326 return space.call_method(w_str, "replace", w_substr, w_replstr,
1327 space.newint(maxcount))
1328
1329 @cpython_api([PyObject, PyObject, Py_ssize_t, Py_ssize_t, rffi.INT_real],
1330 rffi.INT_real, error=-1)
1331 def PyUnicode_Tailmatch(space, w_str, w_substr, start, end, direction):
1332 """Return 1 if substr matches str[start:end] at the given tail end
1333 (direction == -1 means to do a prefix match, direction == 1 a
1334 suffix match), 0 otherwise. Return -1 if an error occurred."""
1335 space.utf8_w(w_str) # type check
1336 space.utf8_w(w_substr)
1337 w_start = space.newint(start)
1338 w_end = space.newint(end)
1339 if rffi.cast(lltype.Signed, direction) <= 0:
1340 w_result = space.call_method(
1341 w_str, "startswith", w_substr, w_start, w_end)
1342 else:
1343 w_result = space.call_method(
1344 w_str, "endswith", w_substr, w_start, w_end)
1345 return space.int_w(w_result)
1346
1347 @cpython_api([PyObject, PyObject, Py_ssize_t, Py_ssize_t], Py_ssize_t, error=-1)
1348 def PyUnicode_Count(space, w_str, w_substr, start, end):
1349 """Return the number of non-overlapping occurrences of substr in
1350 str[start:end]. Return -1 if an error occurred."""
1351 w_count = space.call_method(w_str, "count", w_substr,
1352 space.newint(start), space.newint(end))
1353 return space.int_w(w_count)
1354
1355 @cpython_api([PyObject, PyObject, Py_ssize_t, Py_ssize_t, rffi.INT_real],
1356 Py_ssize_t, error=-2)
1357 def PyUnicode_Find(space, w_str, w_substr, start, end, direction):
1358 """Return the first position of substr in str*[*start:end] using
1359 the given direction (direction == 1 means to do a forward search,
1360 direction == -1 a backward search). The return value is the index
1361 of the first match; a value of -1 indicates that no match was
1362 found, and -2 indicates that an error occurred and an exception
1363 has been set."""
1364 if rffi.cast(lltype.Signed, direction) > 0:
1365 w_pos = space.call_method(w_str, "find", w_substr,
1366 space.newint(start), space.newint(end))
1367 else:
1368 w_pos = space.call_method(w_str, "rfind", w_substr,
1369 space.newint(start), space.newint(end))
1370 return space.int_w(w_pos)
1371
1372 @cpython_api([PyObject, PyObject], rffi.INT_real, error=-1)
1373 def PyUnicode_Contains(space, w_str, w_substr):
1374 """Check whether element is contained in container and return true or false
1375 accordingly.
1376
1377 element has to coerce to a one element Unicode string. -1 is returned if
1378 there was an error."""
1379 if not space.isinstance_w(w_substr, space.w_unicode):
1380 raise oefmt(space.w_TypeError,
1381 "in <string> requires string as left operand, not %T",
1382 w_substr)
1383 if not space.isinstance_w(w_str, space.w_unicode):
1384 raise oefmt(space.w_TypeError, "must be str, not %T", w_str)
1385 return space.int_w(space.call_method(w_str, '__contains__', w_substr))
1386
1387 @cpython_api([PyObject, PyObject, Py_ssize_t], PyObject)
1388 def PyUnicode_Split(space, w_str, w_sep, maxsplit):
1389 """Split a string giving a list of Unicode strings. If sep is
1390 NULL, splitting will be done at all whitespace substrings.
1391 Otherwise, splits occur at the given separator. At most maxsplit
1392 splits will be done. If negative, no limit is set. Separators
1393 are not included in the resulting list."""
1394 if w_sep is None:
1395 w_sep = space.w_None
1396 return space.call_method(w_str, "split", w_sep, space.newint(maxsplit))
1397
1398 @cpython_api([PyObject, rffi.INT_real], PyObject)
1399 def PyUnicode_Splitlines(space, w_str, keepend):
1400 """Split a Unicode string at line breaks, returning a list of
1401 Unicode strings. CRLF is considered to be one line break. If
1402 keepend is 0, the Line break characters are not included in the
1403 resulting strings."""
1404 w_keepend = space.newbool(bool(rffi.cast(lltype.Signed, keepend)))
1405 return space.call_method(w_str, "splitlines", w_keepend)
1406
1407 @cpython_api([PyObject, Py_ssize_t, Py_ssize_t], PyObject)
1408 def PyUnicode_Substring(space, w_str, start, end):
1409 return space.call_method(w_str, '__getitem__',
1410 space.newslice(space.newint(start), space.newint(end),
1411 space.newint(1)))
1412
1413 @cts.decl("Py_UCS4 *PyUnicode_AsUCS4(PyObject *u, Py_UCS4 *buffer, Py_ssize_t buflen, int copy_null)")
1414 def PyUnicode_AsUCS4(space, w_obj, pbuffer, buflen, copy_null):
1415 from pypy.module._codecs.locale import _utf82rawwcharp_loop
1416 # Use the underlying RPython object
1417 utf8 = space.utf8_w(w_obj)
1418 ulen = space.len_w(w_obj)
1419 if rffi.cast(lltype.Signed, copy_null):
1420 ulen += 1
1421 if not pbuffer: # internal, for PyUnicode_AsUCS4Copy()
1422 pbuffer = lltype.malloc(rffi.CArray(Py_UCS4), ulen,
1423 flavor='raw', track_allocation=False)
1424 elif buflen < ulen:
1425 raise oefmt(space.w_SystemError, "PyUnicode_AsUCS4: buflen too short")
1426 u_iter = rutf8.Utf8StringIterator(utf8)
1427 count = 0
1428 for oc in u_iter:
1429 pbuffer[count] = rffi.cast(Py_UCS4, oc)
1430 count += 1
1431 if rffi.cast(lltype.Signed, copy_null):
1432 pbuffer[count] = rffi.cast(Py_UCS4, 0)
1433 return pbuffer
1434
1435
1436 @cts.decl("Py_UCS4 *PyUnicode_AsUCS4Copy(PyObject *u)")
1437 def PyUnicode_AsUCS4Copy(space, ref):
1438 return PyUnicode_AsUCS4(space, ref, cts.cast('Py_UCS4*', 0), 0,
1439 rffi.cast(rffi.INT_real, 1))
1440
1441 @cts.decl("PyObject* PyUnicode_New(Py_ssize_t size, Py_UCS4 maxchar)",
1442 result_is_ll=True)
1443 def PyUnicode_New(space, size, maxchar):
1444 PyASCIIObject = cts.gettype('PyASCIIObject')
1445 PyCompactUnicodeObject = cts.gettype('PyCompactUnicodeObject')
1446 PyCompactUnicodeObject = cts.gettype('PyCompactUnicodeObject')
1447
1448 is_ascii = False
1449 is_sharing = False
1450 is_compact = False
1451 maxchar = widen(maxchar)
1452 struct_size = rffi.sizeof(PyCompactUnicodeObject)
1453 if maxchar < 128:
1454 kind = _1BYTE_KIND
1455 char_size = 1
1456 is_ascii = True
1457 is_compact = True
1458 struct_size = rffi.sizeof(PyASCIIObject)
1459 elif maxchar < 256:
1460 kind = _1BYTE_KIND
1461 char_size = 1
1462 is_compact = True
1463 elif maxchar < 65536:
1464 kind = _2BYTE_KIND
1465 char_size = 2
1466 struct_size = rffi.sizeof(PyUnicodeObject.TO)
1467 if rffi.sizeof(lltype.UniChar) == 2:
1468 is_sharing = True
1469 else:
1470 if maxchar > rutf8.MAXUNICODE:
1471 raise oefmt(space.w_SystemError,
1472 "invalid maximum character passed to PyUnicode_New")
1473 kind = _4BYTE_KIND
1474 char_size = 4
1475 struct_size = rffi.sizeof(PyUnicodeObject.TO)
1476 if rffi.sizeof(lltype.UniChar) == 4:
1477 is_sharing = True
1478
1479 # Ensure we won't overflow the size.
1480 if size < 0:
1481 raise oefmt(space.w_SystemError,
1482 "Negative size passed to PyUnicode_New")
1483 if size > ((sys.maxint - struct_size) / char_size - 1):
1484 raise oefmt(space.w_MemoryError, "PyUnicode_New: size too big")
1485
1486 # Duplicated allocation code from _PyObject_New() instead of a call to
1487 # PyObject_New() so we are able to allocate space for the object and
1488 # its data buffer.
1489 pytype = as_pyobj(space, space.w_unicode)
1490 pytype = rffi.cast(PyTypeObjectPtr, pytype)
1491 buf = lltype.malloc(rffi.VOIDP.TO, struct_size + (size + 1) * char_size,
1492 flavor='raw', zero=True,
1493 add_memory_pressure=True)
1494 pyobj = rffi.cast(PyObject, buf)
1495 pyobj.c_ob_refcnt = 1
1496 pyvarobj = rffi.cast(PyVarObject, pyobj)
1497 pyvarobj.c_ob_size = size
1498 #pyobj.c_ob_pypy_link remains null for now
1499 pyobj.c_ob_type = pytype
1500
1501 set_len(pyobj, size)
1502 set_kind(pyobj, kind)
1503 set_compact(pyobj, is_compact)
1504 if is_compact:
1505 set_ascii(pyobj, is_ascii)
1506 else:
1507 unicode_size = rffi.sizeof(PyUnicodeObject.TO)
1508 data = rffi.ptradd(rffi.cast(rffi.CCHARP, pyobj), unicode_size)
1509 set_data(pyobj, cts.cast('void *', data))
1510 if is_sharing:
1511 set_wbuffer(pyobj, rffi.cast(rffi.CWCHARP, get_data(pyobj)))
1512 if not is_ascii:
1513 set_wsize(pyobj, size)
1514 set_ready(pyobj, True)
1515 return pyobj
1516
1517 @cts.decl("""Py_ssize_t PyUnicode_FindChar(PyObject *str, Py_UCS4 ch,
1518 Py_ssize_t start, Py_ssize_t end, int direction)""", error=-1)
1519 def PyUnicode_FindChar(space, ref, ch, start, end, direction):
1520 if not pyunicode_check(ref):
1521 PyErr_BadArgument(space)
1522 w_str = from_ref(space, ref)
1523 ch = widen(ch)
1524 if ch > rutf8.MAXUNICODE:
1525 raise oefmt(space.w_ValueError, "character out of range")
1526 w_ch = space.newtext(rutf8.unichr_as_utf8(r_uint(ch)), 1)
1527 if rffi.cast(lltype.Signed, direction) > 0:
1528 w_pos = space.call_method(w_str, "find", w_ch,
1529 space.newint(start), space.newint(end))
1530 else:
1531 w_pos = space.call_method(w_str, "rfind", w_ch,
1532 space.newint(start), space.newint(end))
1533 return space.int_w(w_pos)
1534
1535 @cts.decl("Py_UCS4 PyUnicode_ReadChar(PyObject *unicode, Py_ssize_t index)", error=-1)
1536 def PyUnicode_ReadChar(space, ref, index):
1537 if not pyunicode_check(ref):
1538 PyErr_BadArgument(space)
1539 if not get_ready(ref):
1540 PyErr_BadArgument(space)
1541 if index < 0 or index > get_len(ref):
1542 raise oefmt(space.w_IndexError, "string index out of range")
1543 w_obj = from_ref(space, ref)
1544 w_ch = space.getitem(w_obj, space.newint(index))
1545 return space.int_w(space.ord(w_ch))
1546
1547 @cts.decl("int PyUnicode_WriteChar(PyObject *unicode, Py_ssize_t index, Py_UCS4 ch)", error=-1)
1548 def PyUnicode_WriteChar(space, ref, index, ch):
1549 """ Write a single ch at index before ref is ready. In order for this to
1550 succeed:
1551 - ch and ref[index] when converted to utf8 must be the same length
1552 - ref must not have a RPython object
1553 - ref must not have been processed by _PyUnicode_Ready
1554 """
1555 if not pyunicode_check(ref):
1556 PyErr_BadArgument(space)
1557 if index < 0 or index > get_len(ref):
1558 raise oefmt(space.w_IndexError, "string index out of range")
1559 if get_ready(ref):
1560 raise oefmt(space.w_SystemError, "Cannot modify a string currently used")
1561 if not has_utf8_memory(ref):
1562 raise oefmt(space.w_SystemError, "Cannot modify a string currently used")
1563 # this is rarithetic.r_uint, not rffi.r_uint
1564 ch = r_uint(ch)
1565 if ch > rutf8.MAXUNICODE:
1566 raise oefmt(space.w_ValueError, "character out of range")
1567 if get_compact(ref):
1568 raise oefmt(space.w_SystemError, "Cannot modify compact via PyUnicode_WriteChar")
1569 utf8 = get_utf8(ref)
1570 as_str = rffi.charp2str(utf8)
1571 start = 0
1572 if index > 0:
1573 start = rutf8.next_codepoint_pos(as_str, index - 1)
1574 end = rutf8.next_codepoint_pos(as_str, index)
1575 ch_as_utf8 = rutf8.unichr_as_utf8(ch)
1576 if len(ch_as_utf8) != end - start:
1577 raise oefmt(space.w_ValueError,
1578 'cannot write ch to string, would need to reallocate')
1579 j = 0
1580 for i in range(start, end):
1581 utf8[i] = ch_as_utf8[j]
1582 j += 1
1583 return 0
1584
1585 @cpython_api([PyObjectP, PyObject], lltype.Void)
1586 def PyUnicode_Append(space, p_left, right):
1587 state = space.fromcache(State)
1588 operror = state.get_exception()
1589 if not p_left:
1590 if operror is not None:
1591 PyErr_BadInternalCall(space)
1592 return
1593 left = p_left[0]
1594 if not left or not right or not pyunicode_check(left) or not pyunicode_check(right):
1595 if operror is not None:
1596 PyErr_BadInternalCall(space)
1597 p_left[0] = rffi.cast(PyObject, 0)
1598 return
1599 w_left = from_ref(space, left)
1600 w_right = from_ref(space, right)
1601 w_append = space.add(w_left, w_right)
1602 p_left[0] = make_ref(space, w_append)
1603
1604 @cpython_api([PyObject], PyObject)
1605 def PyUnicode_AsRawUnicodeEscapeString(space, w_obj):
1606 """Encode a Unicode object using Raw-Unicode-Escape and return the result as
1607 Python string object. Error handling is "strict". Return NULL if an exception
1608 was raised by the codec."""
1609 utf8 = space.utf8_w(w_obj)
1610 ulen = space.len_w(w_obj)
1611 res = utf8_encode_raw_unicode_escape(space, utf8, w_obj, "strict", None)
1612 return space.newbytes(res)
1613
1614
1615 @cpython_api([CONST_STRING, Py_ssize_t, CONST_STRING], PyObject)
1616 def PyUnicode_DecodeRawUnicodeEscape(space, p_string, length, p_errors):
1617 if not p_string:
1618 PyErr_BadInternalCall(space)
1619 if not p_errors:
1620 errors = "strict"
1621 else:
1622 errors = rffi.charp2str(p_errors)
1623 b = rffi.charpsize2str(p_string, length)
1624 w_b = space.newbytes(b)
1625 state = space.fromcache(CodecState)
1626 eh = state.decode_error_handler
1627 s, u_len, _ = str_decode_raw_unicode_escape(space, b, w_b, errors, True, eh)
1628 return space.newtext(s, u_len)