Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit eb4b5ac

Browse files
committed
Close #16757: Avoid calling the expensive _PyUnicode_FindMaxChar() function
when possible
1 parent cfc4c13 commit eb4b5ac

2 files changed

Lines changed: 15 additions & 8 deletions

File tree

Objects/unicodeobject.c

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -13777,7 +13777,7 @@ unicode_format_arg_output(struct unicode_formatter_t *ctx,
1377713777
Py_ssize_t pindex;
1377813778
Py_UCS4 signchar;
1377913779
Py_ssize_t buflen;
13780-
Py_UCS4 maxchar, bufmaxchar;
13780+
Py_UCS4 maxchar;
1378113781
Py_ssize_t sublen;
1378213782
_PyUnicodeWriter *writer = &ctx->writer;
1378313783
Py_UCS4 fill;
@@ -13830,23 +13830,26 @@ unicode_format_arg_output(struct unicode_formatter_t *ctx,
1383013830
arg->width = len;
1383113831

1383213832
/* Prepare the writer */
13833-
bufmaxchar = 127;
13833+
maxchar = writer->maxchar;
1383413834
if (!(arg->flags & F_LJUST)) {
1383513835
if (arg->sign) {
1383613836
if ((arg->width-1) > len)
13837-
bufmaxchar = MAX_MAXCHAR(bufmaxchar, fill);
13837+
maxchar = MAX_MAXCHAR(maxchar, fill);
1383813838
}
1383913839
else {
1384013840
if (arg->width > len)
13841-
bufmaxchar = MAX_MAXCHAR(bufmaxchar, fill);
13841+
maxchar = MAX_MAXCHAR(maxchar, fill);
1384213842
}
1384313843
}
13844-
maxchar = _PyUnicode_FindMaxChar(str, 0, pindex+len);
13845-
bufmaxchar = MAX_MAXCHAR(bufmaxchar, maxchar);
13844+
if (PyUnicode_MAX_CHAR_VALUE(str) > maxchar) {
13845+
Py_UCS4 strmaxchar = _PyUnicode_FindMaxChar(str, 0, pindex+len);
13846+
maxchar = MAX_MAXCHAR(maxchar, strmaxchar);
13847+
}
13848+
1384613849
buflen = arg->width;
1384713850
if (arg->sign && len == arg->width)
1384813851
buflen++;
13849-
if (_PyUnicodeWriter_Prepare(writer, buflen, bufmaxchar) == -1)
13852+
if (_PyUnicodeWriter_Prepare(writer, buflen, maxchar) == -1)
1385013853
return -1;
1385113854

1385213855
/* Write the sign if needed */

Python/formatter_unicode.c

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -771,9 +771,13 @@ format_string_internal(PyObject *value, const InternalFormatSpec *format,
771771

772772
calc_padding(len, format->width, format->align, &lpad, &rpad, &total);
773773

774-
maxchar = _PyUnicode_FindMaxChar(value, 0, len);
774+
maxchar = writer->maxchar;
775775
if (lpad != 0 || rpad != 0)
776776
maxchar = Py_MAX(maxchar, format->fill_char);
777+
if (PyUnicode_MAX_CHAR_VALUE(value) > maxchar) {
778+
Py_UCS4 valmaxchar = _PyUnicode_FindMaxChar(value, 0, len);
779+
maxchar = Py_MAX(maxchar, valmaxchar);
780+
}
777781

778782
/* allocate the resulting string */
779783
if (_PyUnicodeWriter_Prepare(writer, total, maxchar) == -1)

0 commit comments

Comments
 (0)