Skip to content

Commit 6b8d072

Browse files
authored
[libc] Fix incorrect unsigned comparison (#135595)
There is a problem with such unsigned comparison pattern: ``` if(unsigned_a - unsigned_b > 0) { /* only NOT go here when unsigned_a==unsigned_b */ } ``` When `unsigned_a` < `unsigned_b`, the result will still be `>0` due to underflow. This patch fixes two of the occurrences I found. Also remove two redundant `if` where its condition is guaranteed by outer `if`.
1 parent 6d8bf3c commit 6b8d072

File tree

1 file changed

+7
-9
lines changed

1 file changed

+7
-9
lines changed

Diff for: libc/src/stdio/printf_core/float_dec_converter.h

+7-9
Original file line numberDiff line numberDiff line change
@@ -186,13 +186,12 @@ template <WriteMode write_mode> class FloatWriter {
186186
if (total_digits_written < digits_before_decimal &&
187187
total_digits_written + buffered_digits >= digits_before_decimal &&
188188
has_decimal_point) {
189+
// digits_to_write > 0 guaranteed by outer if
189190
size_t digits_to_write = digits_before_decimal - total_digits_written;
190-
if (digits_to_write > 0) {
191-
// Write the digits before the decimal point.
192-
RET_IF_RESULT_NEGATIVE(writer->write({block_buffer, digits_to_write}));
193-
}
191+
// Write the digits before the decimal point.
192+
RET_IF_RESULT_NEGATIVE(writer->write({block_buffer, digits_to_write}));
194193
RET_IF_RESULT_NEGATIVE(writer->write(DECIMAL_POINT));
195-
if (buffered_digits - digits_to_write > 0) {
194+
if (buffered_digits > digits_to_write) {
196195
// Write the digits after the decimal point.
197196
RET_IF_RESULT_NEGATIVE(
198197
writer->write({block_buffer + digits_to_write,
@@ -217,12 +216,11 @@ template <WriteMode write_mode> class FloatWriter {
217216
total_digits_written + BLOCK_SIZE * max_block_count >=
218217
digits_before_decimal &&
219218
has_decimal_point) {
219+
// digits_to_write > 0 guaranteed by outer if
220220
size_t digits_to_write = digits_before_decimal - total_digits_written;
221-
if (digits_to_write > 0) {
222-
RET_IF_RESULT_NEGATIVE(writer->write(MAX_BLOCK_DIGIT, digits_to_write));
223-
}
221+
RET_IF_RESULT_NEGATIVE(writer->write(MAX_BLOCK_DIGIT, digits_to_write));
224222
RET_IF_RESULT_NEGATIVE(writer->write(DECIMAL_POINT));
225-
if ((BLOCK_SIZE * max_block_count) - digits_to_write > 0) {
223+
if ((BLOCK_SIZE * max_block_count) > digits_to_write) {
226224
RET_IF_RESULT_NEGATIVE(writer->write(
227225
MAX_BLOCK_DIGIT, (BLOCK_SIZE * max_block_count) - digits_to_write));
228226
}

0 commit comments

Comments
 (0)