Skip to content

Commit 482fd0c

Browse files
gh-60462: Fix locale.strxfrm() on Solaris (GH-138242)
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.
1 parent 2985c63 commit 482fd0c

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
@@ -483,7 +483,54 @@ _locale_strxfrm_impl(PyObject *module, PyObject *str)
483483
goto exit;
484484
}
485485
}
486-
result = PyUnicode_FromWideChar(buf, n2);
486+
/* The result is just a sequence of integers, they are not necessary
487+
Unicode code points, so PyUnicode_FromWideChar() cannot be used
488+
here. For example, 0xD83D 0xDC0D should not be larger than 0xFF41.
489+
*/
490+
#if SIZEOF_WCHAR_T == 4
491+
{
492+
/* Some codes can exceed the range of Unicode code points
493+
(0 - 0x10FFFF), so they cannot be directly used in
494+
PyUnicode_FromKindAndData(). They should be first encoded in
495+
a way that preserves the lexicographical order.
496+
497+
Codes in the range 0-0xFFFF represent themself.
498+
Codes larger than 0xFFFF are encoded as a pair:
499+
* 0x1xxxx -- the highest 16 bits
500+
* 0x0xxxx -- the lowest 16 bits
501+
*/
502+
size_t n3 = 0;
503+
for (size_t i = 0; i < n2; i++) {
504+
if ((Py_UCS4)buf[i] > 0x10000u) {
505+
n3++;
506+
}
507+
}
508+
if (n3) {
509+
n3 += n2; // no integer overflow
510+
Py_UCS4 *buf2 = PyMem_New(Py_UCS4, n3);
511+
if (buf2 == NULL) {
512+
PyErr_NoMemory();
513+
goto exit;
514+
}
515+
size_t j = 0;
516+
for (size_t i = 0; i < n2; i++) {
517+
Py_UCS4 c = (Py_UCS4)buf[i];
518+
if (c > 0x10000u) {
519+
buf2[j++] = (c >> 16) | 0x10000u;
520+
buf2[j++] = c & 0xFFFFu;
521+
}
522+
else {
523+
buf2[j++] = c;
524+
}
525+
}
526+
assert(j == n3);
527+
result = PyUnicode_FromKindAndData(PyUnicode_4BYTE_KIND, buf2, n3);
528+
PyMem_Free(buf2);
529+
goto exit;
530+
}
531+
}
532+
#endif
533+
result = PyUnicode_FromKindAndData(sizeof(wchar_t), buf, n2);
487534
exit:
488535
PyMem_Free(buf);
489536
PyMem_Free(s);

0 commit comments

Comments
 (0)