PageRenderTime 49ms CodeModel.GetById 15ms RepoModel.GetById 1ms app.codeStats 0ms

/pypy/module/cpyext/unicodeobject.py

https://bitbucket.org/pypy/pypy/
Python | 761 lines | 697 code | 31 blank | 33 comment | 7 complexity | 00bf2400d9e5043a347a37a65d762767 MD5 | raw file
Possible License(s): AGPL-3.0, BSD-3-Clause, Apache-2.0
  1. from pypy.interpreter.error import OperationError, oefmt
  2. from rpython.rtyper.lltypesystem import rffi, lltype
  3. from pypy.module.unicodedata import unicodedb
  4. from pypy.module.cpyext.api import (
  5. CANNOT_FAIL, Py_ssize_t, build_type_checkers, cpython_api,
  6. bootstrap_function, PyObjectFields, cpython_struct, CONST_STRING,
  7. CONST_WSTRING)
  8. from pypy.module.cpyext.pyerrors import PyErr_BadArgument
  9. from pypy.module.cpyext.pyobject import (
  10. PyObject, PyObjectP, Py_DecRef, make_ref, from_ref, track_reference,
  11. make_typedescr, get_typedescr, as_pyobj)
  12. from pypy.module.cpyext.bytesobject import PyString_Check
  13. from pypy.module.sys.interp_encoding import setdefaultencoding
  14. from pypy.module._codecs.interp_codecs import CodecState
  15. from pypy.objspace.std import unicodeobject
  16. from rpython.rlib import rstring, runicode
  17. from rpython.tool.sourcetools import func_renamer
  18. import sys
  19. ## See comment in bytesobject.py.
  20. PyUnicodeObjectStruct = lltype.ForwardReference()
  21. PyUnicodeObject = lltype.Ptr(PyUnicodeObjectStruct)
  22. PyUnicodeObjectFields = (PyObjectFields +
  23. (("str", rffi.CWCHARP), ("length", Py_ssize_t),
  24. ("hash", rffi.LONG), ("defenc", PyObject)))
  25. cpython_struct("PyUnicodeObject", PyUnicodeObjectFields, PyUnicodeObjectStruct)
  26. @bootstrap_function
  27. def init_unicodeobject(space):
  28. make_typedescr(space.w_unicode.layout.typedef,
  29. basestruct=PyUnicodeObject.TO,
  30. attach=unicode_attach,
  31. dealloc=unicode_dealloc,
  32. realize=unicode_realize)
  33. # Buffer for the default encoding (used by PyUnicde_GetDefaultEncoding)
  34. DEFAULT_ENCODING_SIZE = 100
  35. default_encoding = lltype.malloc(rffi.CCHARP.TO, DEFAULT_ENCODING_SIZE,
  36. flavor='raw', zero=True)
  37. PyUnicode_Check, PyUnicode_CheckExact = build_type_checkers("Unicode", "w_unicode")
  38. Py_UNICODE = lltype.UniChar
  39. def new_empty_unicode(space, length):
  40. """
  41. Allocate a PyUnicodeObject and its buffer, but without a corresponding
  42. interpreter object. The buffer may be mutated, until unicode_realize() is
  43. called. Refcount of the result is 1.
  44. """
  45. typedescr = get_typedescr(space.w_unicode.layout.typedef)
  46. py_obj = typedescr.allocate(space, space.w_unicode)
  47. py_uni = rffi.cast(PyUnicodeObject, py_obj)
  48. buflen = length + 1
  49. py_uni.c_length = length
  50. py_uni.c_str = lltype.malloc(rffi.CWCHARP.TO, buflen,
  51. flavor='raw', zero=True,
  52. add_memory_pressure=True)
  53. py_uni.c_hash = -1
  54. py_uni.c_defenc = lltype.nullptr(PyObject.TO)
  55. return py_uni
  56. def unicode_attach(space, py_obj, w_obj):
  57. "Fills a newly allocated PyUnicodeObject with a unicode string"
  58. py_unicode = rffi.cast(PyUnicodeObject, py_obj)
  59. py_unicode.c_length = len(space.unicode_w(w_obj))
  60. py_unicode.c_str = lltype.nullptr(rffi.CWCHARP.TO)
  61. py_unicode.c_hash = space.hash_w(w_obj)
  62. py_unicode.c_defenc = lltype.nullptr(PyObject.TO)
  63. def unicode_realize(space, py_obj):
  64. """
  65. Creates the unicode in the interpreter. The PyUnicodeObject buffer must not
  66. be modified after this call.
  67. """
  68. py_uni = rffi.cast(PyUnicodeObject, py_obj)
  69. s = rffi.wcharpsize2unicode(py_uni.c_str, py_uni.c_length)
  70. w_type = from_ref(space, rffi.cast(PyObject, py_obj.c_ob_type))
  71. w_obj = space.allocate_instance(unicodeobject.W_UnicodeObject, w_type)
  72. w_obj.__init__(s)
  73. py_uni.c_hash = space.hash_w(w_obj)
  74. track_reference(space, py_obj, w_obj)
  75. return w_obj
  76. @cpython_api([PyObject], lltype.Void, header=None)
  77. def unicode_dealloc(space, py_obj):
  78. py_unicode = rffi.cast(PyUnicodeObject, py_obj)
  79. Py_DecRef(space, py_unicode.c_defenc)
  80. if py_unicode.c_str:
  81. lltype.free(py_unicode.c_str, flavor="raw")
  82. from pypy.module.cpyext.object import _dealloc
  83. _dealloc(space, py_obj)
  84. @cpython_api([Py_UNICODE], rffi.INT_real, error=CANNOT_FAIL)
  85. def Py_UNICODE_ISSPACE(space, ch):
  86. """Return 1 or 0 depending on whether ch is a whitespace character."""
  87. return unicodedb.isspace(ord(ch))
  88. @cpython_api([Py_UNICODE], rffi.INT_real, error=CANNOT_FAIL)
  89. def Py_UNICODE_ISALPHA(space, ch):
  90. """Return 1 or 0 depending on whether ch is an alphabetic character."""
  91. return unicodedb.isalpha(ord(ch))
  92. @cpython_api([Py_UNICODE], rffi.INT_real, error=CANNOT_FAIL)
  93. def Py_UNICODE_ISALNUM(space, ch):
  94. """Return 1 or 0 depending on whether ch is an alphanumeric character."""
  95. return unicodedb.isalnum(ord(ch))
  96. @cpython_api([Py_UNICODE], rffi.INT_real, error=CANNOT_FAIL)
  97. def Py_UNICODE_ISLINEBREAK(space, ch):
  98. """Return 1 or 0 depending on whether ch is a linebreak character."""
  99. return unicodedb.islinebreak(ord(ch))
  100. @cpython_api([Py_UNICODE], rffi.INT_real, error=CANNOT_FAIL)
  101. def Py_UNICODE_ISDECIMAL(space, ch):
  102. """Return 1 or 0 depending on whether ch is a decimal character."""
  103. return unicodedb.isdecimal(ord(ch))
  104. @cpython_api([Py_UNICODE], rffi.INT_real, error=CANNOT_FAIL)
  105. def Py_UNICODE_ISDIGIT(space, ch):
  106. """Return 1 or 0 depending on whether ch is a digit character."""
  107. return unicodedb.isdigit(ord(ch))
  108. @cpython_api([Py_UNICODE], rffi.INT_real, error=CANNOT_FAIL)
  109. def Py_UNICODE_ISNUMERIC(space, ch):
  110. """Return 1 or 0 depending on whether ch is a numeric character."""
  111. return unicodedb.isnumeric(ord(ch))
  112. @cpython_api([Py_UNICODE], rffi.INT_real, error=CANNOT_FAIL)
  113. def Py_UNICODE_ISLOWER(space, ch):
  114. """Return 1 or 0 depending on whether ch is a lowercase character."""
  115. return unicodedb.islower(ord(ch))
  116. @cpython_api([Py_UNICODE], rffi.INT_real, error=CANNOT_FAIL)
  117. def Py_UNICODE_ISUPPER(space, ch):
  118. """Return 1 or 0 depending on whether ch is an uppercase character."""
  119. return unicodedb.isupper(ord(ch))
  120. @cpython_api([Py_UNICODE], rffi.INT_real, error=CANNOT_FAIL)
  121. def Py_UNICODE_ISTITLE(space, ch):
  122. """Return 1 or 0 depending on whether ch is a titlecase character."""
  123. return unicodedb.istitle(ord(ch))
  124. @cpython_api([Py_UNICODE], Py_UNICODE, error=CANNOT_FAIL)
  125. def Py_UNICODE_TOLOWER(space, ch):
  126. """Return the character ch converted to lower case."""
  127. return unichr(unicodedb.tolower(ord(ch)))
  128. @cpython_api([Py_UNICODE], Py_UNICODE, error=CANNOT_FAIL)
  129. def Py_UNICODE_TOUPPER(space, ch):
  130. """Return the character ch converted to upper case."""
  131. return unichr(unicodedb.toupper(ord(ch)))
  132. @cpython_api([Py_UNICODE], Py_UNICODE, error=CANNOT_FAIL)
  133. def Py_UNICODE_TOTITLE(space, ch):
  134. """Return the character ch converted to title case."""
  135. return unichr(unicodedb.totitle(ord(ch)))
  136. @cpython_api([Py_UNICODE], rffi.INT_real, error=CANNOT_FAIL)
  137. def Py_UNICODE_TODECIMAL(space, ch):
  138. """Return the character ch converted to a decimal positive integer. Return
  139. -1 if this is not possible. This macro does not raise exceptions."""
  140. try:
  141. return unicodedb.decimal(ord(ch))
  142. except KeyError:
  143. return -1
  144. @cpython_api([Py_UNICODE], rffi.INT_real, error=CANNOT_FAIL)
  145. def Py_UNICODE_TODIGIT(space, ch):
  146. """Return the character ch converted to a single digit integer. Return -1 if
  147. this is not possible. This macro does not raise exceptions."""
  148. try:
  149. return unicodedb.digit(ord(ch))
  150. except KeyError:
  151. return -1
  152. @cpython_api([Py_UNICODE], rffi.DOUBLE, error=CANNOT_FAIL)
  153. def Py_UNICODE_TONUMERIC(space, ch):
  154. """Return the character ch converted to a double. Return -1.0 if this is not
  155. possible. This macro does not raise exceptions."""
  156. try:
  157. return unicodedb.numeric(ord(ch))
  158. except KeyError:
  159. return -1.0
  160. @cpython_api([], Py_UNICODE, error=CANNOT_FAIL)
  161. def PyUnicode_GetMax(space):
  162. """Get the maximum ordinal for a Unicode character."""
  163. return runicode.UNICHR(runicode.MAXUNICODE)
  164. @cpython_api([rffi.VOIDP], rffi.CCHARP, error=CANNOT_FAIL)
  165. def PyUnicode_AS_DATA(space, ref):
  166. """Return a pointer to the internal buffer of the object. o has to be a
  167. PyUnicodeObject (not checked)."""
  168. return rffi.cast(rffi.CCHARP, PyUnicode_AS_UNICODE(space, ref))
  169. @cpython_api([rffi.VOIDP], Py_ssize_t, error=CANNOT_FAIL)
  170. def PyUnicode_GET_DATA_SIZE(space, w_obj):
  171. """Return the size of the object's internal buffer in bytes. o has to be a
  172. PyUnicodeObject (not checked)."""
  173. return rffi.sizeof(lltype.UniChar) * PyUnicode_GET_SIZE(space, w_obj)
  174. @cpython_api([rffi.VOIDP], Py_ssize_t, error=CANNOT_FAIL)
  175. def PyUnicode_GET_SIZE(space, w_obj):
  176. """Return the size of the object. o has to be a PyUnicodeObject (not
  177. checked)."""
  178. assert isinstance(w_obj, unicodeobject.W_UnicodeObject)
  179. return space.len_w(w_obj)
  180. @cpython_api([rffi.VOIDP], rffi.CWCHARP, error=CANNOT_FAIL)
  181. def PyUnicode_AS_UNICODE(space, ref):
  182. """Return a pointer to the internal Py_UNICODE buffer of the object. ref
  183. has to be a PyUnicodeObject (not checked)."""
  184. ref_unicode = rffi.cast(PyUnicodeObject, ref)
  185. if not ref_unicode.c_str:
  186. # Copy unicode buffer
  187. w_unicode = from_ref(space, rffi.cast(PyObject, ref))
  188. u = space.unicode_w(w_unicode)
  189. ref_unicode.c_str = rffi.unicode2wcharp(u)
  190. return ref_unicode.c_str
  191. @cpython_api([PyObject], rffi.CWCHARP)
  192. def PyUnicode_AsUnicode(space, ref):
  193. """Return a read-only pointer to the Unicode object's internal Py_UNICODE
  194. buffer, NULL if unicode is not a Unicode object."""
  195. # Don't use PyUnicode_Check, it will realize the object :-(
  196. w_type = from_ref(space, rffi.cast(PyObject, ref.c_ob_type))
  197. if not space.issubtype_w(w_type, space.w_unicode):
  198. raise oefmt(space.w_TypeError, "expected unicode object")
  199. return PyUnicode_AS_UNICODE(space, rffi.cast(rffi.VOIDP, ref))
  200. @cpython_api([PyObject], Py_ssize_t, error=-1)
  201. def PyUnicode_GetSize(space, ref):
  202. if from_ref(space, rffi.cast(PyObject, ref.c_ob_type)) is space.w_unicode:
  203. ref = rffi.cast(PyUnicodeObject, ref)
  204. return ref.c_length
  205. else:
  206. w_obj = from_ref(space, ref)
  207. return space.len_w(w_obj)
  208. @cpython_api([PyUnicodeObject, rffi.CWCHARP, Py_ssize_t], Py_ssize_t, error=-1)
  209. def PyUnicode_AsWideChar(space, ref, buf, size):
  210. """Copy the Unicode object contents into the wchar_t buffer w. At most
  211. size wchar_t characters are copied (excluding a possibly trailing
  212. 0-termination character). Return the number of wchar_t characters
  213. copied or -1 in case of an error. Note that the resulting wchar_t
  214. string may or may not be 0-terminated. It is the responsibility of the caller
  215. to make sure that the wchar_t string is 0-terminated in case this is
  216. required by the application."""
  217. c_str = PyUnicode_AS_UNICODE(space, rffi.cast(rffi.VOIDP, ref))
  218. c_length = ref.c_length
  219. # If possible, try to copy the 0-termination as well
  220. if size > c_length:
  221. size = c_length + 1
  222. i = 0
  223. while i < size:
  224. buf[i] = c_str[i]
  225. i += 1
  226. if size > c_length:
  227. return c_length
  228. else:
  229. return size
  230. @cpython_api([], rffi.CCHARP, error=CANNOT_FAIL)
  231. def PyUnicode_GetDefaultEncoding(space):
  232. """Returns the currently active default encoding."""
  233. if default_encoding[0] == '\x00':
  234. encoding = unicodeobject.getdefaultencoding(space)
  235. i = 0
  236. while i < len(encoding) and i < DEFAULT_ENCODING_SIZE:
  237. default_encoding[i] = encoding[i]
  238. i += 1
  239. return default_encoding
  240. @cpython_api([CONST_STRING], rffi.INT_real, error=-1)
  241. def PyUnicode_SetDefaultEncoding(space, encoding):
  242. """Sets the currently active default encoding. Returns 0 on
  243. success, -1 in case of an error."""
  244. if not encoding:
  245. PyErr_BadArgument(space)
  246. w_encoding = space.wrap(rffi.charp2str(encoding))
  247. setdefaultencoding(space, w_encoding)
  248. default_encoding[0] = '\x00'
  249. return 0
  250. @cpython_api([PyObject, CONST_STRING, CONST_STRING], PyObject)
  251. def PyUnicode_AsEncodedObject(space, w_unicode, llencoding, llerrors):
  252. """Encode a Unicode object and return the result as Python object.
  253. encoding and errors have the same meaning as the parameters of the same name
  254. in the Unicode encode() method. The codec to be used is looked up using
  255. the Python codec registry. Return NULL if an exception was raised by the
  256. codec."""
  257. if not PyUnicode_Check(space, w_unicode):
  258. PyErr_BadArgument(space)
  259. encoding = errors = None
  260. if llencoding:
  261. encoding = rffi.charp2str(llencoding)
  262. if llerrors:
  263. errors = rffi.charp2str(llerrors)
  264. return unicodeobject.encode_object(space, w_unicode, encoding, errors)
  265. @cpython_api([PyObject, CONST_STRING, CONST_STRING], PyObject)
  266. def PyUnicode_AsEncodedString(space, w_unicode, llencoding, llerrors):
  267. """Encode a Unicode object and return the result as Python string object.
  268. encoding and errors have the same meaning as the parameters of the same name
  269. in the Unicode encode() method. The codec to be used is looked up using
  270. the Python codec registry. Return NULL if an exception was raised by the
  271. codec."""
  272. w_str = PyUnicode_AsEncodedObject(space, w_unicode, llencoding, llerrors)
  273. if not PyString_Check(space, w_str):
  274. raise oefmt(space.w_TypeError,
  275. "encoder did not return a string object")
  276. return w_str
  277. @cpython_api([PyObject], PyObject)
  278. def PyUnicode_AsUnicodeEscapeString(space, w_unicode):
  279. """Encode a Unicode object using Unicode-Escape and return the result as Python
  280. string object. Error handling is "strict". Return NULL if an exception was
  281. raised by the codec."""
  282. if not PyUnicode_Check(space, w_unicode):
  283. PyErr_BadArgument(space)
  284. return unicodeobject.encode_object(space, w_unicode, 'unicode-escape', 'strict')
  285. @cpython_api([CONST_WSTRING, Py_ssize_t], PyObject, result_is_ll=True)
  286. def PyUnicode_FromUnicode(space, wchar_p, length):
  287. """Create a Unicode Object from the Py_UNICODE buffer u of the given size. u
  288. may be NULL which causes the contents to be undefined. It is the user's
  289. responsibility to fill in the needed data. The buffer is copied into the new
  290. object. If the buffer is not NULL, the return value might be a shared object.
  291. Therefore, modification of the resulting Unicode object is only allowed when u
  292. is NULL."""
  293. if wchar_p:
  294. s = rffi.wcharpsize2unicode(wchar_p, length)
  295. return make_ref(space, space.wrap(s))
  296. else:
  297. return rffi.cast(PyObject, new_empty_unicode(space, length))
  298. @cpython_api([CONST_WSTRING, Py_ssize_t], PyObject, result_is_ll=True)
  299. def PyUnicode_FromWideChar(space, wchar_p, length):
  300. """Create a Unicode object from the wchar_t buffer w of the given size.
  301. Return NULL on failure."""
  302. # PyPy supposes Py_UNICODE == wchar_t
  303. return PyUnicode_FromUnicode(space, wchar_p, length)
  304. @cpython_api([PyObject, CONST_STRING], PyObject, result_is_ll=True)
  305. def _PyUnicode_AsDefaultEncodedString(space, ref, errors):
  306. # Returns a borrowed reference.
  307. py_uni = rffi.cast(PyUnicodeObject, ref)
  308. if not py_uni.c_defenc:
  309. py_uni.c_defenc = make_ref(
  310. space, PyUnicode_AsEncodedString(
  311. space, ref,
  312. lltype.nullptr(rffi.CCHARP.TO), errors))
  313. return py_uni.c_defenc
  314. @cpython_api([CONST_STRING, Py_ssize_t, CONST_STRING, CONST_STRING], PyObject)
  315. def PyUnicode_Decode(space, s, size, encoding, errors):
  316. """Create a Unicode object by decoding size bytes of the encoded string s.
  317. encoding and errors have the same meaning as the parameters of the same name
  318. in the unicode() built-in function. The codec to be used is looked up
  319. using the Python codec registry. Return NULL if an exception was raised by
  320. the codec."""
  321. if not encoding:
  322. # This tracks CPython 2.7, in CPython 3.4 'utf-8' is hardcoded instead
  323. encoding = PyUnicode_GetDefaultEncoding(space)
  324. w_str = space.newbytes(rffi.charpsize2str(s, size))
  325. w_encoding = space.wrap(rffi.charp2str(encoding))
  326. if errors:
  327. w_errors = space.newbytes(rffi.charp2str(errors))
  328. else:
  329. w_errors = None
  330. return space.call_method(w_str, 'decode', w_encoding, w_errors)
  331. @cpython_api([PyObject], PyObject)
  332. def PyUnicode_FromObject(space, w_obj):
  333. """Shortcut for PyUnicode_FromEncodedObject(obj, NULL, "strict") which is used
  334. throughout the interpreter whenever coercion to Unicode is needed."""
  335. if space.is_w(space.type(w_obj), space.w_unicode):
  336. return w_obj
  337. else:
  338. return space.call_function(space.w_unicode, w_obj)
  339. @cpython_api([PyObject, CONST_STRING, CONST_STRING], PyObject)
  340. def PyUnicode_FromEncodedObject(space, w_obj, encoding, errors):
  341. """Coerce an encoded object obj to an Unicode object and return a reference with
  342. incremented refcount.
  343. String and other char buffer compatible objects are decoded according to the
  344. given encoding and using the error handling defined by errors. Both can be
  345. NULL to have the interface use the default values (see the next section for
  346. details).
  347. All other objects, including Unicode objects, cause a TypeError to be
  348. set."""
  349. if not encoding:
  350. raise oefmt(space.w_TypeError, "decoding Unicode is not supported")
  351. w_encoding = space.wrap(rffi.charp2str(encoding))
  352. if errors:
  353. w_errors = space.wrap(rffi.charp2str(errors))
  354. else:
  355. w_errors = None
  356. # - unicode is disallowed
  357. # - raise TypeError for non-string types
  358. if space.isinstance_w(w_obj, space.w_unicode):
  359. w_meth = None
  360. else:
  361. try:
  362. w_meth = space.getattr(w_obj, space.wrap('decode'))
  363. except OperationError as e:
  364. if not e.match(space, space.w_AttributeError):
  365. raise
  366. w_meth = None
  367. if w_meth is None:
  368. raise oefmt(space.w_TypeError, "decoding Unicode is not supported")
  369. return space.call_function(w_meth, w_encoding, w_errors)
  370. @cpython_api([CONST_STRING], PyObject)
  371. def PyUnicode_FromString(space, s):
  372. """Create a Unicode object from an UTF-8 encoded null-terminated char buffer"""
  373. w_str = space.newbytes(rffi.charp2str(s))
  374. return space.call_method(w_str, 'decode', space.wrap("utf-8"))
  375. @cpython_api([CONST_STRING, Py_ssize_t], PyObject, result_is_ll=True)
  376. def PyUnicode_FromStringAndSize(space, s, size):
  377. """Create a Unicode Object from the char buffer u. The bytes will be
  378. interpreted as being UTF-8 encoded. u may also be NULL which causes the
  379. contents to be undefined. It is the user's responsibility to fill in the
  380. needed data. The buffer is copied into the new object. If the buffer is not
  381. NULL, the return value might be a shared object. Therefore, modification of
  382. the resulting Unicode object is only allowed when u is NULL."""
  383. if s:
  384. return make_ref(space, PyUnicode_DecodeUTF8(
  385. space, s, size, lltype.nullptr(rffi.CCHARP.TO)))
  386. else:
  387. return rffi.cast(PyObject, new_empty_unicode(space, size))
  388. @cpython_api([rffi.INT_real], PyObject)
  389. def PyUnicode_FromOrdinal(space, ordinal):
  390. """Create a Unicode Object from the given Unicode code point ordinal.
  391. The ordinal must be in range(0x10000) on narrow Python builds
  392. (UCS2), and range(0x110000) on wide builds (UCS4). A ValueError is
  393. raised in case it is not."""
  394. w_ordinal = space.wrap(rffi.cast(lltype.Signed, ordinal))
  395. return space.call_function(space.builtin.get('unichr'), w_ordinal)
  396. @cpython_api([PyObjectP, Py_ssize_t], rffi.INT_real, error=-1)
  397. def PyUnicode_Resize(space, ref, newsize):
  398. # XXX always create a new string so far
  399. py_uni = rffi.cast(PyUnicodeObject, ref[0])
  400. if not py_uni.c_str:
  401. raise oefmt(space.w_SystemError,
  402. "PyUnicode_Resize called on already created string")
  403. try:
  404. py_newuni = new_empty_unicode(space, newsize)
  405. except MemoryError:
  406. Py_DecRef(space, ref[0])
  407. ref[0] = lltype.nullptr(PyObject.TO)
  408. raise
  409. to_cp = newsize
  410. oldsize = py_uni.c_length
  411. if oldsize < newsize:
  412. to_cp = oldsize
  413. for i in range(to_cp):
  414. py_newuni.c_str[i] = py_uni.c_str[i]
  415. Py_DecRef(space, ref[0])
  416. ref[0] = rffi.cast(PyObject, py_newuni)
  417. return 0
  418. def make_conversion_functions(suffix, encoding):
  419. @cpython_api([PyObject], PyObject)
  420. @func_renamer('PyUnicode_As%sString' % suffix)
  421. def PyUnicode_AsXXXString(space, w_unicode):
  422. """Encode a Unicode object and return the result as Python
  423. string object. Error handling is "strict". Return NULL if an
  424. exception was raised by the codec."""
  425. if not PyUnicode_Check(space, w_unicode):
  426. PyErr_BadArgument(space)
  427. return unicodeobject.encode_object(space, w_unicode, encoding, "strict")
  428. @cpython_api([CONST_STRING, Py_ssize_t, CONST_STRING], PyObject)
  429. @func_renamer('PyUnicode_Decode%s' % suffix)
  430. def PyUnicode_DecodeXXX(space, s, size, errors):
  431. """Create a Unicode object by decoding size bytes of the
  432. encoded string s. Return NULL if an exception was raised by
  433. the codec.
  434. """
  435. w_s = space.newbytes(rffi.charpsize2str(s, size))
  436. if errors:
  437. w_errors = space.wrap(rffi.charp2str(errors))
  438. else:
  439. w_errors = None
  440. return space.call_method(w_s, 'decode', space.wrap(encoding), w_errors)
  441. globals()['PyUnicode_Decode%s' % suffix] = PyUnicode_DecodeXXX
  442. @cpython_api([CONST_WSTRING, Py_ssize_t, CONST_STRING], PyObject)
  443. @func_renamer('PyUnicode_Encode%s' % suffix)
  444. def PyUnicode_EncodeXXX(space, s, size, errors):
  445. """Encode the Py_UNICODE buffer of the given size and return a
  446. Python string object. Return NULL if an exception was raised
  447. by the codec."""
  448. w_u = space.wrap(rffi.wcharpsize2unicode(s, size))
  449. if errors:
  450. w_errors = space.wrap(rffi.charp2str(errors))
  451. else:
  452. w_errors = None
  453. return space.call_method(w_u, 'encode', space.wrap(encoding), w_errors)
  454. globals()['PyUnicode_Encode%s' % suffix] = PyUnicode_EncodeXXX
  455. make_conversion_functions('UTF8', 'utf-8')
  456. make_conversion_functions('ASCII', 'ascii')
  457. make_conversion_functions('Latin1', 'latin-1')
  458. if sys.platform == 'win32':
  459. make_conversion_functions('MBCS', 'mbcs')
  460. @cpython_api([rffi.CCHARP, Py_ssize_t, rffi.CCHARP, rffi.INTP], PyObject)
  461. def PyUnicode_DecodeUTF16(space, s, size, llerrors, pbyteorder):
  462. """Decode length bytes from a UTF-16 encoded buffer string and return the
  463. corresponding Unicode object. errors (if non-NULL) defines the error
  464. handling. It defaults to "strict".
  465. If byteorder is non-NULL, the decoder starts decoding using the given byte
  466. order:
  467. *byteorder == -1: little endian
  468. *byteorder == 0: native order
  469. *byteorder == 1: big endian
  470. If *byteorder is zero, and the first two bytes of the input data are a
  471. byte order mark (BOM), the decoder switches to this byte order and the BOM is
  472. not copied into the resulting Unicode string. If *byteorder is -1 or
  473. 1, any byte order mark is copied to the output (where it will result in
  474. either a \ufeff or a \ufffe character).
  475. After completion, *byteorder is set to the current byte order at the end
  476. of input data.
  477. If byteorder is NULL, the codec starts in native order mode.
  478. Return NULL if an exception was raised by the codec."""
  479. string = rffi.charpsize2str(s, size)
  480. if pbyteorder is not None:
  481. llbyteorder = rffi.cast(lltype.Signed, pbyteorder[0])
  482. if llbyteorder < 0:
  483. byteorder = "little"
  484. elif llbyteorder > 0:
  485. byteorder = "big"
  486. else:
  487. byteorder = "native"
  488. else:
  489. byteorder = "native"
  490. if llerrors:
  491. errors = rffi.charp2str(llerrors)
  492. else:
  493. errors = None
  494. result, length, byteorder = runicode.str_decode_utf_16_helper(
  495. string, size, errors,
  496. True, # final ? false for multiple passes?
  497. None, # errorhandler
  498. byteorder)
  499. if pbyteorder is not None:
  500. pbyteorder[0] = rffi.cast(rffi.INT, byteorder)
  501. return space.wrap(result)
  502. @cpython_api([rffi.CCHARP, Py_ssize_t, rffi.CCHARP, rffi.INTP], PyObject)
  503. def PyUnicode_DecodeUTF32(space, s, size, llerrors, pbyteorder):
  504. """Decode length bytes from a UTF-32 encoded buffer string and
  505. return the corresponding Unicode object. errors (if non-NULL)
  506. defines the error handling. It defaults to "strict".
  507. If byteorder is non-NULL, the decoder starts decoding using the
  508. given byte order:
  509. *byteorder == -1: little endian
  510. *byteorder == 0: native order
  511. *byteorder == 1: big endian
  512. If *byteorder is zero, and the first four bytes of the input data
  513. are a byte order mark (BOM), the decoder switches to this byte
  514. order and the BOM is not copied into the resulting Unicode string.
  515. If *byteorder is -1 or 1, any byte order mark is copied to the
  516. output.
  517. After completion, *byteorder is set to the current byte order at
  518. the end of input data.
  519. In a narrow build codepoints outside the BMP will be decoded as
  520. surrogate pairs.
  521. If byteorder is NULL, the codec starts in native order mode.
  522. Return NULL if an exception was raised by the codec.
  523. """
  524. string = rffi.charpsize2str(s, size)
  525. if pbyteorder:
  526. llbyteorder = rffi.cast(lltype.Signed, pbyteorder[0])
  527. if llbyteorder < 0:
  528. byteorder = "little"
  529. elif llbyteorder > 0:
  530. byteorder = "big"
  531. else:
  532. byteorder = "native"
  533. else:
  534. byteorder = "native"
  535. if llerrors:
  536. errors = rffi.charp2str(llerrors)
  537. else:
  538. errors = None
  539. result, length, byteorder = runicode.str_decode_utf_32_helper(
  540. string, size, errors,
  541. True, # final ? false for multiple passes?
  542. None, # errorhandler
  543. byteorder)
  544. if pbyteorder is not None:
  545. pbyteorder[0] = rffi.cast(rffi.INT, byteorder)
  546. return space.wrap(result)
  547. @cpython_api([rffi.CWCHARP, Py_ssize_t, rffi.CCHARP, rffi.CCHARP],
  548. rffi.INT_real, error=-1)
  549. def PyUnicode_EncodeDecimal(space, s, length, output, llerrors):
  550. """Takes a Unicode string holding a decimal value and writes it
  551. into an output buffer using standard ASCII digit codes.
  552. The output buffer has to provide at least length+1 bytes of
  553. storage area. The output string is 0-terminated.
  554. The encoder converts whitespace to ' ', decimal characters to
  555. their corresponding ASCII digit and all other Latin-1 characters
  556. except \0 as-is. Characters outside this range (Unicode ordinals
  557. 1-256) are treated as errors. This includes embedded NULL bytes.
  558. Returns 0 on success, -1 on failure.
  559. """
  560. u = rffi.wcharpsize2unicode(s, length)
  561. if llerrors:
  562. errors = rffi.charp2str(llerrors)
  563. else:
  564. errors = None
  565. state = space.fromcache(CodecState)
  566. result = runicode.unicode_encode_decimal(u, length, errors,
  567. state.encode_error_handler)
  568. i = len(result)
  569. output[i] = '\0'
  570. i -= 1
  571. while i >= 0:
  572. output[i] = result[i]
  573. i -= 1
  574. return 0
  575. @cpython_api([PyObject, PyObject], rffi.INT_real, error=-2)
  576. def PyUnicode_Compare(space, w_left, w_right):
  577. """Compare two strings and return -1, 0, 1 for less than, equal, and greater
  578. than, respectively."""
  579. return space.int_w(space.cmp(w_left, w_right))
  580. @cpython_api([PyObject, PyObject], PyObject)
  581. def PyUnicode_Concat(space, w_left, w_right):
  582. """Concat two strings giving a new Unicode string."""
  583. return space.add(w_left, w_right)
  584. @cpython_api([rffi.CWCHARP, rffi.CWCHARP, Py_ssize_t], lltype.Void)
  585. def Py_UNICODE_COPY(space, target, source, length):
  586. """Roughly equivalent to memcpy() only the base size is Py_UNICODE
  587. copies sizeof(Py_UNICODE) * length bytes from source to target"""
  588. for i in range(0, length):
  589. target[i] = source[i]
  590. @cpython_api([PyObject, PyObject], PyObject)
  591. def PyUnicode_Format(space, w_format, w_args):
  592. """Return a new string object from format and args; this is analogous to
  593. format % args. The args argument must be a tuple."""
  594. return space.mod(w_format, w_args)
  595. @cpython_api([PyObject, PyObject], PyObject)
  596. def PyUnicode_Join(space, w_sep, w_seq):
  597. """Join a sequence of strings using the given separator and return
  598. the resulting Unicode string."""
  599. return space.call_method(w_sep, 'join', w_seq)
  600. @cpython_api([PyObject, PyObject, PyObject, Py_ssize_t], PyObject)
  601. def PyUnicode_Replace(space, w_str, w_substr, w_replstr, maxcount):
  602. """Replace at most maxcount occurrences of substr in str with replstr and
  603. return the resulting Unicode object. maxcount == -1 means replace all
  604. occurrences."""
  605. return space.call_method(w_str, "replace", w_substr, w_replstr,
  606. space.wrap(maxcount))
  607. @cpython_api([PyObject, PyObject, Py_ssize_t, Py_ssize_t, rffi.INT_real],
  608. rffi.INT_real, error=-1)
  609. def PyUnicode_Tailmatch(space, w_str, w_substr, start, end, direction):
  610. """Return 1 if substr matches str[start:end] at the given tail end
  611. (direction == -1 means to do a prefix match, direction == 1 a
  612. suffix match), 0 otherwise. Return -1 if an error occurred."""
  613. str = space.unicode_w(w_str)
  614. substr = space.unicode_w(w_substr)
  615. if rffi.cast(lltype.Signed, direction) <= 0:
  616. return rstring.startswith(str, substr, start, end)
  617. else:
  618. return rstring.endswith(str, substr, start, end)
  619. @cpython_api([PyObject, PyObject, Py_ssize_t, Py_ssize_t], Py_ssize_t, error=-1)
  620. def PyUnicode_Count(space, w_str, w_substr, start, end):
  621. """Return the number of non-overlapping occurrences of substr in
  622. str[start:end]. Return -1 if an error occurred."""
  623. w_count = space.call_method(w_str, "count", w_substr,
  624. space.wrap(start), space.wrap(end))
  625. return space.int_w(w_count)
  626. @cpython_api([PyObject, PyObject, Py_ssize_t, Py_ssize_t, rffi.INT_real],
  627. Py_ssize_t, error=-2)
  628. def PyUnicode_Find(space, w_str, w_substr, start, end, direction):
  629. """Return the first position of substr in str*[*start:end] using
  630. the given direction (direction == 1 means to do a forward search,
  631. direction == -1 a backward search). The return value is the index
  632. of the first match; a value of -1 indicates that no match was
  633. found, and -2 indicates that an error occurred and an exception
  634. has been set."""
  635. if rffi.cast(lltype.Signed, direction) > 0:
  636. w_pos = space.call_method(w_str, "find", w_substr,
  637. space.wrap(start), space.wrap(end))
  638. else:
  639. w_pos = space.call_method(w_str, "rfind", w_substr,
  640. space.wrap(start), space.wrap(end))
  641. return space.int_w(w_pos)
  642. @cpython_api([PyObject, PyObject, Py_ssize_t], PyObject)
  643. def PyUnicode_Split(space, w_str, w_sep, maxsplit):
  644. """Split a string giving a list of Unicode strings. If sep is
  645. NULL, splitting will be done at all whitespace substrings.
  646. Otherwise, splits occur at the given separator. At most maxsplit
  647. splits will be done. If negative, no limit is set. Separators
  648. are not included in the resulting list."""
  649. if w_sep is None:
  650. w_sep = space.w_None
  651. return space.call_method(w_str, "split", w_sep, space.wrap(maxsplit))
  652. @cpython_api([PyObject, rffi.INT_real], PyObject)
  653. def PyUnicode_Splitlines(space, w_str, keepend):
  654. """Split a Unicode string at line breaks, returning a list of
  655. Unicode strings. CRLF is considered to be one line break. If
  656. keepend is 0, the Line break characters are not included in the
  657. resulting strings."""
  658. return space.call_method(w_str, "splitlines", space.wrap(keepend))