summaryrefslogtreecommitdiff
path: root/sprintf.c
diff options
context:
space:
mode:
authorusa <usa@b2dd03c8-39d4-4d8f-98ff-823fe69b080e>2017-06-30 10:47:34 +0000
committerusa <usa@b2dd03c8-39d4-4d8f-98ff-823fe69b080e>2017-06-30 10:47:34 +0000
commitd25b9efdaa40041a894206e54a3e3ee83b2f106b (patch)
treea75b2f44a925648ee909a3e6546b2ea5f1f24ef8 /sprintf.c
parentef763e7d0c1f7b1d1e3a2b6ed593fd324c3264e9 (diff)
merge revision(s) 58453,58454: [Backport #13499]
Fix space flag when Inf/NaN and width==3 * sprintf.c (rb_str_format): while `"% 2f"` and `"% 4f"` result in `" Inf"` and `" Inf"` respectively, `"% 3f"` results in `"Inf"` (no space). 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/branches/ruby_2_3@59218 b2dd03c8-39d4-4d8f-98ff-823fe69b080e
Diffstat (limited to 'sprintf.c')
-rw-r--r--sprintf.c37
1 files changed, 17 insertions, 20 deletions
diff --git a/sprintf.c b/sprintf.c
index 6c49fe07b6..bc1c629058 100644
--- a/sprintf.c
+++ b/sprintf.c
@@ -1147,6 +1147,8 @@ rb_str_format(int argc, const VALUE *argv, VALUE fmt)
fval = RFLOAT_VALUE(rb_Float(val));
if (isnan(fval) || isinf(fval)) {
const char *expr;
+ int elen;
+ char sign = '\0';
if (isnan(fval)) {
expr = "NaN";
@@ -1155,33 +1157,28 @@ rb_str_format(int argc, const VALUE *argv, VALUE fmt)
expr = "Inf";
}
need = (int)strlen(expr);
- if ((!isnan(fval) && fval < 0.0) || (flags & FPLUS))
- 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] = '+';
- else if ((flags & FSPACE) && need > width)
- blen++;
- 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;
}