PageRenderTime 58ms CodeModel.GetById 26ms RepoModel.GetById 1ms app.codeStats 0ms

/pypy/module/cpyext/unicodeobject.py

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