Refactor "%f" % Inf/NaN
* sprintf.c (rb_str_format): as for non-finite float, calculate the exact needed size with the space flag. git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk@58454 b2dd03c8-39d4-4d8f-98ff-823fe69b080e
This commit is contained in:
parent
6f8f950cc3
commit
be7309ddf6
35
sprintf.c
35
sprintf.c
@ -1128,6 +1128,8 @@ rb_str_format(int argc, const VALUE *argv, VALUE fmt)
|
|||||||
fval = RFLOAT_VALUE(rb_Float(val));
|
fval = RFLOAT_VALUE(rb_Float(val));
|
||||||
if (isnan(fval) || isinf(fval)) {
|
if (isnan(fval) || isinf(fval)) {
|
||||||
const char *expr;
|
const char *expr;
|
||||||
|
int elen;
|
||||||
|
char sign = '\0';
|
||||||
|
|
||||||
if (isnan(fval)) {
|
if (isnan(fval)) {
|
||||||
expr = "NaN";
|
expr = "NaN";
|
||||||
@ -1136,31 +1138,28 @@ rb_str_format(int argc, const VALUE *argv, VALUE fmt)
|
|||||||
expr = "Inf";
|
expr = "Inf";
|
||||||
}
|
}
|
||||||
need = (int)strlen(expr);
|
need = (int)strlen(expr);
|
||||||
if ((!isnan(fval) && fval < 0.0) || (flags & (FPLUS|FSPACE)))
|
elen = need;
|
||||||
need++;
|
i = 0;
|
||||||
|
if (!isnan(fval) && fval < 0.0)
|
||||||
|
sign = '-';
|
||||||
|
else if (flags & (FPLUS|FSPACE))
|
||||||
|
sign = (flags & FPLUS) ? '+' : ' ';
|
||||||
|
if (sign)
|
||||||
|
++need;
|
||||||
if ((flags & FWIDTH) && need < width)
|
if ((flags & FWIDTH) && need < width)
|
||||||
need = width;
|
need = width;
|
||||||
|
|
||||||
CHECK(need + 1);
|
FILL(' ', need);
|
||||||
snprintf(&buf[blen], need + 1, "%*s", need, "");
|
|
||||||
if (flags & FMINUS) {
|
if (flags & FMINUS) {
|
||||||
if (!isnan(fval) && fval < 0.0)
|
if (sign)
|
||||||
buf[blen++] = '-';
|
buf[blen - need--] = sign;
|
||||||
else if (flags & FPLUS)
|
memcpy(&buf[blen - need], expr, elen);
|
||||||
buf[blen++] = '+';
|
|
||||||
else if (flags & FSPACE)
|
|
||||||
blen++;
|
|
||||||
memcpy(&buf[blen], expr, strlen(expr));
|
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
if (!isnan(fval) && fval < 0.0)
|
if (sign)
|
||||||
buf[blen + need - strlen(expr) - 1] = '-';
|
buf[blen - elen - 1] = sign;
|
||||||
else if (flags & FPLUS)
|
memcpy(&buf[blen - elen], expr, elen);
|
||||||
buf[blen + need - strlen(expr) - 1] = '+';
|
|
||||||
memcpy(&buf[blen + need - strlen(expr)], expr,
|
|
||||||
strlen(expr));
|
|
||||||
}
|
}
|
||||||
blen += strlen(&buf[blen]);
|
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Loading…
x
Reference in New Issue
Block a user