9 # This is truth in an if statement, and could be a skip message
10 my $no_endianness = $] > 5.009 ? '' :
11 "Endianness pack modifiers not available on this perl";
12 my $no_signedness = $] > 5.009 ? '' :
13 "Signed/unsigned pack modifiers not available on this perl";
21 my $Is_EBCDIC = (defined $Config{ebcdic} && $Config{ebcdic} eq 'define');
22 my $Perl = which_perl();
23 my @valid_errors = (qr/^Invalid type '\w'/);
25 my $ByteOrder = 'unknown';
26 my $maybe_not_avail = '(?:hto[bl]e|[bl]etoh)';
28 push @valid_errors, qr/^Invalid type '[<>]'/;
29 } elsif ($Config{byteorder} =~ /^1234(?:5678)?$/) {
30 $ByteOrder = 'little';
31 $maybe_not_avail = '(?:htobe|betoh)';
33 elsif ($Config{byteorder} =~ /^(?:8765)?4321$/) {
35 $maybe_not_avail = '(?:htole|letoh)';
38 push @valid_errors, qr/^Can't (?:un)?pack (?:big|little)-endian .*? on this platform/;
42 push @valid_errors, qr/^'!' allowed only after types sSiIlLxX in (?:un)?pack/;
45 for my $size ( 16, 32, 64 ) {
46 if (exists $Config{"u${size}size"} and $Config{"u${size}size"} != ($size >> 3)) {
47 push @valid_errors, qr/^Perl_my_$maybe_not_avail$size\(\) not available/;
51 my $IsTwosComplement = pack('i', -1) eq "\xFF" x $Config{intsize};
52 print "# \$IsTwosComplement = $IsTwosComplement\n";
58 for my $e (@valid_errors) {
59 $err =~ $e and return 1;
66 my @result = map {_qq($_)} @_;
70 return '(' . join (', ', @result) . ')';
76 return 0 unless @$l == @$r;
78 if (defined $l->[$i]) {
79 return 0 unless defined ($r->[$i]) && $l->[$i] eq $r->[$i];
81 return 0 if defined $r->[$i]
87 ##############################################################################
89 # Here starteth the tests
93 my $format = "c2 x5 C C x s d i l a6";
94 # Need the expression in here to force ary[5] to be numeric. This avoids
95 # test2 failing because ary2 goes str->numeric->str and ary doesn't.
96 my @ary = (1,-100,127,128,32767,987.654321098 / 100.0,12345,123456,
98 my $foo = pack($format,@ary);
99 my @ary2 = unpack($format,$foo);
103 my $out1=join(':',@ary);
104 my $out2=join(':',@ary2);
105 # Using long double NVs may introduce greater accuracy than wanted.
106 $out1 =~ s/:9\.87654321097999\d*:/:9.87654321098:/;
107 $out2 =~ s/:9\.87654321097999\d*:/:9.87654321098:/;
112 # How about counting bits?
116 is( ($x = unpack("%32B*", "\001\002\004\010\020\040\100\200\377")), 16 );
118 is( ($x = unpack("%32b69", "\001\002\004\010\020\040\100\200\017")), 12 );
120 is( ($x = unpack("%32B69", "\001\002\004\010\020\040\100\200\017")), 9 );
124 my $sum = 129; # ASCII
125 $sum = 103 if $Is_EBCDIC;
128 is( ($x = unpack("%32B*", "Now is the time for all good blurfl")), $sum );
131 open(BIN, $Perl) || die "Can't open $Perl: $!\n";
132 sysread BIN, $foo, 8192;
135 $sum = unpack("%32b*", $foo);
136 my $longway = unpack("b*", $foo);
137 is( $sum, $longway =~ tr/1/1/ );
142 is( ($x = unpack("I",pack("I", 0xFFFFFFFF))), 0xFFFFFFFF );
147 my @x = (5,130,256,560,32000,3097152,268435455,1073741844, 2**33,
148 '4503599627365785','23728385234614992549757750638446');
149 my $x = pack('w*', @x);
150 my $y = pack 'H*', '0581028200843081fa0081bd8440ffffff7f8480808014A0808'.
151 '0800087ffffffffffdb19caefe8e1eeeea0c2e1e3e8ede1ee6e';
155 my @y = unpack('w*', $y);
157 while ($a = pop @x) {
162 @y = unpack('w2', $x);
166 $x = pack('w*', 5000000000); $y = '';
169 $y = pack('w*', Math::BigInt::->new(5000000000));
174 $y = pack 'w', (~0).'';
176 is(unpack ('w',$x), ~0);
177 is(unpack ('w',$y), ~0);
179 $x = pack 'w', ~0 - 1;
180 $y = pack 'w', (~0) - 2;
182 if (~0 - 1 == (~0) - 2) {
183 is($x, $y, "NV arithmetic");
185 isnt($x, $y, "IV/NV arithmetic");
187 cmp_ok(unpack ('w',$x), '==', ~0 - 1);
188 cmp_ok(unpack ('w',$y), '==', ~0 - 2);
190 # These should spot that pack 'w' is using NV, not double, on platforms
191 # where IVs are smaller than doubles, and harmlessly pass elsewhere.
192 # (tests for change 16861)
200 is($x, $y, "NV arithmetic");
202 isnt($x, $y, "IV/NV arithmetic");
204 cmp_ok(unpack ('w',$x), '==', $x0);
205 cmp_ok(unpack ('w',$y), '==', $y0);
210 print "# test exceptions\n";
212 eval { $x = unpack 'w', pack 'C*', 0xff, 0xff};
213 like($@, qr/^Unterminated compressed integer/);
215 eval { $x = unpack 'w', pack 'C*', 0xff, 0xff, 0xff, 0xff};
216 like($@, qr/^Unterminated compressed integer/);
218 eval { $x = unpack 'w', pack 'C*', 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff};
219 like($@, qr/^Unterminated compressed integer/);
221 eval { $x = pack 'w', -1 };
222 like ($@, qr/^Cannot compress negative numbers/);
224 eval { $x = pack 'w', '1'x(1 + length ~0) . 'e0' };
225 like ($@, qr/^Can only compress unsigned integers/);
227 # Check that the warning behaviour on the modifiers !, < and > is as we
228 # expect it for this perl.
229 my $can_endian = $no_endianness ? '' : 'sSiIlLqQjJfFdDpP';
230 my $can_shriek = 'sSiIlL';
231 $can_shriek .= 'nNvV' unless $no_signedness;
232 # h and H can't do either, so act as sanity checks in blead
233 foreach my $base (split '', 'hHsSiIlLqQjJfFdDpPnNvV') {
234 foreach my $mod ('', '<', '>', '!', '<!', '>!', '!<', '!>') {
236 # Avoid void context warnings.
237 my $a = eval {pack "$base$mod"};
238 skip "pack can't $base", 1 if $@ =~ /^Invalid type '\w'/;
239 # Which error you get when 2 would be possible seems to be emergent
240 # behaviour of pack's format parser.
242 my $fails_shriek = $mod =~ /!/ && index ($can_shriek, $base) == -1;
243 my $fails_endian = $mod =~ /[<>]/ && index ($can_endian, $base) == -1;
244 my $shriek_first = $mod =~ /^!/;
246 if ($no_endianness and ($mod eq '<!' or $mod eq '>!')) {
247 # The ! isn't seem as part of $base. Instead it's seen as a modifier
251 } elsif ($fails_shriek and $fails_endian) {
258 if ($no_endianness) {
259 # < and > are seen as pattern letters, not modifiers
260 like ($@, qr/^Invalid type '[<>]'/, "pack can't $base$mod");
262 like ($@, qr/^'[<>]' allowed only after types/,
263 "pack can't $base$mod");
265 } elsif ($fails_shriek) {
266 like ($@, qr/^'!' allowed only after types/,
267 "pack can't $base$mod");
269 is ($@, '', "pack can $base$mod");
276 skip $no_endianness, 2*3 + 2*8 if $no_endianness;
277 for my $mod (qw( ! < > )) {
278 eval { $x = pack "a$mod", 42 };
279 like ($@, qr/^'$mod' allowed only after types \S+ in pack/);
281 eval { $x = unpack "a$mod", 'x'x8 };
282 like ($@, qr/^'$mod' allowed only after types \S+ in unpack/);
285 for my $mod (qw( <> >< !<> !>< <!> >!< <>! ><! )) {
286 eval { $x = pack "sI${mod}s", 42, 47, 11 };
287 like ($@, qr/^Can't use both '<' and '>' after type 'I' in pack/);
289 eval { $x = unpack "sI${mod}s", 'x'x16 };
290 like ($@, qr/^Can't use both '<' and '>' after type 'I' in unpack/);
295 # Is this a stupid thing to do on VMS, VOS and other unusual platforms?
297 skip("-- the IEEE infinity model is unavailable in this configuration.", 1)
298 if (($^O eq 'VMS') && !defined($Config{useieee}));
300 skip("-- $^O has serious fp indigestion on w-packed infinities", 1)
306 ($^O =~ /^svr4/ && -f "/etc/issue" && -f "/etc/.relid") # NCR MP-RAS
309 my $inf = eval '2**1000000';
311 skip("Couldn't generate infinity - got error '$@'", 1)
312 unless defined $inf and $inf == $inf / 2 and $inf + 1 == $inf;
315 $TODO = "VOS needs a fix for posix-1022 to pass this test."
318 eval { $x = pack 'w', $inf };
319 like ($@, qr/^Cannot compress integer/, "Cannot compress integer");
324 skip("-- the full range of an IEEE double may not be available in this configuration.", 3)
325 if (($^O eq 'VMS') && !defined($Config{useieee}));
327 skip("-- $^O does not like 2**1023", 3)
328 if (($^O eq 'ultrix'));
330 # This should be about the biggest thing possible on an IEEE double
331 my $big = eval '2**1023';
333 skip("Couldn't generate 2**1023 - got error '$@'", 3)
334 unless defined $big and $big != $big / 2;
336 eval { $x = pack 'w', $big };
337 is ($@, '', "Should be able to pack 'w', $big # 2**1023");
339 my $y = eval {unpack 'w', $x};
341 "Should be able to unpack 'w' the result of pack 'w', $big # 2**1023");
343 # I'm getting about 1e-16 on FreeBSD
344 my $quotient = int (100 * ($y - $big) / $big);
345 ok($quotient < 2 && $quotient > -2,
346 "Round trip pack, unpack 'w' of $big is within 1% ($quotient%)");
351 print "# test the 'p' template\n";
354 is(unpack("p",pack("p","foo")), "foo");
356 skip $no_endianness, 2 if $no_endianness;
357 is(unpack("p<",pack("p<","foo")), "foo");
358 is(unpack("p>",pack("p>","foo")), "foo");
361 is(unpack("p",pack("p",239)), 239);
363 skip $no_endianness, 2 if $no_endianness;
364 is(unpack("p<",pack("p<",239)), 239);
365 is(unpack("p>",pack("p>",239)), 239);
369 sub foo { my $a = "a"; return $a . $a++ . $a++ }
373 local $SIG{__WARN__} = sub {
376 my $junk = pack("p", &foo);
378 like($warning, qr/temporary val/);
381 # undef should give null pointer
382 like(pack("p", undef), qr/^\0+$/);
384 skip $no_endianness, 2 if $no_endianness;
385 like(pack("p<", undef), qr/^\0+$/);
386 like(pack("p>", undef), qr/^\0+$/);
389 # Check for optimizer bug (e.g. Digital Unix GEM cc with -O4 on DU V4.0B gives
390 # 4294967295 instead of -1)
391 # see #ifdef __osf__ in pp.c pp_unpack
392 is((unpack("i",pack("i",-1))), -1);
394 print "# test the pack lengths of s S i I l L n N v V + modifiers\n";
397 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),
398 's!' => $Config{shortsize}, 'S!' => $Config{shortsize},
399 'i!' => $Config{intsize}, 'I!' => $Config{intsize},
400 'l!' => $Config{longsize}, 'L!' => $Config{longsize},
403 while (my ($base, $expect) = splice @lengths, 0, 2) {
404 my @formats = ($base);
405 $base =~ /^[nv]/i or push @formats, "$base>", "$base<";
406 for my $format (@formats) {
408 skip $no_endianness, 1 if $no_endianness && $format =~ m/[<>]/;
409 skip $no_signedness, 1 if $no_signedness && $format =~ /[nNvV]!/;
410 my $len = length(pack($format, 0));
412 is($expect, $len, "format '$format'");
415 ok ($len >= $expect, "format '$format'") ||
416 print "# format '$format' has length $len, expected >= $expect\n";
423 print "# test unpack-pack lengths\n";
425 my @templates = qw(c C W i I s S l L n N v V f d q Q);
427 foreach my $base (@templates) {
429 $base =~ /^[cwnv]/i or push @tmpl, "$base>", "$base<";
430 foreach my $t (@tmpl) {
432 my @t = eval { unpack("$t*", pack("$t*", 12, 34)) };
434 skip "cannot pack '$t' on this perl", 4
435 if is_valid_error($@);
437 is( $@, '', "Template $t works");
449 # Note that first uuencoding known 'text' data and then checking the
450 # binary values of the uuencoded version would not be portable between
451 # character sets. Uuencoding is meant for encoding binary data, not
454 my $in = pack 'C*', 0 .. 255;
456 # just to be anal, we do some random tr/`/ /
458 M` $"`P0%!@<("0H+# T.#Q`1$A,4%187&!D:&QP='A\@(2(C)"4F)R@I*BLL
459 M+2XO,#$R,S0U-C<X.3H[/#T^/T!!0D-$149'2$E*2TQ-3D]045)35%565UA9
460 M6EM<75Y?8&%B8V1E9F=H:6IK;&UN;W!Q<G-T=79W>'EZ>WQ]?G^`@8*#A(6&
461 MAXB)BHN,C8Z/D)&2DY25EI>8F9J;G)V>GZ"AHJ.DI::GJ*FJJZRMKJ^PL;*S
462 MM+6VM[BYNKN\O;Z_P,'"P\3%QL?(R<K+S,W.S]#1TM/4U=;7V-G:V]S=WM_@
463 ?X>+CY.7FY^CIZNOL[>[O\/'R\_3U]O?X^?K[_/W^_P `
469 is(pack('u', $in), $_);
471 is(unpack('u', $uu), $in);
473 $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";
475 M'XL("%C<Q#4"`TI!4%4`\RHM+E%(S,LOR4@M4@A(+<I1*"U-SD])+>("`&1F
479 is(unpack('u', $uu), $in);
481 # This is identical to the above except that backquotes have been
485 M'XL("%C<Q#4" TI!4%4 \RHM+E%(S,LOR4@M4@A(+<I1*"U-SD])+>(" &1F
490 is(unpack('u', $uu), $in);
494 # test the ascii template types (A, a, Z)
497 ['p', 'A*', "foo\0bar\0 ", "foo\0bar\0 "],
498 ['p', 'A11', "foo\0bar\0 ", "foo\0bar\0 "],
499 ['u', 'A*', "foo\0bar \0", "foo\0bar"],
500 ['u', 'A8', "foo\0bar \0", "foo\0bar"],
501 ['p', 'a*', "foo\0bar\0 ", "foo\0bar\0 "],
502 ['p', 'a11', "foo\0bar\0 ", "foo\0bar\0 \0\0"],
503 ['u', 'a*', "foo\0bar \0", "foo\0bar \0"],
504 ['u', 'a8', "foo\0bar \0", "foo\0bar "],
505 ['p', 'Z*', "foo\0bar\0 ", "foo\0bar\0 \0"],
506 ['p', 'Z11', "foo\0bar\0 ", "foo\0bar\0 \0\0"],
507 ['p', 'Z3', "foo", "fo\0"],
508 ['u', 'Z*', "foo\0bar \0", "foo"],
509 ['u', 'Z8', "foo\0bar \0", "foo"],
512 my ($what, $template, $in, $out) = @$_;
513 my $got = $what eq 'u' ? (unpack $template, $in) : (pack $template, $in);
514 unless (is($got, $out)) {
515 my $un = $what eq 'u' ? 'un' : '';
516 print "# ${un}pack ('$template', "._qq($in).') gave '._qq($out).
517 ' not '._qq($got)."\n";
521 print "# packing native shorts/ints/longs\n";
523 is(length(pack("s!", 0)), $Config{shortsize});
524 is(length(pack("i!", 0)), $Config{intsize});
525 is(length(pack("l!", 0)), $Config{longsize});
526 ok(length(pack("s!", 0)) <= length(pack("i!", 0)));
527 ok(length(pack("i!", 0)) <= length(pack("l!", 0)));
528 is(length(pack("i!", 0)), length(pack("i", 0)));
532 my @formats = ($base);
533 $base =~ /^[silqjfdp]/i and push @formats, "$base>", "$base<";
534 for my $format (@formats) {
535 numbers_with_total ($format, undef, @_);
539 sub numbers_with_total {
542 if (!defined $total) {
547 print "# numbers test for $format\n";
550 my $out = eval {unpack($format, pack($format, $_))};
551 skip "cannot pack '$format' on this perl", 2
552 if is_valid_error($@);
554 is($@, '', "no error");
555 is($out, $_, "unpack pack $format $_");
559 my $skip_if_longer_than = ~0; # "Infinity"
561 # If we're running with -DNO_PERLPRESERVE_IVUV and NVs don't preserve all
562 # UVs (in which case ~0 is NV, ~0-1 will be the same NV) then we can't
563 # correctly in perl calculate UV totals for long checksums, as pp_unpack
564 # is using UV maths, and we've only got NVs.
565 $skip_if_longer_than = $Config{nv_preserves_uv_bits};
568 foreach ('', 1, 2, 3, 15, 16, 17, 31, 32, 33, 53, 54, 63, 64, 65) {
570 my $sum = eval {unpack "%$_$format*", pack "$format*", @_};
571 skip "cannot pack '$format' on this perl", 3
572 if is_valid_error($@);
574 is($@, '', "no error");
575 ok(defined $sum, "sum bits $_, format $format defined");
577 my $len = $_; # Copy, so that we can reassign ''
578 $len = 16 unless length $len;
581 skip "cannot test checksums over $skip_if_longer_than bits", 1
582 if $len > $skip_if_longer_than;
584 # Our problem with testing this portably is that the checksum code in
585 # pp_unpack is able to cast signed to unsigned, and do modulo 2**n
586 # arithmetic in unsigned ints, which perl has no operators to do.
587 # (use integer; does signed ints, which won't wrap on UTS, which is just
588 # fine with ANSI, but not with most people's assumptions.
589 # This is why we need to supply the totals for 'Q' as there's no way in
590 # perl to calculate them, short of unpack '%0Q' (is that documented?)
591 # ** returns NVs; make sure it's IV.
592 my $max = 1 + 2 * (int (2 ** ($len-1))-1); # The max possible checksum
593 my $max_p1 = $max + 1;
594 my ($max_is_integer, $max_p1_is_integer);
595 $max_p1_is_integer = 1 unless $max_p1 + 1 == $max_p1;
596 $max_is_integer = 1 if $max - 1 < ~0;
600 $calc_sum = &$total($len);
603 # Shift into range by some multiple of the total
604 my $mult = $max_p1 ? int ($total / $max_p1) : undef;
605 # Need this to make sure that -1 + (~0+1) is ~0 (ie still integer)
606 $calc_sum = $total - $mult;
607 $calc_sum -= $mult * $max;
613 if ($calc_sum == $calc_sum - 1 && $calc_sum == $max_p1) {
614 # we're into floating point (either by getting out of the range of
615 # UV arithmetic, or because we're doing a floating point checksum)
616 # and our calculation of the checksum has become rounded up to
621 if ($calc_sum == $sum) { # HAS to be ==, not eq (so no is()).
622 pass ("unpack '%$_$format' gave $sum");
624 my $delta = 1.000001;
625 if ($format =~ tr /dDfF//
626 && ($calc_sum <= $sum * $delta && $calc_sum >= $sum / $delta)) {
627 pass ("unpack '%$_$format' gave $sum, expected $calc_sum");
629 my $text = ref $total ? &$total($len) : $total;
631 print "# For list (" . join (", ", @_) . ") (total $text)"
632 . " packed with $format unpack '%$_$format' gave $sum,"
633 . " expected $calc_sum\n";
641 numbers ('c', -128, -1, 0, 1, 127);
642 numbers ('C', 0, 1, 127, 128, 255);
643 numbers ('W', 0, 1, 127, 128, 255, 256, 0x7ff, 0x800, 0xfffd);
644 numbers ('s', -32768, -1, 0, 1, 32767);
645 numbers ('S', 0, 1, 32767, 32768, 65535);
646 numbers ('i', -2147483648, -1, 0, 1, 2147483647);
647 numbers ('I', 0, 1, 2147483647, 2147483648, 4294967295);
648 numbers ('l', -2147483648, -1, 0, 1, 2147483647);
649 numbers ('L', 0, 1, 2147483647, 2147483648, 4294967295);
650 numbers ('s!', -32768, -1, 0, 1, 32767);
651 numbers ('S!', 0, 1, 32767, 32768, 65535);
652 numbers ('i!', -2147483648, -1, 0, 1, 2147483647);
653 numbers ('I!', 0, 1, 2147483647, 2147483648, 4294967295);
654 numbers ('l!', -2147483648, -1, 0, 1, 2147483647);
655 numbers ('L!', 0, 1, 2147483647, 2147483648, 4294967295);
656 numbers ('n', 0, 1, 32767, 32768, 65535);
657 numbers ('v', 0, 1, 32767, 32768, 65535);
658 numbers ('N', 0, 1, 2147483647, 2147483648, 4294967295);
659 numbers ('V', 0, 1, 2147483647, 2147483648, 4294967295);
660 numbers ('n!', -32768, -1, 0, 1, 32767);
661 numbers ('v!', -32768, -1, 0, 1, 32767);
662 numbers ('N!', -2147483648, -1, 0, 1, 2147483647);
663 numbers ('V!', -2147483648, -1, 0, 1, 2147483647);
664 # All these should have exact binary representations:
665 numbers ('f', -1, 0, 0.5, 42, 2**34);
666 numbers ('d', -(2**34), -1, 0, 1, 2**34);
667 ## These don't, but 'd' is NV. XXX wrong, it's double
668 #numbers ('d', -1, 0, 1, 1-exp(-1), -exp(1));
670 numbers_with_total ('q', -1,
671 -9223372036854775808, -1, 0, 1,9223372036854775807);
672 # This total is icky, but the true total is 2**65-1, and need a way to generate
673 # the epxected checksum on any system including those where NVs can preserve
674 # 65 bits. (long double is 128 bits on sparc, so they certainly can)
675 # or where rounding is down not up on binary conversion (crays)
676 numbers_with_total ('Q', sub {
678 $len = 65 if $len > 65; # unmasked total is 2**65-1 here
679 my $total = 1 + 2 * (int (2**($len - 1)) - 1);
680 return 0 if $total == $total - 1; # Overflowed integers
681 return $total; # NVs still accurate to nearest integer
683 0, 1,9223372036854775807, 9223372036854775808,
684 18446744073709551615);
686 print "# pack nvNV byteorders\n";
688 is(pack("n", 0xdead), "\xde\xad");
689 is(pack("v", 0xdead), "\xad\xde");
690 is(pack("N", 0xdeadbeef), "\xde\xad\xbe\xef");
691 is(pack("V", 0xdeadbeef), "\xef\xbe\xad\xde");
694 skip $no_signedness, 4 if $no_signedness;
695 is(pack("n!", 0xdead), "\xde\xad");
696 is(pack("v!", 0xdead), "\xad\xde");
697 is(pack("N!", 0xdeadbeef), "\xde\xad\xbe\xef");
698 is(pack("V!", 0xdeadbeef), "\xef\xbe\xad\xde");
701 print "# test big-/little-endian conversion\n";
706 print "# byteorder test for $format\n";
709 my($nat,$be,$le) = eval { map { pack $format.$_, $value } '', '>', '<' };
710 skip "cannot pack '$format' on this perl", 5
711 if is_valid_error($@);
713 print "# [$value][$nat][$be][$le][$@]\n";
716 skip "cannot compare native byteorder with big-/little-endian", 1
717 if $ByteOrder eq 'unknown';
719 is($nat, $ByteOrder eq 'big' ? $be : $le);
721 is($be, reverse($le));
722 my @x = eval { unpack "$format$format>$format<", $nat.$be.$le };
724 print "# [$value][", join('][', @x), "][$@]\n";
733 byteorder('s', -32768, -1, 0, 1, 32767);
734 byteorder('S', 0, 1, 32767, 32768, 65535);
735 byteorder('i', -2147483648, -1, 0, 1, 2147483647);
736 byteorder('I', 0, 1, 2147483647, 2147483648, 4294967295);
737 byteorder('l', -2147483648, -1, 0, 1, 2147483647);
738 byteorder('L', 0, 1, 2147483647, 2147483648, 4294967295);
739 byteorder('j', -2147483648, -1, 0, 1, 2147483647);
740 byteorder('J', 0, 1, 2147483647, 2147483648, 4294967295);
741 byteorder('s!', -32768, -1, 0, 1, 32767);
742 byteorder('S!', 0, 1, 32767, 32768, 65535);
743 byteorder('i!', -2147483648, -1, 0, 1, 2147483647);
744 byteorder('I!', 0, 1, 2147483647, 2147483648, 4294967295);
745 byteorder('l!', -2147483648, -1, 0, 1, 2147483647);
746 byteorder('L!', 0, 1, 2147483647, 2147483648, 4294967295);
747 byteorder('q', -9223372036854775808, -1, 0, 1, 9223372036854775807);
748 byteorder('Q', 0, 1, 9223372036854775807, 9223372036854775808, 18446744073709551615);
749 byteorder('f', -1, 0, 0.5, 42, 2**34);
750 byteorder('F', -1, 0, 0.5, 42, 2**34);
751 byteorder('d', -(2**34), -1, 0, 1, 2**34);
752 byteorder('D', -(2**34), -1, 0, 1, 2**34);
754 print "# test negative numbers\n";
757 skip "platform is not using two's complement for negative integers", 120
758 unless $IsTwosComplement;
760 for my $format (qw(s i l j s! i! l! q)) {
762 my($nat,$be,$le) = eval { map { pack $format.$_, -1 } '', '>', '<' };
763 skip "cannot pack '$format' on this perl", 15
764 if is_valid_error($@);
766 my $len = length $nat;
767 is($_, "\xFF"x$len) for $nat, $be, $le;
771 @val = (-2, -81985529216486896, -9223372036854775808);
772 @ref = ("\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFE",
773 "\xFE\xDC\xBA\x98\x76\x54\x32\x10",
774 "\x80\x00\x00\x00\x00\x00\x00\x00");
777 @val = (-2, -19088744, -2147483648);
778 @ref = ("\xFF\xFF\xFF\xFE",
783 @val = (-2, -292, -32768);
789 if ($len > length $x) {
790 $x = $x . "\xFF" x ($len - length $x);
794 for my $i (0 .. $#val) {
795 my($nat,$be,$le) = eval { map { pack $format.$_, $val[$i] } '', '>', '<' };
799 skip "cannot compare native byteorder with big-/little-endian", 1
800 if $ByteOrder eq 'unknown';
802 is($nat, $ByteOrder eq 'big' ? $be : $le);
806 is($be, reverse($le));
816 eval { ($x) = unpack '/a*','hello' };
817 like($@, qr!'/' must follow a numeric type!);
819 eval { $x = unpack '/a*','hello' };
820 like($@, qr!'/' must follow a numeric type!);
823 eval { ($z,$x,$y) = unpack 'a3/A C/a* C/Z', "003ok \003yes\004z\000abc" };
829 eval { $z = unpack 'a3/A C/a* C/Z', "003ok \003yes\004z\000abc" };
835 eval { ($x) = pack '/a*','hello' };
836 like($@, qr!Invalid type '/'!);
838 eval { $x = pack '/a*','hello' };
839 like($@, qr!Invalid type '/'!);
841 $z = pack 'n/a* N/Z* w/A*','string','hi there ','etc';
842 my $expect = "\000\006string\0\0\0\012hi there \000\003etc";
846 $expect = 'hello world';
847 eval { ($x) = unpack ("w/a", chr (11) . "hello world!")};
852 # Doing this in scalar context used to fail.
853 eval { $x = unpack ("w/a", chr (11) . "hello world!")};
858 ['a/a*/a*', '212ab345678901234567','ab3456789012'],
859 ['a/a*/a*', '3012ab345678901234567', 'ab3456789012'],
860 ['a/a*/b*', '212ab', $Is_EBCDIC ? '100000010100' : '100001100100'],
863 my ($pat, $in, $expect) = @$_;
865 eval { ($x) = unpack $pat, $in };
868 printf "# list unpack ('$pat', '$in') gave %s, expected '$expect'\n",
872 eval { $x = unpack $pat, $in };
875 printf "# scalar unpack ('$pat', '$in') gave %s, expected '$expect'\n",
881 my $pattern = <<'EOU';
882 a3/A # Count in ASCII
883 C/a* # Count in a C char
884 C/Z # Count in a C char but skip after \0
888 eval { ($z,$x,$y) = unpack $pattern, "003ok \003yes\004z\000abc" };
894 eval { $z = unpack $pattern, "003ok \003yes\004z\000abc" };
899 n/a* # Count as network short
900 w/A* # Count a BER integer
902 $expect = "\000\006string\003etc";
903 $z = pack $pattern,'string','etc';
909 skip("(EBCDIC and) version strings are bad idea", 2) if $Is_EBCDIC;
911 is("1.20.300.4000", sprintf "%vd", pack("U*",1,20,300,4000));
912 is("1.20.300.4000", sprintf "%vd", pack(" U*",1,20,300,4000));
914 isnt(v1.20.300.4000, sprintf "%vd", pack("C0U*",1,20,300,4000));
916 my $rslt = $Is_EBCDIC ? "156 67" : "199 162";
917 is(join(" ", unpack("C*", chr(0x1e2))), $rslt);
919 # does pack U create Unicode?
920 is(ord(pack('U', 300)), 300);
922 # does unpack U deref Unicode?
923 is((unpack('U', chr(300)))[0], 300);
925 # is unpack U the reverse of pack U for Unicode string?
926 is("@{[unpack('U*', pack('U*', 100, 200, 300))]}", "100 200 300");
928 # is unpack U the reverse of pack U for byte string?
929 is("@{[unpack('U*', pack('U*', 100, 200))]}", "100 200");
933 skip "Not for EBCDIC", 4 if $Is_EBCDIC;
935 # does unpack C unravel pack U?
936 is("@{[unpack('C*', pack('U*', 100, 200))]}", "100 195 136");
938 # does pack U0C create Unicode?
939 is("@{[pack('U0C*', 100, 195, 136)]}", v100.v200);
941 # does pack C0U create characters?
942 is("@{[pack('C0U*', 100, 200)]}", pack("C*", 100, 195, 136));
944 # does unpack U0U on byte data warn?
946 my $bad = pack("U0C", 255);
947 local $SIG{__WARN__} = sub { $@ = "@_" };
948 my @null = unpack('U0U', $bad);
949 like($@, qr/^Malformed UTF-8 character /);
954 my $p = pack 'i*', -2147483648, ~0, 0, 1, 2147483647;
956 # bug - % had to be at the start of the pattern, no leading whitespace or
957 # comments. %i! didn't work at all.
958 foreach my $pat ('%32i*', ' %32i*', "# Muhahahaha\n%32i*", '%32i* ',
959 '%32i!*', ' %32i!*', "\n#\n#\n\r \t\f%32i!*", '%32i!*#') {
960 @a = unpack $pat, $p;
961 is($a[0], 0xFFFFFFFF) || print "# $pat\n";
962 @a = scalar unpack $pat, $p;
963 is($a[0], 0xFFFFFFFF) || print "# $pat\n";
967 $p = pack 'I*', 42, 12;
968 # Multiline patterns in scalar context failed.
969 foreach my $pat ('I', <<EOPOEMSNIPPET, 'I#I', 'I # I', 'I # !!!') {
970 # On the Ning Nang Nong
971 # Where the Cows go Bong!
972 # And the Monkeys all say Boo!
975 @a = unpack $pat, $p;
978 @a = scalar unpack $pat, $p;
983 # shorts (of all flavours) didn't calculate checksums > 32 bits with floating
984 # point, so a pathologically long pattern would wrap at 32 bits.
985 my $pat = "\xff\xff"x65538; # Start with it long, to save any copying.
986 foreach (4,3,2,1,0) {
987 my $len = 65534 + $_;
988 is(unpack ("%33n$len", $pat), 65535 * $len);
998 ['xXa*', "Nick", "Nick"],
999 ['a5Xa5', "cameL", "llama", "camellama"],
1000 ['@4', 'N', "\0"x4],
1001 ['a*@8a*', 'Camel', 'Dromedary', "Camel\0\0\0Dromedary"],
1002 ['a*@4a', 'Perl rules', '!', 'Perl!'],
1005 my ($template, @in) = @$_;
1007 my $got = eval {pack $template, @in};
1010 printf "# pack ('$template', %s) gave %s expected %s\n",
1011 encode_list (@in), encode_list ($got), encode_list ($out);
1018 ['xXa*', "Nick", "Nick"],
1019 ['a5Xa5', "camellama", "camel", "llama"],
1021 ['@2a2', "water", "te"],
1022 ['a*@1a3', "steam", "steam", "tea"],
1025 my ($template, $in, @out) = @$_;
1026 my @got = eval {unpack $template, $in};
1028 ok (list_eq (\@got, \@out)) ||
1029 printf "# list unpack ('$template', %s) gave %s expected %s\n",
1030 _qq($in), encode_list (@got), encode_list (@out);
1032 my $got = eval {unpack $template, $in};
1034 @out ? is( $got, $out[0] ) # 1 or more items; should get first
1035 : ok( !defined $got ) # 0 items; should get undef
1036 or printf "# scalar unpack ('$template', %s) gave %s expected %s\n",
1037 _qq($in), encode_list ($got), encode_list ($out[0]);
1042 my ($u, $v) = qw(foo xyzzy);
1043 my $p = pack($t, $u, $v);
1044 my @u = unpack($t, $p);
1051 is((unpack("w/a*", "\x02abc"))[0], "ab");
1053 # "w/a*" should be seen as one unit
1055 is(scalar unpack("w/a*", "\x02abc"), "ab");
1059 print "# group modifiers\n";
1061 skip $no_endianness, 3 * 2 + 3 * 2 + 1 if $no_endianness;
1063 for my $t (qw{ (s<)< (sl>s)> (s(l(sl)<l)s)< }) {
1064 print "# testing pattern '$t'\n";
1065 eval { ($_) = unpack($t, 'x'x18); };
1067 eval { $_ = pack($t, (0)x6); };
1071 for my $t (qw{ (s<)> (sl>s)< (s(l(sl)<l)s)> }) {
1072 print "# testing pattern '$t'\n";
1073 eval { ($_) = unpack($t, 'x'x18); };
1074 like($@, qr/Can't use '[<>]' in a group with different byte-order in unpack/);
1075 eval { $_ = pack($t, (0)x6); };
1076 like($@, qr/Can't use '[<>]' in a group with different byte-order in pack/);
1079 is(pack('L<L>', (0x12345678)x2),
1080 pack('(((L1)1)<)(((L)1)1)>1', (0x12345678)x2));
1084 sub compress_template {
1086 for my $mod (qw( < > )) {
1087 $t =~ s/((?:(?:[SILQJFDP]!?$mod|[^SILQJFDP\W]!?)(?:\d+|\*|\[(?:[^]]+)\])?\/?){2,})/
1088 my $x = $1; $x =~ s!$mod!!g ? "($x)$mod" : $x /ieg;
1095 's<c2x![S]S<' => [-42, -11, 12, 4711],
1096 '(i<j<[s]l<)3' => [-11, -22, -33, 1000000, 1100, 2201, 3302,
1097 -1000000, 32767, -32768, 1, -123456789 ],
1098 '(I!<4(J<2L<)3)5' => [1 .. 65],
1099 'q<Q<' => [-50000000005, 60000000006],
1100 'f<F<d<' => [3.14159, 111.11, 2222.22],
1101 'D<cCD<' => [1e42, -128, 255, 1e-42],
1102 'n/a*' => ['/usr/bin/perl'],
1103 'C/a*S</A*L</Z*I</a*' => [qw(Just another Perl hacker)],
1106 for my $tle (sort keys %templates) {
1107 my @d = @{$templates{$tle}};
1110 for my $t ($tbe, $tle) {
1111 my $c = compress_template($t);
1112 print "# '$t' -> '$c'\n";
1114 my $p1 = eval { pack $t, @d };
1115 skip "cannot pack '$t' on this perl", 5 if is_valid_error($@);
1116 my $p2 = eval { pack $c, @d };
1119 s!(/[aAZ])\*!$1!g for $t, $c;
1120 my @u1 = eval { unpack $t, $p1 };
1122 my @u2 = eval { unpack $c, $p2 };
1124 is(join('!', @u1), join('!', @u2));
1131 # from Wolfgang Laun: fix in change #13163
1136 my $buf = pack( 'Z*/A* C', $s, $x );
1140 $h =~ s/[^[:print:]]/./g;
1141 ( $s, $y ) = unpack( "Z*/A* C", $buf );
1142 is($h, "30.ABCABCABCABCABCABCABCABCABCABC$t");
1143 is(length $buf, 34);
1144 is($s, "ABCABCABCABCABCABCABCABCABCABC");
1149 # from Wolfgang Laun: fix in change #13288
1151 eval { my $t=unpack("P*", "abc") };
1152 like($@, qr/'P' must have an explicit size/);
1155 { # Grouping constructs
1157 @a = unpack '(SL)', pack 'SLSLSL', 67..90;
1159 @a = unpack '(SL)3', pack 'SLSLSL', 67..90;
1162 @a = unpack '(SL)3', pack 'SLSLSLSL', 67..90;
1164 @a = unpack '(SL)[3]', pack 'SLSLSLSL', 67..90;
1166 @a = unpack '(SL)[2] SL', pack 'SLSLSLSL', 67..90;
1168 @a = unpack 'A/(SL)', pack 'ASLSLSLSL', 3, 67..90;
1170 @a = unpack 'A/(SL)SL', pack 'ASLSLSLSL', 2, 67..90;
1172 @a = unpack '(SL)*', pack 'SLSLSLSL', 67..90;
1175 @a = unpack '(SL)*SL', pack 'SLSLSLSL', 67..90;
1177 eval { @a = unpack '(*SL)', '' };
1178 like($@, qr/\(\)-group starts with a count/);
1179 eval { @a = unpack '(3SL)', '' };
1180 like($@, qr/\(\)-group starts with a count/);
1181 eval { @a = unpack '([3]SL)', '' };
1182 like($@, qr/\(\)-group starts with a count/);
1183 eval { @a = pack '(*SL)' };
1184 like($@, qr/\(\)-group starts with a count/);
1185 @a = unpack '(SL)3 SL', pack '(SL)4', 67..74;
1187 @a = unpack '(SL)3 SL', pack '(SL)[4]', 67..74;
1189 @a = unpack '(SL)3 SL', pack '(SL)*', 67..74;
1193 { # more on grouping (W.Laun)
1196 local $SIG{__WARN__} = sub {
1199 # @ absolute within ()-group
1200 my $badc = pack( '(a)*', unpack( '(@1a @0a @2)*', 'abcd' ) );
1201 is( $badc, 'badc' );
1202 my @b = ( 1, 2, 3 );
1203 my $buf = pack( '(@1c)((@2C)@3c)', @b );
1204 is( $buf, "\0\1\0\0\2\3" );
1205 my @a = unpack( '(@1c)((@2c)@3c)', $buf );
1208 # various unpack count/code scenarios
1209 my @Env = ( a => 'AAA', b => 'BBB' );
1210 my $env = pack( 'S(S/A*S/A*)*', @Env/2, @Env );
1212 # unpack full length - ok
1213 my @pup = unpack( 'S/(S/A* S/A*)', $env );
1214 is( "@pup", "@Env" );
1216 # warn when count/code goes beyond end of string
1217 # \0002 \0001 a \0003 AAA \0001 b \0003 BBB
1219 eval { @pup = unpack( 'S/(S/A* S/A*)', substr( $env, 0, 13 ) ) };
1220 like( $@, qr{length/code after end of string} );
1222 # postfix repeat count
1223 $env = pack( '(S/A* S/A*)' . @Env/2, @Env );
1225 # warn when count/code goes beyond end of string
1226 # \0001 a \0003 AAA \0001 b \0003 BBB
1227 # 2 3c 5 8 10 11 13 16
1228 eval { @pup = unpack( '(S/A* S/A*)' . @Env/2, substr( $env, 0, 11 ) ) };
1229 like( $@, qr{length/code after end of string} );
1231 # catch stack overflow/segfault
1232 eval { $_ = pack( ('(' x 105) . 'A' . (')' x 105) ); };
1233 like( $@, qr{Too deeply nested \(\)-groups} );
1236 { # syntax checks (W.Laun)
1239 local $SIG{__WARN__} = sub {
1240 push( @warning, $_[0] );
1242 eval { my $s = pack( 'Ax![4c]A', 1..5 ); };
1243 like( $@, qr{Malformed integer in \[\]} );
1245 eval { my $buf = pack( '(c/*a*)', 'AAA', 'BB' ); };
1246 like( $@, qr{'/' does not take a repeat count} );
1248 eval { my @inf = unpack( 'c/1a', "\x03AAA\x02BB" ); };
1249 like( $@, qr{'/' does not take a repeat count} );
1251 eval { my @inf = unpack( 'c/*a', "\x03AAA\x02BB" ); };
1252 like( $@, qr{'/' does not take a repeat count} );
1254 # white space where possible
1255 my @Env = ( a => 'AAA', b => 'BBB' );
1256 my $env = pack( ' S ( S / A* S / A* )* ', @Env/2, @Env );
1257 my @pup = unpack( ' S / ( S / A* S / A* ) ', $env );
1258 is( "@pup", "@Env" );
1260 # white space in 4 wrong places
1261 for my $temp ( 'A ![4]', 'A [4]', 'A *', 'A 4' ){
1262 eval { my $s = pack( $temp, 'B' ); };
1263 like( $@, qr{Invalid type } );
1266 # warning for commas
1268 my $x = pack( 'I,A', 4, 'X' );
1269 like( $warning[0], qr{Invalid type ','} );
1271 # comma warning only once
1273 $x = pack( 'C(C,C)C,C', 65..71 );
1274 like( scalar @warning, 1 );
1276 # forbidden code in []
1277 eval { my $x = pack( 'A[@4]', 'XXXX' ); };
1278 like( $@, qr{Within \[\]-length '\@' not allowed} );
1280 # @ repeat default 1
1281 my $s = pack( 'AA@A', 'A', 'B', 'C' );
1282 my @c = unpack( 'AA@A', $s );
1284 is( "@c", "A C C" );
1286 # no unpack code after /
1287 eval { my @a = unpack( "C/", "\3" ); };
1288 like( $@, qr{Code missing after '/'} );
1291 skip $no_endianness, 6 if $no_endianness;
1295 $x = pack "I>>s!!", 47, 11;
1296 ($x) = unpack "I<<l!>!>", 'x'x20;
1297 is(scalar @warning, 5);
1298 like($warning[0], qr/Duplicate modifier '>' after 'I' in pack/);
1299 like($warning[1], qr/Duplicate modifier '!' after 's' in pack/);
1300 like($warning[2], qr/Duplicate modifier '<' after 'I' in unpack/);
1301 like($warning[3], qr/Duplicate modifier '!' after 'l' in unpack/);
1302 like($warning[4], qr/Duplicate modifier '>' after 'l' in unpack/);
1306 { # Repeat count [SUBEXPR]
1307 my @codes = qw( x A Z a c C W B b H h s v n S i I l V N L p P f F d
1308 s! S! i! I! l! L! j J);
1310 if (eval { pack 'q', 1 } ) {
1311 push @codes, qw(q Q);
1313 push @codes, qw(s S); # Keep the count the same
1315 if (eval { pack 'D', 1 } ) {
1318 push @codes, 'd'; # Keep the count the same
1321 push @codes, map { /^[silqjfdp]/i ? ("$_<", "$_>") : () } @codes;
1324 @val{@codes} = map { / [Xx] (?{ undef })
1325 | [AZa] (?{ 'something' })
1331 | [svnSiIlVNLqQjJ] (?{ 10111 })
1332 | [FfDd] (?{ 1.36514538e67 })
1333 | [pP] (?{ "try this buffer" })
1335 my @end = (0x12345678, 0x23456781, 0x35465768, 0x15263748);
1338 for my $type (@codes) {
1339 my @list = $val{$type};
1340 @list = () unless defined $list[0];
1341 for my $count ('', '3', '[11]') {
1343 $c = $1 if $count =~ /(\d+)/;
1345 @list1 = (@list1) x $c unless $type =~ /[XxAaZBbHhP]/;
1346 for my $groupend ('', ')2', ')[8]') {
1347 my $groupbegin = ($groupend ? '(' : '');
1349 $c = $1 if $groupend =~ /(\d+)/;
1350 my @list2 = (@list1) x $c;
1353 my $junk1 = "$groupbegin $type$count $groupend";
1354 # print "# junk1=$junk1\n";
1355 my $p = eval { pack $junk1, @list2 };
1356 skip "cannot pack '$type' on this perl", 12
1357 if is_valid_error($@);
1359 my $half = int( (length $p)/2 );
1360 for my $move ('', "X$half", "X!$half", 'x1', 'x!8', "x$half") {
1361 my $junk = "$junk1 $move";
1362 # print "# junk='$junk', list=(@list2)\n";
1363 $p = pack "$junk $end", @list2, @end;
1364 my @l = unpack "x[$junk] $end", $p;
1365 is(scalar @l, scalar @end);
1366 is("@l", "@end", "skipping x[$junk]");
1374 # / is recognized after spaces in scalar context
1375 # XXXX no spaces are allowed in pack... In pack only before the slash...
1376 is(scalar unpack('A /A Z20', pack 'A/A* Z20', 'bcde', 'xxxxx'), 'bcde');
1377 is(scalar unpack('A /A /A Z20', '3004bcde'), 'bcde');
1380 my $t = 'C[3] x!8 C[2]';
1381 my @a = (0x73..0x77);
1382 my $p = pack($t, @a);
1383 is($p, "\x73\x74\x75\0\0\0\0\0\x76\x77");
1384 my @b = unpack $t, $p;
1385 is(scalar @b, scalar @a);
1386 is("@b", "@a", 'x!8');
1387 $t = 'x[5] C[6] X!8 C[2]';
1390 is($p, "\0\0\0\0\0\x73\x74\x75\x79\x7a");
1392 @a = (0x73..0x75, 0x79, 0x7a, 0x79, 0x7a);
1393 is(scalar @b, scalar @a);
1397 { # struct {char c1; double d; char cc[2];}
1398 my $t = 'C x![d] d C[2]';
1399 my @a = (173, 1.283476517e-45, 42, 215);
1400 my $p = pack $t, @a;
1402 my @b = unpack "$t X[$t] $t", $p; # Extract, step back, extract again
1403 is(scalar @b, 2 * scalar @a);
1405 $b =~ s/(?:17000+|16999+)\d+(e-45) /17$1 /gi; # stringification is gamble
1409 local $SIG{__WARN__} = sub {
1412 @b = unpack "x[C] x[$t] X[$t] X[C] $t", "$p\0";
1414 is($warning, undef);
1415 is(scalar @b, scalar @a);
1417 $b =~ s/(?:17000+|16999+)\d+(e-45) /17$1 /gi; # stringification is gamble
1421 is(length(pack("j", 0)), $Config{ivsize});
1422 is(length(pack("J", 0)), $Config{uvsize});
1423 is(length(pack("F", 0)), $Config{nvsize});
1425 numbers ('j', -2147483648, -1, 0, 1, 2147483647);
1426 numbers ('J', 0, 1, 2147483647, 2147483648, 4294967295);
1427 numbers ('F', -(2**34), -1, 0, 1, 2**34);
1429 my $t = eval { unpack("D*", pack("D", 12.34)) };
1431 skip "Long doubles not in use", 166 if $@ =~ /Invalid type/;
1433 is(length(pack("D", 0)), $Config{longdblsize});
1434 numbers ('D', -(2**34), -1, 0, 1, 2**34);
1437 # Maybe this knowledge needs to be "global" for all of pack.t
1438 # Or a "can checksum" which would effectively be all the number types"
1439 my %cant_checksum = map {$_=> 1} qw(A Z u w);
1441 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)) {
1443 my $packed = eval {pack "${template}4", 1, 4, 9, 16};
1445 die unless $@ =~ /Invalid type '$template'/;
1446 skip ("$template not supported on this perl",
1447 $cant_checksum{$template} ? 4 : 8);
1449 my @unpack4 = unpack "${template}4", $packed;
1450 my @unpack = unpack "${template}*", $packed;
1451 my @unpack1 = unpack "${template}", $packed;
1452 my @unpack1s = scalar unpack "${template}", $packed;
1453 my @unpack4s = scalar unpack "${template}4", $packed;
1454 my @unpacks = scalar unpack "${template}*", $packed;
1456 my @tests = ( ["${template}4 vs ${template}*", \@unpack4, \@unpack],
1457 ["scalar ${template} ${template}", \@unpack1s, \@unpack1],
1458 ["scalar ${template}4 vs ${template}", \@unpack4s, \@unpack1],
1459 ["scalar ${template}* vs ${template}", \@unpacks, \@unpack1],
1462 unless ($cant_checksum{$template}) {
1463 my @unpack4_c = unpack "\%${template}4", $packed;
1464 my @unpack_c = unpack "\%${template}*", $packed;
1465 my @unpack1_c = unpack "\%${template}", $packed;
1466 my @unpack1s_c = scalar unpack "\%${template}", $packed;
1467 my @unpack4s_c = scalar unpack "\%${template}4", $packed;
1468 my @unpacks_c = scalar unpack "\%${template}*", $packed;
1471 ( ["% ${template}4 vs ${template}*", \@unpack4_c, \@unpack_c],
1472 ["% scalar ${template} ${template}", \@unpack1s_c, \@unpack1_c],
1473 ["% scalar ${template}4 vs ${template}*", \@unpack4s_c, \@unpack_c],
1474 ["% scalar ${template}* vs ${template}*", \@unpacks_c, \@unpack_c],
1477 foreach my $test (@tests) {
1478 ok (list_eq ($test->[1], $test->[2]), $test->[0]) ||
1479 printf "# unpack gave %s expected %s\n",
1480 encode_list (@{$test->[1]}), encode_list (@{$test->[2]});
1485 ok(pack('u2', 'AA'), "[perl #8026]"); # used to hang and eat RAM in perl 5.7.2
1487 $_ = pack('c', 65); # 'A' would not be EBCDIC-friendly
1488 is(unpack('c'), 65, "one-arg unpack (change #18751)"); # defaulting to $_
1491 my $a = "X\t01234567\n" x 100;
1492 my @a = unpack("(a1 c/a)*", $a);
1493 is(scalar @a, 200, "[perl #15288]");
1494 is($a[-1], "01234567\n", "[perl #15288]");
1495 is($a[-2], "X", "[perl #15288]");
1500 # verify that unpack advances correctly wrt a checksum
1501 my (@x) = unpack("b10a", "abcd");
1502 my (@y) = unpack("%b10a", "abcd");
1503 is($x[1], $y[1], "checksum advance ok");
1505 # verify that the checksum is not overflowed with C0
1506 is(unpack("C0%128U", "abcd"), unpack("U0%128U", "abcd"), "checksum not overflowed");
1510 # U0 and C0 must be scoped
1511 my (@x) = unpack("a(U0)U", "b\341\277\274");
1512 is($x[0], 'b', 'before scope');
1513 is($x[1], 8188, 'after scope');
1515 is(pack("a(U0)U", "b", 8188), "b\341\277\274");
1519 # counted length prefixes shouldn't change C0/U0 mode
1520 # (note the length is actually 0 in this test)
1521 is(join(',', unpack("aC/UU", "b\0\341\277\274")), 'b,8188');
1522 is(join(',', unpack("aC/CU", "b\0\341\277\274")), 'b,8188');
1523 is(join(',', unpack("aU0C/UU", "b\0\341\277\274")), 'b,225');
1524 is(join(',', unpack("aU0C/CU", "b\0\341\277\274")), 'b,225');
1529 my (@x) = unpack("C*", pack("CZ0", 1, "b"));
1530 is(join(',', @x), '1', 'pack Z0 doesn\'t destroy the character before');
1534 # Encoding neutrality
1535 # String we will pull apart and rebuild in several ways:
1536 my $down = "\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff\x05\x06";
1542 # how many chars it should progress,
1543 # (optional) expected result of pack]
1544 (a5 => ["\xf8\xf9\xfa\xfb\xfc", 5],
1545 A5 => ["\xf8\xf9\xfa\xfb\xfc", 5],
1546 Z5 => ["\xf8\xf9\xfa\xfb\xfc", 5, "\xf8\xf9\xfa\xfb\x00\xfd"],
1547 b21 => ["000111111001111101011", 3, "\xf8\xf9\x1a\xfb"],
1548 B21 => ["111110001111100111111", 3, "\xf8\xf9\xf8\xfb"],
1549 H5 => ["f8f9f", 3, "\xf8\xf9\xf0\xfb"],
1550 h5 => ["8f9fa", 3, "\xf8\xf9\x0a\xfb"],
1553 "S<" => [0xf9f8, 2],
1554 "S>" => [0xf8f9, 2],
1555 "l<" => [-67438088, 4],
1556 "l>" => [-117835013, 4],
1557 "L>" => [0xf8f9fafb, 4],
1558 "L<" => [0xfbfaf9f8, 4],
1560 N => [0xf8f9fafb, 4],
1562 V => [0xfbfaf9f8, 4],
1565 w => ["8715569050387726213", 9],
1566 q => ["-283686952306184", 8],
1567 Q => ["18446460386757245432", 8],
1570 for my $string ($down, $up) {
1571 for my $format (sort {lc($a) cmp lc($b) || $a cmp $b } keys %expect) {
1573 my $expect = $expect{$format};
1574 # unpack upgraded and downgraded string
1575 my @result = eval { unpack("$format C0 W", $string) };
1576 skip "cannot pack/unpack '$format C0 W' on this perl", 5 if
1577 $@ && is_valid_error($@);
1578 is(@result, 2, "Two results from unpack $format C0 W");
1580 # pack to downgraded
1581 my $new = pack("$format C0 W", @result);
1582 is(length($new), $expect->[1]+1,
1583 "pack $format C0 W should give $expect->[1]+1 chars");
1584 is($new, $expect->[2] || substr($string, 0, length $new),
1585 "pack $format C0 W returns expected value");
1588 $new = pack("a0 $format C0 W", chr(256), @result);
1589 is(length($new), $expect->[1]+1,
1590 "pack a0 $format C0 W should give $expect->[1]+1 chars");
1591 is($new, $expect->[2] || substr($string, 0, length $new),
1592 "pack a0 $format C0 W returns expected value");
1599 # Encoding neutrality, numbers
1601 for my $format (qw(s S i I l L j J f d F D q Q
1602 s! S! i! I! l! L! n! N! v! V!)) {
1604 my $down = eval { pack($format, $val) };
1605 skip "cannot pack/unpack $format on this perl", 9 if
1606 $@ && is_valid_error($@);
1607 ok(!utf8::is_utf8($down), "Simple $format pack doesn't get upgraded");
1608 my $up = pack("a0 $format", chr(256), $val);
1609 ok(utf8::is_utf8($up), "a0 $format with high char leads to upgrade");
1610 is($down, $up, "$format generated strings are equal though");
1611 my @down_expanded = unpack("$format W", $down . chr(0xce));
1612 is(@down_expanded, 2, "Expand to two values");
1613 is($down_expanded[1], 0xce,
1614 "unpack $format left us at the expected position");
1615 my @up_expanded = unpack("$format W", $up . chr(0xce));
1616 is(@up_expanded, 2, "Expand to two values");
1617 is($up_expanded[1], 0xce,
1618 "unpack $format left us at the expected position");
1619 is($down_expanded[0], $up_expanded[0], "$format unpack was neutral");
1620 is(pack($format, $down_expanded[0]), $down, "Pack $format undoes unpack $format");
1626 # C is *not* neutral
1627 my $down = "\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff\x05\x06";
1630 my @down = unpack("C*", $down);
1631 my @expect_down = (0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff, 0x05, 0x06);
1632 is("@down", "@expect_down", "byte expand");
1633 is(pack("C*", @down), $down, "byte join");
1635 my @up = unpack("C*", $up);
1636 my @expect_up = (0xc3, 0xb8, 0xc3, 0xb9, 0xc3, 0xba, 0xc3, 0xbb, 0xc3, 0xbc, 0xc3, 0xbd, 0xc3, 0xbe, 0xc3, 0xbf, 0x05, 0x06);
1637 is("@up", "@expect_up", "UTF-8 expand");
1638 is(pack("U0C0C*", @up), $up, "UTF-8 join");
1642 # Harder cases for the neutrality test
1645 my $down = "\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff\x05\x06";
1648 is(pack("u", $down), pack("u", $up), "u pack is neutral");
1649 is(unpack("u", pack("u", $down)), $down, "u unpack to downgraded works");
1650 is(unpack("U0C0u", pack("u", $down)), $up, "u unpack to upgraded works");
1653 # This actually only tests something if the address contains a byte >= 0x80
1654 my $str = "abc\xa5\x00\xfede";
1655 $down = pack("p", $str);
1656 is(pack("P", $str), $down);
1657 is(pack("U0C0p", $str), $down);
1658 is(pack("U0C0P", $str), $down);
1659 is(unpack("p", $down), "abc\xa5", "unpack p downgraded");
1662 is(unpack("p", $up), "abc\xa5", "unpack p upgraded");
1664 is(unpack("P7", $down), "abc\xa5\x00\xfed", "unpack P downgraded");
1665 is(unpack("P7", $up), "abc\xa5\x00\xfed", "unpack P upgraded");
1668 $down = "\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff\x05\x06";
1672 is(unpack('@4W', $down), 0xfc, "\@positioning on downgraded string");
1673 is(unpack('@4W', $up), 0xfc, "\@positioning on upgraded string");
1675 is(unpack('@4x2W', $down), 0xfe, "x moving on downgraded string");
1676 is(unpack('@4x2W', $up), 0xfe, "x moving on upgraded string");
1677 is(unpack('@4x!4W', $down), 0xfc, "x! moving on downgraded string");
1678 is(unpack('@4x!4W', $up), 0xfc, "x! moving on upgraded string");
1679 is(unpack('@5x!4W', $down), 0x05, "x! moving on downgraded string");
1680 is(unpack('@5x!4W', $up), 0x05, "x! moving on upgraded string");
1682 is(unpack('@4X2W', $down), 0xfa, "X moving on downgraded string");
1683 is(unpack('@4X2W', $up), 0xfa, "X moving on upgraded string");
1684 is(unpack('@4X!4W', $down), 0xfc, "X! moving on downgraded string");
1685 is(unpack('@4X!4W', $up), 0xfc, "X! moving on upgraded string");
1686 is(unpack('@5X!4W', $down), 0xfc, "X! moving on downgraded string");
1687 is(unpack('@5X!4W', $up), 0xfc, "X! moving on upgraded string");
1688 is(unpack('@5X!8W', $down), 0xf8, "X! moving on downgraded string");
1689 is(unpack('@5X!8W', $up), 0xf8, "X! moving on upgraded string");
1691 is(pack("W2x", 0xfa, 0xe3), "\xfa\xe3\x00", "x on downgraded string");
1692 is(pack("W2x!4", 0xfa, 0xe3), "\xfa\xe3\x00\x00",
1693 "x! on downgraded string");
1694 is(pack("W2x!2", 0xfa, 0xe3), "\xfa\xe3", "x! on downgraded string");
1695 is(pack("U0C0W2x", 0xfa, 0xe3), "\xfa\xe3\x00", "x on upgraded string");
1696 is(pack("U0C0W2x!4", 0xfa, 0xe3), "\xfa\xe3\x00\x00",
1697 "x! on upgraded string");
1698 is(pack("U0C0W2x!2", 0xfa, 0xe3), "\xfa\xe3", "x! on upgraded string");
1699 is(pack("W2X", 0xfa, 0xe3), "\xfa", "X on downgraded string");
1700 is(pack("U0C0W2X", 0xfa, 0xe3), "\xfa", "X on upgraded string");
1701 is(pack("W2X!2", 0xfa, 0xe3), "\xfa\xe3", "X! on downgraded string");
1702 is(pack("U0C0W2X!2", 0xfa, 0xe3), "\xfa\xe3", "X! on upgraded string");
1703 is(pack("W3X!2", 0xfa, 0xe3, 0xa6), "\xfa\xe3", "X! on downgraded string");
1704 is(pack("U0C0W3X!2", 0xfa, 0xe3, 0xa6), "\xfa\xe3",
1705 "X! on upgraded string");
1707 # backward eating through a ( moves the group starting point backwards
1708 is(pack("a*(Xa)", "abc", "q"), "abq",
1709 "eating before strbeg moves it back");
1710 is(pack("a*(Xa)", "ab" . chr(512), "q"), "abq",
1711 "eating before strbeg moves it back");
1713 # Check marked_upgrade
1714 is(pack('W(W(Wa@3W)@6W)@9W', 0xa1, 0xa2, 0xa3, "a", 0xa4, 0xa5, 0xa6),
1715 "\xa1\xa2\xa3a\x00\xa4\x00\xa5\x00\xa6");
1718 is(pack('W(W(Wa@3W)@6W)@9W', 0xa1, 0xa2, 0xa3, $up, 0xa4, 0xa5, 0xa6),
1719 "\xa1\xa2\xa3a\x00\xa4\x00\xa5\x00\xa6", "marked upgrade caused by a");
1720 is(pack('W(W(WW@3W)@6W)@9W', 0xa1, 0xa2, 0xa3, 256, 0xa4, 0xa5, 0xa6),
1721 "\xa1\xa2\xa3\x{100}\x00\xa4\x00\xa5\x00\xa6",
1722 "marked upgrade caused by W");
1723 is(pack('W(W(WU0aC0@3W)@6W)@9W', 0xa1, 0xa2, 0xa3, "a", 0xa4, 0xa5, 0xa6),
1724 "\xa1\xa2\xa3a\x00\xa4\x00\xa5\x00\xa6", "marked upgrade caused by U0");
1727 $down = "\xa4\xa6\xa7";
1730 utf8::upgrade(my $high = "\xfeb");
1732 for my $format ("a0", "A0", "Z0", "U0a0C0", "U0A0C0", "U0Z0C0") {
1733 is(pack("a* $format a*", "ab", $down, "cd"), "abcd",
1734 "$format format on plain string");
1735 is(pack("a* $format a*", "ab", $up, "cd"), "abcd",
1736 "$format format on upgraded string");
1737 is(pack("a* $format a*", $high, $down, "cd"), "\xfebcd",
1738 "$format format on plain string");
1739 is(pack("a* $format a*", $high, $up, "cd"), "\xfebcd",
1740 "$format format on upgraded string");
1741 my @down = unpack("a1 $format a*", "\xfeb");
1742 is("@down", "\xfe b", "unpack $format");
1743 my @up = unpack("a1 $format a*", $high);
1744 is("@up", "\xfe b", "unpack $format");
1746 is(pack("a1", $high), "\xfe");
1747 is(pack("A1", $high), "\xfe");
1748 is(pack("Z1", $high), "\x00");
1749 is(pack("a2", $high), "\xfeb");
1750 is(pack("A2", $high), "\xfeb");
1751 is(pack("Z2", $high), "\xfe\x00");
1752 is(pack("a5", $high), "\xfeb\x00\x00\x00");
1753 is(pack("A5", $high), "\xfeb ");
1754 is(pack("Z5", $high), "\xfeb\x00\x00\x00");
1755 is(pack("a*", $high), "\xfeb");
1756 is(pack("A*", $high), "\xfeb");
1757 is(pack("Z*", $high), "\xfeb\x00");
1759 utf8::upgrade($high = "\xc3\xbeb");
1760 is(pack("U0a2", $high), "\xfe");
1761 is(pack("U0A2", $high), "\xfe");
1762 is(pack("U0Z1", $high), "\x00");
1763 is(pack("U0a3", $high), "\xfeb");
1764 is(pack("U0A3", $high), "\xfeb");
1765 is(pack("U0Z3", $high), "\xfe\x00");
1766 is(pack("U0a6", $high), "\xfeb\x00\x00\x00");
1767 is(pack("U0A6", $high), "\xfeb ");
1768 is(pack("U0Z6", $high), "\xfeb\x00\x00\x00");
1769 is(pack("U0a*", $high), "\xfeb");
1770 is(pack("U0A*", $high), "\xfeb");
1771 is(pack("U0Z*", $high), "\xfeb\x00");