Ruby 4.1.0dev (2026-08-28 revision 5eb9a6925b805a17dced976d5b741afe5086aab1)
pack.c (5eb9a6925b805a17dced976d5b741afe5086aab1)
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 NEXTSTEP and 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*,long,int,int);
123static void qpencode(VALUE,VALUE,long);
124
125static unsigned long utf8_to_uv(const char*,long*);
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, long len)
198{
199 long 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 long
287pack_align_pad(long pos, long base, size_t alignment)
288{
289 long offset, mod;
290
291 if (alignment <= 1) return 0;
292 if (alignment > LONG_MAX) rb_raise(rb_eRangeError, "alignment too big");
293 offset = pos - base;
294 mod = offset % (long)alignment;
295 if (mod < 0) mod += alignment;
296 return mod ? (long)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 long 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 long 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 if (RSTRING_END(fmt) != pend) {
375 rb_raise(rb_eRuntimeError, "format string modified");
376 }
377 const char type = *p++; /* get data type */
378 USING_NATINT(int natint = 0); /* native integer */
379
380 if (skip_blank(p, type)) continue;
381
382 /* Directives that do not take modifiers. */
383 if ((type == 'x' || type == '@') && p < pend && *p == '!') {
384 p++;
385 p = pack_alignment_size(p, pend, fmt, &align);
386 len = pack_align_pad(RSTRING_LEN(res), type == '@' ? 0 : align_base, align);
388 str_expand_fill(res, '\0', len);
389 continue;
390 }
391
392 p = pack_modifiers(p, pend, type, &natint, &explicit_endian);
393
394 if (*p == '*') { /* set data length */
395 len = strchr("@Xxu", type) ? 0
396 : strchr("PMm", type) ? 1
397 : RARRAY_LEN(ary) - idx;
398 p++;
399 }
400 else if (ISDIGIT(*p)) {
401 errno = 0;
402 len = STRTOUL(p, (char**)&p, 10);
403 if (len < 0 || errno) {
404 rb_raise(rb_eRangeError, "pack length too big");
405 }
406 }
407 else {
408 len = 1;
409 }
410
411 switch (type) {
412 case 'U':
413 /* if encoding is US-ASCII, upgrade to UTF-8 */
414 if (enc_info == 1) enc_info = 2;
415 break;
416 case 'm': case 'M': case 'u':
417 /* keep US-ASCII (do nothing) */
418 break;
419 default:
420 /* fall back to BINARY */
421 enc_info = 0;
422 break;
423 }
424 switch (type) {
425 case 'A': case 'a': case 'Z':
426 case 'B': case 'b':
427 case 'H': case 'h':
428 from = NEXTFROM;
429 if (NIL_P(from)) {
430 ptr = "";
431 plen = 0;
432 }
433 else {
434 STR_FROM(from);
435 ptr = RSTRING_PTR(from);
436 plen = RSTRING_LEN(from);
437 }
438
439 if (p[-1] == '*')
440 len = plen;
441
442 switch (type) {
443 case 'a': /* arbitrary binary string (null padded) */
444 case 'A': /* arbitrary binary string (ASCII space padded) */
445 case 'Z': /* null terminated string */
446 if (plen >= len) {
447 rb_str_buf_cat(res, ptr, len);
448 if (p[-1] == '*' && type == 'Z')
449 rb_str_buf_cat(res, "", 1);
450 }
451 else {
453 rb_str_buf_cat(res, ptr, plen);
454 str_expand_fill(res, (type == 'A' ? ' ' : '\0'), len - plen);
455 }
456 break;
457
458#define castchar(from) (char)((from) & 0xff)
459
460 case 'b': /* bit string (ascending) */
461 {
462 int byte = 0;
463 long i, j = 0;
464
465 if (len > plen) {
466 j = (len - plen + 1)/2;
467 len = plen;
468 }
469 for (i=0; i++ < len; ptr++) {
470 if (*ptr & 1)
471 byte |= 128;
472 if (i & 7)
473 byte >>= 1;
474 else {
475 char c = castchar(byte);
476 rb_str_buf_cat(res, &c, 1);
477 byte = 0;
478 }
479 }
480 if (len & 7) {
481 char c;
482 byte >>= 7 - (len & 7);
483 c = castchar(byte);
484 rb_str_buf_cat(res, &c, 1);
485 }
486 len = j;
487 goto grow;
488 }
489 break;
490
491 case 'B': /* bit string (descending) */
492 {
493 int byte = 0;
494 long i, j = 0;
495
496 if (len > plen) {
497 j = (len - plen + 1)/2;
498 len = plen;
499 }
500 for (i=0; i++ < len; ptr++) {
501 byte |= *ptr & 1;
502 if (i & 7)
503 byte <<= 1;
504 else {
505 char c = castchar(byte);
506 rb_str_buf_cat(res, &c, 1);
507 byte = 0;
508 }
509 }
510 if (len & 7) {
511 char c;
512 byte <<= 7 - (len & 7);
513 c = castchar(byte);
514 rb_str_buf_cat(res, &c, 1);
515 }
516 len = j;
517 goto grow;
518 }
519 break;
520
521 case 'h': /* hex string (low nibble first) */
522 {
523 int byte = 0;
524 long i, j = 0;
525
526 if (len > plen) {
527 j = (len + 1) / 2 - (plen + 1) / 2;
528 len = plen;
529 }
530 for (i=0; i++ < len; ptr++) {
531 if (ISALPHA(*ptr))
532 byte |= (((*ptr & 15) + 9) & 15) << 4;
533 else
534 byte |= (*ptr & 15) << 4;
535 if (i & 1)
536 byte >>= 4;
537 else {
538 char c = castchar(byte);
539 rb_str_buf_cat(res, &c, 1);
540 byte = 0;
541 }
542 }
543 if (len & 1) {
544 char c = castchar(byte);
545 rb_str_buf_cat(res, &c, 1);
546 }
547 len = j;
548 goto grow;
549 }
550 break;
551
552 case 'H': /* hex string (high nibble first) */
553 {
554 int byte = 0;
555 long i, j = 0;
556
557 if (len > plen) {
558 j = (len + 1) / 2 - (plen + 1) / 2;
559 len = plen;
560 }
561 for (i=0; i++ < len; ptr++) {
562 if (ISALPHA(*ptr))
563 byte |= ((*ptr & 15) + 9) & 15;
564 else
565 byte |= *ptr & 15;
566 if (i & 1)
567 byte <<= 4;
568 else {
569 char c = castchar(byte);
570 rb_str_buf_cat(res, &c, 1);
571 byte = 0;
572 }
573 }
574 if (len & 1) {
575 char c = castchar(byte);
576 rb_str_buf_cat(res, &c, 1);
577 }
578 len = j;
579 goto grow;
580 }
581 break;
582 }
583 break;
584
585 case 'c': /* signed char */
586 case 'C': /* unsigned char */
587 integer_size = 1;
588 bigendian_p = BIGENDIAN_P(); /* not effective */
589 goto pack_integer;
590
591 case 's': /* s for int16_t, s! for signed short */
592 case 'S': /* S for uint16_t, S! for unsigned short */
593 integer_size = NATINT_LEN(short, 2);
594 bigendian_p = BIGENDIAN_P();
595 goto pack_integer;
596
597 case 'i': /* i and i! for signed int */
598 case 'I': /* I and I! for unsigned int */
599 integer_size = (int)sizeof(int);
600 bigendian_p = BIGENDIAN_P();
601 goto pack_integer;
602
603 case 'l': /* l for int32_t, l! for signed long */
604 case 'L': /* L for uint32_t, L! for unsigned long */
605 integer_size = NATINT_LEN(long, 4);
606 bigendian_p = BIGENDIAN_P();
607 goto pack_integer;
608
609 case 'q': /* q for int64_t, q! for signed long long */
610 case 'Q': /* Q for uint64_t, Q! for unsigned long long */
611 integer_size = NATINT_LEN_Q;
612 bigendian_p = BIGENDIAN_P();
613 goto pack_integer;
614
615 case 'j': /* j for intptr_t */
616 integer_size = sizeof(intptr_t);
617 bigendian_p = BIGENDIAN_P();
618 goto pack_integer;
619
620 case 'J': /* J for uintptr_t */
621 integer_size = sizeof(uintptr_t);
622 bigendian_p = BIGENDIAN_P();
623 goto pack_integer;
624
625 case 'n': /* 16 bit (2 bytes) integer (network byte-order) */
626 integer_size = 2;
627 bigendian_p = 1;
628 goto pack_integer;
629
630 case 'N': /* 32 bit (4 bytes) integer (network byte-order) */
631 integer_size = 4;
632 bigendian_p = 1;
633 goto pack_integer;
634
635 case 'v': /* 16 bit (2 bytes) integer (VAX byte-order) */
636 integer_size = 2;
637 bigendian_p = 0;
638 goto pack_integer;
639
640 case 'V': /* 32 bit (4 bytes) integer (VAX byte-order) */
641 integer_size = 4;
642 bigendian_p = 0;
643 goto pack_integer;
644
645 pack_integer:
646 if (explicit_endian) {
647 bigendian_p = explicit_endian == '>';
648 }
649 if (integer_size > MAX_INTEGER_PACK_SIZE)
650 rb_bug("unexpected integer size for pack: %d", integer_size);
651 while (len-- > 0) {
652 char intbuf[MAX_INTEGER_PACK_SIZE];
653
654 from = NEXTFROM;
655 rb_integer_pack(from, intbuf, integer_size, 1, 0,
658 rb_str_buf_cat(res, intbuf, integer_size);
659 }
660 break;
661
662 case 'f': /* single precision float in native format */
663 case 'F': /* ditto */
664 while (len-- > 0) {
665 float f;
666
667 from = NEXTFROM;
668 f = VALUE_to_float(from);
669 rb_str_buf_cat(res, (char*)&f, sizeof(float));
670 }
671 break;
672
673 case 'e': /* single precision float in VAX byte-order */
674 while (len-- > 0) {
675 FLOAT_CONVWITH(tmp);
676
677 from = NEXTFROM;
678 tmp.f = VALUE_to_float(from);
679 HTOVF(tmp);
680 rb_str_buf_cat(res, tmp.buf, sizeof(float));
681 }
682 break;
683
684 case 'E': /* double precision float in VAX byte-order */
685 while (len-- > 0) {
686 DOUBLE_CONVWITH(tmp);
687 from = NEXTFROM;
688 tmp.d = RFLOAT_VALUE(rb_to_float(from));
689 HTOVD(tmp);
690 rb_str_buf_cat(res, tmp.buf, sizeof(double));
691 }
692 break;
693
694 case 'd': /* double precision float in native format */
695 case 'D': /* ditto */
696 while (len-- > 0) {
697 double d;
698
699 from = NEXTFROM;
700 d = RFLOAT_VALUE(rb_to_float(from));
701 rb_str_buf_cat(res, (char*)&d, sizeof(double));
702 }
703 break;
704
705 case 'g': /* single precision float in network byte-order */
706 while (len-- > 0) {
707 FLOAT_CONVWITH(tmp);
708 from = NEXTFROM;
709 tmp.f = VALUE_to_float(from);
710 HTONF(tmp);
711 rb_str_buf_cat(res, tmp.buf, sizeof(float));
712 }
713 break;
714
715 case 'G': /* double precision float in network byte-order */
716 while (len-- > 0) {
717 DOUBLE_CONVWITH(tmp);
718
719 from = NEXTFROM;
720 tmp.d = RFLOAT_VALUE(rb_to_float(from));
721 HTOND(tmp);
722 rb_str_buf_cat(res, tmp.buf, sizeof(double));
723 }
724 break;
725
726 case 'x': /* null byte */
727 grow:
729 str_expand_fill(res, '\0', len);
730 break;
731
732 case 'X': /* back up byte */
733 shrink:
734 plen = RSTRING_LEN(res);
735 if (plen < len)
736 rb_raise(rb_eArgError, "X outside of string");
737 rb_str_set_len(res, plen - len);
738 break;
739
740 case '@': /* null fill to absolute position */
741 len -= RSTRING_LEN(res);
742 if (len > 0) goto grow;
743 len = -len;
744 if (len > 0) goto shrink;
745 break;
746
747 case '%':
748 rb_raise(rb_eArgError, "%% is not supported");
749 break;
750
751 case 'U': /* Unicode character */
752 while (len-- > 0) {
753 SIGNED_VALUE l;
754 char buf[8];
755 int le;
756
757 from = NEXTFROM;
758 from = rb_to_int(from);
759 l = NUM2LONG(from);
760 if (l < 0) {
761 rb_raise(rb_eRangeError, "pack(U): value out of range");
762 }
763 le = rb_uv_to_utf8(buf, l);
764 rb_str_buf_cat(res, (char*)buf, le);
765 }
766 break;
767
768 case 'r': /* r for SLEB128 encoding (signed) */
769 case 'R': /* R for ULEB128 encoding (unsigned) */
770 {
771 int pack_flags = INTEGER_PACK_LITTLE_ENDIAN;
772
773 if (type == 'r') {
774 pack_flags |= INTEGER_PACK_2COMP;
775 }
776
777 while (len-- > 0) {
778 size_t numbytes, nlz_bits;
779 int sign, extra = 0;
780 char *cp;
781 const long start = RSTRING_LEN(res);
782
783 from = NEXTFROM;
784 from = rb_to_int(from);
785 if (type == 'R' && rb_int_negative_p(from)) {
786 rb_raise(rb_eArgError, "can't encode negative numbers in ULEB128");
787 }
788
789 numbytes = rb_absint_numwords(from, 7, &nlz_bits);
790 if (numbytes == 0) {
791 numbytes = 1;
792 }
793 else if (nlz_bits == 0 && type == 'r') {
794 /* No leading zero bits, we need an extra byte for sign extension */
795 extra = 1;
796 }
797 rb_str_modify_expand(res, numbytes + extra);
798
799 cp = RSTRING_PTR(res) + start;
800 sign = rb_integer_pack(from, cp, numbytes, 1, 1, pack_flags);
801
802 if (extra) {
803 /* Need an extra byte */
804 cp[numbytes++] = sign < 0 ? 0x7f : 0x00;
805 }
806 rb_str_set_len(res, start + numbytes);
807
808 while (1 < numbytes) {
809 *cp |= 0x80;
810 cp++;
811 numbytes--;
812 }
813 }
814 }
815 break;
816 case 'u': /* uuencoded string */
817 case 'm': /* base64 encoded string */
818 from = NEXTFROM;
819 STR_FROM(from);
820 ptr = RSTRING_PTR(from);
821 plen = RSTRING_LEN(from);
822
823 if (len == 0 && type == 'm') {
824 encodes(res, ptr, plen, type, 0);
825 ptr += plen;
826 break;
827 }
828 if (len <= 2)
829 len = 45;
830 else if (len > 63 && type == 'u')
831 len = 63;
832 else
833 len = len / 3 * 3;
834 while (plen > 0) {
835 long todo;
836
837 if (plen > len)
838 todo = len;
839 else
840 todo = plen;
841 encodes(res, ptr, todo, type, 1);
842 plen -= todo;
843 ptr += todo;
844 }
845 break;
846
847 case 'M': /* quoted-printable encoded string */
848 from = rb_obj_as_string(NEXTFROM);
849 NOT_BUFFER(from);
850 if (len <= 1)
851 len = 72;
852 qpencode(res, from, len);
853 break;
854
855 case 'P': /* pointer to packed byte string */
856 from = THISFROM;
857 if (!NIL_P(from)) {
858 STR_FROM(from);
859 if (RSTRING_LEN(from) < len) {
860 rb_raise(rb_eArgError, "too short buffer for P(%ld for %ld)",
861 RSTRING_LEN(from), len);
862 }
863 }
864 len = 1;
865 /* FALL THROUGH */
866 case 'p': /* pointer to string */
867 while (len-- > 0) {
868 const char *t = 0;
869 from = NEXTFROM;
870 if (!NIL_P(from)) {
871 STR_FROM(from);
872 t = RSTRING_PTR(from);
873 }
874 if (!associates) {
875 associates = rb_ary_new();
876 }
877 rb_ary_push(associates, from);
878 rb_str_buf_cat(res, (char*)&t, sizeof(char*));
879 }
880 break;
881
882 case 'w': /* BER compressed integer */
883 while (len-- > 0) {
884 VALUE buf;
885 size_t numbytes;
886 int sign;
887 char *cp;
888
889 from = NEXTFROM;
890 from = rb_to_int(from);
891 numbytes = rb_absint_numwords(from, 7, NULL);
892 if (numbytes == 0)
893 numbytes = 1;
894 buf = rb_str_new(NULL, numbytes);
895
896 sign = rb_integer_pack(from, RSTRING_PTR(buf), RSTRING_LEN(buf), 1, 1, INTEGER_PACK_BIG_ENDIAN);
897
898 if (sign < 0)
899 rb_raise(rb_eArgError, "can't compress negative numbers");
900 if (sign == 2)
901 rb_bug("buffer size problem?");
902
903 cp = RSTRING_PTR(buf);
904 while (1 < numbytes) {
905 *cp |= 0x80;
906 cp++;
907 numbytes--;
908 }
909
910 rb_str_buf_cat(res, RSTRING_PTR(buf), RSTRING_LEN(buf));
911 }
912 break;
913
914 default: {
915 unknown_directive("pack", type, fmt);
916 break;
917 }
918 }
919 }
920
921 if (associates) {
922 str_associate(res, associates);
923 }
924 switch (enc_info) {
925 case 1:
926 ENCODING_CODERANGE_SET(res, rb_usascii_encindex(), ENC_CODERANGE_7BIT);
927 break;
928 case 2:
929 rb_enc_set_index(res, rb_utf8_encindex());
930 break;
931 default:
932 /* do nothing, keep ASCII-8BIT */
933 break;
934 }
935 return res;
936}
937
938VALUE
939rb_ec_pack_ary(rb_execution_context_t *ec, VALUE ary, VALUE fmt, VALUE buffer)
940{
941 return pack_pack(ec, ary, fmt, buffer);
942}
943
944static const char uu_table[] =
945"`!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_";
946static const char b64_table[] =
947"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
948
949static void
950encodes(VALUE str, const char *s0, long len, int type, int tail_lf)
951{
952 enum {buff_size = 4096, encoded_unit = 4, input_unit = 3};
953 char buff[buff_size + 1]; /* +1 for tail_lf */
954 long i = 0;
955 const char *const trans = type == 'u' ? uu_table : b64_table;
956 char padding;
957 const unsigned char *s = (const unsigned char *)s0;
958
959 if (type == 'u') {
960 buff[i++] = (char)len + ' ';
961 padding = '`';
962 }
963 else {
964 padding = '=';
965 }
966 while (len >= input_unit) {
967 while (len >= input_unit && buff_size-i >= encoded_unit) {
968 buff[i++] = trans[077 & (*s >> 2)];
969 buff[i++] = trans[077 & (((*s << 4) & 060) | ((s[1] >> 4) & 017))];
970 buff[i++] = trans[077 & (((s[1] << 2) & 074) | ((s[2] >> 6) & 03))];
971 buff[i++] = trans[077 & s[2]];
972 s += input_unit;
973 len -= input_unit;
974 }
975 if (buff_size-i < encoded_unit) {
976 rb_str_buf_cat(str, buff, i);
977 i = 0;
978 }
979 }
980
981 if (len == 2) {
982 buff[i++] = trans[077 & (*s >> 2)];
983 buff[i++] = trans[077 & (((*s << 4) & 060) | ((s[1] >> 4) & 017))];
984 buff[i++] = trans[077 & (((s[1] << 2) & 074) | (('\0' >> 6) & 03))];
985 buff[i++] = padding;
986 }
987 else if (len == 1) {
988 buff[i++] = trans[077 & (*s >> 2)];
989 buff[i++] = trans[077 & (((*s << 4) & 060) | (('\0' >> 4) & 017))];
990 buff[i++] = padding;
991 buff[i++] = padding;
992 }
993 if (tail_lf) buff[i++] = '\n';
994 rb_str_buf_cat(str, buff, i);
995 if ((size_t)i > sizeof(buff)) rb_bug("encodes() buffer overrun");
996}
997
998static const char hex_table[] = "0123456789ABCDEF";
999
1000static void
1001qpencode(VALUE str, VALUE from, long len)
1002{
1003 char buff[1024];
1004 long i = 0, n = 0, prev = EOF;
1005 unsigned char *s = (unsigned char*)RSTRING_PTR(from);
1006 unsigned char *send = s + RSTRING_LEN(from);
1007
1008 while (s < send) {
1009 if ((*s > 126) ||
1010 (*s < 32 && *s != '\n' && *s != '\t') ||
1011 (*s == '=')) {
1012 buff[i++] = '=';
1013 buff[i++] = hex_table[*s >> 4];
1014 buff[i++] = hex_table[*s & 0x0f];
1015 n += 3;
1016 prev = EOF;
1017 }
1018 else if (*s == '\n') {
1019 if (prev == ' ' || prev == '\t') {
1020 buff[i++] = '=';
1021 buff[i++] = *s;
1022 }
1023 buff[i++] = *s;
1024 n = 0;
1025 prev = *s;
1026 }
1027 else {
1028 buff[i++] = *s;
1029 n++;
1030 prev = *s;
1031 }
1032 if (n > len) {
1033 buff[i++] = '=';
1034 buff[i++] = '\n';
1035 n = 0;
1036 prev = '\n';
1037 }
1038 if (i > 1024 - 5) {
1039 rb_str_buf_cat(str, buff, i);
1040 i = 0;
1041 }
1042 s++;
1043 }
1044 if (n > 0) {
1045 buff[i++] = '=';
1046 buff[i++] = '\n';
1047 }
1048 if (i > 0) {
1049 rb_str_buf_cat(str, buff, i);
1050 }
1051}
1052
1053static inline int
1054hex2num(char c)
1055{
1056 int n;
1057 n = ruby_digit36_to_number_table[(unsigned char)c];
1058 if (16 <= n)
1059 n = -1;
1060 return n;
1061}
1062
1063#define PACK_LENGTH_ADJUST_SIZE(sz) do { \
1064 tmp_len = 0; \
1065 if (mode == UNPACK_ARRAY) { \
1066 rb_ary_modify_expand(ary, len); \
1067 } \
1068 if (len > (long)((send-s)/(sz))) { \
1069 if (!star) { \
1070 tmp_len = len-(send-s)/(sz); \
1071 } \
1072 len = (send-s)/(sz); \
1073 } \
1074} while (0)
1075
1076#define PACK_ITEM_ADJUST() do { \
1077 if (tmp_len > 0 && mode == UNPACK_ARRAY) \
1078 rb_ary_resize(ary, RARRAY_LEN(ary)+tmp_len); \
1079} while (0)
1080
1081/* Workaround for Oracle Developer Studio (Oracle Solaris Studio)
1082 * 12.4/12.5/12.6 C compiler optimization bug
1083 * with "-xO4" optimization option.
1084 */
1085#if defined(__SUNPRO_C) && 0x5130 <= __SUNPRO_C && __SUNPRO_C <= 0x5150
1086# define AVOID_CC_BUG volatile
1087#else
1088# define AVOID_CC_BUG
1089#endif
1090
1091enum unpack_mode {
1092 UNPACK_ARRAY,
1093 UNPACK_BLOCK,
1094 UNPACK_1
1095};
1096
1097static VALUE
1098pack_unpack_internal(VALUE str, VALUE fmt, VALUE ofs, enum unpack_mode mode)
1099{
1100#define hexdigits ruby_hexdigits
1101 const char *s, *send;
1102 const char *p, *pend;
1103 VALUE ary, associates = Qfalse;
1104 long len;
1105 AVOID_CC_BUG long tmp_len;
1106 int signed_p, integer_size, bigendian_p;
1107 long align_base;
1108#define UNPACK_PUSH(item) do {\
1109 VALUE item_val = (item);\
1110 if ((mode) == UNPACK_BLOCK) {\
1111 rb_yield(item_val);\
1112 }\
1113 else if ((mode) == UNPACK_ARRAY) {\
1114 rb_ary_push(ary, item_val);\
1115 }\
1116 else /* if ((mode) == UNPACK_1) { */ {\
1117 return item_val; \
1118 }\
1119 } while (0)
1120
1121 StringValue(str);
1122 StringValue(fmt);
1123 long offset = NUM2LONG(ofs);
1125
1126 len = RSTRING_LEN(str);
1127 if (offset < 0 ? (offset += len) < 0 : offset > len) {
1128 rb_raise(rb_eArgError, "offset outside of string");
1129 }
1130
1131 s = RSTRING_PTR(str);
1132 send = s + len;
1133 s += offset;
1134 align_base = offset;
1135
1136 p = RSTRING_PTR(fmt);
1137 pend = p + RSTRING_LEN(fmt);
1138
1139#define UNPACK_FETCH(var, type) (memcpy((var), s, sizeof(type)), s += sizeof(type))
1140
1141 ary = mode == UNPACK_ARRAY ? rb_ary_new() : Qnil;
1142 while (p < pend) {
1143 int explicit_endian = 0;
1144 const char type = *p++;
1145 size_t align = 0;
1146 int star = 0;
1147 USING_NATINT(int natint = 0); /* native integer */
1148
1149 if (skip_blank(p, type)) continue;
1150
1151 /* Directives that do not take modifiers. */
1152 if ((type == 'x' || type == '@') && p < pend && *p == '!') {
1153 p++;
1154 p = pack_alignment_size(p, pend, fmt, &align);
1155 len = pack_align_pad(s - RSTRING_PTR(str), type == '@' ? 0 : align_base, align);
1156 if (len > send - s) {
1157 rb_raise(rb_eArgError, type == '@' ? "@ outside of string" : "x outside of string");
1158 }
1159 s += len;
1160 continue;
1161 }
1162
1163 p = pack_modifiers(p, pend, type, &natint, &explicit_endian);
1164
1165 if (p >= pend)
1166 len = 1;
1167 else if (*p == '*') {
1168 star = 1;
1169 len = send - s;
1170 p++;
1171 }
1172 else if (ISDIGIT(*p)) {
1173 errno = 0;
1174 len = STRTOUL(p, (char**)&p, 10);
1175 if (len < 0 || errno) {
1176 rb_raise(rb_eRangeError, "pack length too big");
1177 }
1178 }
1179 else {
1180 len = (type != '@');
1181 }
1182
1183 switch (type) {
1184 case '%':
1185 rb_raise(rb_eArgError, "%% is not supported");
1186 break;
1187
1188 case 'A':
1189 if (len > send - s) len = send - s;
1190 {
1191 long end = len;
1192 const char *t = s + len - 1;
1193
1194 while (t >= s) {
1195 if (*t != ' ' && *t != '\0') break;
1196 t--; len--;
1197 }
1198 UNPACK_PUSH(rb_str_new(s, len));
1199 s += end;
1200 }
1201 break;
1202
1203 case 'Z':
1204 {
1205 const char *t = s;
1206
1207 if (len > send-s) len = send-s;
1208 while (t < s+len && *t) t++;
1209 UNPACK_PUSH(rb_str_new(s, t-s));
1210 if (t < send) t++;
1211 s = star ? t : s+len;
1212 }
1213 break;
1214
1215 case 'a':
1216 if (len > send - s) len = send - s;
1217 UNPACK_PUSH(rb_str_new(s, len));
1218 s += len;
1219 break;
1220
1221 case 'b':
1222 {
1223 VALUE bitstr;
1224 char *t;
1225 int bits;
1226 long i;
1227
1228 if (p[-1] == '*' || len > (send - s) * 8)
1229 len = (send - s) * 8;
1230 bits = 0;
1231 bitstr = rb_usascii_str_new(0, len);
1232 t = RSTRING_PTR(bitstr);
1233 for (i=0; i<len; i++) {
1234 if (i & 7) bits >>= 1;
1235 else bits = (unsigned char)*s++;
1236 *t++ = (bits & 1) ? '1' : '0';
1237 }
1238 UNPACK_PUSH(bitstr);
1239 }
1240 break;
1241
1242 case 'B':
1243 {
1244 VALUE bitstr;
1245 char *t;
1246 int bits;
1247 long i;
1248
1249 if (p[-1] == '*' || len > (send - s) * 8)
1250 len = (send - s) * 8;
1251 bits = 0;
1252 bitstr = rb_usascii_str_new(0, len);
1253 t = RSTRING_PTR(bitstr);
1254 for (i=0; i<len; i++) {
1255 if (i & 7) bits <<= 1;
1256 else bits = (unsigned char)*s++;
1257 *t++ = (bits & 128) ? '1' : '0';
1258 }
1259 UNPACK_PUSH(bitstr);
1260 }
1261 break;
1262
1263 case 'h':
1264 {
1265 VALUE bitstr;
1266 char *t;
1267 int bits;
1268 long i;
1269
1270 if (p[-1] == '*' || len > (send - s) * 2)
1271 len = (send - s) * 2;
1272 bits = 0;
1273 bitstr = rb_usascii_str_new(0, len);
1274 t = RSTRING_PTR(bitstr);
1275 for (i=0; i<len; i++) {
1276 if (i & 1)
1277 bits >>= 4;
1278 else
1279 bits = (unsigned char)*s++;
1280 *t++ = hexdigits[bits & 15];
1281 }
1282 UNPACK_PUSH(bitstr);
1283 }
1284 break;
1285
1286 case 'H':
1287 {
1288 VALUE bitstr;
1289 char *t;
1290 int bits;
1291 long i;
1292
1293 if (p[-1] == '*' || len > (send - s) * 2)
1294 len = (send - s) * 2;
1295 bits = 0;
1296 bitstr = rb_usascii_str_new(0, len);
1297 t = RSTRING_PTR(bitstr);
1298 for (i=0; i<len; i++) {
1299 if (i & 1)
1300 bits <<= 4;
1301 else
1302 bits = (unsigned char)*s++;
1303 *t++ = hexdigits[(bits >> 4) & 15];
1304 }
1305 UNPACK_PUSH(bitstr);
1306 }
1307 break;
1308
1309 case 'c':
1310 signed_p = 1;
1311 integer_size = 1;
1312 bigendian_p = BIGENDIAN_P(); /* not effective */
1313 goto unpack_integer;
1314
1315 case 'C':
1316 signed_p = 0;
1317 integer_size = 1;
1318 bigendian_p = BIGENDIAN_P(); /* not effective */
1319 goto unpack_integer;
1320
1321 case 's':
1322 signed_p = 1;
1323 integer_size = NATINT_LEN(short, 2);
1324 bigendian_p = BIGENDIAN_P();
1325 goto unpack_integer;
1326
1327 case 'S':
1328 signed_p = 0;
1329 integer_size = NATINT_LEN(short, 2);
1330 bigendian_p = BIGENDIAN_P();
1331 goto unpack_integer;
1332
1333 case 'i':
1334 signed_p = 1;
1335 integer_size = (int)sizeof(int);
1336 bigendian_p = BIGENDIAN_P();
1337 goto unpack_integer;
1338
1339 case 'I':
1340 signed_p = 0;
1341 integer_size = (int)sizeof(int);
1342 bigendian_p = BIGENDIAN_P();
1343 goto unpack_integer;
1344
1345 case 'l':
1346 signed_p = 1;
1347 integer_size = NATINT_LEN(long, 4);
1348 bigendian_p = BIGENDIAN_P();
1349 goto unpack_integer;
1350
1351 case 'L':
1352 signed_p = 0;
1353 integer_size = NATINT_LEN(long, 4);
1354 bigendian_p = BIGENDIAN_P();
1355 goto unpack_integer;
1356
1357 case 'q':
1358 signed_p = 1;
1359 integer_size = NATINT_LEN_Q;
1360 bigendian_p = BIGENDIAN_P();
1361 goto unpack_integer;
1362
1363 case 'Q':
1364 signed_p = 0;
1365 integer_size = NATINT_LEN_Q;
1366 bigendian_p = BIGENDIAN_P();
1367 goto unpack_integer;
1368
1369 case 'j':
1370 signed_p = 1;
1371 integer_size = sizeof(intptr_t);
1372 bigendian_p = BIGENDIAN_P();
1373 goto unpack_integer;
1374
1375 case 'J':
1376 signed_p = 0;
1377 integer_size = sizeof(uintptr_t);
1378 bigendian_p = BIGENDIAN_P();
1379 goto unpack_integer;
1380
1381 case 'n':
1382 signed_p = 0;
1383 integer_size = 2;
1384 bigendian_p = 1;
1385 goto unpack_integer;
1386
1387 case 'N':
1388 signed_p = 0;
1389 integer_size = 4;
1390 bigendian_p = 1;
1391 goto unpack_integer;
1392
1393 case 'v':
1394 signed_p = 0;
1395 integer_size = 2;
1396 bigendian_p = 0;
1397 goto unpack_integer;
1398
1399 case 'V':
1400 signed_p = 0;
1401 integer_size = 4;
1402 bigendian_p = 0;
1403 goto unpack_integer;
1404
1405 unpack_integer:
1406 if (explicit_endian) {
1407 bigendian_p = explicit_endian == '>';
1408 }
1409 PACK_LENGTH_ADJUST_SIZE(integer_size);
1410 while (len-- > 0) {
1411 int flags = bigendian_p ? INTEGER_PACK_BIG_ENDIAN : INTEGER_PACK_LITTLE_ENDIAN;
1412 VALUE val;
1413 if (signed_p)
1414 flags |= INTEGER_PACK_2COMP;
1415 val = rb_integer_unpack(s, integer_size, 1, 0, flags);
1416 UNPACK_PUSH(val);
1417 s += integer_size;
1418 }
1419 PACK_ITEM_ADJUST();
1420 break;
1421
1422 case 'f':
1423 case 'F':
1424 PACK_LENGTH_ADJUST_SIZE(sizeof(float));
1425 while (len-- > 0) {
1426 float tmp;
1427 UNPACK_FETCH(&tmp, float);
1428 UNPACK_PUSH(DBL2NUM((double)tmp));
1429 }
1430 PACK_ITEM_ADJUST();
1431 break;
1432
1433 case 'e':
1434 PACK_LENGTH_ADJUST_SIZE(sizeof(float));
1435 while (len-- > 0) {
1436 FLOAT_CONVWITH(tmp);
1437 UNPACK_FETCH(tmp.buf, float);
1438 VTOHF(tmp);
1439 UNPACK_PUSH(DBL2NUM(tmp.f));
1440 }
1441 PACK_ITEM_ADJUST();
1442 break;
1443
1444 case 'E':
1445 PACK_LENGTH_ADJUST_SIZE(sizeof(double));
1446 while (len-- > 0) {
1447 DOUBLE_CONVWITH(tmp);
1448 UNPACK_FETCH(tmp.buf, double);
1449 VTOHD(tmp);
1450 UNPACK_PUSH(DBL2NUM(tmp.d));
1451 }
1452 PACK_ITEM_ADJUST();
1453 break;
1454
1455 case 'D':
1456 case 'd':
1457 PACK_LENGTH_ADJUST_SIZE(sizeof(double));
1458 while (len-- > 0) {
1459 double tmp;
1460 UNPACK_FETCH(&tmp, double);
1461 UNPACK_PUSH(DBL2NUM(tmp));
1462 }
1463 PACK_ITEM_ADJUST();
1464 break;
1465
1466 case 'g':
1467 PACK_LENGTH_ADJUST_SIZE(sizeof(float));
1468 while (len-- > 0) {
1469 FLOAT_CONVWITH(tmp);
1470 UNPACK_FETCH(tmp.buf, float);
1471 NTOHF(tmp);
1472 UNPACK_PUSH(DBL2NUM(tmp.f));
1473 }
1474 PACK_ITEM_ADJUST();
1475 break;
1476
1477 case 'G':
1478 PACK_LENGTH_ADJUST_SIZE(sizeof(double));
1479 while (len-- > 0) {
1480 DOUBLE_CONVWITH(tmp);
1481 UNPACK_FETCH(tmp.buf, double);
1482 NTOHD(tmp);
1483 UNPACK_PUSH(DBL2NUM(tmp.d));
1484 }
1485 PACK_ITEM_ADJUST();
1486 break;
1487
1488 case 'U':
1489 if (len > send - s) len = send - s;
1490 while (len > 0 && s < send) {
1491 long alen = send - s;
1492 unsigned long l;
1493
1494 l = utf8_to_uv(s, &alen);
1495 s += alen; len--;
1496 UNPACK_PUSH(ULONG2NUM(l));
1497 }
1498 break;
1499
1500 case 'u':
1501 {
1502 VALUE buf = rb_str_new(0, (send - s)*3/4);
1503 char *ptr = RSTRING_PTR(buf);
1504 long total = 0;
1505
1506 while (s < send && (unsigned char)*s > ' ' && (unsigned char)*s < 'a') {
1507 long a,b,c,d;
1508 char hunk[3];
1509
1510 len = ((unsigned char)*s++ - ' ') & 077;
1511
1512 total += len;
1513 if (total > RSTRING_LEN(buf)) {
1514 len -= total - RSTRING_LEN(buf);
1515 total = RSTRING_LEN(buf);
1516 }
1517
1518 while (len > 0) {
1519 long mlen = len > 3 ? 3 : len;
1520
1521 if (s < send && (unsigned char)*s >= ' ' && (unsigned char)*s < 'a')
1522 a = ((unsigned char)*s++ - ' ') & 077;
1523 else
1524 a = 0;
1525 if (s < send && (unsigned char)*s >= ' ' && (unsigned char)*s < 'a')
1526 b = ((unsigned char)*s++ - ' ') & 077;
1527 else
1528 b = 0;
1529 if (s < send && (unsigned char)*s >= ' ' && (unsigned char)*s < 'a')
1530 c = ((unsigned char)*s++ - ' ') & 077;
1531 else
1532 c = 0;
1533 if (s < send && (unsigned char)*s >= ' ' && (unsigned char)*s < 'a')
1534 d = ((unsigned char)*s++ - ' ') & 077;
1535 else
1536 d = 0;
1537 hunk[0] = (char)(a << 2 | b >> 4);
1538 hunk[1] = (char)(b << 4 | c >> 2);
1539 hunk[2] = (char)(c << 6 | d);
1540 memcpy(ptr, hunk, mlen);
1541 ptr += mlen;
1542 len -= mlen;
1543 }
1544 if (s < send && (unsigned char)*s != '\r' && *s != '\n')
1545 s++; /* possible checksum byte */
1546 if (s < send && *s == '\r') s++;
1547 if (s < send && *s == '\n') s++;
1548 }
1549
1550 rb_str_set_len(buf, total);
1551 UNPACK_PUSH(buf);
1552 }
1553 break;
1554
1555 case 'm':
1556 {
1557 VALUE buf = rb_str_new(0, (send - s + 3)*3/4); /* +3 is for skipping paddings */
1558 char *ptr = RSTRING_PTR(buf);
1559 int a = -1,b = -1,c = 0,d = 0;
1560 static signed char b64_xtable[256];
1561
1562 if (b64_xtable['/'] <= 0) {
1563 int i;
1564
1565 for (i = 0; i < 256; i++) {
1566 b64_xtable[i] = -1;
1567 }
1568 for (i = 0; i < 64; i++) {
1569 b64_xtable[(unsigned char)b64_table[i]] = (char)i;
1570 }
1571 }
1572 if (len == 0) {
1573 while (s < send) {
1574 a = b = c = d = -1;
1575 a = b64_xtable[(unsigned char)*s++];
1576 if (s >= send || a == -1) rb_raise(rb_eArgError, "invalid base64");
1577 b = b64_xtable[(unsigned char)*s++];
1578 if (s >= send || b == -1) rb_raise(rb_eArgError, "invalid base64");
1579 if (*s == '=') {
1580 if (s + 2 == send && *(s + 1) == '=') break;
1581 rb_raise(rb_eArgError, "invalid base64");
1582 }
1583 c = b64_xtable[(unsigned char)*s++];
1584 if (s >= send || c == -1) rb_raise(rb_eArgError, "invalid base64");
1585 if (s + 1 == send && *s == '=') break;
1586 d = b64_xtable[(unsigned char)*s++];
1587 if (d == -1) rb_raise(rb_eArgError, "invalid base64");
1588 *ptr++ = castchar(a << 2 | b >> 4);
1589 *ptr++ = castchar(b << 4 | c >> 2);
1590 *ptr++ = castchar(c << 6 | d);
1591 }
1592 if (c == -1) {
1593 *ptr++ = castchar(a << 2 | b >> 4);
1594 if (b & 0xf) rb_raise(rb_eArgError, "invalid base64");
1595 }
1596 else if (d == -1) {
1597 *ptr++ = castchar(a << 2 | b >> 4);
1598 *ptr++ = castchar(b << 4 | c >> 2);
1599 if (c & 0x3) rb_raise(rb_eArgError, "invalid base64");
1600 }
1601 }
1602 else {
1603 while (s < send) {
1604 a = b = c = d = -1;
1605 while ((a = b64_xtable[(unsigned char)*s]) == -1 && s < send) {s++;}
1606 if (s >= send) break;
1607 s++;
1608 while ((b = b64_xtable[(unsigned char)*s]) == -1 && s < send) {s++;}
1609 if (s >= send) break;
1610 s++;
1611 while ((c = b64_xtable[(unsigned char)*s]) == -1 && s < send) {if (*s == '=') break; s++;}
1612 if (*s == '=' || s >= send) break;
1613 s++;
1614 while ((d = b64_xtable[(unsigned char)*s]) == -1 && s < send) {if (*s == '=') break; s++;}
1615 if (*s == '=' || s >= send) break;
1616 s++;
1617 *ptr++ = castchar(a << 2 | b >> 4);
1618 *ptr++ = castchar(b << 4 | c >> 2);
1619 *ptr++ = castchar(c << 6 | d);
1620 a = -1;
1621 }
1622 if (a != -1 && b != -1) {
1623 if (c == -1)
1624 *ptr++ = castchar(a << 2 | b >> 4);
1625 else {
1626 *ptr++ = castchar(a << 2 | b >> 4);
1627 *ptr++ = castchar(b << 4 | c >> 2);
1628 }
1629 }
1630 }
1631 rb_str_set_len(buf, ptr - RSTRING_PTR(buf));
1632 UNPACK_PUSH(buf);
1633 }
1634 break;
1635
1636 case 'M':
1637 {
1638 VALUE buf = rb_str_new(0, send - s);
1639 char *ptr = RSTRING_PTR(buf);
1640 const char *ss = s;
1641 int csum = 0;
1642 int c1, c2;
1643
1644 while (s < send) {
1645 if (*s == '=') {
1646 if (++s == send) break;
1647 if (s+1 < send && *s == '\r' && *(s+1) == '\n')
1648 s++;
1649 if (*s != '\n') {
1650 if ((c1 = hex2num(*s)) == -1) break;
1651 if (++s == send) break;
1652 if ((c2 = hex2num(*s)) == -1) break;
1653 csum |= *ptr++ = castchar(c1 << 4 | c2);
1654 }
1655 }
1656 else {
1657 csum |= *ptr++ = *s;
1658 }
1659 s++;
1660 ss = s;
1661 }
1662 rb_str_set_len(buf, ptr - RSTRING_PTR(buf));
1663 rb_str_buf_cat(buf, ss, send-ss);
1665 ENCODING_CODERANGE_SET(buf, rb_ascii8bit_encindex(), csum);
1666 UNPACK_PUSH(buf);
1667 }
1668 break;
1669
1670 case '@':
1671 if (len > RSTRING_LEN(str))
1672 rb_raise(rb_eArgError, "@ outside of string");
1673 s = RSTRING_PTR(str) + len;
1674 break;
1675
1676 case 'X':
1677 if (len > s - RSTRING_PTR(str))
1678 rb_raise(rb_eArgError, "X outside of string");
1679 s -= len;
1680 break;
1681
1682 case 'x':
1683 if (len > send - s)
1684 rb_raise(rb_eArgError, "x outside of string");
1685 s += len;
1686 break;
1687
1688 case '^':
1689 UNPACK_PUSH(SSIZET2NUM(s - RSTRING_PTR(str)));
1690 break;
1691
1692 case 'P':
1693 if (sizeof(char *) <= (size_t)(send - s)) {
1694 VALUE tmp = Qnil;
1695 const char *t;
1696
1697 UNPACK_FETCH(&t, char *);
1698 if (t) {
1699 if (!associates) associates = str_associated(str);
1700 tmp = associated_pointer(associates, t);
1701 if (len < RSTRING_LEN(tmp)) {
1702 tmp = rb_str_new(t, len);
1703 str_associate(tmp, associates);
1704 }
1705 }
1706 UNPACK_PUSH(tmp);
1707 }
1708 break;
1709
1710 case 'p':
1711 if (len > (long)((send - s) / sizeof(char *)))
1712 len = (send - s) / sizeof(char *);
1713 while (len-- > 0) {
1714 if ((size_t)(send - s) < sizeof(char *))
1715 break;
1716 else {
1717 VALUE tmp = Qnil;
1718 const char *t;
1719
1720 UNPACK_FETCH(&t, char *);
1721 if (t) {
1722 if (!associates) associates = str_associated(str);
1723 tmp = associated_pointer(associates, t);
1724 }
1725 UNPACK_PUSH(tmp);
1726 }
1727 }
1728 break;
1729
1730 case 'r':
1731 case 'R':
1732 {
1733 int pack_flags = INTEGER_PACK_LITTLE_ENDIAN;
1734
1735 if (type == 'r') {
1736 pack_flags |= INTEGER_PACK_2COMP;
1737 }
1738 const char *s0 = s;
1739 while (len > 0 && s < send) {
1740 if (*s & 0x80) {
1741 s++;
1742 }
1743 else {
1744 s++;
1745 UNPACK_PUSH(rb_integer_unpack(s0, s-s0, 1, 1, pack_flags));
1746 len--;
1747 s0 = s;
1748 }
1749 }
1750 /* Handle incomplete value and remaining expected values with nil (only if not using *) */
1751 if (!star) {
1752 if (s0 != s && len > 0) {
1753 UNPACK_PUSH(Qnil);
1754 len--;
1755 }
1756 while (len-- > 0) {
1757 UNPACK_PUSH(Qnil);
1758 }
1759 }
1760 }
1761 break;
1762
1763 case 'w':
1764 {
1765 const char *s0 = s;
1766 while (len > 0 && s < send) {
1767 if (*s & 0x80) {
1768 s++;
1769 }
1770 else {
1771 s++;
1772 UNPACK_PUSH(rb_integer_unpack(s0, s-s0, 1, 1, INTEGER_PACK_BIG_ENDIAN));
1773 len--;
1774 s0 = s;
1775 }
1776 }
1777 }
1778 break;
1779
1780 default:
1781 unknown_directive("unpack", type, fmt);
1782 break;
1783 }
1784 }
1785
1786 return ary;
1787}
1788
1789static VALUE
1790pack_unpack(rb_execution_context_t *ec, VALUE str, VALUE fmt, VALUE offset)
1791{
1792 enum unpack_mode mode = rb_block_given_p() ? UNPACK_BLOCK : UNPACK_ARRAY;
1793 return pack_unpack_internal(str, fmt, offset, mode);
1794}
1795
1796static VALUE
1797pack_unpack1(rb_execution_context_t *ec, VALUE str, VALUE fmt, VALUE offset)
1798{
1799 return pack_unpack_internal(str, fmt, offset, UNPACK_1);
1800}
1801
1802int
1803rb_uv_to_utf8(char buf[6], unsigned long uv)
1804{
1805 if (uv <= 0x7f) {
1806 buf[0] = (char)uv;
1807 return 1;
1808 }
1809 if (uv <= 0x7ff) {
1810 buf[0] = castchar(((uv>>6)&0xff)|0xc0);
1811 buf[1] = castchar((uv&0x3f)|0x80);
1812 return 2;
1813 }
1814 if (uv <= 0xffff) {
1815 buf[0] = castchar(((uv>>12)&0xff)|0xe0);
1816 buf[1] = castchar(((uv>>6)&0x3f)|0x80);
1817 buf[2] = castchar((uv&0x3f)|0x80);
1818 return 3;
1819 }
1820 if (uv <= 0x1fffff) {
1821 buf[0] = castchar(((uv>>18)&0xff)|0xf0);
1822 buf[1] = castchar(((uv>>12)&0x3f)|0x80);
1823 buf[2] = castchar(((uv>>6)&0x3f)|0x80);
1824 buf[3] = castchar((uv&0x3f)|0x80);
1825 return 4;
1826 }
1827 if (uv <= 0x3ffffff) {
1828 buf[0] = castchar(((uv>>24)&0xff)|0xf8);
1829 buf[1] = castchar(((uv>>18)&0x3f)|0x80);
1830 buf[2] = castchar(((uv>>12)&0x3f)|0x80);
1831 buf[3] = castchar(((uv>>6)&0x3f)|0x80);
1832 buf[4] = castchar((uv&0x3f)|0x80);
1833 return 5;
1834 }
1835 if (uv <= 0x7fffffff) {
1836 buf[0] = castchar(((uv>>30)&0xff)|0xfc);
1837 buf[1] = castchar(((uv>>24)&0x3f)|0x80);
1838 buf[2] = castchar(((uv>>18)&0x3f)|0x80);
1839 buf[3] = castchar(((uv>>12)&0x3f)|0x80);
1840 buf[4] = castchar(((uv>>6)&0x3f)|0x80);
1841 buf[5] = castchar((uv&0x3f)|0x80);
1842 return 6;
1843 }
1844 rb_raise(rb_eRangeError, "pack(U): value out of range");
1845
1847}
1848
1849static const unsigned long utf8_limits[] = {
1850 0x0, /* 1 */
1851 0x80, /* 2 */
1852 0x800, /* 3 */
1853 0x10000, /* 4 */
1854 0x200000, /* 5 */
1855 0x4000000, /* 6 */
1856 0x80000000, /* 7 */
1857};
1858
1859static unsigned long
1860utf8_to_uv(const char *p, long *lenp)
1861{
1862 int c = *p++ & 0xff;
1863 unsigned long uv = c;
1864 long n;
1865
1866 if (!(uv & 0x80)) {
1867 *lenp = 1;
1868 return uv;
1869 }
1870 if (!(uv & 0x40)) {
1871 *lenp = 1;
1872 rb_raise(rb_eArgError, "malformed UTF-8 character");
1873 }
1874
1875 if (!(uv & 0x20)) { n = 2; uv &= 0x1f; }
1876 else if (!(uv & 0x10)) { n = 3; uv &= 0x0f; }
1877 else if (!(uv & 0x08)) { n = 4; uv &= 0x07; }
1878 else if (!(uv & 0x04)) { n = 5; uv &= 0x03; }
1879 else if (!(uv & 0x02)) { n = 6; uv &= 0x01; }
1880 else {
1881 *lenp = 1;
1882 rb_raise(rb_eArgError, "malformed UTF-8 character");
1883 }
1884 if (n > *lenp) {
1885 rb_raise(rb_eArgError, "malformed UTF-8 character (expected %ld bytes, given %ld bytes)",
1886 n, *lenp);
1887 }
1888 *lenp = n--;
1889 if (n != 0) {
1890 while (n--) {
1891 c = *p++ & 0xff;
1892 if ((c & 0xc0) != 0x80) {
1893 *lenp -= n + 1;
1894 rb_raise(rb_eArgError, "malformed UTF-8 character");
1895 }
1896 else {
1897 c &= 0x3f;
1898 uv = uv << 6 | c;
1899 }
1900 }
1901 }
1902 n = *lenp - 1;
1903 if (uv < utf8_limits[n]) {
1904 rb_raise(rb_eArgError, "redundant UTF-8 sequence");
1905 }
1906 return uv;
1907}
1908
1909#include "pack.rbinc"
1910
1911void
1912Init_pack(void)
1913{
1914 id_associated = rb_make_internal_id();
1915}
#define RUBY_ALIGNOF
Wraps (or simulates) alignof.
Definition stdalign.h:28
int rb_block_given_p(void)
Determines if the current method is given a block.
Definition eval.c:1032
#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 STRTOUL
Old name of ruby_strtoul.
Definition ctype.h:104
#define ISDIGIT
Old name of rb_isdigit.
Definition ctype.h:93
#define ISALPHA
Old name of rb_isalpha.
Definition ctype.h:92
#define ISASCII
Old name of rb_isascii.
Definition ctype.h:85
#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 ISPRINT
Old name of rb_isprint.
Definition ctype.h:86
#define NUM2LONG
Old name of RB_NUM2LONG.
Definition long.h:51
#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:1435
VALUE rb_eTypeError
TypeError exception.
Definition error.c:1431
VALUE rb_eRuntimeError
RuntimeError exception.
Definition error.c:1429
VALUE rb_to_float(VALUE val)
Identical to rb_check_to_float(), except it raises on error.
Definition object.c:3772
VALUE rb_to_int(VALUE val)
Identical to rb_check_to_int(), except it raises in case of conversion mismatch.
Definition object.c:3326
Defines RBIMPL_HAS_BUILTIN.
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:1803
#define INTEGER_PACK_2COMP
Uses 2's complement representation.
Definition bignum.h:553
#define rb_str_new(str, len)
Allocates an instance of rb_cString.
Definition string.h:1499
#define rb_str_buf_cat
Just another name of rb_str_cat.
Definition string.h:1682
#define rb_usascii_str_new(str, len)
Identical to rb_str_new, except it generates a string of "US ASCII" encoding.
Definition string.h:1533
void rb_str_set_len(VALUE str, long len)
Overwrites the length of the string.
Definition string.c:3484
void rb_must_asciicompat(VALUE obj)
Asserts that the given string's encoding is (Ruby's definition of) ASCII compatible.
Definition string.c:2846
void rb_str_modify_expand(VALUE str, long capa)
Identical to rb_str_modify(), except it additionally expands the capacity of the receiver.
Definition string.c:2800
VALUE rb_str_buf_new(long capa)
Allocates a "string buffer".
Definition string.c:1754
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:1886
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:2059
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'->11etc.
Definition util.c:60
VALUE type(ANYARGS)
ANYARGS-ed function type.
#define RBIMPL_ATTR_NORETURN()
Wraps (or simulates) [[noreturn]]
Definition noreturn.h:38
#define RARRAY_LEN
Just another name of rb_array_len.
Definition rarray.h:50
#define RARRAY_CONST_PTR
Just another name of rb_array_const_ptr.
Definition rarray.h:51
#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:529
#define errno
Ractor-aware version of errno.
Definition ruby.h:388
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