gh-95504: Fix negative numbers in PyUnicode_FromFormat (GH-95848)

Co-authored-by: philg314 <110174000+philg314@users.noreply.github.com>
This commit is contained in:
Petr Viktorin 2022-08-10 13:12:40 +02:00 committed by GitHub
parent cf28540fd3
commit 71c3d649b5
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
5 changed files with 86 additions and 7 deletions

View file

@ -2481,21 +2481,34 @@ unicode_fromformat_arg(_PyUnicodeWriter *writer,
}
assert(len >= 0);
if (precision < len)
precision = len;
int negative = (buffer[0] == '-');
len -= negative;
precision = Py_MAX(precision, len);
width = Py_MAX(width, precision + negative);
arglen = Py_MAX(precision, width);
if (_PyUnicodeWriter_Prepare(writer, arglen, 127) == -1)
return NULL;
if (width > precision) {
Py_UCS4 fillchar;
fill = width - precision;
fillchar = zeropad?'0':' ';
if (negative && zeropad) {
if (_PyUnicodeWriter_WriteChar(writer, '-') == -1)
return NULL;
}
Py_UCS4 fillchar = zeropad?'0':' ';
fill = width - precision - negative;
if (PyUnicode_Fill(writer->buffer, writer->pos, fill, fillchar) == -1)
return NULL;
writer->pos += fill;
if (negative && !zeropad) {
if (_PyUnicodeWriter_WriteChar(writer, '-') == -1)
return NULL;
}
}
if (precision > len) {
fill = precision - len;
if (PyUnicode_Fill(writer->buffer, writer->pos, fill, '0') == -1)
@ -2503,7 +2516,7 @@ unicode_fromformat_arg(_PyUnicodeWriter *writer,
writer->pos += fill;
}
if (_PyUnicodeWriter_WriteASCIIString(writer, buffer, len) < 0)
if (_PyUnicodeWriter_WriteASCIIString(writer, &buffer[negative], len) < 0)
return NULL;
break;
}