15 my $Is_EBCDIC = (defined $Config{ebcdic} && $Config{ebcdic} eq 'define');
16 my $Perl = which_perl();
19 my @result = map {_qq($_)} @_;
23 return '(' . join (', ', @result) . ')';
29 return 0 unless @$l == @$r;
31 if (defined $l->[$i]) {
32 return 0 unless defined ($r->[$i]) && $l->[$i] eq $r->[$i];
34 return 0 if defined $r->[$i]
40 ##############################################################################
42 # Here starteth the tests
46 my $format = "c2 x5 C C x s d i l a6";
47 # Need the expression in here to force ary[5] to be numeric. This avoids
48 # test2 failing because ary2 goes str->numeric->str and ary doesn't.
49 my @ary = (1,-100,127,128,32767,987.654321098 / 100.0,12345,123456,
51 my $foo = pack($format,@ary);
52 my @ary2 = unpack($format,$foo);
56 my $out1=join(':',@ary);
57 my $out2=join(':',@ary2);
58 # Using long double NVs may introduce greater accuracy than wanted.
59 $out1 =~ s/:9\.87654321097999\d*:/:9.87654321098:/;
60 $out2 =~ s/:9\.87654321097999\d*:/:9.87654321098:/;
65 # How about counting bits?
69 is( ($x = unpack("%32B*", "\001\002\004\010\020\040\100\200\377")), 16 );
71 is( ($x = unpack("%32b69", "\001\002\004\010\020\040\100\200\017")), 12 );
73 is( ($x = unpack("%32B69", "\001\002\004\010\020\040\100\200\017")), 9 );
77 my $sum = 129; # ASCII
78 $sum = 103 if $Is_EBCDIC;
81 is( ($x = unpack("%32B*", "Now is the time for all good blurfl")), $sum );
84 open(BIN, $Perl) || die "Can't open $Perl: $!\n";
85 sysread BIN, $foo, 8192;
88 $sum = unpack("%32b*", $foo);
89 my $longway = unpack("b*", $foo);
90 is( $sum, $longway =~ tr/1/1/ );
95 is( ($x = unpack("I",pack("I", 0xFFFFFFFF))), 0xFFFFFFFF );
100 my @x = (5,130,256,560,32000,3097152,268435455,1073741844, 2**33,
101 '4503599627365785','23728385234614992549757750638446');
102 my $x = pack('w*', @x);
103 my $y = pack 'H*', '0581028200843081fa0081bd8440ffffff7f8480808014A0808'.
104 '0800087ffffffffffdb19caefe8e1eeeea0c2e1e3e8ede1ee6e';
108 my @y = unpack('w*', $y);
110 while ($a = pop @x) {
115 @y = unpack('w2', $x);
119 $x = pack('w*', 5000000000); $y = '';
122 $y = pack('w*', Math::BigInt::->new(5000000000));
127 $y = pack 'w', (~0).'';
129 is(unpack ('w',$x), ~0);
130 is(unpack ('w',$y), ~0);
132 $x = pack 'w', ~0 - 1;
133 $y = pack 'w', (~0) - 2;
135 if (~0 - 1 == (~0) - 2) {
136 is($x, $y, "NV arithmetic");
138 isnt($x, $y, "IV/NV arithmetic");
140 cmp_ok(unpack ('w',$x), '==', ~0 - 1);
141 cmp_ok(unpack ('w',$y), '==', ~0 - 2);
143 # These should spot that pack 'w' is using NV, not double, on platforms
144 # where IVs are smaller than doubles, and harmlessly pass elsewhere.
145 # (tests for change 16861)
153 is($x, $y, "NV arithmetic");
155 isnt($x, $y, "IV/NV arithmetic");
157 cmp_ok(unpack ('w',$x), '==', $x0);
158 cmp_ok(unpack ('w',$y), '==', $y0);
163 print "# test exceptions\n";
165 eval { $x = unpack 'w', pack 'C*', 0xff, 0xff};
166 like($@, qr/^Unterminated compressed integer/);
168 eval { $x = unpack 'w', pack 'C*', 0xff, 0xff, 0xff, 0xff};
169 like($@, qr/^Unterminated compressed integer/);
171 eval { $x = unpack 'w', pack 'C*', 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff};
172 like($@, qr/^Unterminated compressed integer/);
174 eval { $x = pack 'w', -1 };
175 like ($@, qr/^Cannot compress negative numbers/);
177 eval { $x = pack 'w', '1'x(1 + length ~0) . 'e0' };
178 like ($@, qr/^Can only compress unsigned integers/);
181 # Is this a stupid thing to do on VMS, VOS and other unusual platforms?
183 skip("-- the IEEE infinity model is unavailable in this configuration.", 1)
184 if (($^O eq 'VMS') && !defined($Config{useieee}));
186 skip("-- $^O has serious fp indigestion on w-packed infinities", 1)
187 if (($^O eq 'mpeix') || ($^O eq 'ultrix'));
189 my $inf = eval '2**10000';
191 skip("Couldn't generate infinity - got error '$@'", 1)
192 unless defined $inf and $inf == $inf / 2 and $inf + 1 == $inf;
195 $TODO = "VOS needs a fix for posix-1022 to pass this test."
198 eval { $x = pack 'w', $inf };
199 like ($@, qr/^Cannot compress integer/, "Cannot compress integer");
204 skip("-- the full range of an IEEE double may not be available in this configuration.", 3)
205 if (($^O eq 'VMS') && !defined($Config{useieee}));
207 skip("-- $^O does not like 2**1023", 3)
208 if (($^O eq 'ultrix'));
210 # This should be about the biggest thing possible on an IEEE double
211 my $big = eval '2**1023';
213 skip("Couldn't generate 2**1023 - got error '$@'", 3)
214 unless defined $big and $big != $big / 2;
216 eval { $x = pack 'w', $big };
217 is ($@, '', "Should be able to pack 'w', $big # 2**1023");
219 my $y = eval {unpack 'w', $x};
221 "Should be able to unpack 'w' the result of pack 'w', $big # 2**1023");
223 # I'm getting about 1e-16 on FreeBSD
224 my $quotient = int (100 * ($y - $big) / $big);
225 ok($quotient < 2 && $quotient > -2,
226 "Round trip pack, unpack 'w' of $big is withing 1% ($quotient%)");
231 print "# test the 'p' template\n";
234 is(unpack("p",pack("p","foo")), "foo");
237 is(unpack("p",pack("p",239)), 239);
240 sub foo { my $a = "a"; return $a . $a++ . $a++ }
244 local $SIG{__WARN__} = sub {
247 my $junk = pack("p", &foo);
249 like($warning, qr/temporary val/);
252 # undef should give null pointer
253 like(pack("p", undef), qr/^\0+/);
255 # Check for optimizer bug (e.g. Digital Unix GEM cc with -O4 on DU V4.0B gives
256 # 4294967295 instead of -1)
257 # see #ifdef __osf__ in pp.c pp_unpack
258 is((unpack("i",pack("i",-1))), -1);
260 print "# test the pack lengths of s S i I l L n N v V\n";
262 my @lengths = qw(s 2 S 2 i -4 I -4 l 4 L 4 n 2 N 4 v 2 V 4);
263 while (my ($format, $expect) = splice @lengths, 0, 2) {
264 my $len = length(pack($format, 0));
266 is($expect, $len, "format '$format'");
269 ok ($len >= $expect, "format '$format'") ||
270 print "# format '$format' has length $len, expected >= $expect\n";
275 print "# test unpack-pack lengths\n";
277 my @templates = qw(c C i I s S l L n N v V f d q Q);
279 foreach my $t (@templates) {
281 my @t = eval { unpack("$t*", pack("$t*", 12, 34)) };
283 # quads not supported everywhere
284 skip "Quads not supported", 4 if $@ =~ /Invalid type/;
290 skip "$t not expected to work for some reason", 2 if $t =~ /[nv]/i;
301 # Note that first uuencoding known 'text' data and then checking the
302 # binary values of the uuencoded version would not be portable between
303 # character sets. Uuencoding is meant for encoding binary data, not
306 my $in = pack 'C*', 0 .. 255;
308 # just to be anal, we do some random tr/`/ /
310 M` $"`P0%!@<("0H+# T.#Q`1$A,4%187&!D:&QP='A\@(2(C)"4F)R@I*BLL
311 M+2XO,#$R,S0U-C<X.3H[/#T^/T!!0D-$149'2$E*2TQ-3D]045)35%565UA9
312 M6EM<75Y?8&%B8V1E9F=H:6IK;&UN;W!Q<G-T=79W>'EZ>WQ]?G^`@8*#A(6&
313 MAXB)BHN,C8Z/D)&2DY25EI>8F9J;G)V>GZ"AHJ.DI::GJ*FJJZRMKJ^PL;*S
314 MM+6VM[BYNKN\O;Z_P,'"P\3%QL?(R<K+S,W.S]#1TM/4U=;7V-G:V]S=WM_@
315 ?X>+CY.7FY^CIZNOL[>[O\/'R\_3U]O?X^?K[_/W^_P `
321 is(pack('u', $in), $_);
323 is(unpack('u', $uu), $in);
325 $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";
327 M'XL("%C<Q#4"`TI!4%4`\RHM+E%(S,LOR4@M4@A(+<I1*"U-SD])+>("`&1F
331 is(unpack('u', $uu), $in);
333 # This is identical to the above except that backquotes have been
337 M'XL("%C<Q#4" TI!4%4 \RHM+E%(S,LOR4@M4@A(+<I1*"U-SD])+>(" &1F
342 is(unpack('u', $uu), $in);
346 # test the ascii template types (A, a, Z)
349 ['p', 'A*', "foo\0bar\0 ", "foo\0bar\0 "],
350 ['p', 'A11', "foo\0bar\0 ", "foo\0bar\0 "],
351 ['u', 'A*', "foo\0bar \0", "foo\0bar"],
352 ['u', 'A8', "foo\0bar \0", "foo\0bar"],
353 ['p', 'a*', "foo\0bar\0 ", "foo\0bar\0 "],
354 ['p', 'a11', "foo\0bar\0 ", "foo\0bar\0 \0\0"],
355 ['u', 'a*', "foo\0bar \0", "foo\0bar \0"],
356 ['u', 'a8', "foo\0bar \0", "foo\0bar "],
357 ['p', 'Z*', "foo\0bar\0 ", "foo\0bar\0 \0"],
358 ['p', 'Z11', "foo\0bar\0 ", "foo\0bar\0 \0\0"],
359 ['p', 'Z3', "foo", "fo\0"],
360 ['u', 'Z*', "foo\0bar \0", "foo"],
361 ['u', 'Z8', "foo\0bar \0", "foo"],
364 my ($what, $template, $in, $out) = @$_;
365 my $got = $what eq 'u' ? (unpack $template, $in) : (pack $template, $in);
366 unless (is($got, $out)) {
367 my $un = $what eq 'u' ? 'un' : '';
368 print "# ${un}pack ('$template', "._qq($in).') gave '._qq($out).
369 ' not '._qq($got)."\n";
373 print "# packing native shorts/ints/longs\n";
375 is(length(pack("s!", 0)), $Config{shortsize});
376 is(length(pack("i!", 0)), $Config{intsize});
377 is(length(pack("l!", 0)), $Config{longsize});
378 ok(length(pack("s!", 0)) <= length(pack("i!", 0)));
379 ok(length(pack("i!", 0)) <= length(pack("l!", 0)));
380 is(length(pack("i!", 0)), length(pack("i", 0)));
384 return numbers_with_total ($format, undef, @_);
387 sub numbers_with_total {
390 if (!defined $total) {
395 print "# numbers test for $format\n";
398 my $out = eval {unpack($format, pack($format, $_))};
399 skip "cannot pack '$format' on this perl", 2 if
400 $@ =~ /Invalid type '$format'/;
407 my $skip_if_longer_than = ~0; # "Infinity"
409 # If we're running with -DNO_PERLPRESERVE_IVUV and NVs don't preserve all
410 # UVs (in which case ~0 is NV, ~0-1 will be the same NV) then we can't
411 # correctly in perl calculate UV totals for long checksums, as pp_unpack
412 # is using UV maths, and we've only got NVs.
413 $skip_if_longer_than = $Config{nv_preserves_uv_bits};
416 foreach ('', 1, 2, 3, 15, 16, 17, 31, 32, 33, 53, 54, 63, 64, 65) {
418 my $sum = eval {unpack "%$_$format*", pack "$format*", @_};
419 skip "cannot pack '$format' on this perl", 3
420 if $@ =~ /Invalid type '$format'/;
425 my $len = $_; # Copy, so that we can reassign ''
426 $len = 16 unless length $len;
429 skip "cannot test checksums over $skip_if_longer_than bits", 1
430 if $len > $skip_if_longer_than;
432 # Our problem with testing this portably is that the checksum code in
433 # pp_unpack is able to cast signed to unsigned, and do modulo 2**n
434 # arithmetic in unsigned ints, which perl has no operators to do.
435 # (use integer; does signed ints, which won't wrap on UTS, which is just
436 # fine with ANSI, but not with most people's assumptions.
437 # This is why we need to supply the totals for 'Q' as there's no way in
438 # perl to calculate them, short of unpack '%0Q' (is that documented?)
439 # ** returns NVs; make sure it's IV.
440 my $max = 1 + 2 * (int (2 ** ($len-1))-1); # The max possible checksum
441 my $max_p1 = $max + 1;
442 my ($max_is_integer, $max_p1_is_integer);
443 $max_p1_is_integer = 1 unless $max_p1 + 1 == $max_p1;
444 $max_is_integer = 1 if $max - 1 < ~0;
448 $calc_sum = &$total($len);
451 # Shift into range by some multiple of the total
452 my $mult = $max_p1 ? int ($total / $max_p1) : undef;
453 # Need this to make sure that -1 + (~0+1) is ~0 (ie still integer)
454 $calc_sum = $total - $mult;
455 $calc_sum -= $mult * $max;
461 if ($calc_sum == $calc_sum - 1 && $calc_sum == $max_p1) {
462 # we're into floating point (either by getting out of the range of
463 # UV arithmetic, or because we're doing a floating point checksum)
464 # and our calculation of the checksum has become rounded up to
469 if ($calc_sum == $sum) { # HAS to be ==, not eq (so no is()).
470 ok ("unpack '%$_$format' gave $sum");
472 my $delta = 1.000001;
473 if ($format =~ tr /dDfF//
474 && ($calc_sum <= $sum * $delta && $calc_sum >= $sum / $delta)) {
475 pass ("unpack '%$_$format' gave $sum, expected $calc_sum");
477 my $text = ref $total ? &$total($len) : $total;
479 print "# For list (" . join (", ", @_) . ") (total $text)"
480 . " packed with $format unpack '%$_$format' gave $sum,"
481 . " expected $calc_sum\n";
489 numbers ('c', -128, -1, 0, 1, 127);
490 numbers ('C', 0, 1, 127, 128, 255);
491 numbers ('s', -32768, -1, 0, 1, 32767);
492 numbers ('S', 0, 1, 32767, 32768, 65535);
493 numbers ('i', -2147483648, -1, 0, 1, 2147483647);
494 numbers ('I', 0, 1, 2147483647, 2147483648, 4294967295);
495 numbers ('l', -2147483648, -1, 0, 1, 2147483647);
496 numbers ('L', 0, 1, 2147483647, 2147483648, 4294967295);
497 numbers ('s!', -32768, -1, 0, 1, 32767);
498 numbers ('S!', 0, 1, 32767, 32768, 65535);
499 numbers ('i!', -2147483648, -1, 0, 1, 2147483647);
500 numbers ('I!', 0, 1, 2147483647, 2147483648, 4294967295);
501 numbers ('l!', -2147483648, -1, 0, 1, 2147483647);
502 numbers ('L!', 0, 1, 2147483647, 2147483648, 4294967295);
503 numbers ('n', 0, 1, 32767, 32768, 65535);
504 numbers ('v', 0, 1, 32767, 32768, 65535);
505 numbers ('N', 0, 1, 2147483647, 2147483648, 4294967295);
506 numbers ('V', 0, 1, 2147483647, 2147483648, 4294967295);
507 # All these should have exact binary representations:
508 numbers ('f', -1, 0, 0.5, 42, 2**34);
509 numbers ('d', -(2**34), -1, 0, 1, 2**34);
510 ## These don't, but 'd' is NV. XXX wrong, it's double
511 #numbers ('d', -1, 0, 1, 1-exp(-1), -exp(1));
513 numbers_with_total ('q', -1,
514 -9223372036854775808, -1, 0, 1,9223372036854775807);
515 # This total is icky, but the true total is 2**65-1, and need a way to generate
516 # the epxected checksum on any system including those where NVs can preserve
517 # 65 bits. (long double is 128 bits on sparc, so they certainly can)
518 # or where rounding is down not up on binary conversion (crays)
519 numbers_with_total ('Q', sub {
521 $len = 65 if $len > 65; # unmasked total is 2**65-1 here
522 my $total = 1 + 2 * (int (2**($len - 1)) - 1);
523 return 0 if $total == $total - 1; # Overflowed integers
524 return $total; # NVs still accurate to nearest integer
526 0, 1,9223372036854775807, 9223372036854775808,
527 18446744073709551615);
529 print "# pack nvNV byteorders\n";
531 is(pack("n", 0xdead), "\xde\xad");
532 is(pack("v", 0xdead), "\xad\xde");
533 is(pack("N", 0xdeadbeef), "\xde\xad\xbe\xef");
534 is(pack("V", 0xdeadbeef), "\xef\xbe\xad\xde");
540 eval { ($x) = unpack '/a*','hello' };
541 like($@, qr!'/' must follow a numeric type!);
543 eval { $x = unpack '/a*','hello' };
544 like($@, qr!'/' must follow a numeric type!);
547 eval { ($z,$x,$y) = unpack 'a3/A C/a* C/Z', "003ok \003yes\004z\000abc" };
553 eval { $z = unpack 'a3/A C/a* C/Z', "003ok \003yes\004z\000abc" };
559 eval { ($x) = pack '/a*','hello' };
560 like($@, qr!Invalid type '/'!);
562 eval { $x = pack '/a*','hello' };
563 like($@, qr!Invalid type '/'!);
565 $z = pack 'n/a* N/Z* w/A*','string','hi there ','etc';
566 my $expect = "\000\006string\0\0\0\012hi there \000\003etc";
570 $expect = 'hello world';
571 eval { ($x) = unpack ("w/a", chr (11) . "hello world!")};
576 # Doing this in scalar context used to fail.
577 eval { $x = unpack ("w/a", chr (11) . "hello world!")};
582 ['a/a*/a*', '212ab345678901234567','ab3456789012'],
583 ['a/a*/a*', '3012ab345678901234567', 'ab3456789012'],
584 ['a/a*/b*', '212ab', $Is_EBCDIC ? '100000010100' : '100001100100'],
587 my ($pat, $in, $expect) = @$_;
589 eval { ($x) = unpack $pat, $in };
592 printf "# list unpack ('$pat', '$in') gave %s, expected '$expect'\n",
596 eval { $x = unpack $pat, $in };
599 printf "# scalar unpack ('$pat', '$in') gave %s, expected '$expect'\n",
605 my $pattern = <<'EOU';
606 a3/A # Count in ASCII
607 C/a* # Count in a C char
608 C/Z # Count in a C char but skip after \0
612 eval { ($z,$x,$y) = unpack $pattern, "003ok \003yes\004z\000abc" };
618 eval { $z = unpack $pattern, "003ok \003yes\004z\000abc" };
623 n/a* # Count as network short
624 w/A* # Count a BER integer
626 $expect = "\000\006string\003etc";
627 $z = pack $pattern,'string','etc';
633 skip("(EBCDIC and) version strings are bad idea", 2) if $Is_EBCDIC;
635 is("1.20.300.4000", sprintf "%vd", pack("U*",1,20,300,4000));
636 is("1.20.300.4000", sprintf "%vd", pack(" U*",1,20,300,4000));
638 isnt(v1.20.300.4000, sprintf "%vd", pack("C0U*",1,20,300,4000));
640 my $rslt = $Is_EBCDIC ? "156 67" : "199 162";
641 is(join(" ", unpack("C*", chr(0x1e2))), $rslt);
643 # does pack U create Unicode?
644 is(ord(pack('U', 300)), 300);
646 # does unpack U deref Unicode?
647 is((unpack('U', chr(300)))[0], 300);
649 # is unpack U the reverse of pack U for Unicode string?
650 is("@{[unpack('U*', pack('U*', 100, 200, 300))]}", "100 200 300");
652 # is unpack U the reverse of pack U for byte string?
653 is("@{[unpack('U*', pack('U*', 100, 200))]}", "100 200");
657 skip "Not for EBCDIC", 4 if $Is_EBCDIC;
659 # does unpack C unravel pack U?
660 is("@{[unpack('C*', pack('U*', 100, 200))]}", "100 195 136");
662 # does pack U0C create Unicode?
663 is("@{[pack('U0C*', 100, 195, 136)]}", v100.v200);
665 # does pack C0U create characters?
666 is("@{[pack('C0U*', 100, 200)]}", pack("C*", 100, 195, 136));
668 # does unpack U0U on byte data warn?
670 local $SIG{__WARN__} = sub { $@ = "@_" };
671 my @null = unpack('U0U', chr(255));
672 like($@, /^Malformed UTF-8 character /);
677 my $p = pack 'i*', -2147483648, ~0, 0, 1, 2147483647;
679 # bug - % had to be at the start of the pattern, no leading whitespace or
680 # comments. %i! didn't work at all.
681 foreach my $pat ('%32i*', ' %32i*', "# Muhahahaha\n%32i*", '%32i* ',
682 '%32i!*', ' %32i!*', "\n#\n#\n\r \t\f%32i!*", '%32i!*#') {
683 @a = unpack $pat, $p;
684 is($a[0], 0xFFFFFFFF) || print "# $pat\n";
685 @a = scalar unpack $pat, $p;
686 is($a[0], 0xFFFFFFFF) || print "# $pat\n";
690 $p = pack 'I*', 42, 12;
691 # Multiline patterns in scalar context failed.
692 foreach my $pat ('I', <<EOPOEMSNIPPET, 'I#I', 'I # I', 'I # !!!') {
693 # On the Ning Nang Nong
694 # Where the Cows go Bong!
695 # And the Monkeys all say Boo!
698 @a = unpack $pat, $p;
701 @a = scalar unpack $pat, $p;
706 # shorts (of all flavours) didn't calculate checksums > 32 bits with floating
707 # point, so a pathologically long pattern would wrap at 32 bits.
708 my $pat = "\xff\xff"x65538; # Start with it long, to save any copying.
709 foreach (4,3,2,1,0) {
710 my $len = 65534 + $_;
711 is(unpack ("%33n$len", $pat), 65535 * $len);
721 ['xXa*', "Nick", "Nick"],
722 ['a5Xa5', "cameL", "llama", "camellama"],
724 ['a*@8a*', 'Camel', 'Dromedary', "Camel\0\0\0Dromedary"],
725 ['a*@4a', 'Perl rules', '!', 'Perl!'],
728 my ($template, @in) = @$_;
730 my $got = eval {pack $template, @in};
733 printf "# pack ('$template', %s) gave %s expected %s\n",
734 encode_list (@in), encode_list ($got), encode_list ($out);
741 ['xXa*', "Nick", "Nick"],
742 ['a5Xa5', "camellama", "camel", "llama"],
744 ['@2a2', "water", "te"],
745 ['a*@1a3', "steam", "steam", "tea"],
748 my ($template, $in, @out) = @$_;
749 my @got = eval {unpack $template, $in};
751 ok (list_eq (\@got, \@out)) ||
752 printf "# list unpack ('$template', %s) gave %s expected %s\n",
753 _qq($in), encode_list (@got), encode_list (@out);
755 my $got = eval {unpack $template, $in};
757 @out ? is( $got, $out[0] ) # 1 or more items; should get first
758 : ok( !defined $got ) # 0 items; should get undef
759 or printf "# scalar unpack ('$template', %s) gave %s expected %s\n",
760 _qq($in), encode_list ($got), encode_list ($out[0]);
765 my ($u, $v) = qw(foo xyzzy);
766 my $p = pack($t, $u, $v);
767 my @u = unpack($t, $p);
774 is((unpack("w/a*", "\x02abc"))[0], "ab");
776 # "w/a*" should be seen as one unit
778 is(scalar unpack("w/a*", "\x02abc"), "ab");
782 # from Wolfgang Laun: fix in change #13163
787 my $buf = pack( 'Z*/A* C', $s, $x );
791 $h =~ s/[^[:print:]]/./g;
792 ( $s, $y ) = unpack( "Z*/A* C", $buf );
793 is($h, "30.ABCABCABCABCABCABCABCABCABCABC$t");
795 is($s, "ABCABCABCABCABCABCABCABCABCABC");
800 # from Wolfgang Laun: fix in change #13288
802 eval { my $t=unpack("P*", "abc") };
803 like($@, qr/'P' must have an explicit size/);
806 { # Grouping constructs
808 @a = unpack '(SL)', pack 'SLSLSL', 67..90;
810 @a = unpack '(SL)3', pack 'SLSLSL', 67..90;
813 @a = unpack '(SL)3', pack 'SLSLSLSL', 67..90;
815 @a = unpack '(SL)[3]', pack 'SLSLSLSL', 67..90;
817 @a = unpack '(SL)[2] SL', pack 'SLSLSLSL', 67..90;
819 @a = unpack 'A/(SL)', pack 'ASLSLSLSL', 3, 67..90;
821 @a = unpack 'A/(SL)SL', pack 'ASLSLSLSL', 2, 67..90;
823 @a = unpack '(SL)*', pack 'SLSLSLSL', 67..90;
826 @a = unpack '(SL)*SL', pack 'SLSLSLSL', 67..90;
828 eval { @a = unpack '(*SL)', '' };
829 like($@, qr/\(\)-group starts with a count/);
830 eval { @a = unpack '(3SL)', '' };
831 like($@, qr/\(\)-group starts with a count/);
832 eval { @a = unpack '([3]SL)', '' };
833 like($@, qr/\(\)-group starts with a count/);
834 eval { @a = pack '(*SL)' };
835 like($@, qr/\(\)-group starts with a count/);
836 @a = unpack '(SL)3 SL', pack '(SL)4', 67..74;
838 @a = unpack '(SL)3 SL', pack '(SL)[4]', 67..74;
840 @a = unpack '(SL)3 SL', pack '(SL)*', 67..74;
844 { # more on grouping (W.Laun)
847 local $SIG{__WARN__} = sub {
850 # @ absolute within ()-group
851 my $badc = pack( '(a)*', unpack( '(@1a @0a @2)*', 'abcd' ) );
854 my $buf = pack( '(@1c)((@2C)@3c)', @b );
855 is( $buf, "\0\1\0\0\2\3" );
856 my @a = unpack( '(@1c)((@2c)@3c)', $buf );
859 # various unpack count/code scenarios
860 my @Env = ( a => 'AAA', b => 'BBB' );
861 my $env = pack( 'S(S/A*S/A*)*', @Env/2, @Env );
863 # unpack full length - ok
864 my @pup = unpack( 'S/(S/A* S/A*)', $env );
865 is( "@pup", "@Env" );
867 # warn when count/code goes beyond end of string
868 # \0002 \0001 a \0003 AAA \0001 b \0003 BBB
870 eval { @pup = unpack( 'S/(S/A* S/A*)', substr( $env, 0, 13 ) ) };
871 like( $@, qr{length/code after end of string} );
873 # postfix repeat count
874 $env = pack( '(S/A* S/A*)' . @Env/2, @Env );
876 # warn when count/code goes beyond end of string
877 # \0001 a \0003 AAA \0001 b \0003 BBB
878 # 2 3c 5 8 10 11 13 16
879 eval { @pup = unpack( '(S/A* S/A*)' . @Env/2, substr( $env, 0, 11 ) ) };
880 like( $@, qr{length/code after end of string} );
882 # catch stack overflow/segfault
883 eval { $_ = pack( ('(' x 105) . 'A' . (')' x 105) ); };
884 like( $@, qr{Too deeply nested \(\)-groups} );
887 { # syntax checks (W.Laun)
890 local $SIG{__WARN__} = sub {
891 push( @warning, $_[0] );
893 eval { my $s = pack( 'Ax![4c]A', 1..5 ); };
894 like( $@, qr{Malformed integer in \[\]} );
896 eval { my $buf = pack( '(c/*a*)', 'AAA', 'BB' ); };
897 like( $@, qr{'/' does not take a repeat count} );
899 eval { my @inf = unpack( 'c/1a', "\x03AAA\x02BB" ); };
900 like( $@, qr{'/' does not take a repeat count} );
902 eval { my @inf = unpack( 'c/*a', "\x03AAA\x02BB" ); };
903 like( $@, qr{'/' does not take a repeat count} );
905 # white space where possible
906 my @Env = ( a => 'AAA', b => 'BBB' );
907 my $env = pack( ' S ( S / A* S / A* )* ', @Env/2, @Env );
908 my @pup = unpack( ' S / ( S / A* S / A* ) ', $env );
909 is( "@pup", "@Env" );
911 # white space in 4 wrong places
912 for my $temp ( 'A ![4]', 'A [4]', 'A *', 'A 4' ){
913 eval { my $s = pack( $temp, 'B' ); };
914 like( $@, qr{Invalid type } );
919 my $x = pack( 'I,A', 4, 'X' );
920 like( $warning[0], qr{Invalid type ','} );
922 # comma warning only once
924 $x = pack( 'C(C,C)C,C', 65..71 );
925 like( scalar @warning, 1 );
927 # forbidden code in []
928 eval { my $x = pack( 'A[@4]', 'XXXX' ); };
929 like( $@, qr{Within \[\]-length '\@' not allowed} );
932 my $s = pack( 'AA@A', 'A', 'B', 'C' );
933 my @c = unpack( 'AA@A', $s );
937 # no unpack code after /
938 eval { my @a = unpack( "C/", "\3" ); };
939 like( $@, qr{Code missing after '/'} );
943 { # Repeat count [SUBEXPR]
944 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
945 s! S! i! I! l! L! j J);
947 if (eval { pack 'q', 1 } ) {
948 push @codes, qw(q Q);
950 push @codes, qw(c C); # Keep the count the same
952 if (eval { pack 'D', 1 } ) {
955 push @codes, 'd'; # Keep the count the same
959 @val{@codes} = map { / [Xx] (?{ undef })
960 | [AZa] (?{ 'something' })
965 | [svnSiIlVNLqQjJ] (?{ 10111 })
966 | [FfDd] (?{ 1.36514538e67 })
967 | [pP] (?{ "try this buffer" })
969 my @end = (0x12345678, 0x23456781, 0x35465768, 0x15263748);
972 for my $type (@codes) {
973 my @list = $val{$type};
974 @list = () unless defined $list[0];
975 for my $count ('', '3', '[11]') {
977 $c = $1 if $count =~ /(\d+)/;
979 @list1 = (@list1) x $c unless $type =~ /[XxAaZBbHhP]/;
980 for my $groupend ('', ')2', ')[8]') {
981 my $groupbegin = ($groupend ? '(' : '');
983 $c = $1 if $groupend =~ /(\d+)/;
984 my @list2 = (@list1) x $c;
986 my $junk1 = "$groupbegin $type$count $groupend";
987 # print "# junk1=$junk1\n";
988 my $p = pack $junk1, @list2;
989 my $half = int( (length $p)/2 );
990 for my $move ('', "X$half", "X!$half", 'x1', 'x!8', "x$half") {
991 my $junk = "$junk1 $move";
992 # print "# junk='$junk', list=(@list2)\n";
993 $p = pack "$junk $end", @list2, @end;
994 my @l = unpack "x[$junk] $end", $p;
995 is(scalar @l, scalar @end);
996 is("@l", "@end", "skipping x[$junk]");
1003 # / is recognized after spaces in scalar context
1004 # XXXX no spaces are allowed in pack... In pack only before the slash...
1005 is(scalar unpack('A /A Z20', pack 'A/A* Z20', 'bcde', 'xxxxx'), 'bcde');
1006 is(scalar unpack('A /A /A Z20', '3004bcde'), 'bcde');
1009 my $t = 'C[3] x!8 C[2]';
1010 my @a = (0x73..0x77);
1011 my $p = pack($t, @a);
1012 is($p, "\x73\x74\x75\0\0\0\0\0\x76\x77");
1013 my @b = unpack $t, $p;
1014 is(scalar @b, scalar @a);
1015 is("@b", "@a", 'x!8');
1016 $t = 'x[5] C[6] X!8 C[2]';
1019 is($p, "\0\0\0\0\0\x73\x74\x75\x79\x7a");
1021 @a = (0x73..0x75, 0x79, 0x7a, 0x79, 0x7a);
1022 is(scalar @b, scalar @a);
1026 { # struct {char c1; double d; char cc[2];}
1027 my $t = 'C x![d] d C[2]';
1028 my @a = (173, 1.283476517e-45, 42, 215);
1029 my $p = pack $t, @a;
1031 my @b = unpack "$t X[$t] $t", $p; # Extract, step back, extract again
1032 is(scalar @b, 2 * scalar @a);
1034 $b =~ s/(?:17000+|16999+)\d+(e-45) /17$1 /gi; # stringification is gamble
1038 local $SIG{__WARN__} = sub {
1041 @b = unpack "x[C] x[$t] X[$t] X[C] $t", "$p\0";
1043 is($warning, undef);
1044 is(scalar @b, scalar @a);
1046 $b =~ s/(?:17000+|16999+)\d+(e-45) /17$1 /gi; # stringification is gamble
1050 is(length(pack("j", 0)), $Config{ivsize});
1051 is(length(pack("J", 0)), $Config{uvsize});
1052 is(length(pack("F", 0)), $Config{nvsize});
1054 numbers ('j', -2147483648, -1, 0, 1, 2147483647);
1055 numbers ('J', 0, 1, 2147483647, 2147483648, 4294967295);
1056 numbers ('F', -(2**34), -1, 0, 1, 2**34);
1058 my $t = eval { unpack("D*", pack("D", 12.34)) };
1060 skip "Long doubles not in use", 56 if $@ =~ /Invalid type/;
1062 is(length(pack("D", 0)), $Config{longdblsize});
1063 numbers ('D', -(2**34), -1, 0, 1, 2**34);
1066 # Maybe this knowledge needs to be "global" for all of pack.t
1067 # Or a "can checksum" which would effectively be all the number types"
1068 my %cant_checksum = map {$_=> 1} qw(A Z u w);
1070 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)) {
1072 my $packed = eval {pack "${template}4", 1, 4, 9, 16};
1074 die unless $@ =~ /Invalid type '$template'/;
1075 skip ("$template not supported on this perl",
1076 $cant_checksum{$template} ? 4 : 8);
1078 my @unpack4 = unpack "${template}4", $packed;
1079 my @unpack = unpack "${template}*", $packed;
1080 my @unpack1 = unpack "${template}", $packed;
1081 my @unpack1s = scalar unpack "${template}", $packed;
1082 my @unpack4s = scalar unpack "${template}4", $packed;
1083 my @unpacks = scalar unpack "${template}*", $packed;
1085 my @tests = ( ["${template}4 vs ${template}*", \@unpack4, \@unpack],
1086 ["scalar ${template} ${template}", \@unpack1s, \@unpack1],
1087 ["scalar ${template}4 vs ${template}", \@unpack4s, \@unpack1],
1088 ["scalar ${template}* vs ${template}", \@unpacks, \@unpack1],
1091 unless ($cant_checksum{$template}) {
1092 my @unpack4_c = unpack "\%${template}4", $packed;
1093 my @unpack_c = unpack "\%${template}*", $packed;
1094 my @unpack1_c = unpack "\%${template}", $packed;
1095 my @unpack1s_c = scalar unpack "\%${template}", $packed;
1096 my @unpack4s_c = scalar unpack "\%${template}4", $packed;
1097 my @unpacks_c = scalar unpack "\%${template}*", $packed;
1100 ( ["% ${template}4 vs ${template}*", \@unpack4_c, \@unpack_c],
1101 ["% scalar ${template} ${template}", \@unpack1s_c, \@unpack1_c],
1102 ["% scalar ${template}4 vs ${template}*", \@unpack4s_c, \@unpack_c],
1103 ["% scalar ${template}* vs ${template}*", \@unpacks_c, \@unpack_c],
1106 foreach my $test (@tests) {
1107 ok (list_eq ($test->[1], $test->[2]), $test->[0]) ||
1108 printf "# unpack gave %s expected %s\n",
1109 encode_list (@{$test->[1]}), encode_list (@{$test->[2]});
1114 ok(pack('u2', 'AA'), "[perl #8026]"); # used to hang and eat RAM in perl 5.7.2
1116 $_ = pack('c', 65); # 'A' would not be EBCDIC-friendly
1117 is(unpack('c'), 65, "one-arg unpack (change #18751)"); # defaulting to $_
1120 my $a = "X\t01234567\n" x 100;
1121 my @a = unpack("(a1 c/a)*", $a);
1122 is(scalar @a, 200, "[perl #15288]");
1123 is($a[-1], "01234567\n", "[perl #15288]");
1124 is($a[-2], "X", "[perl #15288]");