Skip to content

Commit

Permalink
Refactor "%f" % Inf/NaN
Browse files Browse the repository at this point in the history
As for non-finite float, calculate the exact needed size with the
space flag.
  • Loading branch information
nobu committed Apr 23, 2017
1 parent 7314423 commit cd4e9a0
Showing 1 changed file with 14 additions and 20 deletions.
34 changes: 14 additions & 20 deletions mrbgems/mruby-sprintf/src/sprintf.c
Original file line number Diff line number Diff line change
Expand Up @@ -1040,6 +1040,7 @@ mrb_str_format(mrb_state *mrb, int argc, const mrb_value *argv, mrb_value fmt)
if (!isfinite(fval)) {
const char *expr;
const int elen = 3;
char sign = '\0';

if (isnan(fval)) {
expr = "NaN";
Expand All @@ -1048,33 +1049,26 @@ mrb_str_format(mrb_state *mrb, int argc, const mrb_value *argv, mrb_value fmt)
expr = "Inf";
}
need = elen;
if ((!isnan(fval) && fval < 0.0) || (flags & (FPLUS|FSPACE)))
need++;
if (!isnan(fval) && fval < 0.0)
sign = '-';
else if (flags & (FPLUS|FSPACE))
sign = (flags & FPLUS) ? '+' : ' ';
if (sign)
++need;
if ((flags & FWIDTH) && need < width)
need = width;

CHECK(need + 1);
n = snprintf(&buf[blen], need + 1, "%*s", need, "");
if (n < 0) {
mrb_raise(mrb, E_RUNTIME_ERROR, "formatting error");
}
FILL(' ', need);
if (flags & FMINUS) {
if (!isnan(fval) && fval < 0.0)
buf[blen++] = '-';
else if (flags & FPLUS)
buf[blen++] = '+';
else if (flags & FSPACE)
blen++;
memcpy(&buf[blen], expr, elen);
if (sign)
buf[blen - need--] = sign;
memcpy(&buf[blen - need], expr, elen);
}
else {
if (!isnan(fval) && fval < 0.0)
buf[blen + need - elen - 1] = '-';
else if (flags & FPLUS)
buf[blen + need - elen - 1] = '+';
memcpy(&buf[blen + need - elen], expr, elen);
if (sign)
buf[blen - elen - 1] = sign;
memcpy(&buf[blen - elen], expr, elen);
}
blen += strlen(&buf[blen]);
break;
}

Expand Down

0 comments on commit cd4e9a0

Please sign in to comment.