Ruby 4.1.0dev (2026-12-03 revision da234ef6cade3309d163e0cbeaaf616f3367b377)
pack.c (da234ef6cade3309d163e0cbeaaf616f3367b377)
1/**********************************************************************
2
3 pack.c -
4
5 $Author$
6 created at: Thu Feb 10 15:17:05 JST 1994
7
8 Copyright (C) 1993-2007 Yukihiro Matsumoto
9
10**********************************************************************/
11
12#include "ruby/internal/config.h"
13
14#include <ctype.h>
15#include <errno.h>
16#include <float.h>
17#include <sys/types.h>
18
19#include "internal.h"
20#include "internal/array.h"
21#include "internal/bits.h"
22#include "internal/numeric.h"
23#include "internal/string.h"
24#include "internal/symbol.h"
25#include "internal/variable.h"
26#include "ruby/util.h"
27
28#include "builtin.h"
29
30/*
31 * It is intentional that the condition for natstr is HAVE_TRUE_LONG_LONG
32 * instead of HAVE_LONG_LONG or LONG_LONG.
33 * This means q! and Q! means always the standard long long type and
34 * causes ArgumentError for platforms which has no long long type,
35 * even if the platform has an implementation specific 64bit type.
36 * This behavior is consistent with the document of pack/unpack.
37 */
38#ifdef HAVE_TRUE_LONG_LONG
39static const char natstr[] = "sSiIlLqQjJ";
40# define endstr natstr
41#else
42static const char natstr[] = "sSiIlLjJ";
43static const char endstr[] = "sSiIlLqQjJ";
44#endif
45
46#ifdef HAVE_TRUE_LONG_LONG
47/* It is intentional to use long long instead of LONG_LONG. */
48# define NATINT_LEN_Q NATINT_LEN(long long, 8)
49#else
50# define NATINT_LEN_Q 8
51#endif
52
53#if SIZEOF_SHORT != 2 || SIZEOF_LONG != 4 || (defined(HAVE_TRUE_LONG_LONG) && SIZEOF_LONG_LONG != 8)
54# define NATINT_PACK
55#endif
56
57#ifdef DYNAMIC_ENDIAN
58/* for universal binary of MacOS X */
59/* useless since autoconf 2.63? */
60static int
61is_bigendian(void)
62{
63 static const union {int i; char b[1];} endian_value = {1};
64 return !endian_value.b[0];
65}
66# define BIGENDIAN_P() (is_bigendian())
67#elif defined(WORDS_BIGENDIAN)
68# define BIGENDIAN_P() 1
69#else
70# define BIGENDIAN_P() 0
71#endif
72
73#ifdef NATINT_PACK
74# define NATINT_LEN(type,len) (natint?(int)sizeof(type):(int)(len))
75# define NATINT_ALIGN(type,len) (natint?(int)RUBY_ALIGNOF(type):(int)(len))
76# define USING_NATINT(expr) expr
77#else
78# define NATINT_LEN(type,len) ((int)sizeof(type))
79# define NATINT_ALIGN(type,len) ((int)RUBY_ALIGNOF(type))
80# define USING_NATINT(expr) /* void */
81#endif
82
83typedef union {
84 float f;
85 uint32_t u;
86 char buf[4];
88typedef union {
89 double d;
90 uint64_t u;
91 char buf[8];
93#define swapf(x) swap32(x)
94#define swapd(x) swap64(x)
95
96#define rb_ntohf(x) (BIGENDIAN_P()?(x):swapf(x))
97#define rb_ntohd(x) (BIGENDIAN_P()?(x):swapd(x))
98#define rb_htonf(x) (BIGENDIAN_P()?(x):swapf(x))
99#define rb_htond(x) (BIGENDIAN_P()?(x):swapd(x))
100#define rb_htovf(x) (BIGENDIAN_P()?swapf(x):(x))
101#define rb_htovd(x) (BIGENDIAN_P()?swapd(x):(x))
102#define rb_vtohf(x) (BIGENDIAN_P()?swapf(x):(x))
103#define rb_vtohd(x) (BIGENDIAN_P()?swapd(x):(x))
104
105#define FLOAT_CONVWITH(x) FLOAT_SWAPPER x;
106#define HTONF(x) ((x).u = rb_htonf((x).u))
107#define HTOVF(x) ((x).u = rb_htovf((x).u))
108#define NTOHF(x) ((x).u = rb_ntohf((x).u))
109#define VTOHF(x) ((x).u = rb_vtohf((x).u))
110
111#define DOUBLE_CONVWITH(x) DOUBLE_SWAPPER x;
112#define HTOND(x) ((x).u = rb_htond((x).u))
113#define HTOVD(x) ((x).u = rb_htovd((x).u))
114#define NTOHD(x) ((x).u = rb_ntohd((x).u))
115#define VTOHD(x) ((x).u = rb_vtohd((x).u))
116
117#define MAX_INTEGER_PACK_SIZE 8
118
119static const char toofew[] = "too few arguments";
120static const char intoitself[] = "cannot pack buffer object into itself";
121
122static void encodes(VALUE,const char*,rb_len_t,int,int);
123static void qpencode(VALUE,VALUE,rb_len_t);
124
125static unsigned long utf8_to_uv(const char*,rb_len_t*);
126
127static ID id_associated;
128
129static void
130str_associate(VALUE str, VALUE add)
131{
132 /* assert(NIL_P(rb_attr_get(str, id_associated))); */
133 rb_ivar_set(str, id_associated, add);
134}
135
136static VALUE
137str_associated(VALUE str)
138{
139 VALUE associates = rb_ivar_lookup(str, id_associated, Qfalse);
140 if (!associates)
141 rb_raise(rb_eArgError, "no associated pointer");
142 return associates;
143}
144
145static VALUE
146associated_pointer(VALUE associates, const char *t)
147{
148 const VALUE *p = RARRAY_CONST_PTR(associates);
149 const VALUE *pend = p + RARRAY_LEN(associates);
150 for (; p < pend; p++) {
151 VALUE tmp = *p;
152 if (RB_TYPE_P(tmp, T_STRING) && RSTRING_PTR(tmp) == t) return tmp;
153 }
154 rb_raise(rb_eArgError, "non associated pointer");
156}
157
159static void
160unknown_directive(const char *mode, char type, VALUE fmt)
161{
162 char unknown[5];
163
164 if (ISPRINT(type)) {
165 unknown[0] = type;
166 unknown[1] = '\0';
167 }
168 else {
169 snprintf(unknown, sizeof(unknown), "\\x%.2x", type & 0xff);
170 }
171 fmt = rb_str_quote_unprintable(fmt);
172 rb_raise(rb_eArgError, "unknown %s directive '%s' in '%"PRIsVALUE"'",
173 mode, unknown, fmt);
174}
175
176static float
177VALUE_to_float(VALUE obj)
178{
179 VALUE v = rb_to_float(obj);
180 double d = RFLOAT_VALUE(v);
181
182 if (isnan(d)) {
183 return NAN;
184 }
185 else if (d < -FLT_MAX) {
186 return -INFINITY;
187 }
188 else if (d <= FLT_MAX) {
189 return d;
190 }
191 else {
192 return INFINITY;
193 }
194}
195
196static void
197str_expand_fill(VALUE res, int c, rb_len_t len)
198{
199 rb_len_t olen = RSTRING_LEN(res);
200 memset(RSTRING_PTR(res) + olen, c, len);
201 rb_str_set_len(res, olen + len);
202}
203
204static char *
205skip_to_eol(const char *p, const char *pend)
206{
207 p = memchr(p, '\n', pend - p);
208 return (char *)(p ? p + 1 : pend);
209}
210
211#define skip_blank(p, type) \
212 (ISSPACE(type) || (type == '#' && (p = skip_to_eol(p, pend), 1)))
213
214#ifndef NATINT_PACK
215# define pack_modifiers(p, pe, t, n, e) pack_modifiers(p, pe, t, e)
216#endif
217static const char *
218pack_modifiers(const char *p, const char *pend, char type, int *natint, int *explicit_endian)
219{
220 while (p < pend) {
221 switch (*p) {
222 case '_':
223 case '!':
224 if (strchr(natstr, type)) {
225 USING_NATINT(*natint = 1);
226 p++;
227 }
228 else {
229 rb_raise(rb_eArgError, "'%c' allowed only after types %s", *p, natstr);
230 }
231 break;
232
233 case '<':
234 case '>':
235 if (!strchr(endstr, type)) {
236 rb_raise(rb_eArgError, "'%c' allowed only after types %s", *p, endstr);
237 }
238 if (*explicit_endian) {
239 rb_raise(rb_eRangeError, "Can't use both '<' and '>'");
240 }
241 *explicit_endian = *p++;
242 break;
243 default:
244 return (char *)p;
245 }
246 }
247 return p;
248}
249
250#ifndef NATINT_PACK
251# define pack_alignof(t, n) pack_alignof(t)
252#endif
253static size_t
254pack_alignof(char type, int natint)
255{
256 switch (type) {
257 case 'c': case 'C':
258 return RUBY_ALIGNOF(char);
259 case 's': case 'S':
260 return NATINT_ALIGN(short, 2);
261 case 'i': case 'I':
262 return RUBY_ALIGNOF(int);
263 case 'l': case 'L':
264 return NATINT_ALIGN(long, 4);
265 case 'q': case 'Q':
266 return RUBY_ALIGNOF(int64_t);
267 case 'j':
268 return RUBY_ALIGNOF(intptr_t);
269 case 'J':
270 return RUBY_ALIGNOF(uintptr_t);
271 case 'n': case 'v':
272 return RUBY_ALIGNOF(uint16_t);
273 case 'N': case 'V':
274 return RUBY_ALIGNOF(uint32_t);
275 case 'f': case 'F': case 'e': case 'g':
276 return RUBY_ALIGNOF(float);
277 case 'd': case 'D': case 'E': case 'G':
278 return RUBY_ALIGNOF(double);
279 case 'p': case 'P':
280 return RUBY_ALIGNOF(char *);
281 default:
282 return 0;
283 }
284}
285
286static rb_len_t
287pack_align_pad(rb_len_t pos, rb_len_t base, size_t alignment)
288{
289 rb_len_t offset, mod;
290
291 if (alignment <= 1) return 0;
292 if (alignment > RB_LEN_MAX) rb_raise(rb_eRangeError, "alignment too big");
293 offset = pos - base;
294 mod = offset % (rb_len_t)alignment;
295 if (mod < 0) mod += alignment;
296 return mod ? (rb_len_t)alignment - mod : 0;
297}
298
299static char *
300pack_alignment(const char *p, const char *pend, VALUE fmt, size_t *alignment)
301{
302 char type;
303 int explicit_endian = 0;
304 USING_NATINT(int natint = 0);
305
306 if (p >= pend) {
307 rb_raise(rb_eArgError, "missing alignment");
308 }
309 type = *p++;
310 p = pack_modifiers(p, pend, type, &natint, &explicit_endian);
311 if (explicit_endian) {
312 rb_raise(rb_eArgError, "endian modifier is not allowed for alignment");
313 }
314 *alignment = pack_alignof(type, natint);
315 if (!*alignment) {
316 unknown_directive("alignment", type, fmt);
317 }
318 return (char *)p;
319}
320
321static char *
322pack_alignment_size(const char *p, const char *pend, VALUE fmt, size_t *alignment)
323{
324 if (p < pend && ISDIGIT(*p)) {
325 errno = 0;
326 *alignment = STRTOUL(p, (char**)&p, 10);
327 if (*alignment <= 0 || errno) {
328 rb_raise(rb_eRangeError, "invalid alignment");
329 }
330 return (char *)p;
331 }
332 return pack_alignment(p, pend, fmt, alignment);
333}
334
335static VALUE
336pack_pack(rb_execution_context_t *ec, VALUE ary, VALUE fmt, VALUE buffer)
337{
338 const char *p, *pend;
339 VALUE res, from, associates = 0;
340 rb_len_t len, idx, plen;
341 const char *ptr;
342 int enc_info = 1; /* 0 - BINARY, 1 - US-ASCII, 2 - UTF-8 */
343 int integer_size, bigendian_p;
344 rb_len_t align_base;
345
346 StringValue(fmt);
348 p = RSTRING_PTR(fmt);
349 pend = p + RSTRING_LEN(fmt);
350
351 if (NIL_P(buffer)) {
352 res = rb_str_buf_new(0);
353 }
354 else {
355 if (!RB_TYPE_P(buffer, T_STRING))
356 rb_raise(rb_eTypeError, "buffer must be String, not %s", rb_obj_classname(buffer));
357 rb_str_modify(buffer);
358 res = buffer;
359 }
360
361 idx = 0;
362 align_base = RSTRING_LEN(res);
363
364#define TOO_FEW (rb_raise(rb_eArgError, toofew), 0)
365#define MORE_ITEM (idx < RARRAY_LEN(ary))
366#define THISFROM (MORE_ITEM ? RARRAY_AREF(ary, idx) : TOO_FEW)
367#define NEXTFROM (MORE_ITEM ? RARRAY_AREF(ary, idx++) : TOO_FEW)
368#define NOT_BUFFER(val) (((val) == res) ? rb_raise(rb_eArgError, intoitself) : (void)0)
369#define STR_FROM(val) NOT_BUFFER(StringValue(val))
370
371 while (p < pend) {
372 int explicit_endian = 0;
373 size_t align = 0;
374 bool star = false;
375 if (RSTRING_END(fmt) != pend) {
376 rb_raise(rb_eRuntimeError, "format string modified");
377 }
378 const char type = *p++; /* get data type */
379 USING_NATINT(int natint = 0); /* native integer */
380
381 if (skip_blank(p, type)) continue;
382
383 /* Directives that do not take modifiers. */
384 if ((type == 'x' || type == '@') && p < pend && *p == '!') {
385 p++;
386 p = pack_alignment_size(p, pend, fmt, &align);
387 len = pack_align_pad(RSTRING_LEN(res), type == '@' ? 0 : align_base, align);
389 str_expand_fill(res, '\0', len);
390 continue;
391 }
392
393 p = pack_modifiers(p, pend, type, &natint, &explicit_endian);
394
395 if (*p == '*') { /* set data length */
396 star = true;
397 len = strchr("@Xxu", type) ? 0
398 : strchr("PMm", type) ? 1
399 : RARRAY_LEN(ary) - idx;
400 p++;
401 }
402 else if (ISDIGIT(*p)) {
403 errno = 0;
404 len = STRTOUL(p, (char**)&p, 10);
405 if (len < 0 || errno) {
406 rb_raise(rb_eRangeError, "pack length too big");
407 }
408 }
409 else {
410 len = 1;
411 }
412
413 switch (type) {
414 case 'U':
415 /* if encoding is US-ASCII, upgrade to UTF-8 */
416 if (enc_info == 1) enc_info = 2;
417 break;
418 case 'm': case 'M': case 'u':
419 /* keep US-ASCII (do nothing) */
420 break;
421 default:
422 /* fall back to BINARY */
423 enc_info = 0;
424 break;
425 }
426 switch (type) {
427 case 'A': case 'a': case 'Z':
428 case 'B': case 'b':
429 case 'H': case 'h':
430 from = NEXTFROM;
431 if (NIL_P(from)) {
432 ptr = "";
433 plen = 0;
434 }
435 else {
436 STR_FROM(from);
437 ptr = RSTRING_PTR(from);
438 plen = RSTRING_LEN(from);
439 }
440
441 /* The conversion of from with #to_str may have modified fmt,
442 * so p may be a dangling pointer; use star instead of p[-1]. */
443 if (star)
444 len = plen;
445
446 switch (type) {
447 case 'a': /* arbitrary binary string (null padded) */
448 case 'A': /* arbitrary binary string (ASCII space padded) */
449 case 'Z': /* null terminated string */
450 if (plen >= len) {
451 rb_str_buf_cat(res, ptr, len);
452 if (star && type == 'Z')
453 rb_str_buf_cat(res, "", 1);
454 }
455 else {
457 rb_str_buf_cat(res, ptr, plen);
458 str_expand_fill(res, (type == 'A' ? ' ' : '\0'), len - plen);
459 }
460 break;
461
462#define castchar(from) (char)((from) & 0xff)
463
464 case 'b': /* bit string (ascending) */
465 {
466 int byte = 0;
467 rb_len_t i, j = 0;
468
469 if (len > plen) {
470 j = (len - plen + 1)/2;
471 len = plen;
472 }
473 for (i=0; i++ < len; ptr++) {
474 if (*ptr & 1)
475 byte |= 128;
476 if (i & 7)
477 byte >>= 1;
478 else {
479 char c = castchar(byte);
480 rb_str_buf_cat(res, &c, 1);
481 byte = 0;
482 }
483 }
484 if (len & 7) {
485 char c;
486 byte >>= 7 - (len & 7);
487 c = castchar(byte);
488 rb_str_buf_cat(res, &c, 1);
489 }
490 len = j;
491 goto grow;
492 }
493 break;
494
495 case 'B': /* bit string (descending) */
496 {
497 int byte = 0;
498 rb_len_t i, j = 0;
499
500 if (len > plen) {
501 j = (len - plen + 1)/2;
502 len = plen;
503 }
504 for (i=0; i++ < len; ptr++) {
505 byte |= *ptr & 1;
506 if (i & 7)
507 byte <<= 1;
508 else {
509 char c = castchar(byte);
510 rb_str_buf_cat(res, &c, 1);
511 byte = 0;
512 }
513 }
514 if (len & 7) {
515 char c;
516 byte <<= 7 - (len & 7);
517 c = castchar(byte);
518 rb_str_buf_cat(res, &c, 1);
519 }
520 len = j;
521 goto grow;
522 }
523 break;
524
525 case 'h': /* hex string (low nibble first) */
526 {
527 int byte = 0;
528 rb_len_t i, j = 0;
529
530 if (len > plen) {
531 j = (len + 1) / 2 - (plen + 1) / 2;
532 len = plen;
533 }
534 for (i=0; i++ < len; ptr++) {
535 if (ISALPHA(*ptr))
536 byte |= (((*ptr & 15) + 9) & 15) << 4;
537 else
538 byte |= (*ptr & 15) << 4;
539 if (i & 1)
540 byte >>= 4;
541 else {
542 char c = castchar(byte);
543 rb_str_buf_cat(res, &c, 1);
544 byte = 0;
545 }
546 }
547 if (len & 1) {
548 char c = castchar(byte);
549 rb_str_buf_cat(res, &c, 1);
550 }
551 len = j;
552 goto grow;
553 }
554 break;
555
556 case 'H': /* hex string (high nibble first) */
557 {
558 int byte = 0;
559 rb_len_t i, j = 0;
560
561 if (len > plen) {
562 j = (len + 1) / 2 - (plen + 1) / 2;
563 len = plen;
564 }
565 for (i=0; i++ < len; ptr++) {
566 if (ISALPHA(*ptr))
567 byte |= ((*ptr & 15) + 9) & 15;
568 else
569 byte |= *ptr & 15;
570 if (i & 1)
571 byte <<= 4;
572 else {
573 char c = castchar(byte);
574 rb_str_buf_cat(res, &c, 1);
575 byte = 0;
576 }
577 }
578 if (len & 1) {
579 char c = castchar(byte);
580 rb_str_buf_cat(res, &c, 1);
581 }
582 len = j;
583 goto grow;
584 }
585 break;
586 }
587 break;
588
589 case 'c': /* signed char */
590 case 'C': /* unsigned char */
591 integer_size = 1;
592 bigendian_p = BIGENDIAN_P(); /* not effective */
593 goto pack_integer;
594
595 case 's': /* s for int16_t, s! for signed short */
596 case 'S': /* S for uint16_t, S! for unsigned short */
597 integer_size = NATINT_LEN(short, 2);
598 bigendian_p = BIGENDIAN_P();
599 goto pack_integer;
600
601 case 'i': /* i and i! for signed int */
602 case 'I': /* I and I! for unsigned int */
603 integer_size = (int)sizeof(int);
604 bigendian_p = BIGENDIAN_P();
605 goto pack_integer;
606
607 case 'l': /* l for int32_t, l! for signed long */
608 case 'L': /* L for uint32_t, L! for unsigned long */
609 integer_size = NATINT_LEN(long, 4);
610 bigendian_p = BIGENDIAN_P();
611 goto pack_integer;
612
613 case 'q': /* q for int64_t, q! for signed long long */
614 case 'Q': /* Q for uint64_t, Q! for unsigned long long */
615 integer_size = NATINT_LEN_Q;
616 bigendian_p = BIGENDIAN_P();
617 goto pack_integer;
618
619 case 'j': /* j for intptr_t */
620 integer_size = sizeof(intptr_t);
621 bigendian_p = BIGENDIAN_P();
622 goto pack_integer;
623
624 case 'J': /* J for uintptr_t */
625 integer_size = sizeof(uintptr_t);
626 bigendian_p = BIGENDIAN_P();
627 goto pack_integer;
628
629 case 'n': /* 16 bit (2 bytes) integer (network byte-order) */
630 integer_size = 2;
631 bigendian_p = 1;
632 goto pack_integer;
633
634 case 'N': /* 32 bit (4 bytes) integer (network byte-order) */
635 integer_size = 4;
636 bigendian_p = 1;
637 goto pack_integer;
638
639 case 'v': /* 16 bit (2 bytes) integer (VAX byte-order) */
640 integer_size = 2;
641 bigendian_p = 0;
642 goto pack_integer;
643
644 case 'V': /* 32 bit (4 bytes) integer (VAX byte-order) */
645 integer_size = 4;
646 bigendian_p = 0;
647 goto pack_integer;
648
649 pack_integer:
650 if (explicit_endian) {
651 bigendian_p = explicit_endian == '>';
652 }
653 if (integer_size > MAX_INTEGER_PACK_SIZE)
654 rb_bug("unexpected integer size for pack: %d", integer_size);
655 while (len-- > 0) {
656 char intbuf[MAX_INTEGER_PACK_SIZE];
657
658 from = NEXTFROM;
659 rb_integer_pack(from, intbuf, integer_size, 1, 0,
662 rb_str_buf_cat(res, intbuf, integer_size);
663 }
664 break;
665
666 case 'f': /* single precision float in native format */
667 case 'F': /* ditto */
668 while (len-- > 0) {
669 float f;
670
671 from = NEXTFROM;
672 f = VALUE_to_float(from);
673 rb_str_buf_cat(res, (char*)&f, sizeof(float));
674 }
675 break;
676
677 case 'e': /* single precision float in VAX byte-order */
678 while (len-- > 0) {
679 FLOAT_CONVWITH(tmp);
680
681 from = NEXTFROM;
682 tmp.f = VALUE_to_float(from);
683 HTOVF(tmp);
684 rb_str_buf_cat(res, tmp.buf, sizeof(float));
685 }
686 break;
687
688 case 'E': /* double precision float in VAX byte-order */
689 while (len-- > 0) {
690 DOUBLE_CONVWITH(tmp);
691 from = NEXTFROM;
692 tmp.d = RFLOAT_VALUE(rb_to_float(from));
693 HTOVD(tmp);
694 rb_str_buf_cat(res, tmp.buf, sizeof(double));
695 }
696 break;
697
698 case 'd': /* double precision float in native format */
699 case 'D': /* ditto */
700 while (len-- > 0) {
701 double d;
702
703 from = NEXTFROM;
704 d = RFLOAT_VALUE(rb_to_float(from));
705 rb_str_buf_cat(res, (char*)&d, sizeof(double));
706 }
707 break;
708
709 case 'g': /* single precision float in network byte-order */
710 while (len-- > 0) {
711 FLOAT_CONVWITH(tmp);
712 from = NEXTFROM;
713 tmp.f = VALUE_to_float(from);
714 HTONF(tmp);
715 rb_str_buf_cat(res, tmp.buf, sizeof(float));
716 }
717 break;
718
719 case 'G': /* double precision float in network byte-order */
720 while (len-- > 0) {
721 DOUBLE_CONVWITH(tmp);
722
723 from = NEXTFROM;
724 tmp.d = RFLOAT_VALUE(rb_to_float(from));
725 HTOND(tmp);
726 rb_str_buf_cat(res, tmp.buf, sizeof(double));
727 }
728 break;
729
730 case 'x': /* null byte */
731 grow:
733 str_expand_fill(res, '\0', len);
734 break;
735
736 case 'X': /* back up byte */
737 shrink:
738 plen = RSTRING_LEN(res);
739 if (plen < len)
740 rb_raise(rb_eArgError, "X outside of string");
741 rb_str_set_len(res, plen - len);
742 break;
743
744 case '@': /* null fill to absolute position */
745 len -= RSTRING_LEN(res);
746 if (len > 0) goto grow;
747 len = -len;
748 if (len > 0) goto shrink;
749 break;
750
751 case '%':
752 rb_raise(rb_eArgError, "%% is not supported");
753 break;
754
755 case 'U': /* Unicode character */
756 while (len-- > 0) {
757 SIGNED_VALUE l;
758 char buf[8];
759 int le;
760
761 from = NEXTFROM;
762 from = rb_to_int(from);
763 l = NUM2LONG(from);
764 if (l < 0) {
765 rb_raise(rb_eRangeError, "pack(U): value out of range");
766 }
767 le = rb_uv_to_utf8(buf, l);
768 rb_str_buf_cat(res, (char*)buf, le);
769 }
770 break;
771
772 case 'r': /* r for SLEB128 encoding (signed) */
773 case 'R': /* R for ULEB128 encoding (unsigned) */
774 {
775 int pack_flags = INTEGER_PACK_LITTLE_ENDIAN;
776
777 if (type == 'r') {
778 pack_flags |= INTEGER_PACK_2COMP;
779 }
780
781 while (len-- > 0) {
782 size_t numbytes, nlz_bits;
783 int sign, extra = 0;
784 char *cp;
785
786 from = NEXTFROM;
787 from = rb_to_int(from);
788 if (type == 'R' && rb_int_negative_p(from)) {
789 rb_raise(rb_eArgError, "can't encode negative numbers in ULEB128");
790 }
791
792 numbytes = rb_absint_numwords(from, 7, &nlz_bits);
793 if (numbytes == 0) {
794 numbytes = 1;
795 }
796 else if (nlz_bits == 0 && type == 'r') {
797 /* No leading zero bits, we need an extra byte for sign extension */
798 extra = 1;
799 }
800 rb_str_modify_expand(res, numbytes + extra);
801
802 rb_len_t start = RSTRING_LEN(res);
803
804 cp = RSTRING_PTR(res) + start;
805 sign = rb_integer_pack(from, cp, numbytes, 1, 1, pack_flags);
806
807 if (extra) {
808 /* Need an extra byte */
809 cp[numbytes++] = sign < 0 ? 0x7f : 0x00;
810 }
811 rb_str_set_len(res, start + numbytes);
812
813 while (1 < numbytes) {
814 *cp |= 0x80;
815 cp++;
816 numbytes--;
817 }
818 }
819 }
820 break;
821 case 'u': /* uuencoded string */
822 case 'm': /* base64 encoded string */
823 from = NEXTFROM;
824 STR_FROM(from);
825 ptr = RSTRING_PTR(from);
826 plen = RSTRING_LEN(from);
827
828 if (len == 0 && type == 'm') {
829 encodes(res, ptr, plen, type, 0);
830 ptr += plen;
831 break;
832 }
833 if (len <= 2)
834 len = 45;
835 else if (len > 63 && type == 'u')
836 len = 63;
837 else
838 len = len / 3 * 3;
839 while (plen > 0) {
840 rb_len_t todo;
841
842 if (plen > len)
843 todo = len;
844 else
845 todo = plen;
846 encodes(res, ptr, todo, type, 1);
847 plen -= todo;
848 ptr += todo;
849 }
850 break;
851
852 case 'M': /* quoted-printable encoded string */
853 from = rb_obj_as_string(NEXTFROM);
854 NOT_BUFFER(from);
855 if (len <= 1)
856 len = 72;
857 qpencode(res, from, len);
858 break;
859
860 case 'P': /* pointer to packed byte string */
861 from = THISFROM;
862 if (!NIL_P(from)) {
863 STR_FROM(from);
864 if (RSTRING_LEN(from) < len) {
865 rb_raise(rb_eArgError, "too short buffer for P(%"PRIdLEN" for %"PRIdLEN")",
866 RSTRING_LEN(from), len);
867 }
868 }
869 len = 1;
870 /* FALL THROUGH */
871 case 'p': /* pointer to string */
872 while (len-- > 0) {
873 const char *t = 0;
874 from = NEXTFROM;
875 if (!NIL_P(from)) {
876 STR_FROM(from);
877 t = RSTRING_PTR(from);
878 }
879 if (!associates) {
880 associates = rb_ary_new();
881 }
882 rb_ary_push(associates, from);
883 rb_str_buf_cat(res, (char*)&t, sizeof(char*));
884 }
885 break;
886
887 case 'w': /* BER compressed integer */
888 while (len-- > 0) {
889 VALUE buf;
890 size_t numbytes;
891 int sign;
892 char *cp;
893
894 from = NEXTFROM;
895 from = rb_to_int(from);
896 numbytes = rb_absint_numwords(from, 7, NULL);
897 if (numbytes == 0)
898 numbytes = 1;
899 buf = rb_str_new(NULL, numbytes);
900
901 sign = rb_integer_pack(from, RSTRING_PTR(buf), RSTRING_LEN(buf), 1, 1, INTEGER_PACK_BIG_ENDIAN);
902
903 if (sign < 0)
904 rb_raise(rb_eArgError, "can't compress negative numbers");
905 if (sign == 2)
906 rb_bug("buffer size problem?");
907
908 cp = RSTRING_PTR(buf);
909 while (1 < numbytes) {
910 *cp |= 0x80;
911 cp++;
912 numbytes--;
913 }
914
915 rb_str_buf_cat(res, RSTRING_PTR(buf), RSTRING_LEN(buf));
916 /* rb_str_buf_cat may trigger GC while resizing res before
917 * copying from buf. */
918 RB_GC_GUARD(buf);
919 }
920 break;
921
922 default: {
923 unknown_directive("pack", type, fmt);
924 break;
925 }
926 }
927 }
928
929 if (associates) {
930 str_associate(res, associates);
931 }
932 switch (enc_info) {
933 case 1:
935 break;
936 case 2:
937 rb_enc_set_index(res, rb_utf8_encindex());
938 break;
939 default:
940 /* do nothing, keep ASCII-8BIT */
941 break;
942 }
943 return res;
944}
945
946VALUE
947rb_ec_pack_ary(rb_execution_context_t *ec, VALUE ary, VALUE fmt, VALUE buffer)
948{
949 return pack_pack(ec, ary, fmt, buffer);
950}
951
952static const char uu_table[] =
953"`!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_";
954static const char b64_table[] =
955"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
956
957static void
958encodes(VALUE str, const char *s0, rb_len_t len, int type, int tail_lf)
959{
960 enum {buff_size = 4096, encoded_unit = 4, input_unit = 3};
961 char buff[buff_size + 1]; /* +1 for tail_lf */
962 rb_len_t i = 0;
963 const char *const trans = type == 'u' ? uu_table : b64_table;
964 char padding;
965 const unsigned char *s = (const unsigned char *)s0;
966
967 if (type == 'u') {
968 buff[i++] = (char)len + ' ';
969 padding = '`';
970 }
971 else {
972 padding = '=';
973 }
974 while (len >= input_unit) {
975 while (len >= input_unit && buff_size-i >= encoded_unit) {
976 buff[i++] = trans[077 & (*s >> 2)];
977 buff[i++] = trans[077 & (((*s << 4) & 060) | ((s[1] >> 4) & 017))];
978 buff[i++] = trans[077 & (((s[1] << 2) & 074) | ((s[2] >> 6) & 03))];
979 buff[i++] = trans[077 & s[2]];
980 s += input_unit;
981 len -= input_unit;
982 }
983 if (buff_size-i < encoded_unit) {
984 rb_str_buf_cat(str, buff, i);
985 i = 0;
986 }
987 }
988
989 if (len == 2) {
990 buff[i++] = trans[077 & (*s >> 2)];
991 buff[i++] = trans[077 & (((*s << 4) & 060) | ((s[1] >> 4) & 017))];
992 buff[i++] = trans[077 & (((s[1] << 2) & 074) | (('\0' >> 6) & 03))];
993 buff[i++] = padding;
994 }
995 else if (len == 1) {
996 buff[i++] = trans[077 & (*s >> 2)];
997 buff[i++] = trans[077 & (((*s << 4) & 060) | (('\0' >> 4) & 017))];
998 buff[i++] = padding;
999 buff[i++] = padding;
1000 }
1001 if (tail_lf) buff[i++] = '\n';
1002 rb_str_buf_cat(str, buff, i);
1003 if ((size_t)i > sizeof(buff)) rb_bug("encodes() buffer overrun");
1004}
1005
1006static const char hex_table[] = "0123456789ABCDEF";
1007
1008static void
1009qpencode(VALUE str, VALUE from, rb_len_t len)
1010{
1011 char buff[1024];
1012 rb_len_t i = 0;
1013 long n = 0, prev = EOF;
1014 unsigned char *s = (unsigned char*)RSTRING_PTR(from);
1015 unsigned char *send = s + RSTRING_LEN(from);
1016
1017 while (s < send) {
1018 if ((*s > 126) ||
1019 (*s < 32 && *s != '\n' && *s != '\t') ||
1020 (*s == '=')) {
1021 buff[i++] = '=';
1022 buff[i++] = hex_table[*s >> 4];
1023 buff[i++] = hex_table[*s & 0x0f];
1024 n += 3;
1025 prev = EOF;
1026 }
1027 else if (*s == '\n') {
1028 if (prev == ' ' || prev == '\t') {
1029 buff[i++] = '=';
1030 buff[i++] = *s;
1031 }
1032 buff[i++] = *s;
1033 n = 0;
1034 prev = *s;
1035 }
1036 else {
1037 buff[i++] = *s;
1038 n++;
1039 prev = *s;
1040 }
1041 if (n > len) {
1042 buff[i++] = '=';
1043 buff[i++] = '\n';
1044 n = 0;
1045 prev = '\n';
1046 }
1047 if (i > 1024 - 5) {
1048 rb_str_buf_cat(str, buff, i);
1049 i = 0;
1050 }
1051 s++;
1052 }
1053 if (n > 0) {
1054 buff[i++] = '=';
1055 buff[i++] = '\n';
1056 }
1057 if (i > 0) {
1058 rb_str_buf_cat(str, buff, i);
1059 }
1060}
1061
1062static inline int
1063hex2num(char c)
1064{
1065 int n;
1066 n = ruby_digit36_to_number_table[(unsigned char)c];
1067 if (16 <= n)
1068 n = -1;
1069 return n;
1070}
1071
1072#define PACK_LENGTH_ADJUST_SIZE(sz) do { \
1073 tmp_len = 0; \
1074 if (mode == UNPACK_ARRAY) { \
1075 rb_ary_modify_expand(ary, len); \
1076 } \
1077 if (len > (rb_len_t)((send-s)/(sz))) { \
1078 if (!star) { \
1079 tmp_len = len-(send-s)/(sz); \
1080 } \
1081 len = (send-s)/(sz); \
1082 } \
1083} while (0)
1084
1085#define PACK_ITEM_ADJUST() do { \
1086 if (tmp_len > 0 && mode == UNPACK_ARRAY) \
1087 rb_ary_resize(ary, RARRAY_LEN(ary)+tmp_len); \
1088} while (0)
1089
1090/* Workaround for Oracle Developer Studio (Oracle Solaris Studio)
1091 * 12.4/12.5/12.6 C compiler optimization bug
1092 * with "-xO4" optimization option.
1093 */
1094#if defined(__SUNPRO_C) && 0x5130 <= __SUNPRO_C && __SUNPRO_C <= 0x5150
1095# define AVOID_CC_BUG volatile
1096#else
1097# define AVOID_CC_BUG
1098#endif
1099
1100enum unpack_mode {
1101 UNPACK_ARRAY,
1102 UNPACK_BLOCK,
1103 UNPACK_1
1104};
1105
1106static VALUE
1107pack_unpack_internal(VALUE str, VALUE fmt, VALUE ofs, enum unpack_mode mode)
1108{
1109#define hexdigits ruby_hexdigits
1110 const char *s, *send;
1111 const char *p, *pend;
1112 VALUE ary, associates = Qfalse;
1113 rb_len_t len;
1114 AVOID_CC_BUG rb_len_t tmp_len;
1115 int signed_p, integer_size, bigendian_p;
1116 rb_len_t align_base;
1117 const char *sptr;
1118 rb_len_t slen;
1119 const char *fptr;
1120 rb_len_t flen;
1121#define UNPACK_PUSH(item) do {\
1122 VALUE item_val = (item);\
1123 if ((mode) == UNPACK_BLOCK) {\
1124 rb_yield(item_val);\
1125 /* The block may have modified str and invalidated s */ \
1126 if (RSTRING_PTR(str) != sptr || RSTRING_LEN(str) != slen) {\
1127 rb_raise(rb_eRuntimeError, "string modified");\
1128 }\
1129 /* The block may have also modified fmt and invalidated p */ \
1130 if (RSTRING_PTR(fmt) != fptr || RSTRING_LEN(fmt) != flen) {\
1131 rb_raise(rb_eRuntimeError, "format string modified");\
1132 }\
1133 }\
1134 else if ((mode) == UNPACK_ARRAY) {\
1135 rb_ary_push(ary, item_val);\
1136 }\
1137 else /* if ((mode) == UNPACK_1) { */ {\
1138 return item_val; \
1139 }\
1140 } while (0)
1141
1142 StringValue(str);
1143 StringValue(fmt);
1144 rb_len_t offset = NUM2LEN(ofs);
1146
1147 len = RSTRING_LEN(str);
1148 if (offset < 0 ? (offset += len) < 0 : offset > len) {
1149 rb_raise(rb_eArgError, "offset outside of string");
1150 }
1151
1152 s = RSTRING_PTR(str);
1153 send = s + len;
1154 sptr = s;
1155 slen = len;
1156 s += offset;
1157 align_base = offset;
1158
1159 p = RSTRING_PTR(fmt);
1160 pend = p + RSTRING_LEN(fmt);
1161 fptr = p;
1162 flen = RSTRING_LEN(fmt);
1163
1164#define UNPACK_FETCH(var, type) (memcpy((var), s, sizeof(type)), s += sizeof(type))
1165
1166 ary = mode == UNPACK_ARRAY ? rb_ary_new() : Qnil;
1167 while (p < pend) {
1168 int explicit_endian = 0;
1169 const char type = *p++;
1170 size_t align = 0;
1171 int star = 0;
1172 USING_NATINT(int natint = 0); /* native integer */
1173
1174 if (skip_blank(p, type)) continue;
1175
1176 /* Directives that do not take modifiers. */
1177 if ((type == 'x' || type == '@') && p < pend && *p == '!') {
1178 p++;
1179 p = pack_alignment_size(p, pend, fmt, &align);
1180 len = pack_align_pad(s - RSTRING_PTR(str), type == '@' ? 0 : align_base, align);
1181 if (len > send - s) {
1182 rb_raise(rb_eArgError, type == '@' ? "@ outside of string" : "x outside of string");
1183 }
1184 s += len;
1185 continue;
1186 }
1187
1188 p = pack_modifiers(p, pend, type, &natint, &explicit_endian);
1189
1190 if (p >= pend)
1191 len = 1;
1192 else if (*p == '*') {
1193 star = 1;
1194 len = send - s;
1195 p++;
1196 }
1197 else if (ISDIGIT(*p)) {
1198 errno = 0;
1199 len = STRTOUL(p, (char**)&p, 10);
1200 if (len < 0 || errno) {
1201 rb_raise(rb_eRangeError, "pack length too big");
1202 }
1203 }
1204 else {
1205 len = (type != '@');
1206 }
1207
1208 switch (type) {
1209 case '%':
1210 rb_raise(rb_eArgError, "%% is not supported");
1211 break;
1212
1213 case 'A':
1214 if (len > send - s) len = send - s;
1215 {
1216 rb_len_t end = len;
1217 const char *t = s + len - 1;
1218
1219 while (t >= s) {
1220 if (*t != ' ' && *t != '\0') break;
1221 t--; len--;
1222 }
1223 UNPACK_PUSH(rb_str_new(s, len));
1224 s += end;
1225 }
1226 break;
1227
1228 case 'Z':
1229 {
1230 const char *t = s;
1231
1232 if (len > send-s) len = send-s;
1233 while (t < s+len && *t) t++;
1234 UNPACK_PUSH(rb_str_new(s, t-s));
1235 if (t < send) t++;
1236 s = star ? t : s+len;
1237 }
1238 break;
1239
1240 case 'a':
1241 if (len > send - s) len = send - s;
1242 UNPACK_PUSH(rb_str_new(s, len));
1243 s += len;
1244 break;
1245
1246 case 'b':
1247 {
1248 VALUE bitstr;
1249 char *t;
1250 int bits;
1251 rb_len_t i;
1252
1253 if (p[-1] == '*' || len > (send - s) * 8)
1254 len = (send - s) * 8;
1255 bits = 0;
1256 bitstr = rb_usascii_str_new(0, len);
1257 t = RSTRING_PTR(bitstr);
1258 for (i=0; i<len; i++) {
1259 if (i & 7) bits >>= 1;
1260 else bits = (unsigned char)*s++;
1261 *t++ = (bits & 1) ? '1' : '0';
1262 }
1263 UNPACK_PUSH(bitstr);
1264 }
1265 break;
1266
1267 case 'B':
1268 {
1269 VALUE bitstr;
1270 char *t;
1271 int bits;
1272 rb_len_t i;
1273
1274 if (p[-1] == '*' || len > (send - s) * 8)
1275 len = (send - s) * 8;
1276 bits = 0;
1277 bitstr = rb_usascii_str_new(0, len);
1278 t = RSTRING_PTR(bitstr);
1279 for (i=0; i<len; i++) {
1280 if (i & 7) bits <<= 1;
1281 else bits = (unsigned char)*s++;
1282 *t++ = (bits & 128) ? '1' : '0';
1283 }
1284 UNPACK_PUSH(bitstr);
1285 }
1286 break;
1287
1288 case 'h':
1289 {
1290 VALUE bitstr;
1291 char *t;
1292 int bits;
1293 rb_len_t i;
1294
1295 if (p[-1] == '*' || len > (send - s) * 2)
1296 len = (send - s) * 2;
1297 bits = 0;
1298 bitstr = rb_usascii_str_new(0, len);
1299 t = RSTRING_PTR(bitstr);
1300 for (i=0; i<len; i++) {
1301 if (i & 1)
1302 bits >>= 4;
1303 else
1304 bits = (unsigned char)*s++;
1305 *t++ = hexdigits[bits & 15];
1306 }
1307 UNPACK_PUSH(bitstr);
1308 }
1309 break;
1310
1311 case 'H':
1312 {
1313 VALUE bitstr;
1314 char *t;
1315 int bits;
1316 rb_len_t i;
1317
1318 if (p[-1] == '*' || len > (send - s) * 2)
1319 len = (send - s) * 2;
1320 bits = 0;
1321 bitstr = rb_usascii_str_new(0, len);
1322 t = RSTRING_PTR(bitstr);
1323 for (i=0; i<len; i++) {
1324 if (i & 1)
1325 bits <<= 4;
1326 else
1327 bits = (unsigned char)*s++;
1328 *t++ = hexdigits[(bits >> 4) & 15];
1329 }
1330 UNPACK_PUSH(bitstr);
1331 }
1332 break;
1333
1334 case 'c':
1335 signed_p = 1;
1336 integer_size = 1;
1337 bigendian_p = BIGENDIAN_P(); /* not effective */
1338 goto unpack_integer;
1339
1340 case 'C':
1341 signed_p = 0;
1342 integer_size = 1;
1343 bigendian_p = BIGENDIAN_P(); /* not effective */
1344 goto unpack_integer;
1345
1346 case 's':
1347 signed_p = 1;
1348 integer_size = NATINT_LEN(short, 2);
1349 bigendian_p = BIGENDIAN_P();
1350 goto unpack_integer;
1351
1352 case 'S':
1353 signed_p = 0;
1354 integer_size = NATINT_LEN(short, 2);
1355 bigendian_p = BIGENDIAN_P();
1356 goto unpack_integer;
1357
1358 case 'i':
1359 signed_p = 1;
1360 integer_size = (int)sizeof(int);
1361 bigendian_p = BIGENDIAN_P();
1362 goto unpack_integer;
1363
1364 case 'I':
1365 signed_p = 0;
1366 integer_size = (int)sizeof(int);
1367 bigendian_p = BIGENDIAN_P();
1368 goto unpack_integer;
1369
1370 case 'l':
1371 signed_p = 1;
1372 integer_size = NATINT_LEN(long, 4);
1373 bigendian_p = BIGENDIAN_P();
1374 goto unpack_integer;
1375
1376 case 'L':
1377 signed_p = 0;
1378 integer_size = NATINT_LEN(long, 4);
1379 bigendian_p = BIGENDIAN_P();
1380 goto unpack_integer;
1381
1382 case 'q':
1383 signed_p = 1;
1384 integer_size = NATINT_LEN_Q;
1385 bigendian_p = BIGENDIAN_P();
1386 goto unpack_integer;
1387
1388 case 'Q':
1389 signed_p = 0;
1390 integer_size = NATINT_LEN_Q;
1391 bigendian_p = BIGENDIAN_P();
1392 goto unpack_integer;
1393
1394 case 'j':
1395 signed_p = 1;
1396 integer_size = sizeof(intptr_t);
1397 bigendian_p = BIGENDIAN_P();
1398 goto unpack_integer;
1399
1400 case 'J':
1401 signed_p = 0;
1402 integer_size = sizeof(uintptr_t);
1403 bigendian_p = BIGENDIAN_P();
1404 goto unpack_integer;
1405
1406 case 'n':
1407 signed_p = 0;
1408 integer_size = 2;
1409 bigendian_p = 1;
1410 goto unpack_integer;
1411
1412 case 'N':
1413 signed_p = 0;
1414 integer_size = 4;
1415 bigendian_p = 1;
1416 goto unpack_integer;
1417
1418 case 'v':
1419 signed_p = 0;
1420 integer_size = 2;
1421 bigendian_p = 0;
1422 goto unpack_integer;
1423
1424 case 'V':
1425 signed_p = 0;
1426 integer_size = 4;
1427 bigendian_p = 0;
1428 goto unpack_integer;
1429
1430 unpack_integer:
1431 if (explicit_endian) {
1432 bigendian_p = explicit_endian == '>';
1433 }
1434 PACK_LENGTH_ADJUST_SIZE(integer_size);
1435 while (len-- > 0) {
1436 int flags = bigendian_p ? INTEGER_PACK_BIG_ENDIAN : INTEGER_PACK_LITTLE_ENDIAN;
1437 VALUE val;
1438 if (signed_p)
1439 flags |= INTEGER_PACK_2COMP;
1440 val = rb_integer_unpack(s, integer_size, 1, 0, flags);
1441 UNPACK_PUSH(val);
1442 s += integer_size;
1443 }
1444 PACK_ITEM_ADJUST();
1445 break;
1446
1447 case 'f':
1448 case 'F':
1449 PACK_LENGTH_ADJUST_SIZE(sizeof(float));
1450 while (len-- > 0) {
1451 float tmp;
1452 UNPACK_FETCH(&tmp, float);
1453 UNPACK_PUSH(DBL2NUM((double)tmp));
1454 }
1455 PACK_ITEM_ADJUST();
1456 break;
1457
1458 case 'e':
1459 PACK_LENGTH_ADJUST_SIZE(sizeof(float));
1460 while (len-- > 0) {
1461 FLOAT_CONVWITH(tmp);
1462 UNPACK_FETCH(tmp.buf, float);
1463 VTOHF(tmp);
1464 UNPACK_PUSH(DBL2NUM(tmp.f));
1465 }
1466 PACK_ITEM_ADJUST();
1467 break;
1468
1469 case 'E':
1470 PACK_LENGTH_ADJUST_SIZE(sizeof(double));
1471 while (len-- > 0) {
1472 DOUBLE_CONVWITH(tmp);
1473 UNPACK_FETCH(tmp.buf, double);
1474 VTOHD(tmp);
1475 UNPACK_PUSH(DBL2NUM(tmp.d));
1476 }
1477 PACK_ITEM_ADJUST();
1478 break;
1479
1480 case 'D':
1481 case 'd':
1482 PACK_LENGTH_ADJUST_SIZE(sizeof(double));
1483 while (len-- > 0) {
1484 double tmp;
1485 UNPACK_FETCH(&tmp, double);
1486 UNPACK_PUSH(DBL2NUM(tmp));
1487 }
1488 PACK_ITEM_ADJUST();
1489 break;
1490
1491 case 'g':
1492 PACK_LENGTH_ADJUST_SIZE(sizeof(float));
1493 while (len-- > 0) {
1494 FLOAT_CONVWITH(tmp);
1495 UNPACK_FETCH(tmp.buf, float);
1496 NTOHF(tmp);
1497 UNPACK_PUSH(DBL2NUM(tmp.f));
1498 }
1499 PACK_ITEM_ADJUST();
1500 break;
1501
1502 case 'G':
1503 PACK_LENGTH_ADJUST_SIZE(sizeof(double));
1504 while (len-- > 0) {
1505 DOUBLE_CONVWITH(tmp);
1506 UNPACK_FETCH(tmp.buf, double);
1507 NTOHD(tmp);
1508 UNPACK_PUSH(DBL2NUM(tmp.d));
1509 }
1510 PACK_ITEM_ADJUST();
1511 break;
1512
1513 case 'U':
1514 if (len > send - s) len = send - s;
1515 while (len > 0 && s < send) {
1516 rb_len_t alen = send - s;
1517 unsigned long l;
1518
1519 l = utf8_to_uv(s, &alen);
1520 s += alen; len--;
1521 UNPACK_PUSH(ULONG2NUM(l));
1522 }
1523 break;
1524
1525 case 'u':
1526 {
1527 /* (send - s) * 3 / 4, computed without overflow */
1528 VALUE buf = rb_str_new(0, (send - s) / 4 * 3 + (send - s) % 4 * 3 / 4);
1529 char *ptr = RSTRING_PTR(buf);
1530 rb_len_t total = 0;
1531
1532 while (s < send && (unsigned char)*s > ' ' && (unsigned char)*s < 'a') {
1533 long a,b,c,d;
1534 char hunk[3];
1535
1536 len = ((unsigned char)*s++ - ' ') & 077;
1537
1538 total += len;
1539 if (total > RSTRING_LEN(buf)) {
1540 len -= total - RSTRING_LEN(buf);
1541 total = RSTRING_LEN(buf);
1542 }
1543
1544 while (len > 0) {
1545 rb_len_t mlen = len > 3 ? 3 : len;
1546
1547 if (s < send && (unsigned char)*s >= ' ' && (unsigned char)*s < 'a')
1548 a = ((unsigned char)*s++ - ' ') & 077;
1549 else
1550 a = 0;
1551 if (s < send && (unsigned char)*s >= ' ' && (unsigned char)*s < 'a')
1552 b = ((unsigned char)*s++ - ' ') & 077;
1553 else
1554 b = 0;
1555 if (s < send && (unsigned char)*s >= ' ' && (unsigned char)*s < 'a')
1556 c = ((unsigned char)*s++ - ' ') & 077;
1557 else
1558 c = 0;
1559 if (s < send && (unsigned char)*s >= ' ' && (unsigned char)*s < 'a')
1560 d = ((unsigned char)*s++ - ' ') & 077;
1561 else
1562 d = 0;
1563 hunk[0] = (char)(a << 2 | b >> 4);
1564 hunk[1] = (char)(b << 4 | c >> 2);
1565 hunk[2] = (char)(c << 6 | d);
1566 memcpy(ptr, hunk, mlen);
1567 ptr += mlen;
1568 len -= mlen;
1569 }
1570 if (s < send && (unsigned char)*s != '\r' && *s != '\n')
1571 s++; /* possible checksum byte */
1572 if (s < send && *s == '\r') s++;
1573 if (s < send && *s == '\n') s++;
1574 }
1575
1576 rb_str_set_len(buf, total);
1577 UNPACK_PUSH(buf);
1578 }
1579 break;
1580
1581 case 'm':
1582 {
1583 VALUE buf = rb_str_new(0, (send - s + 3) / 4 * 3); /* +3 is for skipping paddings */
1584 char *ptr = RSTRING_PTR(buf);
1585 int a = -1,b = -1,c = 0,d = 0;
1586 static signed char b64_xtable[256];
1587
1588 if (b64_xtable['/'] <= 0) {
1589 int i;
1590
1591 for (i = 0; i < 256; i++) {
1592 b64_xtable[i] = -1;
1593 }
1594 for (i = 0; i < 64; i++) {
1595 b64_xtable[(unsigned char)b64_table[i]] = (char)i;
1596 }
1597 }
1598 if (len == 0) {
1599 while (s < send) {
1600 a = b = c = d = -1;
1601 a = b64_xtable[(unsigned char)*s++];
1602 if (s >= send || a == -1) rb_raise(rb_eArgError, "invalid base64");
1603 b = b64_xtable[(unsigned char)*s++];
1604 if (s >= send || b == -1) rb_raise(rb_eArgError, "invalid base64");
1605 if (*s == '=') {
1606 if (s + 2 == send && *(s + 1) == '=') break;
1607 rb_raise(rb_eArgError, "invalid base64");
1608 }
1609 c = b64_xtable[(unsigned char)*s++];
1610 if (s >= send || c == -1) rb_raise(rb_eArgError, "invalid base64");
1611 if (s + 1 == send && *s == '=') break;
1612 d = b64_xtable[(unsigned char)*s++];
1613 if (d == -1) rb_raise(rb_eArgError, "invalid base64");
1614 *ptr++ = castchar(a << 2 | b >> 4);
1615 *ptr++ = castchar(b << 4 | c >> 2);
1616 *ptr++ = castchar(c << 6 | d);
1617 }
1618 if (c == -1) {
1619 *ptr++ = castchar(a << 2 | b >> 4);
1620 if (b & 0xf) rb_raise(rb_eArgError, "invalid base64");
1621 }
1622 else if (d == -1) {
1623 *ptr++ = castchar(a << 2 | b >> 4);
1624 *ptr++ = castchar(b << 4 | c >> 2);
1625 if (c & 0x3) rb_raise(rb_eArgError, "invalid base64");
1626 }
1627 }
1628 else {
1629 while (s < send) {
1630 a = b = c = d = -1;
1631 while ((a = b64_xtable[(unsigned char)*s]) == -1 && s < send) {s++;}
1632 if (s >= send) break;
1633 s++;
1634 while ((b = b64_xtable[(unsigned char)*s]) == -1 && s < send) {s++;}
1635 if (s >= send) break;
1636 s++;
1637 while ((c = b64_xtable[(unsigned char)*s]) == -1 && s < send) {if (*s == '=') break; s++;}
1638 if (*s == '=' || s >= send) break;
1639 s++;
1640 while ((d = b64_xtable[(unsigned char)*s]) == -1 && s < send) {if (*s == '=') break; s++;}
1641 if (*s == '=' || s >= send) break;
1642 s++;
1643 *ptr++ = castchar(a << 2 | b >> 4);
1644 *ptr++ = castchar(b << 4 | c >> 2);
1645 *ptr++ = castchar(c << 6 | d);
1646 a = -1;
1647 }
1648 if (a != -1 && b != -1) {
1649 if (c == -1)
1650 *ptr++ = castchar(a << 2 | b >> 4);
1651 else {
1652 *ptr++ = castchar(a << 2 | b >> 4);
1653 *ptr++ = castchar(b << 4 | c >> 2);
1654 }
1655 }
1656 }
1657 rb_str_set_len(buf, ptr - RSTRING_PTR(buf));
1658 UNPACK_PUSH(buf);
1659 }
1660 break;
1661
1662 case 'M':
1663 {
1664 VALUE buf = rb_str_new(0, send - s);
1665 char *ptr = RSTRING_PTR(buf);
1666 const char *ss = s;
1667 int csum = 0;
1668 int c1, c2;
1669
1670 while (s < send) {
1671 if (*s == '=') {
1672 if (++s == send) break;
1673 if (s+1 < send && *s == '\r' && *(s+1) == '\n')
1674 s++;
1675 if (*s != '\n') {
1676 if ((c1 = hex2num(*s)) == -1) break;
1677 if (++s == send) break;
1678 if ((c2 = hex2num(*s)) == -1) break;
1679 csum |= *ptr++ = castchar(c1 << 4 | c2);
1680 }
1681 }
1682 else {
1683 csum |= *ptr++ = *s;
1684 }
1685 s++;
1686 ss = s;
1687 }
1688 rb_str_set_len(buf, ptr - RSTRING_PTR(buf));
1689 rb_str_buf_cat(buf, ss, send-ss);
1690 csum = ISASCII(csum) ? ENC_CODERANGE_7BIT : ENC_CODERANGE_VALID;
1692 UNPACK_PUSH(buf);
1693 }
1694 break;
1695
1696 case '@':
1697 if (len > RSTRING_LEN(str))
1698 rb_raise(rb_eArgError, "@ outside of string");
1699 s = RSTRING_PTR(str) + len;
1700 break;
1701
1702 case 'X':
1703 if (len > s - RSTRING_PTR(str))
1704 rb_raise(rb_eArgError, "X outside of string");
1705 s -= len;
1706 break;
1707
1708 case 'x':
1709 if (len > send - s)
1710 rb_raise(rb_eArgError, "x outside of string");
1711 s += len;
1712 break;
1713
1714 case '^':
1715 UNPACK_PUSH(SSIZET2NUM(s - RSTRING_PTR(str)));
1716 break;
1717
1718 case 'P':
1719 if (sizeof(char *) <= (size_t)(send - s)) {
1720 VALUE tmp = Qnil;
1721 const char *t;
1722
1723 UNPACK_FETCH(&t, char *);
1724 if (t) {
1725 if (!associates) associates = str_associated(str);
1726 tmp = associated_pointer(associates, t);
1727 if (len < RSTRING_LEN(tmp)) {
1728 tmp = rb_str_new(t, len);
1729 str_associate(tmp, associates);
1730 }
1731 }
1732 UNPACK_PUSH(tmp);
1733 }
1734 break;
1735
1736 case 'p':
1737 if (len > (rb_len_t)((send - s) / sizeof(char *)))
1738 len = (send - s) / sizeof(char *);
1739 while (len-- > 0) {
1740 if ((size_t)(send - s) < sizeof(char *))
1741 break;
1742 else {
1743 VALUE tmp = Qnil;
1744 const char *t;
1745
1746 UNPACK_FETCH(&t, char *);
1747 if (t) {
1748 if (!associates) associates = str_associated(str);
1749 tmp = associated_pointer(associates, t);
1750 }
1751 UNPACK_PUSH(tmp);
1752 }
1753 }
1754 break;
1755
1756 case 'r':
1757 case 'R':
1758 {
1759 int pack_flags = INTEGER_PACK_LITTLE_ENDIAN;
1760
1761 if (type == 'r') {
1762 pack_flags |= INTEGER_PACK_2COMP;
1763 }
1764 const char *s0 = s;
1765 while (len > 0 && s < send) {
1766 if (*s & 0x80) {
1767 s++;
1768 }
1769 else {
1770 s++;
1771 UNPACK_PUSH(rb_integer_unpack(s0, s-s0, 1, 1, pack_flags));
1772 len--;
1773 s0 = s;
1774 }
1775 }
1776 /* Handle incomplete value and remaining expected values with nil (only if not using *) */
1777 if (!star) {
1778 if (s0 != s && len > 0) {
1779 UNPACK_PUSH(Qnil);
1780 len--;
1781 }
1782 while (len-- > 0) {
1783 UNPACK_PUSH(Qnil);
1784 }
1785 }
1786 }
1787 break;
1788
1789 case 'w':
1790 {
1791 const char *s0 = s;
1792 while (len > 0 && s < send) {
1793 if (*s & 0x80) {
1794 s++;
1795 }
1796 else {
1797 s++;
1798 UNPACK_PUSH(rb_integer_unpack(s0, s-s0, 1, 1, INTEGER_PACK_BIG_ENDIAN));
1799 len--;
1800 s0 = s;
1801 }
1802 }
1803 }
1804 break;
1805
1806 default:
1807 unknown_directive("unpack", type, fmt);
1808 break;
1809 }
1810 }
1811
1812 return ary;
1813}
1814
1815static VALUE
1816pack_unpack(rb_execution_context_t *ec, VALUE str, VALUE fmt, VALUE offset)
1817{
1818 enum unpack_mode mode = rb_block_given_p() ? UNPACK_BLOCK : UNPACK_ARRAY;
1819 return pack_unpack_internal(str, fmt, offset, mode);
1820}
1821
1822static VALUE
1823pack_unpack1(rb_execution_context_t *ec, VALUE str, VALUE fmt, VALUE offset)
1824{
1825 return pack_unpack_internal(str, fmt, offset, UNPACK_1);
1826}
1827
1828int
1829rb_uv_to_utf8(char buf[6], unsigned long uv)
1830{
1831 if (uv <= 0x7f) {
1832 buf[0] = (char)uv;
1833 return 1;
1834 }
1835 if (uv <= 0x7ff) {
1836 buf[0] = castchar(((uv>>6)&0xff)|0xc0);
1837 buf[1] = castchar((uv&0x3f)|0x80);
1838 return 2;
1839 }
1840 if (uv <= 0xffff) {
1841 buf[0] = castchar(((uv>>12)&0xff)|0xe0);
1842 buf[1] = castchar(((uv>>6)&0x3f)|0x80);
1843 buf[2] = castchar((uv&0x3f)|0x80);
1844 return 3;
1845 }
1846 if (uv <= 0x1fffff) {
1847 buf[0] = castchar(((uv>>18)&0xff)|0xf0);
1848 buf[1] = castchar(((uv>>12)&0x3f)|0x80);
1849 buf[2] = castchar(((uv>>6)&0x3f)|0x80);
1850 buf[3] = castchar((uv&0x3f)|0x80);
1851 return 4;
1852 }
1853 if (uv <= 0x3ffffff) {
1854 buf[0] = castchar(((uv>>24)&0xff)|0xf8);
1855 buf[1] = castchar(((uv>>18)&0x3f)|0x80);
1856 buf[2] = castchar(((uv>>12)&0x3f)|0x80);
1857 buf[3] = castchar(((uv>>6)&0x3f)|0x80);
1858 buf[4] = castchar((uv&0x3f)|0x80);
1859 return 5;
1860 }
1861 if (uv <= 0x7fffffff) {
1862 buf[0] = castchar(((uv>>30)&0xff)|0xfc);
1863 buf[1] = castchar(((uv>>24)&0x3f)|0x80);
1864 buf[2] = castchar(((uv>>18)&0x3f)|0x80);
1865 buf[3] = castchar(((uv>>12)&0x3f)|0x80);
1866 buf[4] = castchar(((uv>>6)&0x3f)|0x80);
1867 buf[5] = castchar((uv&0x3f)|0x80);
1868 return 6;
1869 }
1870 rb_raise(rb_eRangeError, "pack(U): value out of range");
1871
1873}
1874
1875static const unsigned long utf8_limits[] = {
1876 0x0, /* 1 */
1877 0x80, /* 2 */
1878 0x800, /* 3 */
1879 0x10000, /* 4 */
1880 0x200000, /* 5 */
1881 0x4000000, /* 6 */
1882 0x80000000, /* 7 */
1883};
1884
1885static unsigned long
1886utf8_to_uv(const char *p, rb_len_t *lenp)
1887{
1888 int c = *p++ & 0xff;
1889 unsigned long uv = c;
1890 rb_len_t n;
1891
1892 if (!(uv & 0x80)) {
1893 *lenp = 1;
1894 return uv;
1895 }
1896 if (!(uv & 0x40)) {
1897 *lenp = 1;
1898 rb_raise(rb_eArgError, "malformed UTF-8 character");
1899 }
1900
1901 if (!(uv & 0x20)) { n = 2; uv &= 0x1f; }
1902 else if (!(uv & 0x10)) { n = 3; uv &= 0x0f; }
1903 else if (!(uv & 0x08)) { n = 4; uv &= 0x07; }
1904 else if (!(uv & 0x04)) { n = 5; uv &= 0x03; }
1905 else if (!(uv & 0x02)) { n = 6; uv &= 0x01; }
1906 else {
1907 *lenp = 1;
1908 rb_raise(rb_eArgError, "malformed UTF-8 character");
1909 }
1910 if (n > *lenp) {
1911 rb_raise(rb_eArgError, "malformed UTF-8 character (expected %"PRIdLEN" bytes, given %"PRIdLEN" bytes)",
1912 n, *lenp);
1913 }
1914 *lenp = n--;
1915 if (n != 0) {
1916 while (n--) {
1917 c = *p++ & 0xff;
1918 if ((c & 0xc0) != 0x80) {
1919 *lenp -= n + 1;
1920 rb_raise(rb_eArgError, "malformed UTF-8 character");
1921 }
1922 else {
1923 c &= 0x3f;
1924 uv = uv << 6 | c;
1925 }
1926 }
1927 }
1928 n = *lenp - 1;
1929 if (uv < utf8_limits[n]) {
1930 rb_raise(rb_eArgError, "redundant UTF-8 sequence");
1931 }
1932 return uv;
1933}
1934
1935#include "pack.rbinc"
1936
1937void
1938Init_pack(void)
1939{
1940 id_associated = rb_make_internal_id();
1941}
#define RUBY_ALIGNOF
Wraps (or simulates) alignof.
Definition stdalign.h:28
#define STRTOUL
@old{ruby_strtoul}
Definition ctype.h:104
#define ISDIGIT
@old{rb_isdigit}
Definition ctype.h:93
#define ISALPHA
@old{rb_isalpha}
Definition ctype.h:92
#define ISPRINT
@old{rb_isprint}
Definition ctype.h:86
int rb_block_given_p(void)
Determines if the current method is given a block.
Definition eval.c:1042
#define ENC_CODERANGE_7BIT
Old name of RUBY_ENC_CODERANGE_7BIT.
Definition coderange.h:180
#define ENC_CODERANGE_VALID
Old name of RUBY_ENC_CODERANGE_VALID.
Definition coderange.h:181
#define RFLOAT_VALUE
Old name of rb_float_value.
Definition double.h:28
#define T_STRING
Old name of RUBY_T_STRING.
Definition value_type.h:78
#define ULONG2NUM
Old name of RB_ULONG2NUM.
Definition long.h:60
#define UNREACHABLE_RETURN
Old name of RBIMPL_UNREACHABLE_RETURN.
Definition assume.h:29
#define SSIZET2NUM
Old name of RB_SSIZE2NUM.
Definition size_t.h:64
#define Qnil
Old name of RUBY_Qnil.
#define Qfalse
Old name of RUBY_Qfalse.
#define NIL_P
Old name of RB_NIL_P.
#define DBL2NUM
Old name of rb_float_new.
Definition double.h:29
#define NUM2LONG
Old name of RB_NUM2LONG.
Definition long.h:51
#define NUM2LEN
Old name of RB_NUM2LEN.
Definition len_t.h:34
#define ENCODING_CODERANGE_SET(obj, encindex, cr)
Old name of RB_ENCODING_CODERANGE_SET.
Definition coderange.h:189
VALUE rb_eRangeError
RangeError exception.
Definition error.c:1461
VALUE rb_eTypeError
TypeError exception.
Definition error.c:1457
VALUE rb_eRuntimeError
RuntimeError exception.
Definition error.c:1455
VALUE rb_to_float(VALUE val)
Identical to rb_check_to_float(), except it raises on error.
Definition object.c:3783
VALUE rb_to_int(VALUE val)
Identical to rb_check_to_int(), except it raises in case of conversion mismatch.
Definition object.c:3337
#define RBIMPL_ATTR_NORETURN()
Wraps (or simulates) [[noreturn]].
Definition noreturn.h:38
int rb_utf8_encindex(void)
Identical to rb_utf8_encoding(), except it returns the encoding's index instead of the encoding itsel...
Definition encoding.c:1644
int rb_ascii8bit_encindex(void)
Identical to rb_ascii8bit_encoding(), except it returns the encoding's index instead of the encoding ...
Definition encoding.c:1632
int rb_usascii_encindex(void)
Identical to rb_usascii_encoding(), except it returns the encoding's index instead of the encoding it...
Definition encoding.c:1656
VALUE rb_ary_new(void)
Allocates a new, empty array.
VALUE rb_ary_push(VALUE ary, VALUE elem)
Special case of rb_ary_cat() that it adds only one element.
#define INTEGER_PACK_LITTLE_ENDIAN
Little endian combination.
Definition bignum.h:571
#define INTEGER_PACK_BIG_ENDIAN
Big endian combination.
Definition bignum.h:576
int rb_uv_to_utf8(char buf[6], unsigned long uv)
Encodes a Unicode codepoint into its UTF-8 representation.
Definition pack.c:1829
#define INTEGER_PACK_2COMP
Uses 2's complement representation.
Definition bignum.h:553
void rb_str_modify_expand(VALUE str, rb_len_t capa)
Identical to rb_str_modify(), except it additionally expands the capacity of the receiver.
Definition string.c:2872
#define rb_str_new(str, len)
Allocates an instance of rb_cString.
Definition string.h:1523
#define rb_str_buf_cat
Just another name of rb_str_cat.
Definition string.h:1706
#define rb_usascii_str_new(str, len)
Identical to rb_str_new, except it generates a string of "US ASCII" encoding.
Definition string.h:1557
void rb_str_set_len(VALUE str, rb_len_t len)
Overwrites the length of the string.
Definition string.c:3602
void rb_must_asciicompat(VALUE obj)
Asserts that the given string's encoding is (Ruby's definition of) ASCII compatible.
Definition string.c:2919
VALUE rb_str_buf_new(rb_len_t capa)
Allocates a "string buffer".
Definition string.c:1817
VALUE rb_obj_as_string(VALUE obj)
Try converting an object to its stringised representation using its to_s method, if any.
Definition string.c:1950
VALUE rb_ivar_set(VALUE obj, ID name, VALUE val)
Identical to rb_iv_set(), except it accepts the name as an ID instead of a C string.
Definition variable.c:2185
int len
Length of the buffer.
Definition io.h:8
const signed char ruby_digit36_to_number_table[]
Character to number mapping like 'a' -> 10, 'b' -> 11 etc.
Definition util.c:56
#define RB_GC_GUARD(v)
Prevents premature destruction of local objects.
Definition memory.h:170
VALUE type(ANYARGS)
ANYARGS-ed function type.
#define RARRAY_LEN
Just another name of rb_array_len.
Definition rarray.h:51
#define RARRAY_CONST_PTR
Just another name of rb_array_const_ptr.
Definition rarray.h:52
#define StringValue(v)
Ensures that the parameter object is a String.
Definition rstring.h:66
static char * RSTRING_END(VALUE str)
Queries the end of the contents pointer of the string.
Definition rstring.h:409
const char * rb_obj_classname(VALUE obj)
Queries the name of the class of the passed object.
Definition variable.c:532
#define errno
Ractor-aware version of errno.
Definition ruby.h:388
long rb_len_t
A signed integer type for lengths and indices of objects such as String and Array.
Definition value.h:142
#define RB_LEN_MAX
Maximum possible value that a rb_len_t can take.
Definition value.h:156
intptr_t SIGNED_VALUE
A signed integer type that has the same width with VALUE.
Definition value.h:63
uintptr_t ID
Type that represents a Ruby identifier such as a variable name.
Definition value.h:52
uintptr_t VALUE
Type that represents a Ruby object.
Definition value.h:40
static bool RB_TYPE_P(VALUE obj, enum ruby_value_type t)
Queries if the given object is of given type.
Definition value_type.h:376