ruby-changes:46340
From: nobu <ko1@a...>
Date: Sun, 23 Apr 2017 10:04:46 +0900 (JST)
Subject: [ruby-changes:46340] nobu:r58454 (trunk): Refactor "%f" % Inf/NaN
nobu 2017-04-23 10:04:40 +0900 (Sun, 23 Apr 2017) New Revision: 58454 https://svn.ruby-lang.org/cgi-bin/viewvc.cgi?view=revision&revision=58454 Log: Refactor "%f" % Inf/NaN * sprintf.c (rb_str_format): as for non-finite float, calculate the exact needed size with the space flag. Modified files: trunk/sprintf.c Index: sprintf.c =================================================================== --- sprintf.c (revision 58453) +++ sprintf.c (revision 58454) @@ -1128,6 +1128,8 @@ rb_str_format(int argc, const VALUE *arg https://github.com/ruby/ruby/blob/trunk/sprintf.c#L1128 fval = RFLOAT_VALUE(rb_Float(val)); if (isnan(fval) || isinf(fval)) { const char *expr; + int elen; + char sign = '\0'; if (isnan(fval)) { expr = "NaN"; @@ -1136,31 +1138,28 @@ rb_str_format(int argc, const VALUE *arg https://github.com/ruby/ruby/blob/trunk/sprintf.c#L1138 expr = "Inf"; } need = (int)strlen(expr); - if ((!isnan(fval) && fval < 0.0) || (flags & (FPLUS|FSPACE))) - need++; + elen = 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) need = width; - CHECK(need + 1); - snprintf(&buf[blen], need + 1, "%*s", need, ""); + 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, strlen(expr)); + if (sign) + buf[blen - need--] = sign; + memcpy(&buf[blen - need], expr, elen); } else { - if (!isnan(fval) && fval < 0.0) - buf[blen + need - strlen(expr) - 1] = '-'; - else if (flags & FPLUS) - buf[blen + need - strlen(expr) - 1] = '+'; - memcpy(&buf[blen + need - strlen(expr)], expr, - strlen(expr)); + if (sign) + buf[blen - elen - 1] = sign; + memcpy(&buf[blen - elen], expr, elen); } - blen += strlen(&buf[blen]); break; } -- ML: ruby-changes@q... Info: http://www.atdot.net/~ko1/quickml/