Debian Codegraph @

vendor/mruby-source/mrbgems/mruby-sprintf/src/sprintf.c

raw
1 /*
2 ** sprintf.c - Kernel.#sprintf
3 **
4 ** See Copyright Notice in mruby.h
5 */
6
7 #include <mruby.h>
8 #include <mruby/string.h>
9 #include <mruby/hash.h>
10 #include <mruby/numeric.h>
11 #include <mruby/presym.h>
12 #include <string.h>
13 #include <ctype.h>
14
15 #define BIT_DIGITS(N) (((N)*146)/485 + 1) /* log2(10) =~ 146/485 */
16 #define BITSPERDIG MRB_INT_BIT
17 #define EXTENDSIGN(n, l) (((~0U << (n)) >> (((n)*(l)) % BITSPERDIG)) & ~(~0U << (n)))
18
19 mrb_value mrb_str_format(mrb_state *, mrb_int, const mrb_value *, mrb_value);
20
21 static char*
22 remove_sign_bits(char *str, int base)
23 {
24 char *t;
25
26 t = str;
27 if (base == 16) {
28 while (*t == 'f') {
29 t++;
30 }
31 }
32 else if (base == 8) {
33 *t |= EXTENDSIGN(3, strlen(t));
34 while (*t == '7') {
35 t++;
36 }
37 }
38 else if (base == 2) {
39 while (*t == '1') {
40 t++;
41 }
42 }
43
44 return t;
45 }
46
47 static char
48 sign_bits(int base, const char *p)
49 {
50 char c;
51
52 switch (base) {
53 case 16:
54 if (*p == 'X') c = 'F';
55 else c = 'f';
56 break;
57 case 8:
58 c = '7'; break;
59 case 2:
60 c = '1'; break;
61 default:
62 c = '.'; break;
63 }
64 return c;
65 }
66
67 static char *
68 mrb_uint_to_cstr(char *buf, size_t len, mrb_int num, int base)
69 {
70 char *b = buf + len - 1;
71 const int mask = base-1;
72 int shift;
73 mrb_uint val = (uint64_t)num;
74 char d;
75
76 if (num == 0) {
77 buf[0] = '0'; buf[1] = '\0';
78 return buf;
79 }
80 switch (base) {
81 case 16: d = 'f'; shift = 4; break;
82 case 8: d = '7'; shift = 3; break;
83 case 2: d = '1'; shift = 1; break;
84 default: return NULL;
85 }
86 *--b = '\0';
87 do {
88 *--b = mrb_digitmap[(int)(val & mask)];
89 } while (val >>= shift);
90
91 if (num < 0) {
92 b = remove_sign_bits(b, base);
93 if (d && *b != d) {
94 *--b = d;
95 }
96 }
97
98 return b;
99 }
100
101 #define FNONE 0
102 #define FSHARP 1
103 #define FMINUS 2
104 #define FPLUS 4
105 #define FZERO 8
106 #define FSPACE 16
107 #define FWIDTH 32
108 #define FPREC 64
109 #define FPREC0 128
110
111 #ifndef MRB_NO_FLOAT
112 static int
113 fmt_float(char *buf, size_t buf_size, char fmt, int flags, int width, int prec, mrb_float f)
114 {
115 char sign = '\0';
116 int left_align = 0;
117 int zero_pad = 0;
118
119 if (flags & FSHARP) fmt |= 0x80;
120 if (flags & FPLUS) sign = '+';
121 if (flags & FMINUS) left_align = 1;
122 if (flags & FZERO) zero_pad = 1;
123 if (flags & FSPACE) sign = ' ';
124
125 int len = mrb_format_float(f, buf, buf_size, fmt, prec, sign);
126
127 // buf[0] < '0' returns true if the first character is space, + or -
128 // buf[1] < '9' matches a digit, and doesn't match when we get back +nan or +inf
129 if (buf[0] < '0' && buf[1] <= '9' && zero_pad) {
130 buf++;
131 width--;
132 len--;
133 }
134 if (*buf < '0' || *buf >= '9') {
135 // For inf or nan, we don't want to zero pad.
136 zero_pad = 0;
137 }
138 if (len >= width) {
139 return len;
140 }
141 buf[width] = '\0';
142 if (left_align) {
143 memset(&buf[len], ' ', width - len);
144 return width;
145 }
146 memmove(&buf[width - len], buf, len);
147 if (zero_pad) {
148 memset(buf, '0', width - len);
149 }
150 else {
151 memset(buf, ' ', width - len);
152 }
153 return width;
154 }
155 #endif
156
157 #define CHECK(l) do { \
158 if (blen+(l) >= bsiz) {\
159 while (blen+(l) >= bsiz) {\
160 if (bsiz > MRB_INT_MAX/2) mrb_raise(mrb, E_ARGUMENT_ERROR, "too big specifier");\
161 bsiz*=2;\
162 }\
163 mrb_str_resize(mrb, result, bsiz);\
164 }\
165 buf = RSTRING_PTR(result);\
166 } while (0)
167
168 #define PUSH(s, l) do { \
169 CHECK(l);\
170 memcpy(&buf[blen], s, l);\
171 blen += (mrb_int)(l);\
172 } while (0)
173
174 #define FILL(c, l) do { \
175 CHECK(l);\
176 memset(&buf[blen], c, l);\
177 blen += (l);\
178 } while (0)
179
180 static void
181 check_next_arg(mrb_state *mrb, int posarg, int nextarg)
182 {
183 switch (posarg) {
184 case -1:
185 mrb_raisef(mrb, E_ARGUMENT_ERROR, "unnumbered(%d) mixed with numbered", nextarg);
186 break;
187 case -2:
188 mrb_raisef(mrb, E_ARGUMENT_ERROR, "unnumbered(%d) mixed with named", nextarg);
189 break;
190 default:
191 break;
192 }
193 }
194
195 static void
196 check_pos_arg(mrb_state *mrb, int posarg, mrb_int n)
197 {
198 if (posarg > 0) {
199 mrb_raisef(mrb, E_ARGUMENT_ERROR, "numbered(%i) after unnumbered(%d)",
200 n, posarg);
201 }
202 if (posarg == -2) {
203 mrb_raisef(mrb, E_ARGUMENT_ERROR, "numbered(%i) after named", n);
204 }
205 if (n < 1) {
206 mrb_raisef(mrb, E_ARGUMENT_ERROR, "invalid index - %i$", n);
207 }
208 }
209
210 static void
211 check_name_arg(mrb_state *mrb, int posarg, const char *name, size_t len)
212 {
213 if (posarg > 0) {
214 mrb_raisef(mrb, E_ARGUMENT_ERROR, "named%l after unnumbered(%d)",
215 name, len, posarg);
216 }
217 if (posarg == -1) {
218 mrb_raisef(mrb, E_ARGUMENT_ERROR, "named%l after numbered", name, len);
219 }
220 }
221
222 #define GETNEXTARG() (\
223 check_next_arg(mrb, posarg, nextarg),\
224 (posarg = nextarg++, GETNTHARG(posarg)))
225
226 #define GETARG() (!mrb_undef_p(nextvalue) ? nextvalue : GETNEXTARG())
227
228 #define GETPOSARG(n) (\
229 check_pos_arg(mrb, posarg, n),\
230 (posarg = -1, GETNTHARG(n)))
231
232 #define GETNTHARG(nth) \
233 ((nth >= argc) ? (mrb_raise(mrb, E_ARGUMENT_ERROR, "too few arguments"), mrb_undef_value()) : argv[nth])
234
235 #define CHECKNAMEARG(name, len) (\
236 check_name_arg(mrb, posarg, name, len),\
237 posarg = -2)
238
239 #define GETNUM(n, val) do { \
240 if (!(p = get_num(mrb, p, end, &(n)))) \
241 mrb_raise(mrb, E_ARGUMENT_ERROR, #val " too big"); \
242 } while(0)
243
244 #define GETASTER(num) do { \
245 mrb_value tmp_v; \
246 t = p++; \
247 GETNUM(n, val); \
248 if (*p == '$') { \
249 tmp_v = GETPOSARG(n); \
250 } \
251 else { \
252 tmp_v = GETNEXTARG(); \
253 p = t; \
254 } \
255 num = (int)mrb_as_int(mrb, tmp_v); \
256 } while (0)
257
258 static const char*
259 get_num(mrb_state *mrb, const char *p, const char *end, int *valp)
260 {
261 char *e;
262 mrb_int n;
263 if (!mrb_read_int(p, end, &e, &n) || INT_MAX < n) {
264 return NULL;
265 }
266 *valp = (int)n;
267 return e;
268 }
269
270 static void
271 get_hash(mrb_state *mrb, mrb_value *hash, mrb_int argc, const mrb_value *argv)
272 {
273 mrb_value tmp;
274
275 if (!mrb_undef_p(*hash)) return;
276 if (argc != 2) {
277 mrb_raise(mrb, E_ARGUMENT_ERROR, "one hash required");
278 }
279 tmp = mrb_check_hash_type(mrb, argv[1]);
280 if (mrb_nil_p(tmp)) {
281 mrb_raise(mrb, E_ARGUMENT_ERROR, "one hash required");
282 }
283 *hash = tmp;
284 }
285
286 /*
287 * call-seq:
288 * format(format_string [, arguments...] ) -> string
289 * sprintf(format_string [, arguments...] ) -> string
290 *
291 * Returns the string resulting from applying <i>format_string</i> to
292 * any additional arguments. Within the format string, any characters
293 * other than format sequences are copied to the result.
294 *
295 * The syntax of a format sequence is follows.
296 *
297 * %[flags][width][.precision]type
298 *
299 * A format
300 * sequence consists of a percent sign, followed by optional flags,
301 * width, and precision indicators, then terminated with a field type
302 * character. The field type controls how the corresponding
303 * <code>sprintf</code> argument is to be interpreted, while the flags
304 * modify that interpretation.
305 *
306 * The field type characters are:
307 *
308 * Field | Integer Format
309 * ------+--------------------------------------------------------------
310 * b | Convert argument as a binary number.
311 * | Negative numbers will be displayed as a two's complement
312 * | prefixed with '..1'.
313 * B | Equivalent to 'b', but uses an uppercase 0B for prefix
314 * | in the alternative format by #.
315 * d | Convert argument as a decimal number.
316 * i | Identical to 'd'.
317 * o | Convert argument as an octal number.
318 * | Negative numbers will be displayed as a two's complement
319 * | prefixed with '..7'.
320 * u | Identical to 'd'.
321 * x | Convert argument as a hexadecimal number.
322 * | Negative numbers will be displayed as a two's complement
323 * | prefixed with '..f' (representing an infinite string of
324 * | leading 'ff's).
325 * X | Equivalent to 'x', but uses uppercase letters.
326 *
327 * Field | Float Format
328 * ------+--------------------------------------------------------------
329 * e | Convert floating-point argument into exponential notation
330 * | with one digit before the decimal point as [-]d.dddddde[+-]dd.
331 * | The precision specifies the number of digits after the decimal
332 * | point (defaulting to six).
333 * E | Equivalent to 'e', but uses an uppercase E to indicate
334 * | the exponent.
335 * f | Convert floating-point argument as [-]ddd.dddddd,
336 * | where the precision specifies the number of digits after
337 * | the decimal point.
338 * g | Convert a floating-point number using exponential form
339 * | if the exponent is less than -4 or greater than or
340 * | equal to the precision, or in dd.dddd form otherwise.
341 * | The precision specifies the number of significant digits.
342 * G | Equivalent to 'g', but use an uppercase 'E' in exponent form.
343 *
344 * Field | Other Format
345 * ------+--------------------------------------------------------------
346 * c | Argument is the numeric code for a single character or
347 * | a single character string itself.
348 * p | The valuing of argument.inspect.
349 * s | Argument is a string to be substituted. If the format
350 * | sequence contains a precision, at most that many characters
351 * | will be copied.
352 * % | A percent sign itself will be displayed. No argument taken.
353 *
354 * The flags modifies the behavior of the formats.
355 * The flag characters are:
356 *
357 * Flag | Applies to | Meaning
358 * ---------+---------------+-----------------------------------------
359 * space | bBdiouxX | Leave a space at the start of
360 * | aAeEfgG | non-negative numbers.
361 * | (numeric fmt) | For 'o', 'x', 'X', 'b' and 'B', use
362 * | | a minus sign with absolute value for
363 * | | negative values.
364 * ---------+---------------+-----------------------------------------
365 * (digit)$ | all | Specifies the absolute argument number
366 * | | for this field. Absolute and relative
367 * | | argument numbers cannot be mixed in a
368 * | | sprintf string.
369 * ---------+---------------+-----------------------------------------
370 * # | bBoxX | Use an alternative format.
371 * | aAeEfgG | For the conversions 'o', increase the precision
372 * | | until the first digit will be '0' if
373 * | | it is not formatted as complements.
374 * | | For the conversions 'x', 'X', 'b' and 'B'
375 * | | on non-zero, prefix the result with "0x",
376 * | | "0X", "0b" and "0B", respectively.
377 * | | For 'e', 'E', 'f', 'g', and 'G',
378 * | | force a decimal point to be added,
379 * | | even if no digits follow.
380 * | | For 'g' and 'G', do not remove trailing zeros.
381 * ---------+---------------+-----------------------------------------
382 * + | bBdiouxX | Add a leading plus sign to non-negative
383 * | aAeEfgG | numbers.
384 * | (numeric fmt) | For 'o', 'x', 'X', 'b' and 'B', use
385 * | | a minus sign with absolute value for
386 * | | negative values.
387 * ---------+---------------+-----------------------------------------
388 * - | all | Left-justify the result of this conversion.
389 * ---------+---------------+-----------------------------------------
390 * 0 (zero) | bBdiouxX | Pad with zeros, not spaces.
391 * | aAeEfgG | For 'o', 'x', 'X', 'b' and 'B', radix-1
392 * | (numeric fmt) | is used for negative numbers formatted as
393 * | | complements.
394 * ---------+---------------+-----------------------------------------
395 * * | all | Use the next argument as the field width.
396 * | | If negative, left-justify the result. If the
397 * | | asterisk is followed by a number and a dollar
398 * | | sign, use the indicated argument as the width.
399 *
400 * Examples of flags:
401 *
402 * # '+' and space flag specifies the sign of non-negative numbers.
403 * sprintf("%d", 123) #=> "123"
404 * sprintf("%+d", 123) #=> "+123"
405 * sprintf("% d", 123) #=> " 123"
406 *
407 * # '#' flag for 'o' increases number of digits to show '0'.
408 * # '+' and space flag changes format of negative numbers.
409 * sprintf("%o", 123) #=> "173"
410 * sprintf("%#o", 123) #=> "0173"
411 * sprintf("%+o", -123) #=> "-173"
412 * sprintf("%o", -123) #=> "..7605"
413 * sprintf("%#o", -123) #=> "..7605"
414 *
415 * # '#' flag for 'x' add a prefix '0x' for non-zero numbers.
416 * # '+' and space flag disables complements for negative numbers.
417 * sprintf("%x", 123) #=> "7b"
418 * sprintf("%#x", 123) #=> "0x7b"
419 * sprintf("%+x", -123) #=> "-7b"
420 * sprintf("%x", -123) #=> "..f85"
421 * sprintf("%#x", -123) #=> "0x..f85"
422 * sprintf("%#x", 0) #=> "0"
423 *
424 * # '#' for 'X' uses the prefix '0X'.
425 * sprintf("%X", 123) #=> "7B"
426 * sprintf("%#X", 123) #=> "0X7B"
427 *
428 * # '#' flag for 'b' add a prefix '0b' for non-zero numbers.
429 * # '+' and space flag disables complements for negative numbers.
430 * sprintf("%b", 123) #=> "1111011"
431 * sprintf("%#b", 123) #=> "0b1111011"
432 * sprintf("%+b", -123) #=> "-1111011"
433 * sprintf("%b", -123) #=> "..10000101"
434 * sprintf("%#b", -123) #=> "0b..10000101"
435 * sprintf("%#b", 0) #=> "0"
436 *
437 * # '#' for 'B' uses the prefix '0B'.
438 * sprintf("%B", 123) #=> "1111011"
439 * sprintf("%#B", 123) #=> "0B1111011"
440 *
441 * # '#' for 'e' forces to show the decimal point.
442 * sprintf("%.0e", 1) #=> "1e+00"
443 * sprintf("%#.0e", 1) #=> "1.e+00"
444 *
445 * # '#' for 'f' forces to show the decimal point.
446 * sprintf("%.0f", 1234) #=> "1234"
447 * sprintf("%#.0f", 1234) #=> "1234."
448 *
449 * # '#' for 'g' forces to show the decimal point.
450 * # It also disables stripping lowest zeros.
451 * sprintf("%g", 123.4) #=> "123.4"
452 * sprintf("%#g", 123.4) #=> "123.400"
453 * sprintf("%g", 123456) #=> "123456"
454 * sprintf("%#g", 123456) #=> "123456."
455 *
456 * The field width is an optional integer, followed optionally by a
457 * period and a precision. The width specifies the minimum number of
458 * characters that will be written to the result for this field.
459 *
460 * Examples of width:
461 *
462 * # padding is done by spaces, width=20
463 * # 0 or radix-1. <------------------>
464 * sprintf("%20d", 123) #=> " 123"
465 * sprintf("%+20d", 123) #=> " +123"
466 * sprintf("%020d", 123) #=> "00000000000000000123"
467 * sprintf("%+020d", 123) #=> "+0000000000000000123"
468 * sprintf("% 020d", 123) #=> " 0000000000000000123"
469 * sprintf("%-20d", 123) #=> "123 "
470 * sprintf("%-+20d", 123) #=> "+123 "
471 * sprintf("%- 20d", 123) #=> " 123 "
472 * sprintf("%020x", -123) #=> "..ffffffffffffffff85"
473 *
474 * For
475 * numeric fields, the precision controls the number of decimal places
476 * displayed. For string fields, the precision determines the maximum
477 * number of characters to be copied from the string. (Thus, the format
478 * sequence <code>%10.10s</code> will always contribute exactly ten
479 * characters to the result.)
480 *
481 * Examples of precisions:
482 *
483 * # precision for 'd', 'o', 'x' and 'b' is
484 * # minimum number of digits <------>
485 * sprintf("%20.8d", 123) #=> " 00000123"
486 * sprintf("%20.8o", 123) #=> " 00000173"
487 * sprintf("%20.8x", 123) #=> " 0000007b"
488 * sprintf("%20.8b", 123) #=> " 01111011"
489 * sprintf("%20.8d", -123) #=> " -00000123"
490 * sprintf("%20.8o", -123) #=> " ..777605"
491 * sprintf("%20.8x", -123) #=> " ..ffff85"
492 * sprintf("%20.8b", -11) #=> " ..110101"
493 *
494 * # "0x" and "0b" for '#x' and '#b' is not counted for
495 * # precision but "0" for '#o' is counted. <------>
496 * sprintf("%#20.8d", 123) #=> " 00000123"
497 * sprintf("%#20.8o", 123) #=> " 00000173"
498 * sprintf("%#20.8x", 123) #=> " 0x0000007b"
499 * sprintf("%#20.8b", 123) #=> " 0b01111011"
500 * sprintf("%#20.8d", -123) #=> " -00000123"
501 * sprintf("%#20.8o", -123) #=> " ..777605"
502 * sprintf("%#20.8x", -123) #=> " 0x..ffff85"
503 * sprintf("%#20.8b", -11) #=> " 0b..110101"
504 *
505 * # precision for 'e' is number of
506 * # digits after the decimal point <------>
507 * sprintf("%20.8e", 1234.56789) #=> " 1.23456789e+03"
508 *
509 * # precision for 'f' is number of
510 * # digits after the decimal point <------>
511 * sprintf("%20.8f", 1234.56789) #=> " 1234.56789000"
512 *
513 * # precision for 'g' is number of
514 * # significant digits <------->
515 * sprintf("%20.8g", 1234.56789) #=> " 1234.5679"
516 *
517 * # <------->
518 * sprintf("%20.8g", 123456789) #=> " 1.2345679e+08"
519 *
520 * # precision for 's' is
521 * # maximum number of characters <------>
522 * sprintf("%20.8s", "string test") #=> " string t"
523 *
524 * Examples:
525 *
526 * sprintf("%d %04x", 123, 123) #=> "123 007b"
527 * sprintf("%08b '%4s'", 123, 123) #=> "01111011 ' 123'"
528 * sprintf("%1$*2$s %2$d %1$s", "hello", 8) #=> " hello 8 hello"
529 * sprintf("%1$*2$s %2$d", "hello", -8) #=> "hello -8"
530 * sprintf("%+g:% g:%-g", 1.23, 1.23, 1.23) #=> "+1.23: 1.23:1.23"
531 * sprintf("%u", -123) #=> "-123"
532 *
533 * For more complex formatting, Ruby supports a reference by name.
534 * %<name>s style uses format style, but %{name} style doesn't.
535 *
536 * Examples:
537 * sprintf("%<foo>d : %<bar>f", { :foo => 1, :bar => 2 })
538 * #=> 1 : 2.000000
539 * sprintf("%{foo}f", { :foo => 1 })
540 * # => "1f"
541 */
542
543 static mrb_value
544 mrb_f_sprintf(mrb_state *mrb, mrb_value obj)
545 {
546 mrb_int argc;
547 const mrb_value *argv;
548
549 mrb_get_args(mrb, "*", &argv, &argc);
550
551 if (argc <= 0) {
552 mrb_raise(mrb, E_ARGUMENT_ERROR, "too few arguments");
553 return mrb_nil_value();
554 }
555 else {
556 return mrb_str_format(mrb, argc - 1, argv + 1, argv[0]);
557 }
558 }
559
560 mrb_value
561 mrb_str_format(mrb_state *mrb, mrb_int argc, const mrb_value *argv, mrb_value fmt)
562 {
563 const char *p, *end;
564 char *buf;
565 mrb_int blen;
566 mrb_int bsiz;
567 mrb_value result;
568 int n;
569 int width;
570 int prec;
571 int nextarg = 1;
572 int posarg = 0;
573 mrb_value nextvalue;
574 mrb_value str;
575 mrb_value hash = mrb_undef_value();
576
577 #define CHECK_FOR_WIDTH(f) \
578 if ((f) & FWIDTH) { \
579 mrb_raise(mrb, E_ARGUMENT_ERROR, "width given twice"); \
580 } \
581 if ((f) & FPREC0) { \
582 mrb_raise(mrb, E_ARGUMENT_ERROR, "width after precision"); \
583 }
584 #define CHECK_FOR_FLAGS(f) \
585 if ((f) & FWIDTH) { \
586 mrb_raise(mrb, E_ARGUMENT_ERROR, "flag after width"); \
587 } \
588 if ((f) & FPREC0) { \
589 mrb_raise(mrb, E_ARGUMENT_ERROR, "flag after precision"); \
590 }
591
592 argc++;
593 argv--;
594 mrb_ensure_string_type(mrb, fmt);
595 p = RSTRING_PTR(fmt);
596 end = p + RSTRING_LEN(fmt);
597 blen = 0;
598 bsiz = 120;
599 result = mrb_str_new_capa(mrb, bsiz);
600 buf = RSTRING_PTR(result);
601 memset(buf, 0, bsiz);
602
603 for (; p < end; p++) {
604 const char *t;
605 mrb_sym id = 0;
606 int flags = FNONE;
607
608 for (t = p; t < end && *t != '%'; t++)
609 ;
610 if (t + 1 == end) t++;
611 PUSH(p, t - p);
612 if (t >= end)
613 goto sprint_exit; /* end of fmt string */
614
615 p = t + 1; /* skip '%' */
616
617 width = prec = -1;
618 nextvalue = mrb_undef_value();
619
620 retry:
621 switch (*p) {
622 default:
623 mrb_raisef(mrb, E_ARGUMENT_ERROR, "malformed format string - %%%c", *p);
624 break;
625
626 case ' ':
627 CHECK_FOR_FLAGS(flags);
628 flags |= FSPACE;
629 p++;
630 goto retry;
631
632 case '#':
633 CHECK_FOR_FLAGS(flags);
634 flags |= FSHARP;
635 p++;
636 goto retry;
637
638 case '+':
639 CHECK_FOR_FLAGS(flags);
640 flags |= FPLUS;
641 p++;
642 goto retry;
643
644 case '-':
645 CHECK_FOR_FLAGS(flags);
646 flags |= FMINUS;
647 p++;
648 goto retry;
649
650 case '0':
651 CHECK_FOR_FLAGS(flags);
652 flags |= FZERO;
653 p++;
654 goto retry;
655
656 case '1': case '2': case '3': case '4':
657 case '5': case '6': case '7': case '8': case '9':
658 GETNUM(n, width);
659 if (*p == '$') {
660 if (!mrb_undef_p(nextvalue)) {
661 mrb_raisef(mrb, E_ARGUMENT_ERROR, "value given twice - %i$", n);
662 }
663 nextvalue = GETPOSARG(n);
664 p++;
665 goto retry;
666 }
667 CHECK_FOR_WIDTH(flags);
668 width = n;
669 flags |= FWIDTH;
670 goto retry;
671
672 case '<':
673 case '{': {
674 const char *start = p;
675 char term = (*p == '<') ? '>' : '}';
676
677 for (; p < end && *p != term; )
678 p++;
679 if (id) {
680 mrb_raisef(mrb, E_ARGUMENT_ERROR, "name%l after <%n>",
681 start, p - start + 1, id);
682 }
683 CHECKNAMEARG(start, p - start + 1);
684 get_hash(mrb, &hash, argc, argv);
685 id = mrb_intern_check(mrb, start + 1, p - start - 1);
686 if (id) {
687 nextvalue = mrb_hash_fetch(mrb, hash, mrb_symbol_value(id), mrb_undef_value());
688 }
689 if (!id || mrb_undef_p(nextvalue)) {
690 mrb_raisef(mrb, E_KEY_ERROR, "key%l not found", start, p - start + 1);
691 }
692 if (term == '}') goto format_s;
693 p++;
694 goto retry;
695 }
696
697 case '*':
698 CHECK_FOR_WIDTH(flags);
699 flags |= FWIDTH;
700 GETASTER(width);
701 if (width > INT16_MAX || INT16_MIN > width) {
702 mrb_raise(mrb, E_ARGUMENT_ERROR, "width too big");
703 }
704 if (width < 0) {
705 flags |= FMINUS;
706 width = -width;
707 }
708 p++;
709 goto retry;
710
711 case '.':
712 if (flags & FPREC0) {
713 mrb_raise(mrb, E_ARGUMENT_ERROR, "precision given twice");
714 }
715 flags |= FPREC|FPREC0;
716
717 p++;
718 if (*p == '*') {
719 GETASTER(prec);
720 if (prec < 0) { /* ignore negative precision */
721 flags &= ~FPREC;
722 }
723 p++;
724 goto retry;
725 }
726 GETNUM(prec, precision);
727 goto retry;
728
729 case '\n':
730 case '\0':
731 p--;
732 /* fallthrough */
733 case '%':
734 if (flags != FNONE) {
735 mrb_raise(mrb, E_ARGUMENT_ERROR, "invalid format character - %");
736 }
737 PUSH("%", 1);
738 break;
739
740 case 'c': {
741 mrb_value val = GETARG();
742 mrb_value tmp;
743 char *c;
744
745 tmp = mrb_check_string_type(mrb, val);
746 if (!mrb_nil_p(tmp)) {
747 if (RSTRING_LEN(tmp) != 1) {
748 mrb_raise(mrb, E_ARGUMENT_ERROR, "%c requires a character");
749 }
750 }
751 else if (mrb_integer_p(val)) {
752 mrb_int n = mrb_integer(val);
753 #ifndef MRB_UTF8_STRING
754 char buf[1];
755
756 buf[0] = (char)n&0xff;
757 tmp = mrb_str_new(mrb, buf, 1);
758 #else
759 if (n < 0x80) {
760 char buf[1];
761
762 buf[0] = (char)n;
763 tmp = mrb_str_new(mrb, buf, 1);
764 }
765 else {
766 tmp = mrb_funcall_argv(mrb, val, MRB_SYM(chr), 0, NULL);
767 mrb_check_type(mrb, tmp, MRB_TT_STRING);
768 }
769 #endif
770 }
771 else {
772 mrb_raise(mrb, E_ARGUMENT_ERROR, "invalid character");
773 }
774 c = RSTRING_PTR(tmp);
775 n = (int)RSTRING_LEN(tmp);
776 if (!(flags & FWIDTH)) {
777 PUSH(c, n);
778 }
779 else if ((flags & FMINUS)) {
780 PUSH(c, n);
781 if (width>0) FILL(' ', width-1);
782 }
783 else {
784 if (width>0) FILL(' ', width-1);
785 PUSH(c, n);
786 }
787 }
788 break;
789
790 case 's':
791 case 'p':
792 format_s:
793 {
794 mrb_value arg = GETARG();
795 mrb_int len;
796 mrb_int slen;
797
798 if (*p == 'p') arg = mrb_inspect(mrb, arg);
799 str = mrb_obj_as_string(mrb, arg);
800 len = RSTRING_LEN(str);
801 if (RSTRING(result)->flags & MRB_STR_EMBED) {
802 mrb_int tmp_n = len;
803 RSTRING(result)->flags &= ~MRB_STR_EMBED_LEN_MASK;
804 RSTRING(result)->flags |= tmp_n << MRB_STR_EMBED_LEN_SHIFT;
805 }
806 else {
807 RSTRING(result)->as.heap.len = blen;
808 }
809 if (flags&(FPREC|FWIDTH)) {
810 slen = RSTRING_LEN(str);
811 if (slen < 0) {
812 mrb_raise(mrb, E_ARGUMENT_ERROR, "invalid mbstring sequence");
813 }
814 if ((flags&FPREC) && (prec < slen)) {
815 char *p = RSTRING_PTR(str) + prec;
816 slen = prec;
817 len = (mrb_int)(p - RSTRING_PTR(str));
818 }
819 /* need to adjust multi-byte string pos */
820 if ((flags&FWIDTH) && (width > slen)) {
821 width -= (int)slen;
822 if (!(flags&FMINUS)) {
823 FILL(' ', width);
824 }
825 PUSH(RSTRING_PTR(str), len);
826 if (flags&FMINUS) {
827 FILL(' ', width);
828 }
829 break;
830 }
831 }
832 PUSH(RSTRING_PTR(str), len);
833 }
834 break;
835
836 case 'd':
837 case 'i':
838 case 'o':
839 case 'x':
840 case 'X':
841 case 'b':
842 case 'B':
843 case 'u': {
844 mrb_value val = GETARG();
845 char nbuf[69], *s;
846 const char *prefix = NULL;
847 int sign = 0, dots = 0;
848 char sc = 0;
849 mrb_int v = 0;
850 int base;
851 int len;
852
853 if (flags & FSHARP) {
854 switch (*p) {
855 case 'o': prefix = "0"; break;
856 case 'x': prefix = "0x"; break;
857 case 'X': prefix = "0X"; break;
858 case 'b': prefix = "0b"; break;
859 case 'B': prefix = "0B"; break;
860 default: break;
861 }
862 }
863
864 bin_retry:
865 switch (mrb_type(val)) {
866 #ifndef MRB_NO_FLOAT
867 case MRB_TT_FLOAT:
868 val = mrb_float_to_integer(mrb, val);
869 goto bin_retry;
870 #endif
871 case MRB_TT_STRING:
872 val = mrb_str_to_integer(mrb, val, 0, TRUE);
873 goto bin_retry;
874 case MRB_TT_INTEGER:
875 v = mrb_integer(val);
876 break;
877 default:
878 v = mrb_as_int(mrb, val);
879 break;
880 }
881
882 switch (*p) {
883 case 'o':
884 base = 8; break;
885 case 'x':
886 case 'X':
887 base = 16; break;
888 case 'b':
889 case 'B':
890 base = 2; break;
891 case 'u':
892 case 'd':
893 case 'i':
894 sign = 1;
895 /* fall through */
896 default:
897 base = 10; break;
898 }
899
900 if (sign) {
901 if (v >= 0) {
902 if (flags & FPLUS) {
903 sc = '+';
904 width--;
905 }
906 else if (flags & FSPACE) {
907 sc = ' ';
908 width--;
909 }
910 }
911 else {
912 sc = '-';
913 width--;
914 }
915 s = mrb_int_to_cstr(nbuf, sizeof(nbuf), v, base);
916 if (v < 0) s++; /* skip minus sign */
917 }
918 else {
919 /* print as unsigned */
920 s = mrb_uint_to_cstr(nbuf, sizeof(nbuf), v, base);
921 if (v < 0) {
922 dots = 1;
923 }
924 }
925 {
926 size_t size;
927 size = strlen(s);
928 /* PARANOID: assert(size <= MRB_INT_MAX) */
929 len = (int)size;
930 }
931
932 if (*p == 'X') {
933 char *pp = s;
934 int c;
935 while ((c = (int)(unsigned char)*pp) != 0) {
936 *pp = toupper(c);
937 pp++;
938 }
939 }
940
941 if (prefix && !prefix[1]) { /* octal */
942 if (dots) {
943 prefix = NULL;
944 }
945 else if (len == 1 && *s == '0') {
946 len = 0;
947 if (flags & FPREC) prec--;
948 }
949 else if ((flags & FPREC) && (prec > len)) {
950 prefix = NULL;
951 }
952 }
953 else if (len == 1 && *s == '0') {
954 prefix = NULL;
955 }
956
957 if (prefix) {
958 size_t size;
959 size = strlen(prefix);
960 /* PARANOID: assert(size <= MRB_INT_MAX).
961 * this check is absolutely paranoid. */
962 width -= (int)size;
963 }
964
965 if ((flags & (FZERO|FMINUS|FPREC)) == FZERO) {
966 prec = width;
967 width = 0;
968 }
969 else {
970 if (prec < len) {
971 if (!prefix && prec == 0 && len == 1 && *s == '0') len = 0;
972 prec = len;
973 }
974 width -= prec;
975 }
976
977 if (!(flags&FMINUS) && width > 0) {
978 FILL(' ', width);
979 width = 0;
980 }
981
982 if (sc) PUSH(&sc, 1);
983
984 if (prefix) {
985 int plen = (int)strlen(prefix);
986 PUSH(prefix, plen);
987 }
988 if (dots) {
989 prec -= 2;
990 width -= 2;
991 PUSH("..", 2);
992 }
993
994 if (prec > len) {
995 CHECK(prec - len);
996 if ((flags & (FMINUS|FPREC)) != FMINUS) {
997 char c = '0';
998 FILL(c, prec - len);
999 }
1000 else if (v < 0) {
1001 char c = sign_bits(base, p);
1002 FILL(c, prec - len);
1003 }
1004 }
1005 PUSH(s, len);
1006 if (width > 0) {
1007 FILL(' ', width);
1008 }
1009 }
1010 break;
1011
1012 case 'f':
1013 case 'g':
1014 case 'G':
1015 case 'e':
1016 case 'E': {
1017 #ifdef MRB_NO_FLOAT
1018 mrb_raisef(mrb, E_ARGUMENT_ERROR, "%%%c not supported with MRB_NO_FLOAT defined", *p);
1019 #else
1020 mrb_value val = GETARG();
1021 double fval;
1022 mrb_int need = 6;
1023
1024 fval = mrb_as_float(mrb, val);
1025 if (!isfinite(fval)) {
1026 const char *expr;
1027 const int elen = 3;
1028 char sign = '\0';
1029
1030 if (isnan(fval)) {
1031 expr = "NaN";
1032 }
1033 else {
1034 expr = "Inf";
1035 }
1036 need = elen;
1037 if (!isnan(fval) && fval < 0.0)
1038 sign = '-';
1039 else if (flags & (FPLUS|FSPACE))
1040 sign = (flags & FPLUS) ? '+' : ' ';
1041 if (sign)
1042 need++;
1043 if ((flags & FWIDTH) && need < width)
1044 need = width;
1045
1046 if (need < 0) {
1047 mrb_raise(mrb, E_ARGUMENT_ERROR, "width too big");
1048 }
1049 FILL(' ', need);
1050 if (flags & FMINUS) {
1051 if (sign)
1052 buf[blen - need--] = sign;
1053 memcpy(&buf[blen - need], expr, elen);
1054 }
1055 else {
1056 if (sign)
1057 buf[blen - elen - 1] = sign;
1058 memcpy(&buf[blen - elen], expr, (size_t)elen);
1059 }
1060 break;
1061 }
1062
1063 need = 0;
1064 if (*p != 'e' && *p != 'E') {
1065 int i;
1066 frexp(fval, &i);
1067 if (i > 0)
1068 need = BIT_DIGITS(i);
1069 }
1070 if (need > MRB_INT_MAX - ((flags&FPREC) ? prec : 6)) {
1071 too_big_width_prec:
1072 mrb_raise(mrb, E_ARGUMENT_ERROR,
1073 (width > prec ? "width too big" : "prec too big"));
1074 }
1075 need += (flags&FPREC) ? prec : 6;
1076 if ((flags&FWIDTH) && need < width)
1077 need = width;
1078 if ((mrb_int)need > MRB_INT_MAX - 20) {
1079 goto too_big_width_prec;
1080 }
1081 need += 20;
1082
1083 CHECK(need);
1084 n = fmt_float(&buf[blen], need, *p, flags, width, prec, fval);
1085 if (n < 0 || n >= need) {
1086 mrb_raise(mrb, E_RUNTIME_ERROR, "formatting error");
1087 }
1088 blen += n;
1089 #endif
1090 }
1091 break;
1092 }
1093 flags = FNONE;
1094 }
1095
1096 sprint_exit:
1097 #if 0
1098 /* XXX - We cannot validate the number of arguments if (digit)$ style used.
1099 */
1100 if (posarg >= 0 && nextarg < argc) {
1101 const char *mesg = "too many arguments for format string";
1102 if (mrb_test(ruby_debug)) mrb_raise(mrb, E_ARGUMENT_ERROR, mesg);
1103 if (mrb_test(ruby_verbose)) mrb_warn(mrb, mesg);
1104 }
1105 #endif
1106 mrb_str_resize(mrb, result, blen);
1107
1108 return result;
1109 }
1110
1111
1112 void
1113 mrb_mruby_sprintf_gem_init(mrb_state *mrb)
1114 {
1115 struct RClass *krn = mrb->kernel_module;
1116 mrb_define_module_function(mrb, krn, "sprintf", mrb_f_sprintf, MRB_ARGS_ANY());
1117 mrb_define_module_function(mrb, krn, "format", mrb_f_sprintf, MRB_ARGS_ANY());
1118 }
1119
1120 void
1121 mrb_mruby_sprintf_gem_final(mrb_state *mrb)
1122 {
1123 }