aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorMarco Paland <marco@paland.com>2018-09-14 14:42:41 +0200
committerMarco Paland <marco@paland.com>2018-09-14 14:42:41 +0200
commit7075d314a0875caa45c8571f7aa52f732f3612a9 (patch)
treed565c1968a83557fcd6b614e5f6deaa0eda346d2
parent6dae1687b5fd4dd7ee104079da0df906fe393263 (diff)
downloadprintf-7075d314a0875caa45c8571f7aa52f732f3612a9.tar.gz
printf-7075d314a0875caa45c8571f7aa52f732f3612a9.tar.bz2
printf-7075d314a0875caa45c8571f7aa52f732f3612a9.zip
fix(printf): zero precision and zero value hash problem
Fixes #26
-rw-r--r--printf.c16
-rw-r--r--test/test_suite.cpp14
2 files changed, 27 insertions, 3 deletions
diff --git a/printf.c b/printf.c
index d71665f..9ef669f 100644
--- a/printf.c
+++ b/printf.c
@@ -163,9 +163,9 @@ static size_t _ntoa_format(out_fct_type out, char* buffer, size_t idx, size_t ma
// handle hash
if (flags & FLAGS_HASH) {
- if (((len == prec) || (len == width)) && (len > 0U)) {
+ if (len && ((len == prec) || (len == width))) {
len--;
- if ((base == 16U) && (len > 0U)) {
+ if (len && (base == 16U)) {
len--;
}
}
@@ -181,7 +181,7 @@ static size_t _ntoa_format(out_fct_type out, char* buffer, size_t idx, size_t ma
}
// handle sign
- if ((len == width) && (negative || (flags & FLAGS_PLUS) || (flags & FLAGS_SPACE))) {
+ if (len && (len == width) && (negative || (flags & FLAGS_PLUS) || (flags & FLAGS_SPACE))) {
len--;
}
if (len < PRINTF_NTOA_BUFFER_SIZE) {
@@ -225,6 +225,11 @@ static size_t _ntoa_long(out_fct_type out, char* buffer, size_t idx, size_t maxl
char buf[PRINTF_NTOA_BUFFER_SIZE];
size_t len = 0U;
+ // no hash for 0 values
+ if (!value) {
+ flags &= ~FLAGS_HASH;
+ }
+
// write if precision != 0 and value is != 0
if (!(flags & FLAGS_PRECISION) || value) {
do {
@@ -245,6 +250,11 @@ static size_t _ntoa_long_long(out_fct_type out, char* buffer, size_t idx, size_t
char buf[PRINTF_NTOA_BUFFER_SIZE];
size_t len = 0U;
+ // no hash for 0 values
+ if (!value) {
+ flags &= ~FLAGS_HASH;
+ }
+
// write if precision != 0 and value is != 0
if (!(flags & FLAGS_PRECISION) || value) {
do {
diff --git a/test/test_suite.cpp b/test/test_suite.cpp
index e693851..99e07b7 100644
--- a/test/test_suite.cpp
+++ b/test/test_suite.cpp
@@ -247,6 +247,9 @@ TEST_CASE("+ flag", "[]" ) {
test::sprintf(buffer, "%+c", 'x');
REQUIRE(!strcmp(buffer, "x"));
+
+ test::sprintf(buffer, "%+.0d", 0);
+ REQUIRE(!strcmp(buffer, "+"));
}
@@ -344,6 +347,14 @@ TEST_CASE("- flag", "[]" ) {
}
+TEST_CASE("# flag", "[]" ) {
+ char buffer[100];
+
+ test::sprintf(buffer, "%#.0x", 0);
+ REQUIRE(!strcmp(buffer, ""));
+}
+
+
TEST_CASE("specifier", "[]" ) {
char buffer[100];
@@ -1232,6 +1243,9 @@ TEST_CASE("misc", "[]" ) {
test::sprintf(buffer, "%.3s", "foobar");
REQUIRE(!strcmp(buffer, "foo"));
+ test::sprintf(buffer, "% .0d", 0);
+ REQUIRE(!strcmp(buffer, " "));
+
test::sprintf(buffer, "%10.5d", 4);
REQUIRE(!strcmp(buffer, " 00004"));