From 83bd7e949ab0dfb41adf53708060ac9392a1b780 Mon Sep 17 00:00:00 2001 From: Charles Nicholson Date: Wed, 23 Nov 2022 23:12:36 -0500 Subject: [PATCH] if string precision is set, don't let the strlen loop run past the specified precision (#234) * if string precision is set, don't let the strlen loop run past the specified precision * rewrite to one loop, see if it's smaller * remove npf_min --- nanoprintf.h | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/nanoprintf.h b/nanoprintf.h index 1e0c513..1d2e4e3 100644 --- a/nanoprintf.h +++ b/nanoprintf.h @@ -283,7 +283,6 @@ static int npf_bin_len(npf_uint_t i); #include #endif -static int npf_min(int x, int y) { return (x < y) ? x : y; } static int npf_max(int x, int y) { return (x > y) ? x : y; } int npf_parse_format_spec(char const *format, npf_format_spec_t *out_spec) { @@ -762,11 +761,11 @@ int npf_vpprintf(npf_putc pc, void *pc_ctx, char const *format, va_list args) { case NPF_FMT_SPEC_CONV_STRING: { cbuf = va_arg(args, char *); - for (char const *s = cbuf; *s; ++s, ++cbuf_len); // strlen #if NANOPRINTF_USE_PRECISION_FORMAT_SPECIFIERS == 1 - if (fs.prec_opt == NPF_FMT_SPEC_OPT_LITERAL) { - cbuf_len = npf_min(fs.prec, cbuf_len); // prec truncates strings - } + int const n = (fs.prec_opt == NPF_FMT_SPEC_OPT_NONE) ? -1 : fs.prec; + for (char const *s = cbuf; *s && ((n == -1) || (cbuf_len < n)); ++s, ++cbuf_len); +#else + for (char const *s = cbuf; *s; ++s, ++cbuf_len); // strlen #endif } break;