1
0
Fork 0
mirror of https://github.com/ruby/ruby.git synced 2022-11-09 12:17:21 -05:00
ruby--ruby/sprintf.c

923 lines
21 KiB
C
Raw Normal View History

/**********************************************************************
sprintf.c -
$Author$
$Date$
created at: Fri Oct 15 10:39:26 JST 1993
Copyright (C) 1993-2003 Yukihiro Matsumoto
Copyright (C) 2000 Network Applied Communication Laboratory, Inc.
Copyright (C) 2000 Information-technology Promotion Agency, Japan
**********************************************************************/
#include "ruby.h"
#include <ctype.h>
#include <math.h>
#ifdef HAVE_STDARG_PROTOTYPES
#include <stdarg.h>
#define va_init_list(a,b) va_start(a,b)
#else
#include <varargs.h>
#define va_init_list(a,b) va_start(a)
#endif
#define BIT_DIGITS(N) (((N)*146)/485 + 1) /* log2(10) =~ 146/485 */
static void fmt_setup _((char*,int,int,int,int));
static char*
remove_sign_bits(str, base)
char *str;
int base;
{
char *s, *t;
s = t = str;
if (base == 16) {
while (*t == 'f') {
t++;
}
}
else if (base == 8) {
if (*t == '3') t++;
while (*t == '7') {
t++;
}
}
else if (base == 2) {
while (*t == '1') {
t++;
}
}
if (t > s) {
while (*t) *s++ = *t++;
*s = '\0';
}
return str;
}
static char
sign_bits(base, p)
int base;
const char *p;
{
char c = '.';
switch (base) {
case 16:
if (*p == 'X') c = 'F';
else c = 'f';
break;
case 8:
c = '7'; break;
case 2:
c = '1'; break;
}
return c;
}
#define FNONE 0
#define FSHARP 1
#define FMINUS 2
#define FPLUS 4
#define FZERO 8
#define FSPACE 16
#define FWIDTH 32
#define FPREC 64
#define CHECK(l) do {\
while (blen + (l) >= bsiz) {\
bsiz*=2;\
}\
rb_str_resize(result, bsiz);\
buf = RSTRING(result)->ptr;\
} while (0)
#define PUSH(s, l) do { \
CHECK(l);\
memcpy(&buf[blen], s, l);\
blen += (l);\
} while (0)
#define FILL(c, l) do { \
CHECK(l);\
memset(&buf[blen], c, l);\
blen += (l);\
} while (0)
#define GETARG() (nextvalue != Qundef ? nextvalue : \
posarg < 0 ? \
(rb_raise(rb_eArgError, "unnumbered(%d) mixed with numbered", nextarg), 0) : \
(posarg = nextarg++, GETNTHARG(posarg)))
#define GETPOSARG(n) (posarg > 0 ? \
(rb_raise(rb_eArgError, "numbered(%d) after unnumbered(%d)", n, posarg), 0) : \
((n < 1) ? (rb_raise(rb_eArgError, "invalid index - %d$", n), 0) : \
(posarg = -1, GETNTHARG(n))))
#define GETNTHARG(nth) \
* array.c: replace rb_protect_inspect() and rb_inspecting_p() by rb_exec_recursive() in eval.c. * eval.c (rb_exec_recursive): new function. * array.c (rb_ary_join): use rb_exec_recursive(). * array.c (rb_ary_inspect, rb_ary_hash): ditto. * file.c (rb_file_join): ditto. * hash.c (rb_hash_inspect, rb_hash_to_s, rb_hash_hash): ditto. * io.c (rb_io_puts): ditto. * object.c (rb_obj_inspect): ditto * struct.c (rb_struct_inspect): ditto. * lib/set.rb (SortedSet::setup): a hack to shut up warning. [ruby-talk:132866] * lib/time.rb (Time::strptime): add new function. inspired by [ruby-talk:132815]. * lib/parsedate.rb (ParseDate::strptime): ditto. * regparse.c: move st_*_strend() functions from st.c. fixed some potential memory leaks. * exception error messages updated. [ruby-core:04497] * ext/socket/socket.c (Init_socket): add bunch of Socket constants. Patch from Sam Roberts <sroberts@uniserve.com>. [ruby-core:04409] * array.c (rb_ary_s_create): no need for negative argc check. [ruby-core:04463] * array.c (rb_ary_unshift_m): ditto. * lib/xmlrpc/parser.rb (XMLRPC::FaultException): make it subclass of StandardError class, not Exception class. [ruby-core:04429] * parse.y (fcall_gen): lvar(arg) will be evaluated as lvar.call(arg) when lvar is a defined local variable. [new] * object.c (rb_class_initialize): call inherited method before calling initializing block. * eval.c (rb_thread_start_1): initialize newly pushed frame. * lib/open3.rb (Open3::popen3): $? should not be EXIT_FAILURE. fixed: [ruby-core:04444] * eval.c (is_defined): NODE_IASGN is an assignment. * ext/readline/readline.c (Readline.readline): use rl_outstream and rl_instream. [ruby-dev:25699] * ext/etc/etc.c (Init_etc): sGroup needs HAVE_ST_GR_PASSWD check [ruby-dev:25675] * misc/ruby-mode.el: [ruby-core:04415] * lib/rdoc/generators/html_generator.rb: [ruby-core:04412] * lib/rdoc/generators/ri_generator.rb: ditto. * struct.c (make_struct): fixed: [ruby-core:04402] * ext/curses/curses.c (window_color_set): [ruby-core:04393] * ext/socket/socket.c (Init_socket): SO_REUSEPORT added. [ruby-talk:130092] * object.c: [ruby-doc:818] * parse.y (open_args): fix too verbose warnings for the space before argument parentheses. [ruby-dev:25492] * parse.y (parser_yylex): ditto. * parse.y (parser_yylex): the first expression in the parentheses should not be a command. [ruby-dev:25492] * lib/irb/context.rb (IRB::Context::initialize): [ruby-core:04330] * object.c (Init_Object): remove Object#type. [ruby-core:04335] * st.c (st_foreach): report success/failure by return value. [ruby-Bugs-1396] * parse.y: forgot to initialize parser struct. [ruby-dev:25492] * parse.y (parser_yylex): no tLABEL on EXPR_BEG. [ruby-talk:127711] * document updates - [ruby-core:04296], [ruby-core:04301], [ruby-core:04302], [ruby-core:04307] * dir.c (rb_push_glob): should work for NUL delimited patterns. * dir.c (rb_glob2): should aware of offset in the pattern. * string.c (rb_str_new4): should propagate taintedness. * env.h: rename member names in struct FRAME; last_func -> callee, orig_func -> this_func, last_class -> this_class. * struct.c (rb_struct_set): use original method name, not callee name, to retrieve member slot. [ruby-core:04268] * time.c (time_strftime): protect from format modification from GC finalizers. * object.c (Init_Object): remove rb_obj_id_obsolete() * eval.c (rb_mod_define_method): incomplete subclass check. [ruby-dev:25464] * gc.c (rb_data_object_alloc): klass may be NULL. [ruby-list:40498] * bignum.c (rb_big_rand): should return positive random number. [ruby-dev:25401] * bignum.c (rb_big_rand): do not use rb_big_modulo to generate random bignums. [ruby-dev:25396] * variable.c (rb_autoload): [ruby-dev:25373] * eval.c (svalue_to_avalue): [ruby-dev:25366] * string.c (rb_str_justify): [ruby-dev:25367] * io.c (rb_f_select): [ruby-dev:25312] * ext/socket/socket.c (sock_s_getservbyport): [ruby-talk:124072] * struct.c (make_struct): [ruby-dev:25249] * dir.c (dir_open_dir): new function. [ruby-dev:25242] * io.c (rb_f_open): add type check for return value from to_open. * lib/pstore.rb (PStore#transaction): Use the empty content when a file is not found. [ruby-dev:24561] git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk@8068 b2dd03c8-39d4-4d8f-98ff-823fe69b080e
2005-03-04 01:47:45 -05:00
((nth >= argc) ? (rb_raise(rb_eArgError, "too few arguments"), 0) : argv[nth])
#define GETASTER(val) do { \
t = p++; \
n = 0; \
for (; p < end && ISDIGIT(*p); p++) { \
n = 10 * n + (*p - '0'); \
} \
if (p >= end) { \
rb_raise(rb_eArgError, "malformed format string - %%*[0-9]"); \
} \
if (*p == '$') { \
tmp = GETPOSARG(n); \
} \
else { \
tmp = GETARG(); \
p = t; \
} \
val = NUM2INT(tmp); \
} while (0)
/*
* call-seq:
* format(format_string [, arguments...] ) => string
* sprintf(format_string [, arguments...] ) => string
*
* Returns the string resulting from applying <i>format_string</i> to
* any additional arguments. Within the format string, any characters
* other than format sequences are copied to the result. A format
* sequence consists of a percent sign, followed by optional flags,
* width, and precision indicators, then terminated with a field type
* character. The field type controls how the corresponding
* <code>sprintf</code> argument is to be interpreted, while the flags
* modify that interpretation. The field type characters are listed
* in the table at the end of this section. The flag characters are:
*
* Flag | Applies to | Meaning
* ---------+--------------+-----------------------------------------
* space | bdeEfgGioxXu | Leave a space at the start of
* | | positive numbers.
* ---------+--------------+-----------------------------------------
* (digit)$ | all | Specifies the absolute argument number
* | | for this field. Absolute and relative
* | | argument numbers cannot be mixed in a
* | | sprintf string.
* ---------+--------------+-----------------------------------------
* # | beEfgGoxX | Use an alternative format. For the
* | | conversions `o', `x', `X', and `b',
* | | prefix the result with ``0'', ``0x'', ``0X'',
* | | and ``0b'', respectively. For `e',
* | | `E', `f', `g', and 'G', force a decimal
* | | point to be added, even if no digits follow.
* | | For `g' and 'G', do not remove trailing zeros.
* ---------+--------------+-----------------------------------------
* + | bdeEfgGioxXu | Add a leading plus sign to positive numbers.
* ---------+--------------+-----------------------------------------
* - | all | Left-justify the result of this conversion.
* ---------+--------------+-----------------------------------------
* 0 (zero) | all | Pad with zeros, not spaces.
* ---------+--------------+-----------------------------------------
* * | all | Use the next argument as the field width.
* | | If negative, left-justify the result. If the
* | | asterisk is followed by a number and a dollar
* | | sign, use the indicated argument as the width.
*
*
* The field width is an optional integer, followed optionally by a
* period and a precision. The width specifies the minimum number of
* characters that will be written to the result for this field. For
* numeric fields, the precision controls the number of decimal places
* displayed. For string fields, the precision determines the maximum
* number of characters to be copied from the string. (Thus, the format
* sequence <code>%10.10s</code> will always contribute exactly ten
* characters to the result.)
*
* The field types are:
*
* Field | Conversion
* ------+--------------------------------------------------------------
* b | Convert argument as a binary number.
* c | Argument is the numeric code for a single character.
* d | Convert argument as a decimal number.
* E | Equivalent to `e', but uses an uppercase E to indicate
* | the exponent.
* e | Convert floating point argument into exponential notation
* | with one digit before the decimal point. The precision
* | determines the number of fractional digits (defaulting to six).
* f | Convert floating point argument as [-]ddd.ddd,
* | where the precision determines the number of digits after
* | the decimal point.
* G | Equivalent to `g', but use an uppercase `E' in exponent form.
* g | Convert a floating point number using exponential form
* | if the exponent is less than -4 or greater than or
* | equal to the precision, or in d.dddd form otherwise.
* i | Identical to `d'.
* o | Convert argument as an octal number.
* p | The valuing of argument.inspect.
* s | Argument is a string to be substituted. If the format
* | sequence contains a precision, at most that many characters
* | will be copied.
* u | Treat argument as an unsigned decimal number.
* X | Convert argument as a hexadecimal number using uppercase
* | letters. Negative numbers will be displayed with two
* | leading periods (representing an infinite string of
* | leading 'FF's.
* x | Convert argument as a hexadecimal number.
* | Negative numbers will be displayed with two
* | leading periods (representing an infinite string of
* | leading 'ff's.
*
* Examples:
*
* sprintf("%d %04x", 123, 123) #=> "123 007b"
* sprintf("%08b '%4s'", 123, 123) #=> "01111011 ' 123'"
* sprintf("%1$*2$s %2$d %1$s", "hello", 8) #=> " hello 8 hello"
* sprintf("%1$*2$s %2$d", "hello", -8) #=> "hello -8"
* sprintf("%+g:% g:%-g", 1.23, 1.23, 1.23) #=> "+1.23: 1.23:1.23"
*/
VALUE
rb_f_sprintf(argc, argv)
int argc;
const VALUE *argv;
{
return rb_str_format(argc - 1, argv + 1, GETNTHARG(0));
}
VALUE
rb_str_format(argc, argv, fmt)
int argc;
const VALUE *argv;
VALUE fmt;
{
const char *p, *end;
char *buf;
int blen, bsiz;
VALUE result;
int width, prec, flags = FNONE;
int nextarg = 1;
int posarg = 0;
int tainted = 0;
VALUE nextvalue;
VALUE tmp;
VALUE str;
++argc;
--argv;
if (OBJ_TAINTED(fmt)) tainted = 1;
* eval.c (block_pass): should not downgrade safe level. * ext/dbm/extconf.rb: allow specifying dbm-type explicitly. * ext/dbm/extconf.rb: avoid gdbm if possible, because it leaks memory, whereas gdbm.so doesn't. potential incompatibility. * string.c (rb_str_insert): new method. * parse.y (yylex): lex_state after RESCUE_MOD should be EXPR_BEG. * array.c (rb_ary_insert): new method. * array.c (rb_ary_update): new utility function. * io.c (set_outfile): should check if closed before assignment. * eval.c (rb_eval): should preserve value of ruby_errinfo. * eval.c (rb_thread_schedule): infinite sleep should not cause dead lock. * array.c (rb_ary_flatten_bang): proper recursive detection. * eval.c (yield_under): need not to prohibit at safe level 4. * pack.c (pack_pack): p/P packs nil into NULL. * pack.c (pack_unpack): p/P unpacks NULL into nil. * pack.c (pack_pack): size check for P template. * ruby.c (set_arg0): wrong predicate when new $0 value is bigger than original space. * gc.c (id2ref): should use NUM2ULONG() * object.c (rb_mod_const_get): check whether name is a class variable name. * object.c (rb_mod_const_set): ditto. * object.c (rb_mod_const_defined): ditto. * marshal.c (w_float): precision changed to "%.16g" * eval.c (rb_call0): wrong retry behavior. * numeric.c (fix_aref): a bug on long>int architecture. * eval.c (rb_eval_string_wrap): should restore ruby_wrapper. * regex.c (re_compile_pattern): char class at either edge of range should be invalid. * eval.c (handle_rescue): use === to compare exception match. * error.c (syserr_eqq): comparison between SytemCallErrors should based on their error numbers. * eval.c (safe_getter): should use INT2NUM(). * bignum.c (rb_big2long): 2**31 cannot fit in 31 bit long. * regex.c (calculate_must_string): wrong length calculation. * eval.c (rb_thread_start_0): fixed memory leak. * parse.y (none): should clear cmdarg_stack too. * io.c (rb_fopen): use setvbuf() to avoid recursive malloc() on some platforms. * file.c (rb_stat_dev): device functions should honor stat field types (except long long such as dev_t). * eval.c (rb_mod_nesting): should not push nil for nesting array. * eval.c (rb_mod_s_constants): should not search array by rb_mod_const_at() for nil (happens for singleton class). * class.c (rb_singleton_class_attached): should modify iv_tbl by itself, no longer use rb_iv_set() to avoid freeze check error. * variable.c (rb_const_get): error message "uninitialized constant Foo at Bar::Baz" instead of "uninitialized constantBar::Baz::Foo". * eval.c (rb_mod_included): new hook called from rb_mod_include(). * io.c (opt_i_set): should strdup() inplace_edit string. * eval.c (exec_under): need to push cref too. * eval.c (rb_f_missing): raise NameError for "undefined local variable or method". * error.c (Init_Exception): new exception NoMethodError. NameError moved under ScriptError again. * eval.c (rb_f_missing): use NoMethodError instead of NameError. * file.c (Init_File): should redifine "new" class method. * eval.c (PUSH_CREF): sharing cref node was problematic. maintain runtime cref list instead. * eval.c (rb_eval): copy defn node before registering. * eval.c (rb_load): clear ruby_cref before loading. * variable.c (rb_const_get): no recursion to show full class path for modules. * eval.c (rb_set_safe_level): should set safe level in curr_thread as well. * eval.c (safe_setter): ditto. * object.c (rb_obj_is_instance_of): nil belongs to false, not true. * time.c (make_time_t): proper (I hope) daylight saving time handling for both US and Europe. I HATE DST! * eval.c (rb_thread_wait_for): non blocked signal interrupt should stop the interval. * eval.c (proc_eq): class check aded. * eval.c (proc_eq): typo fixed ("return" was ommitted). * error.c (Init_Exception): move NameError under StandardError. * class.c (rb_mod_clone): should copy method bodies too. * bignum.c (bigdivrem): should trim trailing zero bdigits of remainder, even if dd == 0. * file.c (check3rdbyte): safe string check moved here. * time.c (make_time_t): remove HAVE_TM_ZONE code since it sometimes reports wrong time. * time.c (make_time_t): remove unnecessary range check for platforms where negative time_t is available. * process.c (proc_waitall): should push Process::Status instead of Finuxm status. * process.c (waitall_each): should add all entries in pid_tbl. these changes are inspired by Koji Arai. Thanks. * process.c (proc_wait): should not iterate if pid_tbl is 0. * process.c (proc_waitall): ditto. * numeric.c (flodivmod): a bug in no fmod case. * process.c (pst_wifsignaled): should apply WIFSIGNALED for status (int), not st (VALUE). * io.c (Init_IO): value of $/ and $\ are no longer restricted to strings. type checks are done on demand. * class.c (rb_include_module): module inclusion should be check taints. * ruby.h (STR2CSTR): replace to StringType() and StringTypePtr(). * ruby.h (rb_str2cstr): ditto. * eval.c (rb_load): should not copy topleve local variables. It cause variable/method ambiguity. Thanks to L. Peter Deutsch. * class.c (rb_include_module): freeze check at first. * eval.c (rb_attr): sprintf() and rb_intern() moved into conditional body. git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk@1356 b2dd03c8-39d4-4d8f-98ff-823fe69b080e
2001-05-02 00:22:21 -04:00
StringValue(fmt);
fmt = rb_str_new4(fmt);
* eval.c (block_pass): should not downgrade safe level. * ext/dbm/extconf.rb: allow specifying dbm-type explicitly. * ext/dbm/extconf.rb: avoid gdbm if possible, because it leaks memory, whereas gdbm.so doesn't. potential incompatibility. * string.c (rb_str_insert): new method. * parse.y (yylex): lex_state after RESCUE_MOD should be EXPR_BEG. * array.c (rb_ary_insert): new method. * array.c (rb_ary_update): new utility function. * io.c (set_outfile): should check if closed before assignment. * eval.c (rb_eval): should preserve value of ruby_errinfo. * eval.c (rb_thread_schedule): infinite sleep should not cause dead lock. * array.c (rb_ary_flatten_bang): proper recursive detection. * eval.c (yield_under): need not to prohibit at safe level 4. * pack.c (pack_pack): p/P packs nil into NULL. * pack.c (pack_unpack): p/P unpacks NULL into nil. * pack.c (pack_pack): size check for P template. * ruby.c (set_arg0): wrong predicate when new $0 value is bigger than original space. * gc.c (id2ref): should use NUM2ULONG() * object.c (rb_mod_const_get): check whether name is a class variable name. * object.c (rb_mod_const_set): ditto. * object.c (rb_mod_const_defined): ditto. * marshal.c (w_float): precision changed to "%.16g" * eval.c (rb_call0): wrong retry behavior. * numeric.c (fix_aref): a bug on long>int architecture. * eval.c (rb_eval_string_wrap): should restore ruby_wrapper. * regex.c (re_compile_pattern): char class at either edge of range should be invalid. * eval.c (handle_rescue): use === to compare exception match. * error.c (syserr_eqq): comparison between SytemCallErrors should based on their error numbers. * eval.c (safe_getter): should use INT2NUM(). * bignum.c (rb_big2long): 2**31 cannot fit in 31 bit long. * regex.c (calculate_must_string): wrong length calculation. * eval.c (rb_thread_start_0): fixed memory leak. * parse.y (none): should clear cmdarg_stack too. * io.c (rb_fopen): use setvbuf() to avoid recursive malloc() on some platforms. * file.c (rb_stat_dev): device functions should honor stat field types (except long long such as dev_t). * eval.c (rb_mod_nesting): should not push nil for nesting array. * eval.c (rb_mod_s_constants): should not search array by rb_mod_const_at() for nil (happens for singleton class). * class.c (rb_singleton_class_attached): should modify iv_tbl by itself, no longer use rb_iv_set() to avoid freeze check error. * variable.c (rb_const_get): error message "uninitialized constant Foo at Bar::Baz" instead of "uninitialized constantBar::Baz::Foo". * eval.c (rb_mod_included): new hook called from rb_mod_include(). * io.c (opt_i_set): should strdup() inplace_edit string. * eval.c (exec_under): need to push cref too. * eval.c (rb_f_missing): raise NameError for "undefined local variable or method". * error.c (Init_Exception): new exception NoMethodError. NameError moved under ScriptError again. * eval.c (rb_f_missing): use NoMethodError instead of NameError. * file.c (Init_File): should redifine "new" class method. * eval.c (PUSH_CREF): sharing cref node was problematic. maintain runtime cref list instead. * eval.c (rb_eval): copy defn node before registering. * eval.c (rb_load): clear ruby_cref before loading. * variable.c (rb_const_get): no recursion to show full class path for modules. * eval.c (rb_set_safe_level): should set safe level in curr_thread as well. * eval.c (safe_setter): ditto. * object.c (rb_obj_is_instance_of): nil belongs to false, not true. * time.c (make_time_t): proper (I hope) daylight saving time handling for both US and Europe. I HATE DST! * eval.c (rb_thread_wait_for): non blocked signal interrupt should stop the interval. * eval.c (proc_eq): class check aded. * eval.c (proc_eq): typo fixed ("return" was ommitted). * error.c (Init_Exception): move NameError under StandardError. * class.c (rb_mod_clone): should copy method bodies too. * bignum.c (bigdivrem): should trim trailing zero bdigits of remainder, even if dd == 0. * file.c (check3rdbyte): safe string check moved here. * time.c (make_time_t): remove HAVE_TM_ZONE code since it sometimes reports wrong time. * time.c (make_time_t): remove unnecessary range check for platforms where negative time_t is available. * process.c (proc_waitall): should push Process::Status instead of Finuxm status. * process.c (waitall_each): should add all entries in pid_tbl. these changes are inspired by Koji Arai. Thanks. * process.c (proc_wait): should not iterate if pid_tbl is 0. * process.c (proc_waitall): ditto. * numeric.c (flodivmod): a bug in no fmod case. * process.c (pst_wifsignaled): should apply WIFSIGNALED for status (int), not st (VALUE). * io.c (Init_IO): value of $/ and $\ are no longer restricted to strings. type checks are done on demand. * class.c (rb_include_module): module inclusion should be check taints. * ruby.h (STR2CSTR): replace to StringType() and StringTypePtr(). * ruby.h (rb_str2cstr): ditto. * eval.c (rb_load): should not copy topleve local variables. It cause variable/method ambiguity. Thanks to L. Peter Deutsch. * class.c (rb_include_module): freeze check at first. * eval.c (rb_attr): sprintf() and rb_intern() moved into conditional body. git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk@1356 b2dd03c8-39d4-4d8f-98ff-823fe69b080e
2001-05-02 00:22:21 -04:00
p = RSTRING(fmt)->ptr;
end = p + RSTRING(fmt)->len;
blen = 0;
bsiz = 120;
result = rb_str_buf_new(bsiz);
buf = RSTRING(result)->ptr;
for (; p < end; p++) {
const char *t;
int n;
for (t = p; t < end && *t != '%'; t++) ;
PUSH(p, t - p);
if (t >= end) {
/* end of fmt string */
goto sprint_exit;
}
p = t + 1; /* skip `%' */
width = prec = -1;
nextvalue = Qundef;
retry:
switch (*p) {
default:
if (ISPRINT(*p))
rb_raise(rb_eArgError, "malformed format string - %%%c", *p);
else
rb_raise(rb_eArgError, "malformed format string");
break;
case ' ':
flags |= FSPACE;
p++;
goto retry;
case '#':
flags |= FSHARP;
p++;
goto retry;
case '+':
flags |= FPLUS;
p++;
goto retry;
case '-':
flags |= FMINUS;
p++;
goto retry;
case '0':
flags |= FZERO;
p++;
goto retry;
case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
n = 0;
for (; p < end && ISDIGIT(*p); p++) {
n = 10 * n + (*p - '0');
}
if (p >= end) {
rb_raise(rb_eArgError, "malformed format string - %%[0-9]");
}
if (*p == '$') {
if (nextvalue != Qundef) {
rb_raise(rb_eArgError, "value given twice - %d$", n);
}
nextvalue = GETPOSARG(n);
p++;
goto retry;
}
width = n;
flags |= FWIDTH;
goto retry;
case '*':
if (flags & FWIDTH) {
rb_raise(rb_eArgError, "width given twice");
}
flags |= FWIDTH;
GETASTER(width);
if (width < 0) {
flags |= FMINUS;
width = -width;
}
p++;
goto retry;
case '.':
if (flags & FPREC) {
rb_raise(rb_eArgError, "precision given twice");
}
flags |= FPREC;
prec = 0;
p++;
if (*p == '*') {
GETASTER(prec);
if (prec < 0) { /* ignore negative precision */
flags &= ~FPREC;
}
p++;
goto retry;
}
for (; p < end && ISDIGIT(*p); p++) {
prec = 10 * prec + (*p - '0');
}
if (p >= end) {
rb_raise(rb_eArgError, "malformed format string - %%.[0-9]");
}
goto retry;
case '\n':
p--;
case '\0':
case '%':
if (flags != FNONE) {
rb_raise(rb_eArgError, "illegal format character - %%");
}
PUSH("%", 1);
break;
case 'c':
{
VALUE val = GETARG();
char c;
c = NUM2INT(val) & 0xff;
if (!(flags & FWIDTH)) {
PUSH(&c, 1);
}
else {
FILL(' ', width);
buf[blen - ((flags & FMINUS) ? width : 1)] = c;
}
}
break;
case 's':
case 'p':
{
VALUE arg = GETARG();
long len;
if (*p == 'p') arg = rb_inspect(arg);
str = rb_obj_as_string(arg);
if (OBJ_TAINTED(str)) tainted = 1;
len = RSTRING(str)->len;
if (flags&FPREC) {
if (prec < len) {
len = prec;
}
}
if (flags&FWIDTH) {
if (width > len) {
CHECK(width);
width -= len;
if (!(flags&FMINUS)) {
while (width--) {
buf[blen++] = ' ';
}
}
memcpy(&buf[blen], RSTRING(str)->ptr, len);
blen += len;
if (flags&FMINUS) {
while (width--) {
buf[blen++] = ' ';
}
}
break;
}
}
PUSH(RSTRING(str)->ptr, len);
}
break;
case 'd':
case 'i':
case 'o':
case 'x':
case 'X':
case 'b':
case 'B':
case 'u':
{
volatile VALUE val = GETARG();
char fbuf[32], nbuf[64], *s, *t;
char *prefix = 0;
int sign = 0;
char sc = 0;
long v = 0;
int base, bignum = 0;
int len, pos;
switch (*p) {
case 'd':
case 'i':
sign = 1; break;
case 'o':
case 'x':
case 'X':
case 'b':
case 'B':
case 'u':
default:
if (flags&(FPLUS|FSPACE)) sign = 1;
break;
}
if (flags & FSHARP) {
switch (*p) {
case 'o':
prefix = "0"; break;
case 'x':
prefix = "0x"; break;
case 'X':
prefix = "0X"; break;
case 'b':
prefix = "0b"; break;
case 'B':
prefix = "0B"; break;
}
if (prefix) {
width -= strlen(prefix);
}
}
bin_retry:
switch (TYPE(val)) {
case T_FLOAT:
val = rb_dbl2big(RFLOAT(val)->value);
if (FIXNUM_P(val)) goto bin_retry;
bignum = 1;
break;
case T_STRING:
val = rb_str_to_inum(val, 0, Qtrue);
goto bin_retry;
case T_BIGNUM:
bignum = 1;
break;
case T_FIXNUM:
v = FIX2LONG(val);
break;
default:
val = rb_Integer(val);
goto bin_retry;
}
switch (*p) {
case 'o':
base = 8; break;
case 'x':
case 'X':
base = 16; break;
case 'b':
case 'B':
base = 2; break;
case 'u':
case 'd':
case 'i':
default:
base = 10; break;
}
if (!bignum) {
if (base == 2) {
val = rb_int2big(v);
goto bin_retry;
}
if (sign) {
char c = *p;
if (c == 'i') c = 'd'; /* %d and %i are identical */
if (v < 0) {
v = -v;
sc = '-';
width--;
}
else if (flags & FPLUS) {
sc = '+';
width--;
}
else if (flags & FSPACE) {
sc = ' ';
width--;
}
sprintf(fbuf, "%%l%c", c);
sprintf(nbuf, fbuf, v);
}
else {
s = nbuf;
if (v < 0) {
if (base == 10) {
rb_warning("negative number for %%u specifier");
}
else if (!(flags&(FPREC|FZERO))) {
strcpy(s, "..");
s += 2;
}
}
sprintf(fbuf, "%%l%c", *p == 'X' ? 'x' : *p);
sprintf(s, fbuf, v);
if (v < 0) {
char d = 0;
remove_sign_bits(s, base);
switch (base) {
case 16:
d = 'f'; break;
case 8:
d = '7'; break;
}
if (d && *s != d) {
memmove(s+1, s, strlen(s)+1);
*s = d;
}
}
}
s = nbuf;
}
else {
if (sign) {
tmp = rb_big2str(val, base);
s = RSTRING(tmp)->ptr;
if (s[0] == '-') {
s++;
sc = '-';
width--;
}
else if (flags & FPLUS) {
sc = '+';
width--;
}
else if (flags & FSPACE) {
sc = ' ';
width--;
}
}
else {
if (!RBIGNUM(val)->sign) {
val = rb_big_clone(val);
rb_big_2comp(val);
}
tmp = rb_big2str(val, base);
s = RSTRING(tmp)->ptr;
if (*s == '-') {
if (base == 10) {
rb_warning("negative number for %%u specifier");
}
else {
remove_sign_bits(++s, base);
tmp = rb_str_new(0, 3+strlen(s));
t = RSTRING(tmp)->ptr;
if (!(flags&(FPREC|FZERO))) {
strcpy(t, "..");
t += 2;
}
switch (base) {
case 16:
if (s[0] != 'f') strcpy(t++, "f"); break;
case 8:
if (s[0] != '7') strcpy(t++, "7"); break;
case 2:
if (s[0] != '1') strcpy(t++, "1"); break;
}
strcpy(t, s);
s = RSTRING(tmp)->ptr;
}
}
}
}
pos = -1;
len = strlen(s);
if (*p == 'X') {
char *pp = s;
while (*pp) {
*pp = toupper(*pp);
pp++;
}
}
if ((flags&(FZERO|FPREC)) == FZERO) {
prec = width;
width = 0;
}
else {
if (prec < len) prec = len;
width -= prec;
}
if (!(flags&FMINUS)) {
CHECK(width);
while (width-- > 0) {
buf[blen++] = ' ';
}
}
if (sc) PUSH(&sc, 1);
if (prefix) {
int plen = strlen(prefix);
PUSH(prefix, plen);
}
CHECK(prec - len);
if (!bignum && v < 0) {
char c = sign_bits(base, p);
while (len < prec--) {
buf[blen++] = c;
}
}
else {
char c;
if (!sign && bignum && !RBIGNUM(val)->sign)
c = sign_bits(base, p);
else
c = '0';
while (len < prec--) {
buf[blen++] = c;
}
}
PUSH(s, len);
CHECK(width);
while (width-- > 0) {
buf[blen++] = ' ';
}
}
break;
case 'f':
case 'g':
case 'G':
case 'e':
case 'E':
{
VALUE val = GETARG();
double fval;
int i, need = 6;
char fbuf[32];
fval = RFLOAT(rb_Float(val))->value;
if (isnan(fval) || isinf(fval)) {
char *expr;
if (isnan(fval)) {
expr = "NaN";
}
else {
expr = "Inf";
}
need = strlen(expr);
if ((!isnan(fval) && fval < 0.0) || (flags & FPLUS))
need++;
if ((flags & FWIDTH) && need < width)
need = width;
CHECK(need);
sprintf(&buf[blen], "%*s", need, "");
if (flags & FMINUS) {
if (!isnan(fval) && fval < 0.0)
buf[blen++] = '-';
else if (flags & FPLUS)
buf[blen++] = '+';
else if (flags & FSPACE)
blen++;
strncpy(&buf[blen], expr, strlen(expr));
}
else if (flags & FZERO) {
if (!isnan(fval) && fval < 0.0) {
buf[blen++] = '-';
need--;
}
else if (flags & FPLUS) {
buf[blen++] = '+';
need--;
}
else if (flags & FSPACE) {
blen++;
need--;
}
while (need-- - strlen(expr) > 0) {
buf[blen++] = '0';
}
strncpy(&buf[blen], expr, strlen(expr));
}
else {
if (!isnan(fval) && fval < 0.0)
buf[blen + need - strlen(expr) - 1] = '-';
else if (flags & FPLUS)
buf[blen + need - strlen(expr) - 1] = '+';
strncpy(&buf[blen + need - strlen(expr)], expr,
strlen(expr));
}
blen += strlen(&buf[blen]);
break;
}
fmt_setup(fbuf, *p, flags, width, prec);
need = 0;
if (*p != 'e' && *p != 'E') {
i = INT_MIN;
frexp(fval, &i);
if (i > 0)
need = BIT_DIGITS(i);
}
need += (flags&FPREC) ? prec : 6;
if ((flags&FWIDTH) && need < width)
need = width;
need += 20;
CHECK(need);
sprintf(&buf[blen], fbuf, fval);
blen += strlen(&buf[blen]);
}
break;
}
flags = FNONE;
}
sprint_exit:
/* XXX - We cannot validiate the number of arguments if (digit)$ style used.
*/
if (posarg >= 0 && nextarg < argc) {
const char *mesg = "too many arguments for format string";
if (RTEST(ruby_debug)) rb_raise(rb_eArgError, mesg);
if (RTEST(ruby_verbose)) rb_warn(mesg);
}
rb_str_resize(result, blen);
if (tainted) OBJ_TAINT(result);
return result;
}
static void
fmt_setup(buf, c, flags, width, prec)
char *buf;
int c;
int flags, width, prec;
{
*buf++ = '%';
if (flags & FSHARP) *buf++ = '#';
if (flags & FPLUS) *buf++ = '+';
if (flags & FMINUS) *buf++ = '-';
if (flags & FZERO) *buf++ = '0';
if (flags & FSPACE) *buf++ = ' ';
if (flags & FWIDTH) {
sprintf(buf, "%d", width);
buf += strlen(buf);
}
if (flags & FPREC) {
sprintf(buf, ".%d", prec);
buf += strlen(buf);
}
*buf++ = c;
*buf = '\0';
}
#undef FILE
#define FILE rb_printf_buffer
#define __sbuf rb_printf_sbuf
#define __sFILE rb_printf_sfile
#undef feof
#undef ferror
#undef clearerr
#undef fileno
#if SIZEOF_LONG < SIZEOF_VOIDP
# if SIZEOF_LONG_LONG == SIZEOF_VOIDP
# define _HAVE_SANE_QUAD_
# define _HAVE_LLP64_
# define quad_t LONG_LONG
# define u_quad_t unsigned LONG_LONG
# endif
#endif
#undef vsnprintf
#undef snprintf
#include "missing/vsnprintf.c"
static int
ruby__sfvwrite(fp, uio)
register rb_printf_buffer *fp;
register struct __suio *uio;
{
struct __siov *iov;
VALUE result = (VALUE)fp->_bf._base;
char *buf = (char*)fp->_p;
size_t len, n;
int blen = buf - RSTRING(result)->ptr, bsiz = fp->_w;
if (RBASIC(result)->klass) {
rb_raise(rb_eRuntimeError, "rb_vsprintf reentered");
}
if ((len = uio->uio_resid) == 0)
return 0;
CHECK(len);
buf += blen;
fp->_w = bsiz;
for (iov = uio->uio_iov; len > 0; ++iov) {
MEMCPY(buf, iov->iov_base, char, n = iov->iov_len);
buf += n;
len -= n;
}
fp->_p = (unsigned char *)buf;
return 0;
}
VALUE
rb_vsprintf(fmt, ap)
const char *fmt;
va_list ap;
{
rb_printf_buffer f;
VALUE result;
f._flags = __SWR | __SSTR;
f._bf._size = 0;
f._w = 120;
result = rb_str_buf_new(f._w);
f._bf._base = (unsigned char *)result;
f._p = (unsigned char *)RSTRING(result)->ptr;
RBASIC(result)->klass = 0;
f.vwrite = ruby__sfvwrite;
BSD_vfprintf(&f, fmt, ap);
RBASIC(result)->klass = rb_cString;
rb_str_resize(result, (char *)f._p - RSTRING(result)->ptr);
return result;
}
VALUE
#ifdef HAVE_STDARG_PROTOTYPES
rb_sprintf(const char *format, ...)
#else
rb_sprintf(format, va_alist)
const char *format;
va_dcl
#endif
{
VALUE result;
va_list ap;
va_init_list(ap, format);
result = rb_vsprintf(format, ap);
va_end(ap);
return result;
}