Skip to content

Commit

Permalink
if string precision is set, don't let the strlen loop run past the sp…
Browse files Browse the repository at this point in the history
…ecified 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
  • Loading branch information
charlesnicholson authored Nov 24, 2022
1 parent 4e3d491 commit 83bd7e9
Showing 1 changed file with 4 additions and 5 deletions.
9 changes: 4 additions & 5 deletions nanoprintf.h
Original file line number Diff line number Diff line change
Expand Up @@ -283,7 +283,6 @@ static int npf_bin_len(npf_uint_t i);
#include <intrin.h>
#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) {
Expand Down Expand Up @@ -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;

Expand Down

0 comments on commit 83bd7e9

Please sign in to comment.