From 170344b20ec9e3340d9bb41e9f7434ccd2ae6365 Mon Sep 17 00:00:00 2001 From: nobu Date: Thu, 19 Sep 2013 07:25:09 +0000 Subject: vsnprintf.c: initialize cp * vsnprintf.c (BSD_vfprintf): initialize cp so that size is 0 in the commented case. fix an accidental bug at r16716. git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk@42977 b2dd03c8-39d4-4d8f-98ff-823fe69b080e --- ext/-test-/printf/printf.c | 62 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) (limited to 'ext/-test-') diff --git a/ext/-test-/printf/printf.c b/ext/-test-/printf/printf.c index 28a158beb4..53aad85f19 100644 --- a/ext/-test-/printf/printf.c +++ b/ext/-test-/printf/printf.c @@ -27,6 +27,67 @@ printf_test_q(VALUE self, VALUE obj) return rb_enc_sprintf(rb_usascii_encoding(), "[% "PRIsVALUE"]", obj); } +static char * +utoa(char *p, char *e, unsigned int x) +{ + char *e0 = e; + if (e <= p) return p; + do { + *--e = x % 10 + '0'; + } while ((x /= 10) != 0 && e > p); + memmove(p, e, e0 - e); + return p + (e0 - e); +} + +static VALUE +printf_test_call(int argc, VALUE *argv, VALUE self) +{ + VALUE opt, type, num; + char format[sizeof(int) * 6 + 8], *p = format, cnv; + int n; + + rb_scan_args(argc, argv, "2:", &type, &num, &opt); + Check_Type(type, T_STRING); + if (RSTRING_LEN(type) != 1) rb_raise(rb_eArgError, "wrong length(%ld)", RSTRING_LEN(type)); + switch (cnv = RSTRING_PTR(type)[0]) { + case 'd': case 'x': case 'o': case 'X': break; + default: rb_raise(rb_eArgError, "wrong conversion(%c)", cnv); + } + n = NUM2INT(num); + *p++ = '%'; + if (!NIL_P(opt)) { + VALUE v; + Check_Type(opt, T_HASH); + if (RTEST(rb_hash_aref(opt, ID2SYM(rb_intern("space"))))) { + *p++ = ' '; + } + if (RTEST(rb_hash_aref(opt, ID2SYM(rb_intern("hash"))))) { + *p++ = '#'; + } + if (RTEST(rb_hash_aref(opt, ID2SYM(rb_intern("plus"))))) { + *p++ = '+'; + } + if (RTEST(rb_hash_aref(opt, ID2SYM(rb_intern("minus"))))) { + *p++ = '-'; + } + if (RTEST(rb_hash_aref(opt, ID2SYM(rb_intern("zero"))))) { + *p++ = '0'; + } + if (!NIL_P(v = rb_hash_aref(opt, ID2SYM(rb_intern("width"))))) { + p = utoa(p, format + sizeof(format), NUM2UINT(v)); + } + if (!NIL_P(v = rb_hash_aref(opt, ID2SYM(rb_intern("prec"))))) { + *p++ = '.'; + if (FIXNUM_P(v)) + p = utoa(p, p + sizeof(format), NUM2UINT(v)); + } + } + *p++ = cnv; + *p++ = '\0'; + return rb_assoc_new(rb_enc_sprintf(rb_usascii_encoding(), format, n), + rb_usascii_str_new_cstr(format)); +} + void Init_printf(void) { @@ -35,4 +96,5 @@ Init_printf(void) rb_define_singleton_method(m, "s", printf_test_s, 1); rb_define_singleton_method(m, "v", printf_test_v, 1); rb_define_singleton_method(m, "q", printf_test_q, 1); + rb_define_singleton_method(m, "call", printf_test_call, -1); } -- cgit v1.2.3