Skip to content

Commit a7fd73e

Browse files
[3.13] gh-60462: Fix locale.strxfrm() on Solaris (GH-138242) (GH-138449)
It should interpret the result of wcsxfrm() as a sequence of abstract integers, not a sequence of Unicode code points or using other encoding scheme that does not preserve ordering. (cherry picked from commit 482fd0c) Co-authored-by: Serhiy Storchaka <[email protected]>
1 parent 50048aa commit a7fd73e

File tree

2 files changed

+49
-1
lines changed

2 files changed

+49
-1
lines changed
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Fix :func:`locale.strxfrm` on Solaris (and possibly other platforms).

Modules/_localemodule.c

Lines changed: 48 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -472,7 +472,54 @@ _locale_strxfrm_impl(PyObject *module, PyObject *str)
472472
goto exit;
473473
}
474474
}
475-
result = PyUnicode_FromWideChar(buf, n2);
475+
/* The result is just a sequence of integers, they are not necessary
476+
Unicode code points, so PyUnicode_FromWideChar() cannot be used
477+
here. For example, 0xD83D 0xDC0D should not be larger than 0xFF41.
478+
*/
479+
#if SIZEOF_WCHAR_T == 4
480+
{
481+
/* Some codes can exceed the range of Unicode code points
482+
(0 - 0x10FFFF), so they cannot be directly used in
483+
PyUnicode_FromKindAndData(). They should be first encoded in
484+
a way that preserves the lexicographical order.
485+
486+
Codes in the range 0-0xFFFF represent themself.
487+
Codes larger than 0xFFFF are encoded as a pair:
488+
* 0x1xxxx -- the highest 16 bits
489+
* 0x0xxxx -- the lowest 16 bits
490+
*/
491+
size_t n3 = 0;
492+
for (size_t i = 0; i < n2; i++) {
493+
if ((Py_UCS4)buf[i] > 0x10000u) {
494+
n3++;
495+
}
496+
}
497+
if (n3) {
498+
n3 += n2; // no integer overflow
499+
Py_UCS4 *buf2 = PyMem_New(Py_UCS4, n3);
500+
if (buf2 == NULL) {
501+
PyErr_NoMemory();
502+
goto exit;
503+
}
504+
size_t j = 0;
505+
for (size_t i = 0; i < n2; i++) {
506+
Py_UCS4 c = (Py_UCS4)buf[i];
507+
if (c > 0x10000u) {
508+
buf2[j++] = (c >> 16) | 0x10000u;
509+
buf2[j++] = c & 0xFFFFu;
510+
}
511+
else {
512+
buf2[j++] = c;
513+
}
514+
}
515+
assert(j == n3);
516+
result = PyUnicode_FromKindAndData(PyUnicode_4BYTE_KIND, buf2, n3);
517+
PyMem_Free(buf2);
518+
goto exit;
519+
}
520+
}
521+
#endif
522+
result = PyUnicode_FromKindAndData(sizeof(wchar_t), buf, n2);
476523
exit:
477524
PyMem_Free(buf);
478525
PyMem_Free(s);

0 commit comments

Comments
 (0)