15 my $Is_EBCDIC = (defined $Config{ebcdic} && $Config{ebcdic} eq 'define');
16 my $Perl = which_perl();
17 my @valid_errors = (qr/^Invalid type '\w'/);
19 my $ByteOrder = 'unknown';
20 my $maybe_not_avail = '(?:hto[bl]e|[bl]etoh)';
21 if ($Config{byteorder} =~ /^1234(?:5678)?$/) {
22 $ByteOrder = 'little';
23 $maybe_not_avail = '(?:htobe|betoh)';
25 elsif ($Config{byteorder} =~ /^(?:8765)?4321$/) {
27 $maybe_not_avail = '(?:htole|letoh)';
30 push @valid_errors, qr/^Can't (?:un)?pack (?:big|little)-endian .*? on this platform/;
33 for my $size ( 16, 32, 64 ) {
34 if (exists $Config{"u${size}size"} and $Config{"u${size}size"} != ($size >> 3)) {
35 push @valid_errors, qr/^Perl_my_$maybe_not_avail$size\(\) not available/;
39 my $IsTwosComplement = pack('i', -1) eq "\xFF" x $Config{intsize};
40 print "# \$IsTwosComplement = $IsTwosComplement\n";
46 for my $e (@valid_errors) {
47 $err =~ $e and return 1;
54 my @result = map {_qq($_)} @_;
58 return '(' . join (', ', @result) . ')';
64 return 0 unless @$l == @$r;
66 if (defined $l->[$i]) {
67 return 0 unless defined ($r->[$i]) && $l->[$i] eq $r->[$i];
69 return 0 if defined $r->[$i]
75 ##############################################################################
77 # Here starteth the tests
81 my $format = "c2 x5 C C x s d i l a6";
82 # Need the expression in here to force ary[5] to be numeric. This avoids
83 # test2 failing because ary2 goes str->numeric->str and ary doesn't.
84 my @ary = (1,-100,127,128,32767,987.654321098 / 100.0,12345,123456,
86 my $foo = pack($format,@ary);
87 my @ary2 = unpack($format,$foo);
91 my $out1=join(':',@ary);
92 my $out2=join(':',@ary2);
93 # Using long double NVs may introduce greater accuracy than wanted.
94 $out1 =~ s/:9\.87654321097999\d*:/:9.87654321098:/;
95 $out2 =~ s/:9\.87654321097999\d*:/:9.87654321098:/;
100 # How about counting bits?
104 is( ($x = unpack("%32B*", "\001\002\004\010\020\040\100\200\377")), 16 );
106 is( ($x = unpack("%32b69", "\001\002\004\010\020\040\100\200\017")), 12 );
108 is( ($x = unpack("%32B69", "\001\002\004\010\020\040\100\200\017")), 9 );
112 my $sum = 129; # ASCII
113 $sum = 103 if $Is_EBCDIC;
116 is( ($x = unpack("%32B*", "Now is the time for all good blurfl")), $sum );
119 open(BIN, $Perl) || die "Can't open $Perl: $!\n";
120 sysread BIN, $foo, 8192;
123 $sum = unpack("%32b*", $foo);
124 my $longway = unpack("b*", $foo);
125 is( $sum, $longway =~ tr/1/1/ );
130 is( ($x = unpack("I",pack("I", 0xFFFFFFFF))), 0xFFFFFFFF );
135 my @x = (5,130,256,560,32000,3097152,268435455,1073741844, 2**33,
136 '4503599627365785','23728385234614992549757750638446');
137 my $x = pack('w*', @x);
138 my $y = pack 'H*', '0581028200843081fa0081bd8440ffffff7f8480808014A0808'.
139 '0800087ffffffffffdb19caefe8e1eeeea0c2e1e3e8ede1ee6e';
143 my @y = unpack('w*', $y);
145 while ($a = pop @x) {
150 @y = unpack('w2', $x);
154 $x = pack('w*', 5000000000); $y = '';
157 $y = pack('w*', Math::BigInt::->new(5000000000));
162 $y = pack 'w', (~0).'';
164 is(unpack ('w',$x), ~0);
165 is(unpack ('w',$y), ~0);
167 $x = pack 'w', ~0 - 1;
168 $y = pack 'w', (~0) - 2;
170 if (~0 - 1 == (~0) - 2) {
171 is($x, $y, "NV arithmetic");
173 isnt($x, $y, "IV/NV arithmetic");
175 cmp_ok(unpack ('w',$x), '==', ~0 - 1);
176 cmp_ok(unpack ('w',$y), '==', ~0 - 2);
178 # These should spot that pack 'w' is using NV, not double, on platforms
179 # where IVs are smaller than doubles, and harmlessly pass elsewhere.
180 # (tests for change 16861)
188 is($x, $y, "NV arithmetic");
190 isnt($x, $y, "IV/NV arithmetic");
192 cmp_ok(unpack ('w',$x), '==', $x0);
193 cmp_ok(unpack ('w',$y), '==', $y0);
198 print "# test exceptions\n";
200 eval { $x = unpack 'w', pack 'C*', 0xff, 0xff};
201 like($@, qr/^Unterminated compressed integer/);
203 eval { $x = unpack 'w', pack 'C*', 0xff, 0xff, 0xff, 0xff};
204 like($@, qr/^Unterminated compressed integer/);
206 eval { $x = unpack 'w', pack 'C*', 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff};
207 like($@, qr/^Unterminated compressed integer/);
209 eval { $x = pack 'w', -1 };
210 like ($@, qr/^Cannot compress negative numbers/);
212 eval { $x = pack 'w', '1'x(1 + length ~0) . 'e0' };
213 like ($@, qr/^Can only compress unsigned integers/);
215 for my $mod (qw( ! < > )) {
216 eval { $x = pack "a$mod", 42 };
217 like ($@, qr/^'$mod' allowed only after types \S+ in pack/);
219 eval { $x = unpack "a$mod", 'x'x8 };
220 like ($@, qr/^'$mod' allowed only after types \S+ in unpack/);
223 for my $mod (qw( <> >< !<> !>< <!> >!< <>! ><! )) {
224 eval { $x = pack "sI${mod}s", 42, 47, 11 };
225 like ($@, qr/^Can't use both '<' and '>' after type 'I' in pack/);
227 eval { $x = unpack "sI${mod}s", 'x'x16 };
228 like ($@, qr/^Can't use both '<' and '>' after type 'I' in unpack/);
232 # Is this a stupid thing to do on VMS, VOS and other unusual platforms?
234 skip("-- the IEEE infinity model is unavailable in this configuration.", 1)
235 if (($^O eq 'VMS') && !defined($Config{useieee}));
237 skip("-- $^O has serious fp indigestion on w-packed infinities", 1)
243 ($^O =~ /^svr4/ && -f "/etc/issue" && -f "/etc/.relid") # NCR MP-RAS
246 my $inf = eval '2**1000000';
248 skip("Couldn't generate infinity - got error '$@'", 1)
249 unless defined $inf and $inf == $inf / 2 and $inf + 1 == $inf;
252 $TODO = "VOS needs a fix for posix-1022 to pass this test."
255 eval { $x = pack 'w', $inf };
256 like ($@, qr/^Cannot compress integer/, "Cannot compress integer");
261 skip("-- the full range of an IEEE double may not be available in this configuration.", 3)
262 if (($^O eq 'VMS') && !defined($Config{useieee}));
264 skip("-- $^O does not like 2**1023", 3)
265 if (($^O eq 'ultrix'));
267 # This should be about the biggest thing possible on an IEEE double
268 my $big = eval '2**1023';
270 skip("Couldn't generate 2**1023 - got error '$@'", 3)
271 unless defined $big and $big != $big / 2;
273 eval { $x = pack 'w', $big };
274 is ($@, '', "Should be able to pack 'w', $big # 2**1023");
276 my $y = eval {unpack 'w', $x};
278 "Should be able to unpack 'w' the result of pack 'w', $big # 2**1023");
280 # I'm getting about 1e-16 on FreeBSD
281 my $quotient = int (100 * ($y - $big) / $big);
282 ok($quotient < 2 && $quotient > -2,
283 "Round trip pack, unpack 'w' of $big is within 1% ($quotient%)");
288 print "# test the 'p' template\n";
291 is(unpack("p",pack("p","foo")), "foo");
292 is(unpack("p<",pack("p<","foo")), "foo");
293 is(unpack("p>",pack("p>","foo")), "foo");
296 is(unpack("p",pack("p",239)), 239);
297 is(unpack("p<",pack("p<",239)), 239);
298 is(unpack("p>",pack("p>",239)), 239);
301 sub foo { my $a = "a"; return $a . $a++ . $a++ }
305 local $SIG{__WARN__} = sub {
308 my $junk = pack("p", &foo);
310 like($warning, qr/temporary val/);
313 # undef should give null pointer
314 like(pack("p", undef), qr/^\0+$/);
315 like(pack("p<", undef), qr/^\0+$/);
316 like(pack("p>", undef), qr/^\0+$/);
318 # Check for optimizer bug (e.g. Digital Unix GEM cc with -O4 on DU V4.0B gives
319 # 4294967295 instead of -1)
320 # see #ifdef __osf__ in pp.c pp_unpack
321 is((unpack("i",pack("i",-1))), -1);
323 print "# test the pack lengths of s S i I l L n N v V + modifiers\n";
326 qw(s 2 S 2 i -4 I -4 l 4 L 4 n 2 N 4 v 2 V 4 n! 2 N! 4 v! 2 V! 4),
327 's!' => $Config{shortsize}, 'S!' => $Config{shortsize},
328 'i!' => $Config{intsize}, 'I!' => $Config{intsize},
329 'l!' => $Config{longsize}, 'L!' => $Config{longsize},
332 while (my ($base, $expect) = splice @lengths, 0, 2) {
333 my @formats = ($base);
334 $base =~ /^[nv]/i or push @formats, "$base>", "$base<";
335 for my $format (@formats) {
336 my $len = length(pack($format, 0));
338 is($expect, $len, "format '$format'");
341 ok ($len >= $expect, "format '$format'") ||
342 print "# format '$format' has length $len, expected >= $expect\n";
348 print "# test unpack-pack lengths\n";
350 my @templates = qw(c C i I s S l L n N v V f d q Q);
352 foreach my $base (@templates) {
354 $base =~ /^[cnv]/i or push @tmpl, "$base>", "$base<";
355 foreach my $t (@tmpl) {
357 my @t = eval { unpack("$t*", pack("$t*", 12, 34)) };
359 skip "cannot pack '$t' on this perl", 4
360 if is_valid_error($@);
362 is( $@, '', "Template $t works");
374 # Note that first uuencoding known 'text' data and then checking the
375 # binary values of the uuencoded version would not be portable between
376 # character sets. Uuencoding is meant for encoding binary data, not
379 my $in = pack 'C*', 0 .. 255;
381 # just to be anal, we do some random tr/`/ /
383 M` $"`P0%!@<("0H+# T.#Q`1$A,4%187&!D:&QP='A\@(2(C)"4F)R@I*BLL
384 M+2XO,#$R,S0U-C<X.3H[/#T^/T!!0D-$149'2$E*2TQ-3D]045)35%565UA9
385 M6EM<75Y?8&%B8V1E9F=H:6IK;&UN;W!Q<G-T=79W>'EZ>WQ]?G^`@8*#A(6&
386 MAXB)BHN,C8Z/D)&2DY25EI>8F9J;G)V>GZ"AHJ.DI::GJ*FJJZRMKJ^PL;*S
387 MM+6VM[BYNKN\O;Z_P,'"P\3%QL?(R<K+S,W.S]#1TM/4U=;7V-G:V]S=WM_@
388 ?X>+CY.7FY^CIZNOL[>[O\/'R\_3U]O?X^?K[_/W^_P `
394 is(pack('u', $in), $_);
396 is(unpack('u', $uu), $in);
398 $in = "\x1f\x8b\x08\x08\x58\xdc\xc4\x35\x02\x03\x4a\x41\x50\x55\x00\xf3\x2a\x2d\x2e\x51\x48\xcc\xcb\x2f\xc9\x48\x2d\x52\x08\x48\x2d\xca\x51\x28\x2d\x4d\xce\x4f\x49\x2d\xe2\x02\x00\x64\x66\x60\x5c\x1a\x00\x00\x00";
400 M'XL("%C<Q#4"`TI!4%4`\RHM+E%(S,LOR4@M4@A(+<I1*"U-SD])+>("`&1F
404 is(unpack('u', $uu), $in);
406 # This is identical to the above except that backquotes have been
410 M'XL("%C<Q#4" TI!4%4 \RHM+E%(S,LOR4@M4@A(+<I1*"U-SD])+>(" &1F
415 is(unpack('u', $uu), $in);
419 # test the ascii template types (A, a, Z)
422 ['p', 'A*', "foo\0bar\0 ", "foo\0bar\0 "],
423 ['p', 'A11', "foo\0bar\0 ", "foo\0bar\0 "],
424 ['u', 'A*', "foo\0bar \0", "foo\0bar"],
425 ['u', 'A8', "foo\0bar \0", "foo\0bar"],
426 ['p', 'a*', "foo\0bar\0 ", "foo\0bar\0 "],
427 ['p', 'a11', "foo\0bar\0 ", "foo\0bar\0 \0\0"],
428 ['u', 'a*', "foo\0bar \0", "foo\0bar \0"],
429 ['u', 'a8', "foo\0bar \0", "foo\0bar "],
430 ['p', 'Z*', "foo\0bar\0 ", "foo\0bar\0 \0"],
431 ['p', 'Z11', "foo\0bar\0 ", "foo\0bar\0 \0\0"],
432 ['p', 'Z3', "foo", "fo\0"],
433 ['u', 'Z*', "foo\0bar \0", "foo"],
434 ['u', 'Z8', "foo\0bar \0", "foo"],
437 my ($what, $template, $in, $out) = @$_;
438 my $got = $what eq 'u' ? (unpack $template, $in) : (pack $template, $in);
439 unless (is($got, $out)) {
440 my $un = $what eq 'u' ? 'un' : '';
441 print "# ${un}pack ('$template', "._qq($in).') gave '._qq($out).
442 ' not '._qq($got)."\n";
446 print "# packing native shorts/ints/longs\n";
448 is(length(pack("s!", 0)), $Config{shortsize});
449 is(length(pack("i!", 0)), $Config{intsize});
450 is(length(pack("l!", 0)), $Config{longsize});
451 ok(length(pack("s!", 0)) <= length(pack("i!", 0)));
452 ok(length(pack("i!", 0)) <= length(pack("l!", 0)));
453 is(length(pack("i!", 0)), length(pack("i", 0)));
457 my @formats = ($base);
458 $base =~ /^[silqjfdp]/i and push @formats, "$base>", "$base<";
459 for my $format (@formats) {
460 numbers_with_total ($format, undef, @_);
464 sub numbers_with_total {
467 if (!defined $total) {
472 print "# numbers test for $format\n";
475 my $out = eval {unpack($format, pack($format, $_))};
476 skip "cannot pack '$format' on this perl", 2
477 if is_valid_error($@);
479 is($@, '', "no error");
480 is($out, $_, "unpack pack $format $_");
484 my $skip_if_longer_than = ~0; # "Infinity"
486 # If we're running with -DNO_PERLPRESERVE_IVUV and NVs don't preserve all
487 # UVs (in which case ~0 is NV, ~0-1 will be the same NV) then we can't
488 # correctly in perl calculate UV totals for long checksums, as pp_unpack
489 # is using UV maths, and we've only got NVs.
490 $skip_if_longer_than = $Config{nv_preserves_uv_bits};
493 foreach ('', 1, 2, 3, 15, 16, 17, 31, 32, 33, 53, 54, 63, 64, 65) {
495 my $sum = eval {unpack "%$_$format*", pack "$format*", @_};
496 skip "cannot pack '$format' on this perl", 3
497 if is_valid_error($@);
499 is($@, '', "no error");
500 ok(defined $sum, "sum bits $_, format $format defined");
502 my $len = $_; # Copy, so that we can reassign ''
503 $len = 16 unless length $len;
506 skip "cannot test checksums over $skip_if_longer_than bits", 1
507 if $len > $skip_if_longer_than;
509 # Our problem with testing this portably is that the checksum code in
510 # pp_unpack is able to cast signed to unsigned, and do modulo 2**n
511 # arithmetic in unsigned ints, which perl has no operators to do.
512 # (use integer; does signed ints, which won't wrap on UTS, which is just
513 # fine with ANSI, but not with most people's assumptions.
514 # This is why we need to supply the totals for 'Q' as there's no way in
515 # perl to calculate them, short of unpack '%0Q' (is that documented?)
516 # ** returns NVs; make sure it's IV.
517 my $max = 1 + 2 * (int (2 ** ($len-1))-1); # The max possible checksum
518 my $max_p1 = $max + 1;
519 my ($max_is_integer, $max_p1_is_integer);
520 $max_p1_is_integer = 1 unless $max_p1 + 1 == $max_p1;
521 $max_is_integer = 1 if $max - 1 < ~0;
525 $calc_sum = &$total($len);
528 # Shift into range by some multiple of the total
529 my $mult = $max_p1 ? int ($total / $max_p1) : undef;
530 # Need this to make sure that -1 + (~0+1) is ~0 (ie still integer)
531 $calc_sum = $total - $mult;
532 $calc_sum -= $mult * $max;
538 if ($calc_sum == $calc_sum - 1 && $calc_sum == $max_p1) {
539 # we're into floating point (either by getting out of the range of
540 # UV arithmetic, or because we're doing a floating point checksum)
541 # and our calculation of the checksum has become rounded up to
546 if ($calc_sum == $sum) { # HAS to be ==, not eq (so no is()).
547 pass ("unpack '%$_$format' gave $sum");
549 my $delta = 1.000001;
550 if ($format =~ tr /dDfF//
551 && ($calc_sum <= $sum * $delta && $calc_sum >= $sum / $delta)) {
552 pass ("unpack '%$_$format' gave $sum, expected $calc_sum");
554 my $text = ref $total ? &$total($len) : $total;
556 print "# For list (" . join (", ", @_) . ") (total $text)"
557 . " packed with $format unpack '%$_$format' gave $sum,"
558 . " expected $calc_sum\n";
566 numbers ('c', -128, -1, 0, 1, 127);
567 numbers ('C', 0, 1, 127, 128, 255);
568 numbers ('s', -32768, -1, 0, 1, 32767);
569 numbers ('S', 0, 1, 32767, 32768, 65535);
570 numbers ('i', -2147483648, -1, 0, 1, 2147483647);
571 numbers ('I', 0, 1, 2147483647, 2147483648, 4294967295);
572 numbers ('l', -2147483648, -1, 0, 1, 2147483647);
573 numbers ('L', 0, 1, 2147483647, 2147483648, 4294967295);
574 numbers ('s!', -32768, -1, 0, 1, 32767);
575 numbers ('S!', 0, 1, 32767, 32768, 65535);
576 numbers ('i!', -2147483648, -1, 0, 1, 2147483647);
577 numbers ('I!', 0, 1, 2147483647, 2147483648, 4294967295);
578 numbers ('l!', -2147483648, -1, 0, 1, 2147483647);
579 numbers ('L!', 0, 1, 2147483647, 2147483648, 4294967295);
580 numbers ('n', 0, 1, 32767, 32768, 65535);
581 numbers ('v', 0, 1, 32767, 32768, 65535);
582 numbers ('N', 0, 1, 2147483647, 2147483648, 4294967295);
583 numbers ('V', 0, 1, 2147483647, 2147483648, 4294967295);
584 numbers ('n!', -32768, -1, 0, 1, 32767);
585 numbers ('v!', -32768, -1, 0, 1, 32767);
586 numbers ('N!', -2147483648, -1, 0, 1, 2147483647);
587 numbers ('V!', -2147483648, -1, 0, 1, 2147483647);
588 # All these should have exact binary representations:
589 numbers ('f', -1, 0, 0.5, 42, 2**34);
590 numbers ('d', -(2**34), -1, 0, 1, 2**34);
591 ## These don't, but 'd' is NV. XXX wrong, it's double
592 #numbers ('d', -1, 0, 1, 1-exp(-1), -exp(1));
594 numbers_with_total ('q', -1,
595 -9223372036854775808, -1, 0, 1,9223372036854775807);
596 # This total is icky, but the true total is 2**65-1, and need a way to generate
597 # the epxected checksum on any system including those where NVs can preserve
598 # 65 bits. (long double is 128 bits on sparc, so they certainly can)
599 # or where rounding is down not up on binary conversion (crays)
600 numbers_with_total ('Q', sub {
602 $len = 65 if $len > 65; # unmasked total is 2**65-1 here
603 my $total = 1 + 2 * (int (2**($len - 1)) - 1);
604 return 0 if $total == $total - 1; # Overflowed integers
605 return $total; # NVs still accurate to nearest integer
607 0, 1,9223372036854775807, 9223372036854775808,
608 18446744073709551615);
610 print "# pack nvNV byteorders\n";
612 is(pack("n", 0xdead), "\xde\xad");
613 is(pack("v", 0xdead), "\xad\xde");
614 is(pack("N", 0xdeadbeef), "\xde\xad\xbe\xef");
615 is(pack("V", 0xdeadbeef), "\xef\xbe\xad\xde");
617 is(pack("n!", 0xdead), "\xde\xad");
618 is(pack("v!", 0xdead), "\xad\xde");
619 is(pack("N!", 0xdeadbeef), "\xde\xad\xbe\xef");
620 is(pack("V!", 0xdeadbeef), "\xef\xbe\xad\xde");
622 print "# test big-/little-endian conversion\n";
627 print "# byteorder test for $format\n";
630 my($nat,$be,$le) = eval { map { pack $format.$_, $value } '', '>', '<' };
631 skip "cannot pack '$format' on this perl", 5
632 if is_valid_error($@);
634 print "# [$value][$nat][$be][$le][$@]\n";
637 skip "cannot compare native byteorder with big-/little-endian", 1
638 if $ByteOrder eq 'unknown';
640 is($nat, $ByteOrder eq 'big' ? $be : $le);
642 is($be, reverse($le));
643 my @x = eval { unpack "$format$format>$format<", $nat.$be.$le };
645 print "# [$value][", join('][', @x), "][$@]\n";
654 byteorder('s', -32768, -1, 0, 1, 32767);
655 byteorder('S', 0, 1, 32767, 32768, 65535);
656 byteorder('i', -2147483648, -1, 0, 1, 2147483647);
657 byteorder('I', 0, 1, 2147483647, 2147483648, 4294967295);
658 byteorder('l', -2147483648, -1, 0, 1, 2147483647);
659 byteorder('L', 0, 1, 2147483647, 2147483648, 4294967295);
660 byteorder('j', -2147483648, -1, 0, 1, 2147483647);
661 byteorder('J', 0, 1, 2147483647, 2147483648, 4294967295);
662 byteorder('s!', -32768, -1, 0, 1, 32767);
663 byteorder('S!', 0, 1, 32767, 32768, 65535);
664 byteorder('i!', -2147483648, -1, 0, 1, 2147483647);
665 byteorder('I!', 0, 1, 2147483647, 2147483648, 4294967295);
666 byteorder('l!', -2147483648, -1, 0, 1, 2147483647);
667 byteorder('L!', 0, 1, 2147483647, 2147483648, 4294967295);
668 byteorder('q', -9223372036854775808, -1, 0, 1, 9223372036854775807);
669 byteorder('Q', 0, 1, 9223372036854775807, 9223372036854775808, 18446744073709551615);
670 byteorder('f', -1, 0, 0.5, 42, 2**34);
671 byteorder('F', -1, 0, 0.5, 42, 2**34);
672 byteorder('d', -(2**34), -1, 0, 1, 2**34);
673 byteorder('D', -(2**34), -1, 0, 1, 2**34);
675 print "# test negative numbers\n";
678 skip "platform is not using two's complement for negative integers", 120
679 unless $IsTwosComplement;
681 for my $format (qw(s i l j s! i! l! q)) {
683 my($nat,$be,$le) = eval { map { pack $format.$_, -1 } '', '>', '<' };
684 skip "cannot pack '$format' on this perl", 15
685 if is_valid_error($@);
687 my $len = length $nat;
688 is($_, "\xFF"x$len) for $nat, $be, $le;
692 @val = (-2, -81985529216486896, -9223372036854775808);
693 @ref = ("\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFE",
694 "\xFE\xDC\xBA\x98\x76\x54\x32\x10",
695 "\x80\x00\x00\x00\x00\x00\x00\x00");
698 @val = (-2, -19088744, -2147483648);
699 @ref = ("\xFF\xFF\xFF\xFE",
704 @val = (-2, -292, -32768);
710 if ($len > length $x) {
711 $x = $x . "\xFF" x ($len - length $x);
715 for my $i (0 .. $#val) {
716 my($nat,$be,$le) = eval { map { pack $format.$_, $val[$i] } '', '>', '<' };
720 skip "cannot compare native byteorder with big-/little-endian", 1
721 if $ByteOrder eq 'unknown';
723 is($nat, $ByteOrder eq 'big' ? $be : $le);
727 is($be, reverse($le));
737 eval { ($x) = unpack '/a*','hello' };
738 like($@, qr!'/' must follow a numeric type!);
740 eval { $x = unpack '/a*','hello' };
741 like($@, qr!'/' must follow a numeric type!);
744 eval { ($z,$x,$y) = unpack 'a3/A C/a* C/Z', "003ok \003yes\004z\000abc" };
750 eval { $z = unpack 'a3/A C/a* C/Z', "003ok \003yes\004z\000abc" };
756 eval { ($x) = pack '/a*','hello' };
757 like($@, qr!Invalid type '/'!);
759 eval { $x = pack '/a*','hello' };
760 like($@, qr!Invalid type '/'!);
762 $z = pack 'n/a* N/Z* w/A*','string','hi there ','etc';
763 my $expect = "\000\006string\0\0\0\012hi there \000\003etc";
767 $expect = 'hello world';
768 eval { ($x) = unpack ("w/a", chr (11) . "hello world!")};
773 # Doing this in scalar context used to fail.
774 eval { $x = unpack ("w/a", chr (11) . "hello world!")};
779 ['a/a*/a*', '212ab345678901234567','ab3456789012'],
780 ['a/a*/a*', '3012ab345678901234567', 'ab3456789012'],
781 ['a/a*/b*', '212ab', $Is_EBCDIC ? '100000010100' : '100001100100'],
784 my ($pat, $in, $expect) = @$_;
786 eval { ($x) = unpack $pat, $in };
789 printf "# list unpack ('$pat', '$in') gave %s, expected '$expect'\n",
793 eval { $x = unpack $pat, $in };
796 printf "# scalar unpack ('$pat', '$in') gave %s, expected '$expect'\n",
802 my $pattern = <<'EOU';
803 a3/A # Count in ASCII
804 C/a* # Count in a C char
805 C/Z # Count in a C char but skip after \0
809 eval { ($z,$x,$y) = unpack $pattern, "003ok \003yes\004z\000abc" };
815 eval { $z = unpack $pattern, "003ok \003yes\004z\000abc" };
820 n/a* # Count as network short
821 w/A* # Count a BER integer
823 $expect = "\000\006string\003etc";
824 $z = pack $pattern,'string','etc';
830 skip("(EBCDIC and) version strings are bad idea", 2) if $Is_EBCDIC;
832 is("1.20.300.4000", sprintf "%vd", pack("U*",1,20,300,4000));
833 is("1.20.300.4000", sprintf "%vd", pack(" U*",1,20,300,4000));
835 isnt(v1.20.300.4000, sprintf "%vd", pack("C0U*",1,20,300,4000));
837 my $rslt = $Is_EBCDIC ? "156 67" : "199 162";
838 is(join(" ", unpack("C*", chr(0x1e2))), $rslt);
840 # does pack U create Unicode?
841 is(ord(pack('U', 300)), 300);
843 # does unpack U deref Unicode?
844 is((unpack('U', chr(300)))[0], 300);
846 # is unpack U the reverse of pack U for Unicode string?
847 is("@{[unpack('U*', pack('U*', 100, 200, 300))]}", "100 200 300");
849 # is unpack U the reverse of pack U for byte string?
850 is("@{[unpack('U*', pack('U*', 100, 200))]}", "100 200");
854 skip "Not for EBCDIC", 4 if $Is_EBCDIC;
856 # does unpack C unravel pack U?
857 is("@{[unpack('C*', pack('U*', 100, 200))]}", "100 195 136");
859 # does pack U0C create Unicode?
860 is("@{[pack('U0C*', 100, 195, 136)]}", v100.v200);
862 # does pack C0U create characters?
863 is("@{[pack('C0U*', 100, 200)]}", pack("C*", 100, 195, 136));
865 # does unpack U0U on byte data warn?
867 local $SIG{__WARN__} = sub { $@ = "@_" };
868 my @null = unpack('U0U', chr(255));
869 like($@, qr/^Malformed UTF-8 character /);
874 my $p = pack 'i*', -2147483648, ~0, 0, 1, 2147483647;
876 # bug - % had to be at the start of the pattern, no leading whitespace or
877 # comments. %i! didn't work at all.
878 foreach my $pat ('%32i*', ' %32i*', "# Muhahahaha\n%32i*", '%32i* ',
879 '%32i!*', ' %32i!*', "\n#\n#\n\r \t\f%32i!*", '%32i!*#') {
880 @a = unpack $pat, $p;
881 is($a[0], 0xFFFFFFFF) || print "# $pat\n";
882 @a = scalar unpack $pat, $p;
883 is($a[0], 0xFFFFFFFF) || print "# $pat\n";
887 $p = pack 'I*', 42, 12;
888 # Multiline patterns in scalar context failed.
889 foreach my $pat ('I', <<EOPOEMSNIPPET, 'I#I', 'I # I', 'I # !!!') {
890 # On the Ning Nang Nong
891 # Where the Cows go Bong!
892 # And the Monkeys all say Boo!
895 @a = unpack $pat, $p;
898 @a = scalar unpack $pat, $p;
903 # shorts (of all flavours) didn't calculate checksums > 32 bits with floating
904 # point, so a pathologically long pattern would wrap at 32 bits.
905 my $pat = "\xff\xff"x65538; # Start with it long, to save any copying.
906 foreach (4,3,2,1,0) {
907 my $len = 65534 + $_;
908 is(unpack ("%33n$len", $pat), 65535 * $len);
918 ['xXa*', "Nick", "Nick"],
919 ['a5Xa5', "cameL", "llama", "camellama"],
921 ['a*@8a*', 'Camel', 'Dromedary', "Camel\0\0\0Dromedary"],
922 ['a*@4a', 'Perl rules', '!', 'Perl!'],
925 my ($template, @in) = @$_;
927 my $got = eval {pack $template, @in};
930 printf "# pack ('$template', %s) gave %s expected %s\n",
931 encode_list (@in), encode_list ($got), encode_list ($out);
938 ['xXa*', "Nick", "Nick"],
939 ['a5Xa5', "camellama", "camel", "llama"],
941 ['@2a2', "water", "te"],
942 ['a*@1a3', "steam", "steam", "tea"],
945 my ($template, $in, @out) = @$_;
946 my @got = eval {unpack $template, $in};
948 ok (list_eq (\@got, \@out)) ||
949 printf "# list unpack ('$template', %s) gave %s expected %s\n",
950 _qq($in), encode_list (@got), encode_list (@out);
952 my $got = eval {unpack $template, $in};
954 @out ? is( $got, $out[0] ) # 1 or more items; should get first
955 : ok( !defined $got ) # 0 items; should get undef
956 or printf "# scalar unpack ('$template', %s) gave %s expected %s\n",
957 _qq($in), encode_list ($got), encode_list ($out[0]);
962 my ($u, $v) = qw(foo xyzzy);
963 my $p = pack($t, $u, $v);
964 my @u = unpack($t, $p);
971 is((unpack("w/a*", "\x02abc"))[0], "ab");
973 # "w/a*" should be seen as one unit
975 is(scalar unpack("w/a*", "\x02abc"), "ab");
979 print "# group modifiers\n";
981 for my $t (qw{ (s<)< (sl>s)> (s(l(sl)<l)s)< }) {
982 print "# testing pattern '$t'\n";
983 eval { ($_) = unpack($t, 'x'x18); };
985 eval { $_ = pack($t, (0)x6); };
989 for my $t (qw{ (s<)> (sl>s)< (s(l(sl)<l)s)> }) {
990 print "# testing pattern '$t'\n";
991 eval { ($_) = unpack($t, 'x'x18); };
992 like($@, qr/Can't use '[<>]' in a group with different byte-order in unpack/);
993 eval { $_ = pack($t, (0)x6); };
994 like($@, qr/Can't use '[<>]' in a group with different byte-order in pack/);
997 sub compress_template {
999 for my $mod (qw( < > )) {
1000 $t =~ s/((?:(?:[SILQJFDP]!?$mod|[^SILQJFDP\W]!?)(?:\d+|\*|\[(?:[^]]+)\])?\/?){2,})/
1001 my $x = $1; $x =~ s!$mod!!g ? "($x)$mod" : $x /ieg;
1006 is(pack('L<L>', (0x12345678)x2),
1007 pack('(((L1)1)<)(((L)1)1)>1', (0x12345678)x2));
1011 's<c2x![S]S<' => [-42, -11, 12, 4711],
1012 '(i<j<[s]l<)3' => [-11, -22, -33, 1000000, 1100, 2201, 3302,
1013 -1000000, 32767, -32768, 1, -123456789 ],
1014 '(I!<4(J<2L<)3)5' => [1 .. 65],
1015 'q<Q<' => [-50000000005, 60000000006],
1016 'f<F<d<' => [3.14159, 111.11, 2222.22],
1017 'D<cCD<' => [1e42, -128, 255, 1e-42],
1018 'n/a*' => ['/usr/bin/perl'],
1019 'C/a*S</A*L</Z*I</a*' => [qw(Just another Perl hacker)],
1022 for my $tle (sort keys %templates) {
1023 my @d = @{$templates{$tle}};
1026 for my $t ($tbe, $tle) {
1027 my $c = compress_template($t);
1028 print "# '$t' -> '$c'\n";
1030 my $p1 = eval { pack $t, @d };
1031 skip "cannot pack '$t' on this perl", 5 if is_valid_error($@);
1032 my $p2 = eval { pack $c, @d };
1035 s!(/[aAZ])\*!$1!g for $t, $c;
1036 my @u1 = eval { unpack $t, $p1 };
1038 my @u2 = eval { unpack $c, $p2 };
1040 is(join('!', @u1), join('!', @u2));
1047 # from Wolfgang Laun: fix in change #13163
1052 my $buf = pack( 'Z*/A* C', $s, $x );
1056 $h =~ s/[^[:print:]]/./g;
1057 ( $s, $y ) = unpack( "Z*/A* C", $buf );
1058 is($h, "30.ABCABCABCABCABCABCABCABCABCABC$t");
1059 is(length $buf, 34);
1060 is($s, "ABCABCABCABCABCABCABCABCABCABC");
1065 # from Wolfgang Laun: fix in change #13288
1067 eval { my $t=unpack("P*", "abc") };
1068 like($@, qr/'P' must have an explicit size/);
1071 { # Grouping constructs
1073 @a = unpack '(SL)', pack 'SLSLSL', 67..90;
1075 @a = unpack '(SL)3', pack 'SLSLSL', 67..90;
1078 @a = unpack '(SL)3', pack 'SLSLSLSL', 67..90;
1080 @a = unpack '(SL)[3]', pack 'SLSLSLSL', 67..90;
1082 @a = unpack '(SL)[2] SL', pack 'SLSLSLSL', 67..90;
1084 @a = unpack 'A/(SL)', pack 'ASLSLSLSL', 3, 67..90;
1086 @a = unpack 'A/(SL)SL', pack 'ASLSLSLSL', 2, 67..90;
1088 @a = unpack '(SL)*', pack 'SLSLSLSL', 67..90;
1091 @a = unpack '(SL)*SL', pack 'SLSLSLSL', 67..90;
1093 eval { @a = unpack '(*SL)', '' };
1094 like($@, qr/\(\)-group starts with a count/);
1095 eval { @a = unpack '(3SL)', '' };
1096 like($@, qr/\(\)-group starts with a count/);
1097 eval { @a = unpack '([3]SL)', '' };
1098 like($@, qr/\(\)-group starts with a count/);
1099 eval { @a = pack '(*SL)' };
1100 like($@, qr/\(\)-group starts with a count/);
1101 @a = unpack '(SL)3 SL', pack '(SL)4', 67..74;
1103 @a = unpack '(SL)3 SL', pack '(SL)[4]', 67..74;
1105 @a = unpack '(SL)3 SL', pack '(SL)*', 67..74;
1109 { # more on grouping (W.Laun)
1112 local $SIG{__WARN__} = sub {
1115 # @ absolute within ()-group
1116 my $badc = pack( '(a)*', unpack( '(@1a @0a @2)*', 'abcd' ) );
1117 is( $badc, 'badc' );
1118 my @b = ( 1, 2, 3 );
1119 my $buf = pack( '(@1c)((@2C)@3c)', @b );
1120 is( $buf, "\0\1\0\0\2\3" );
1121 my @a = unpack( '(@1c)((@2c)@3c)', $buf );
1124 # various unpack count/code scenarios
1125 my @Env = ( a => 'AAA', b => 'BBB' );
1126 my $env = pack( 'S(S/A*S/A*)*', @Env/2, @Env );
1128 # unpack full length - ok
1129 my @pup = unpack( 'S/(S/A* S/A*)', $env );
1130 is( "@pup", "@Env" );
1132 # warn when count/code goes beyond end of string
1133 # \0002 \0001 a \0003 AAA \0001 b \0003 BBB
1135 eval { @pup = unpack( 'S/(S/A* S/A*)', substr( $env, 0, 13 ) ) };
1136 like( $@, qr{length/code after end of string} );
1138 # postfix repeat count
1139 $env = pack( '(S/A* S/A*)' . @Env/2, @Env );
1141 # warn when count/code goes beyond end of string
1142 # \0001 a \0003 AAA \0001 b \0003 BBB
1143 # 2 3c 5 8 10 11 13 16
1144 eval { @pup = unpack( '(S/A* S/A*)' . @Env/2, substr( $env, 0, 11 ) ) };
1145 like( $@, qr{length/code after end of string} );
1147 # catch stack overflow/segfault
1148 eval { $_ = pack( ('(' x 105) . 'A' . (')' x 105) ); };
1149 like( $@, qr{Too deeply nested \(\)-groups} );
1152 { # syntax checks (W.Laun)
1155 local $SIG{__WARN__} = sub {
1156 push( @warning, $_[0] );
1158 eval { my $s = pack( 'Ax![4c]A', 1..5 ); };
1159 like( $@, qr{Malformed integer in \[\]} );
1161 eval { my $buf = pack( '(c/*a*)', 'AAA', 'BB' ); };
1162 like( $@, qr{'/' does not take a repeat count} );
1164 eval { my @inf = unpack( 'c/1a', "\x03AAA\x02BB" ); };
1165 like( $@, qr{'/' does not take a repeat count} );
1167 eval { my @inf = unpack( 'c/*a', "\x03AAA\x02BB" ); };
1168 like( $@, qr{'/' does not take a repeat count} );
1170 # white space where possible
1171 my @Env = ( a => 'AAA', b => 'BBB' );
1172 my $env = pack( ' S ( S / A* S / A* )* ', @Env/2, @Env );
1173 my @pup = unpack( ' S / ( S / A* S / A* ) ', $env );
1174 is( "@pup", "@Env" );
1176 # white space in 4 wrong places
1177 for my $temp ( 'A ![4]', 'A [4]', 'A *', 'A 4' ){
1178 eval { my $s = pack( $temp, 'B' ); };
1179 like( $@, qr{Invalid type } );
1182 # warning for commas
1184 my $x = pack( 'I,A', 4, 'X' );
1185 like( $warning[0], qr{Invalid type ','} );
1187 # comma warning only once
1189 $x = pack( 'C(C,C)C,C', 65..71 );
1190 like( scalar @warning, 1 );
1192 # forbidden code in []
1193 eval { my $x = pack( 'A[@4]', 'XXXX' ); };
1194 like( $@, qr{Within \[\]-length '\@' not allowed} );
1196 # @ repeat default 1
1197 my $s = pack( 'AA@A', 'A', 'B', 'C' );
1198 my @c = unpack( 'AA@A', $s );
1200 is( "@c", "A C C" );
1202 # no unpack code after /
1203 eval { my @a = unpack( "C/", "\3" ); };
1204 like( $@, qr{Code missing after '/'} );
1208 $x = pack "I>>s!!", 47, 11;
1209 ($x) = unpack "I<<l!>!>", 'x'x20;
1210 is(scalar @warning, 5);
1211 like($warning[0], qr/Duplicate modifier '>' after 'I' in pack/);
1212 like($warning[1], qr/Duplicate modifier '!' after 's' in pack/);
1213 like($warning[2], qr/Duplicate modifier '<' after 'I' in unpack/);
1214 like($warning[3], qr/Duplicate modifier '!' after 'l' in unpack/);
1215 like($warning[4], qr/Duplicate modifier '>' after 'l' in unpack/);
1218 { # Repeat count [SUBEXPR]
1219 my @codes = qw( x A Z a c C B b H h s v n S i I l V N L p P f F d
1220 s! S! i! I! l! L! j J);
1222 if (eval { pack 'q', 1 } ) {
1223 push @codes, qw(q Q);
1225 push @codes, qw(s S); # Keep the count the same
1227 if (eval { pack 'D', 1 } ) {
1230 push @codes, 'd'; # Keep the count the same
1233 push @codes, map { /^[silqjfdp]/i ? ("$_<", "$_>") : () } @codes;
1236 @val{@codes} = map { / [Xx] (?{ undef })
1237 | [AZa] (?{ 'something' })
1242 | [svnSiIlVNLqQjJ] (?{ 10111 })
1243 | [FfDd] (?{ 1.36514538e67 })
1244 | [pP] (?{ "try this buffer" })
1246 my @end = (0x12345678, 0x23456781, 0x35465768, 0x15263748);
1249 for my $type (@codes) {
1250 my @list = $val{$type};
1251 @list = () unless defined $list[0];
1252 for my $count ('', '3', '[11]') {
1254 $c = $1 if $count =~ /(\d+)/;
1256 @list1 = (@list1) x $c unless $type =~ /[XxAaZBbHhP]/;
1257 for my $groupend ('', ')2', ')[8]') {
1258 my $groupbegin = ($groupend ? '(' : '');
1260 $c = $1 if $groupend =~ /(\d+)/;
1261 my @list2 = (@list1) x $c;
1264 my $junk1 = "$groupbegin $type$count $groupend";
1265 # print "# junk1=$junk1\n";
1266 my $p = eval { pack $junk1, @list2 };
1267 skip "cannot pack '$type' on this perl", 12
1268 if is_valid_error($@);
1270 my $half = int( (length $p)/2 );
1271 for my $move ('', "X$half", "X!$half", 'x1', 'x!8', "x$half") {
1272 my $junk = "$junk1 $move";
1273 # print "# junk='$junk', list=(@list2)\n";
1274 $p = pack "$junk $end", @list2, @end;
1275 my @l = unpack "x[$junk] $end", $p;
1276 is(scalar @l, scalar @end);
1277 is("@l", "@end", "skipping x[$junk]");
1285 # / is recognized after spaces in scalar context
1286 # XXXX no spaces are allowed in pack... In pack only before the slash...
1287 is(scalar unpack('A /A Z20', pack 'A/A* Z20', 'bcde', 'xxxxx'), 'bcde');
1288 is(scalar unpack('A /A /A Z20', '3004bcde'), 'bcde');
1291 my $t = 'C[3] x!8 C[2]';
1292 my @a = (0x73..0x77);
1293 my $p = pack($t, @a);
1294 is($p, "\x73\x74\x75\0\0\0\0\0\x76\x77");
1295 my @b = unpack $t, $p;
1296 is(scalar @b, scalar @a);
1297 is("@b", "@a", 'x!8');
1298 $t = 'x[5] C[6] X!8 C[2]';
1301 is($p, "\0\0\0\0\0\x73\x74\x75\x79\x7a");
1303 @a = (0x73..0x75, 0x79, 0x7a, 0x79, 0x7a);
1304 is(scalar @b, scalar @a);
1308 { # struct {char c1; double d; char cc[2];}
1309 my $t = 'C x![d] d C[2]';
1310 my @a = (173, 1.283476517e-45, 42, 215);
1311 my $p = pack $t, @a;
1313 my @b = unpack "$t X[$t] $t", $p; # Extract, step back, extract again
1314 is(scalar @b, 2 * scalar @a);
1316 $b =~ s/(?:17000+|16999+)\d+(e-45) /17$1 /gi; # stringification is gamble
1320 local $SIG{__WARN__} = sub {
1323 @b = unpack "x[C] x[$t] X[$t] X[C] $t", "$p\0";
1325 is($warning, undef);
1326 is(scalar @b, scalar @a);
1328 $b =~ s/(?:17000+|16999+)\d+(e-45) /17$1 /gi; # stringification is gamble
1332 is(length(pack("j", 0)), $Config{ivsize});
1333 is(length(pack("J", 0)), $Config{uvsize});
1334 is(length(pack("F", 0)), $Config{nvsize});
1336 numbers ('j', -2147483648, -1, 0, 1, 2147483647);
1337 numbers ('J', 0, 1, 2147483647, 2147483648, 4294967295);
1338 numbers ('F', -(2**34), -1, 0, 1, 2**34);
1340 my $t = eval { unpack("D*", pack("D", 12.34)) };
1342 skip "Long doubles not in use", 166 if $@ =~ /Invalid type/;
1344 is(length(pack("D", 0)), $Config{longdblsize});
1345 numbers ('D', -(2**34), -1, 0, 1, 2**34);
1348 # Maybe this knowledge needs to be "global" for all of pack.t
1349 # Or a "can checksum" which would effectively be all the number types"
1350 my %cant_checksum = map {$_=> 1} qw(A Z u w);
1352 foreach my $template (qw(A Z c C s S i I l L n N v V q Q j J f d F D u U w)) {
1354 my $packed = eval {pack "${template}4", 1, 4, 9, 16};
1356 die unless $@ =~ /Invalid type '$template'/;
1357 skip ("$template not supported on this perl",
1358 $cant_checksum{$template} ? 4 : 8);
1360 my @unpack4 = unpack "${template}4", $packed;
1361 my @unpack = unpack "${template}*", $packed;
1362 my @unpack1 = unpack "${template}", $packed;
1363 my @unpack1s = scalar unpack "${template}", $packed;
1364 my @unpack4s = scalar unpack "${template}4", $packed;
1365 my @unpacks = scalar unpack "${template}*", $packed;
1367 my @tests = ( ["${template}4 vs ${template}*", \@unpack4, \@unpack],
1368 ["scalar ${template} ${template}", \@unpack1s, \@unpack1],
1369 ["scalar ${template}4 vs ${template}", \@unpack4s, \@unpack1],
1370 ["scalar ${template}* vs ${template}", \@unpacks, \@unpack1],
1373 unless ($cant_checksum{$template}) {
1374 my @unpack4_c = unpack "\%${template}4", $packed;
1375 my @unpack_c = unpack "\%${template}*", $packed;
1376 my @unpack1_c = unpack "\%${template}", $packed;
1377 my @unpack1s_c = scalar unpack "\%${template}", $packed;
1378 my @unpack4s_c = scalar unpack "\%${template}4", $packed;
1379 my @unpacks_c = scalar unpack "\%${template}*", $packed;
1382 ( ["% ${template}4 vs ${template}*", \@unpack4_c, \@unpack_c],
1383 ["% scalar ${template} ${template}", \@unpack1s_c, \@unpack1_c],
1384 ["% scalar ${template}4 vs ${template}*", \@unpack4s_c, \@unpack_c],
1385 ["% scalar ${template}* vs ${template}*", \@unpacks_c, \@unpack_c],
1388 foreach my $test (@tests) {
1389 ok (list_eq ($test->[1], $test->[2]), $test->[0]) ||
1390 printf "# unpack gave %s expected %s\n",
1391 encode_list (@{$test->[1]}), encode_list (@{$test->[2]});
1396 ok(pack('u2', 'AA'), "[perl #8026]"); # used to hang and eat RAM in perl 5.7.2
1398 $_ = pack('c', 65); # 'A' would not be EBCDIC-friendly
1399 is(unpack('c'), 65, "one-arg unpack (change #18751)"); # defaulting to $_
1402 my $a = "X\t01234567\n" x 100;
1403 my @a = unpack("(a1 c/a)*", $a);
1404 is(scalar @a, 200, "[perl #15288]");
1405 is($a[-1], "01234567\n", "[perl #15288]");
1406 is($a[-2], "X", "[perl #15288]");