[libc-commits] [libc] 6b8d072 - [libc] Fix incorrect unsigned comparison (#135595)
via libc-commits
libc-commits at lists.llvm.org
Wed Apr 16 18:33:51 PDT 2025
Author: Wu Yingcong
Date: 2025-04-17T09:33:48+08:00
New Revision: 6b8d072cfd41f647f2c241f0a1a0843a279d049b
URL: https://github.com/llvm/llvm-project/commit/6b8d072cfd41f647f2c241f0a1a0843a279d049b
DIFF: https://github.com/llvm/llvm-project/commit/6b8d072cfd41f647f2c241f0a1a0843a279d049b.diff
LOG: [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`.
Added:
Modified:
libc/src/stdio/printf_core/float_dec_converter.h
Removed:
################################################################################
diff --git a/libc/src/stdio/printf_core/float_dec_converter.h b/libc/src/stdio/printf_core/float_dec_converter.h
index ee5549825a6f2..ed004f9a26a13 100644
--- a/libc/src/stdio/printf_core/float_dec_converter.h
+++ b/libc/src/stdio/printf_core/float_dec_converter.h
@@ -186,13 +186,12 @@ template <WriteMode write_mode> class FloatWriter {
if (total_digits_written < digits_before_decimal &&
total_digits_written + buffered_digits >= digits_before_decimal &&
has_decimal_point) {
+ // digits_to_write > 0 guaranteed by outer if
size_t digits_to_write = digits_before_decimal - total_digits_written;
- if (digits_to_write > 0) {
- // Write the digits before the decimal point.
- RET_IF_RESULT_NEGATIVE(writer->write({block_buffer, digits_to_write}));
- }
+ // Write the digits before the decimal point.
+ RET_IF_RESULT_NEGATIVE(writer->write({block_buffer, digits_to_write}));
RET_IF_RESULT_NEGATIVE(writer->write(DECIMAL_POINT));
- if (buffered_digits - digits_to_write > 0) {
+ if (buffered_digits > digits_to_write) {
// Write the digits after the decimal point.
RET_IF_RESULT_NEGATIVE(
writer->write({block_buffer + digits_to_write,
@@ -217,12 +216,11 @@ template <WriteMode write_mode> class FloatWriter {
total_digits_written + BLOCK_SIZE * max_block_count >=
digits_before_decimal &&
has_decimal_point) {
+ // digits_to_write > 0 guaranteed by outer if
size_t digits_to_write = digits_before_decimal - total_digits_written;
- if (digits_to_write > 0) {
- RET_IF_RESULT_NEGATIVE(writer->write(MAX_BLOCK_DIGIT, digits_to_write));
- }
+ RET_IF_RESULT_NEGATIVE(writer->write(MAX_BLOCK_DIGIT, digits_to_write));
RET_IF_RESULT_NEGATIVE(writer->write(DECIMAL_POINT));
- if ((BLOCK_SIZE * max_block_count) - digits_to_write > 0) {
+ if ((BLOCK_SIZE * max_block_count) > digits_to_write) {
RET_IF_RESULT_NEGATIVE(writer->write(
MAX_BLOCK_DIGIT, (BLOCK_SIZE * max_block_count) - digits_to_write));
}
More information about the libc-commits
mailing list