This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
d_nv_preserves_uv_bits
[perl5.git] / t / op / pack.t
1 #!./perl -w
2
3 BEGIN {
4     chdir 't' if -d 't';
5     @INC = '../lib';
6     require './test.pl';
7 }
8
9 plan tests => 5625;
10
11 use strict;
12 use warnings;
13 use Config;
14
15 my $Is_EBCDIC = (defined $Config{ebcdic} && $Config{ebcdic} eq 'define');
16 my $Perl = which_perl();
17
18 sub encode_list {
19   my @result = map {_qq($_)} @_;
20   if (@result == 1) {
21     return @result;
22   }
23   return '(' . join (', ', @result) . ')';
24 }
25
26
27 sub list_eq ($$) {
28   my ($l, $r) = @_;
29   return unless @$l == @$r;
30   for my $i (0..$#$l) {
31     if (defined $l->[$i]) {
32       return unless defined ($r->[$i]) && $l->[$i] eq $r->[$i];
33     } else {
34       return if defined $r->[$i]
35     }
36   }
37   return 1;
38 }
39
40 ##############################################################################
41 #
42 # Here starteth the tests
43 #
44
45 {
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,
50                "abcdef");
51     my $foo = pack($format,@ary);
52     my @ary2 = unpack($format,$foo);
53
54     is($#ary, $#ary2);
55
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:/;
61     is($out1, $out2);
62
63     like($foo, qr/def/);
64 }
65 # How about counting bits?
66
67 {
68     my $x;
69     is( ($x = unpack("%32B*", "\001\002\004\010\020\040\100\200\377")), 16 );
70
71     is( ($x = unpack("%32b69", "\001\002\004\010\020\040\100\200\017")), 12 );
72
73     is( ($x = unpack("%32B69", "\001\002\004\010\020\040\100\200\017")), 9 );
74 }
75
76 {
77     my $sum = 129; # ASCII
78     $sum = 103 if $Is_EBCDIC;
79
80     my $x;
81     is( ($x = unpack("%32B*", "Now is the time for all good blurfl")), $sum );
82
83     my $foo;
84     open(BIN, $Perl) || die "Can't open $Perl: $!\n";
85     sysread BIN, $foo, 8192;
86     close BIN;
87
88     $sum = unpack("%32b*", $foo);
89     my $longway = unpack("b*", $foo);
90     is( $sum, $longway =~ tr/1/1/ );
91 }
92
93 {
94   my $x;
95   is( ($x = unpack("I",pack("I", 0xFFFFFFFF))), 0xFFFFFFFF );
96 }
97
98 {
99     # check 'w'
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';
105
106     is($x, $y);
107
108     my @y = unpack('w*', $y);
109     my $a;
110     while ($a = pop @x) {
111         my $b = pop @y;
112         is($a, $b);
113     }
114
115     @y = unpack('w2', $x);
116
117     is(scalar(@y), 2);
118     is($y[1], 130);
119     $x = pack('w*', 5000000000); $y = '';
120     eval {
121     use Math::BigInt;
122     $y = pack('w*', Math::BigInt::->new(5000000000));
123     };
124     is($x, $y);
125
126     $x = pack 'w', ~0;
127     $y = pack 'w', (~0).'';
128     is($x, $y);
129     is(unpack ('w',$x), ~0);
130     is(unpack ('w',$y), ~0);
131
132     $x = pack 'w', ~0 - 1;
133     $y = pack 'w', (~0) - 2;
134
135     if (~0 - 1 == (~0) - 2) {
136         is($x, $y, "NV arithmetic");
137     } else {
138         isnt($x, $y, "IV/NV arithmetic");
139     }
140     cmp_ok(unpack ('w',$x), '==', ~0 - 1);
141     cmp_ok(unpack ('w',$y), '==', ~0 - 2);
142 }
143
144
145 {
146   # test exceptions
147   my $x;
148   eval { $x = unpack 'w', pack 'C*', 0xff, 0xff};
149   like($@, qr/^Unterminated compressed integer/);
150
151   eval { $x = unpack 'w', pack 'C*', 0xff, 0xff, 0xff, 0xff};
152   like($@, qr/^Unterminated compressed integer/);
153
154   eval { $x = unpack 'w', pack 'C*', 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff};
155   like($@, qr/^Unterminated compressed integer/);
156 }
157
158 #
159 # test the "p" template
160
161 # literals
162 is(unpack("p",pack("p","foo")), "foo");
163
164 # scalars
165 is(unpack("p",pack("p",239)), 239);
166
167 # temps
168 sub foo { my $a = "a"; return $a . $a++ . $a++ }
169 {
170   use warnings;
171   my $warning;
172   local $SIG{__WARN__} = sub {
173       $warning = $_[0];
174   };
175   my $junk = pack("p", &foo);
176
177   like($warning, qr/temporary val/);
178 }
179
180 # undef should give null pointer
181 like(pack("p", undef), qr/^\0+/);
182
183 # Check for optimizer bug (e.g.  Digital Unix GEM cc with -O4 on DU V4.0B gives
184 #                                4294967295 instead of -1)
185 #                                see #ifdef __osf__ in pp.c pp_unpack
186 is((unpack("i",pack("i",-1))), -1);
187
188 # test the pack lengths of s S i I l L
189 # test the pack lengths of n N v V
190 my @lengths = qw(s 2 S 2 i -4 I -4 l 4 L 4 n 2 N 4 v 2 V 4);
191 while (my ($format, $expect) = splice @lengths, 0, 2) {
192   my $len = length(pack($format, 0));
193   if ($expect > 0) {
194     is($expect, $len, "format '$format'");
195   } else {
196     $expect = -$expect;
197     ok ($len >= $expect, "format '$format'") ||
198       print "# format '$format' has length $len, expected >= $expect\n";
199   }
200 }
201
202
203 # test unpack-pack lengths
204 my @templates = qw(c C i I s S l L n N v V f d q Q);
205
206 foreach my $t (@templates) {
207     SKIP: {
208         my @t = eval { unpack("$t*", pack("$t*", 12, 34)) };
209
210         # quads not supported everywhere
211         skip "Quads not supported", 4 if $@ =~ /Invalid type in pack/;
212         is( $@, '' );
213
214         is(scalar @t, 2);
215
216         SKIP: {
217             skip "$t not expected to work for some reason", 2 if $t =~ /[nv]/i;
218
219             is($t[0], 12);
220             is($t[1], 34);
221         }
222     }
223 }
224
225 {
226     # uuencode/decode
227
228     # Note that first uuencoding known 'text' data and then checking the
229     # binary values of the uuencoded version would not be portable between
230     # character sets.  Uuencoding is meant for encoding binary data, not
231     # text data.
232
233     my $in = pack 'C*', 0 .. 255;
234
235     # just to be anal, we do some random tr/`/ /
236     my $uu = <<'EOUU';
237 M` $"`P0%!@<("0H+# T.#Q`1$A,4%187&!D:&QP='A\@(2(C)"4F)R@I*BLL
238 M+2XO,#$R,S0U-C<X.3H[/#T^/T!!0D-$149'2$E*2TQ-3D]045)35%565UA9
239 M6EM<75Y?8&%B8V1E9F=H:6IK;&UN;W!Q<G-T=79W>'EZ>WQ]?G^`@8*#A(6&
240 MAXB)BHN,C8Z/D)&2DY25EI>8F9J;G)V>GZ"AHJ.DI::GJ*FJJZRMKJ^PL;*S
241 MM+6VM[BYNKN\O;Z_P,'"P\3%QL?(R<K+S,W.S]#1TM/4U=;7V-G:V]S=WM_@
242 ?X>+CY.7FY^CIZNOL[>[O\/'R\_3U]O?X^?K[_/W^_P `
243 EOUU
244
245     $_ = $uu;
246     tr/ /`/;
247
248     is(pack('u', $in), $_);
249
250     is(unpack('u', $uu), $in);
251
252     $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";
253     $uu = <<'EOUU';
254 M'XL("%C<Q#4"`TI!4%4`\RHM+E%(S,LOR4@M4@A(+<I1*"U-SD])+>("`&1F
255 &8%P:````
256 EOUU
257
258     is(unpack('u', $uu), $in);
259
260 # This is identical to the above except that backquotes have been
261 # changed to spaces
262
263     $uu = <<'EOUU';
264 M'XL("%C<Q#4" TI!4%4 \RHM+E%(S,LOR4@M4@A(+<I1*"U-SD])+>(" &1F
265 &8%P:
266 EOUU
267
268     # ' # Grr
269     is(unpack('u', $uu), $in);
270
271 }
272
273 # test the ascii template types (A, a, Z)
274
275 foreach (
276 ['p', 'A*',  "foo\0bar\0 ", "foo\0bar\0 "],
277 ['p', 'A11', "foo\0bar\0 ", "foo\0bar\0   "],
278 ['u', 'A*',  "foo\0bar \0", "foo\0bar"],
279 ['u', 'A8',  "foo\0bar \0", "foo\0bar"],
280 ['p', 'a*',  "foo\0bar\0 ", "foo\0bar\0 "],
281 ['p', 'a11', "foo\0bar\0 ", "foo\0bar\0 \0\0"],
282 ['u', 'a*',  "foo\0bar \0", "foo\0bar \0"],
283 ['u', 'a8',  "foo\0bar \0", "foo\0bar "],
284 ['p', 'Z*',  "foo\0bar\0 ", "foo\0bar\0 \0"],
285 ['p', 'Z11', "foo\0bar\0 ", "foo\0bar\0 \0\0"],
286 ['p', 'Z3',  "foo",         "fo\0"],
287 ['u', 'Z*',  "foo\0bar \0", "foo"],
288 ['u', 'Z8',  "foo\0bar \0", "foo"],
289
290 {
291     my ($what, $template, $in, $out) = @$_;
292     my $got = $what eq 'u' ? (unpack $template, $in) : (pack $template, $in);
293     unless (is($got, $out)) {
294         my $un = $what eq 'u' ? 'un' : '';
295         print "# ${un}pack ('$template', "._qq($in).') gave '._qq($out).
296             ' not '._qq($got)."\n";
297     }
298 }
299
300 # packing native shorts/ints/longs
301
302 is(length(pack("s!", 0)), $Config{shortsize});
303 is(length(pack("i!", 0)), $Config{intsize});
304 is(length(pack("l!", 0)), $Config{longsize});
305 ok(length(pack("s!", 0)) <= length(pack("i!", 0)));
306 ok(length(pack("i!", 0)) <= length(pack("l!", 0)));
307 is(length(pack("i!", 0)), length(pack("i", 0)));
308
309 sub numbers {
310   my $format = shift;
311   return numbers_with_total ($format, undef, @_);
312 }
313
314 sub numbers_with_total {
315   my $format = shift;
316   my $total = shift;
317   if (!defined $total) {
318     foreach (@_) {
319       $total += $_;
320     }
321   }
322   foreach (@_) {
323     SKIP: {
324         my $out = eval {unpack($format, pack($format, $_))};
325         skip "cannot pack '$format' on this perl", 2 if
326           $@ =~ /Invalid type in pack: '$format'/;
327
328         is($@, '');
329         is($out, $_);
330     }
331   }
332
333   my $skip_if_longer_than = ~0; # "Infinity"
334   if (~0 - 1 == ~0) {
335     # If we're running with -DNO_PERLPRESERVE_IVUV and NVs don't preserve all
336     # UVs (in which case ~0 is NV, ~0-1 will be the same NV) then we can't
337     # correctly in perl calculate UV totals for long checksums, as pp_unpack
338     # is using UV maths, and we've only got NVs.
339     $skip_if_longer_than = $Config{nv_preserves_uv_bits};
340   }
341
342   foreach ('', 1, 2, 3, 15, 16, 17, 31, 32, 33, 53, 54, 63, 64, 65) {
343     SKIP: {
344       my $sum = eval {unpack "%$_$format*", pack "$format*", @_};
345       skip "cannot pack '$format' on this perl", 3
346         if $@ =~ /Invalid type in pack: '$format'/;
347
348       is($@, '');
349       ok(defined $sum);
350
351       my $len = $_; # Copy, so that we can reassign ''
352       $len = 16 unless length $len;
353
354       SKIP: {
355         skip "cannot test checksums over $skip_if_longer_than bits", 1
356           if $len > $skip_if_longer_than;
357
358         # Our problem with testing this portably is that the checksum code in
359         # pp_unpack is able to cast signed to unsigned, and do modulo 2**n
360         # arithmetic in unsigned ints, which perl has no operators to do.
361         # (use integer; does signed ints, which won't wrap on UTS, which is just
362         # fine with ANSI, but not with most people's assumptions.
363         # This is why we need to supply the totals for 'Q' as there's no way in
364         # perl to calculate them, short of unpack '%0Q' (is that documented?)
365         # ** returns NVs; make sure it's IV.
366         my $max = 1 + 2 * (int (2 ** ($len-1))-1); # The max possible checksum
367         my $max_p1 = $max + 1;
368         my ($max_is_integer, $max_p1_is_integer);
369         $max_p1_is_integer = 1 unless $max_p1 + 1 == $max_p1;
370         $max_is_integer = 1 if $max - 1 < ~0;
371
372         my $calc_sum;
373         if (ref $total) {
374             $calc_sum = &$total($len);
375         } else {
376             $calc_sum = $total;
377             # Shift into range by some multiple of the total
378             my $mult = int ($total / $max_p1);
379             # Need this to make sure that -1 + (~0+1) is ~0 (ie still integer)
380             $calc_sum = $total - $mult;
381             $calc_sum -= $mult * $max;
382             if ($calc_sum < 0) {
383                 $calc_sum += 1;
384                 $calc_sum += $max;
385             }
386         }
387         if ($calc_sum == $calc_sum - 1 && $calc_sum == $max_p1) {
388             # we're into floating point (either by getting out of the range of
389             # UV arithmetic, or because we're doing a floating point checksum) 
390             # and our calculation of the checksum has become rounded up to
391             # max_checksum + 1
392             $calc_sum = 0;
393         }
394
395         if ($calc_sum == $sum) { # HAS to be ==, not eq (so no is()).
396             ok ("unpack '%$_$format' gave $sum");
397         } else {
398             my $delta = 1.000001;
399             if ($format =~ tr /dDfF//
400                 && ($calc_sum <= $sum * $delta && $calc_sum >= $sum / $delta)) {
401                 pass ("unpack '%$_$format' gave $sum, expected $calc_sum");
402             } else {
403                 my $text = ref $total ? &$total($len) : $total;
404                 fail;
405                 print "# For list (" . join (", ", @_) . ") (total $text)"
406                     . " packed with $format unpack '%$_$format' gave $sum,"
407                     . " expected $calc_sum\n";
408             }
409         }
410       }
411     }   
412   }
413 }
414
415 numbers ('c', -128, -1, 0, 1, 127);
416 numbers ('C', 0, 1, 127, 128, 255);
417 numbers ('s', -32768, -1, 0, 1, 32767);
418 numbers ('S', 0, 1, 32767, 32768, 65535);
419 numbers ('i', -2147483648, -1, 0, 1, 2147483647);
420 numbers ('I', 0, 1, 2147483647, 2147483648, 4294967295);
421 numbers ('l', -2147483648, -1, 0, 1, 2147483647);
422 numbers ('L', 0, 1, 2147483647, 2147483648, 4294967295);
423 numbers ('s!', -32768, -1, 0, 1, 32767);
424 numbers ('S!', 0, 1, 32767, 32768, 65535);
425 numbers ('i!', -2147483648, -1, 0, 1, 2147483647);
426 numbers ('I!', 0, 1, 2147483647, 2147483648, 4294967295);
427 numbers ('l!', -2147483648, -1, 0, 1, 2147483647);
428 numbers ('L!', 0, 1, 2147483647, 2147483648, 4294967295);
429 numbers ('n', 0, 1, 32767, 32768, 65535);
430 numbers ('v', 0, 1, 32767, 32768, 65535);
431 numbers ('N', 0, 1, 2147483647, 2147483648, 4294967295);
432 numbers ('V', 0, 1, 2147483647, 2147483648, 4294967295);
433 # All these should have exact binary representations:
434 numbers ('f', -1, 0, 0.5, 42, 2**34);
435 numbers ('d', -(2**34), -1, 0, 1, 2**34);
436 ## These don't, but 'd' is NV.  XXX wrong, it's double
437 #numbers ('d', -1, 0, 1, 1-exp(-1), -exp(1));
438
439 numbers_with_total ('q', -1,
440                     -9223372036854775808, -1, 0, 1,9223372036854775807);
441 # This total is icky, but the true total is 2**65-1, and need a way to generate
442 # the epxected checksum on any system including those where NVs can preserve
443 # 65 bits. (long double is 128 bits on sparc, so they certainly can)
444 # or where rounding is down not up on binary conversion (crays)
445 numbers_with_total ('Q', sub {
446                       my $len = shift;
447                       $len = 65 if $len > 65; # unmasked total is 2**65-1 here
448                       my $total = 1 + 2 * (int (2**($len - 1)) - 1);
449                       return 0 if $total == $total - 1; # Overflowed integers
450                       return $total; # NVs still accurate to nearest integer
451                     },
452                     0, 1,9223372036854775807, 9223372036854775808,
453                     18446744073709551615);
454
455 # pack nvNV byteorders
456
457 is(pack("n", 0xdead), "\xde\xad");
458 is(pack("v", 0xdead), "\xad\xde");
459 is(pack("N", 0xdeadbeef), "\xde\xad\xbe\xef");
460 is(pack("V", 0xdeadbeef), "\xef\xbe\xad\xde");
461
462 {
463   # /
464
465   my ($x, $y, $z);
466   eval { ($x) = unpack '/a*','hello' };
467   like($@, qr!/ must follow a numeric type!);
468   undef $x;
469   eval { $x = unpack '/a*','hello' };
470   like($@, qr!/ must follow a numeric type!);
471
472   undef $x;
473   eval { ($z,$x,$y) = unpack 'a3/A C/a* C/Z', "003ok \003yes\004z\000abc" };
474   is($@, '');
475   is($z, 'ok');
476   is($x, 'yes');
477   is($y, 'z');
478   undef $z;
479   eval { $z = unpack 'a3/A C/a* C/Z', "003ok \003yes\004z\000abc" };
480   is($@, '');
481   is($z, 'ok');
482
483
484   undef $x;
485   eval { ($x) = pack '/a*','hello' };
486   like($@,  qr!Invalid type in pack: '/'!);
487   undef $x;
488   eval { $x = pack '/a*','hello' };
489   like($@,  qr!Invalid type in pack: '/'!);
490
491   $z = pack 'n/a* N/Z* w/A*','string','hi there ','etc';
492   my $expect = "\000\006string\0\0\0\012hi there \000\003etc";
493   is($z, $expect);
494
495   undef $x;
496   $expect = 'hello world';
497   eval { ($x) = unpack ("w/a", chr (11) . "hello world!")};
498   is($x, $expect);
499   is($@, '');
500
501   undef $x;
502   # Doing this in scalar context used to fail.
503   eval { $x = unpack ("w/a", chr (11) . "hello world!")};
504   is($@, '');
505   is($x, $expect);
506
507   foreach (
508            ['a/a*/a*', '212ab345678901234567','ab3456789012'],
509            ['a/a*/a*', '3012ab345678901234567', 'ab3456789012'],
510            ['a/a*/b*', '212ab', $Is_EBCDIC ? '100000010100' : '100001100100'],
511   ) 
512   {
513     my ($pat, $in, $expect) = @$_;
514     undef $x;
515     eval { ($x) = unpack $pat, $in };
516     is($@, '');
517     is($x, $expect) || 
518       printf "# list unpack ('$pat', '$in') gave %s, expected '$expect'\n",
519              encode_list ($x);
520
521     undef $x;
522     eval { $x = unpack $pat, $in };
523     is($@, '');
524     is($x, $expect) ||
525       printf "# scalar unpack ('$pat', '$in') gave %s, expected '$expect'\n",
526              encode_list ($x);
527   }
528
529   # / with #
530
531   my $pattern = <<'EOU';
532  a3/A                   # Count in ASCII
533  C/a*                   # Count in a C char
534  C/Z                    # Count in a C char but skip after \0
535 EOU
536
537   $x = $y = $z =undef;
538   eval { ($z,$x,$y) = unpack $pattern, "003ok \003yes\004z\000abc" };
539   is($@, '');
540   is($z, 'ok');
541   is($x, 'yes');
542   is($y, 'z');
543   undef $x;
544   eval { $z = unpack $pattern, "003ok \003yes\004z\000abc" };
545   is($@, '');
546   is($z, 'ok');
547
548   $pattern = <<'EOP';
549   n/a*                  # Count as network short
550   w/A*                  # Count a  BER integer
551 EOP
552   $expect = "\000\006string\003etc";
553   $z = pack $pattern,'string','etc';
554   is($z, $expect);
555 }
556
557
558 SKIP: {
559     skip("(EBCDIC and) version strings are bad idea", 2) if $Is_EBCDIC;
560
561     is("1.20.300.4000", sprintf "%vd", pack("U*",1,20,300,4000));
562     is("1.20.300.4000", sprintf "%vd", pack("  U*",1,20,300,4000));
563 }
564 isnt(v1.20.300.4000, sprintf "%vd", pack("C0U*",1,20,300,4000));
565
566 my $rslt = $Is_EBCDIC ? "156 67" : "199 162";
567 is(join(" ", unpack("C*", chr(0x1e2))), $rslt);
568
569 # does pack U create Unicode?
570 is(ord(pack('U', 300)), 300);
571
572 # does unpack U deref Unicode?
573 is((unpack('U', chr(300)))[0], 300);
574
575 # is unpack U the reverse of pack U for Unicode string?
576 is("@{[unpack('U*', pack('U*', 100, 200, 300))]}", "100 200 300");
577
578 # is unpack U the reverse of pack U for byte string?
579 is("@{[unpack('U*', pack('U*', 100, 200))]}", "100 200");
580
581
582 SKIP: {
583     skip "Not for EBCDIC", 4 if $Is_EBCDIC;
584
585     # does unpack C unravel pack U?
586     is("@{[unpack('C*', pack('U*', 100, 200))]}", "100 195 136");
587
588     # does pack U0C create Unicode?
589     is("@{[pack('U0C*', 100, 195, 136)]}", v100.v200);
590
591     # does pack C0U create characters?
592     is("@{[pack('C0U*', 100, 200)]}", pack("C*", 100, 195, 136));
593
594     # does unpack U0U on byte data warn?
595     {
596         local $SIG{__WARN__} = sub { $@ = "@_" };
597         my @null = unpack('U0U', chr(255));
598         like($@, /^Malformed UTF-8 character /);
599     }
600 }
601
602 {
603   my $p = pack 'i*', -2147483648, ~0, 0, 1, 2147483647;
604   my (@a);
605   # bug - % had to be at the start of the pattern, no leading whitespace or
606   # comments. %i! didn't work at all.
607   foreach my $pat ('%32i*', ' %32i*', "# Muhahahaha\n%32i*", '%32i*  ',
608                    '%32i!*', ' %32i!*', "\n#\n#\n\r \t\f%32i!*", '%32i!*#') {
609     @a = unpack $pat, $p;
610     is($a[0], 0xFFFFFFFF) || print "# $pat\n";
611     @a = scalar unpack $pat, $p;
612     is($a[0], 0xFFFFFFFF) || print "# $pat\n";
613   }
614
615
616   $p = pack 'I*', 42, 12;
617   # Multiline patterns in scalar context failed.
618   foreach my $pat ('I', <<EOPOEMSNIPPET, 'I#I', 'I # I', 'I # !!!') {
619 # On the Ning Nang Nong
620 # Where the Cows go Bong!
621 # And the Monkeys all say Boo!
622 I
623 EOPOEMSNIPPET
624     @a = unpack $pat, $p;
625     is(scalar @a, 1);
626     is($a[0], 42);
627     @a = scalar unpack $pat, $p;
628     is(scalar @a, 1);
629     is($a[0], 42);
630   }
631
632   # shorts (of all flavours) didn't calculate checksums > 32 bits with floating
633   # point, so a pathologically long pattern would wrap at 32 bits.
634   my $pat = "\xff\xff"x65538; # Start with it long, to save any copying.
635   foreach (4,3,2,1,0) {
636     my $len = 65534 + $_;
637     is(unpack ("%33n$len", $pat), 65535 * $len);
638   }
639 }
640
641
642 # pack x X @
643 foreach (
644          ['x', "N", "\0"],
645          ['x4', "N", "\0"x4],
646          ['xX', "N", ""],
647          ['xXa*', "Nick", "Nick"],
648          ['a5Xa5', "cameL", "llama", "camellama"],
649          ['@4', 'N', "\0"x4],
650          ['a*@8a*', 'Camel', 'Dromedary', "Camel\0\0\0Dromedary"],
651          ['a*@4a', 'Perl rules', '!', 'Perl!'],
652
653 {
654   my ($template, @in) = @$_;
655   my $out = pop @in;
656   my $got = eval {pack $template, @in};
657   is($@, '');
658   is($out, $got) ||
659     printf "# pack ('$template', %s) gave %s expected %s\n",
660            encode_list (@in), encode_list ($got), encode_list ($out);
661 }
662
663 # unpack x X @
664 foreach (
665          ['x', "N"],
666          ['xX', "N"],
667          ['xXa*', "Nick", "Nick"],
668          ['a5Xa5', "camellama", "camel", "llama"],
669          ['@3', "ice"],
670          ['@2a2', "water", "te"],
671          ['a*@1a3', "steam", "steam", "tea"],
672
673 {
674   my ($template, $in, @out) = @$_;
675   my @got = eval {unpack $template, $in};
676   is($@, '');
677   list_eq (\@got, \@out) ||
678     printf "# list unpack ('$template', %s) gave %s expected %s\n",
679            _qq($in), encode_list (@got), encode_list (@out);
680
681   my $got = eval {unpack $template, $in};
682   is($@, '');
683   @out ? is( $got, $out[0] ) # 1 or more items; should get first
684        : ok( !defined $got ) # 0 items; should get undef
685     or printf "# scalar unpack ('$template', %s) gave %s expected %s\n",
686               _qq($in), encode_list ($got), encode_list ($out[0]);
687 }
688
689 {
690     my $t = 'Z*Z*';
691     my ($u, $v) = qw(foo xyzzy);
692     my $p = pack($t, $u, $v);
693     my @u = unpack($t, $p);
694     is(scalar @u, 2);
695     is($u[0], $u);
696     is($u[1], $v);
697 }
698
699 {
700     is((unpack("w/a*", "\x02abc"))[0], "ab");
701
702     # "w/a*" should be seen as one unit
703
704     is(scalar unpack("w/a*", "\x02abc"), "ab");
705 }
706
707 {
708     # from Wolfgang Laun: fix in change #13163
709
710     my $s = 'ABC' x 10;
711     my $t = '*';
712     my $x = ord($t);
713     my $buf = pack( 'Z*/A* C',  $s, $x );
714     my $y;
715
716     my $h = $buf;
717     $h =~ s/[^[:print:]]/./g;
718     ( $s, $y ) = unpack( "Z*/A* C", $buf );
719     is($h, "30.ABCABCABCABCABCABCABCABCABCABC$t");
720     is(length $buf, 34);
721     is($s, "ABCABCABCABCABCABCABCABCABCABC");
722     is($y, $x);
723 }
724
725 {
726     # from Wolfgang Laun: fix in change #13288
727
728     eval { my $t=unpack("P*", "abc") };
729     like($@, qr/P must have an explicit size/);
730 }
731
732 {   # Grouping constructs
733     my (@a, @b);
734     @a = unpack '(SL)',   pack 'SLSLSL', 67..90;
735     is("@a", "67 68");
736     @a = unpack '(SL)3',   pack 'SLSLSL', 67..90;
737     @b = (67..72);
738     is("@a", "@b");
739     @a = unpack '(SL)3',   pack 'SLSLSLSL', 67..90;
740     is("@a", "@b");
741     @a = unpack '(SL)[3]', pack 'SLSLSLSL', 67..90;
742     is("@a", "@b");
743     @a = unpack '(SL)[2] SL', pack 'SLSLSLSL', 67..90;
744     is("@a", "@b");
745     @a = unpack 'A/(SL)',  pack 'ASLSLSLSL', 3, 67..90;
746     is("@a", "@b");
747     @a = unpack 'A/(SL)SL',  pack 'ASLSLSLSL', 2, 67..90;
748     is("@a", "@b");
749     @a = unpack '(SL)*',   pack 'SLSLSLSL', 67..90;
750     @b = (67..74);
751     is("@a", "@b");
752     @a = unpack '(SL)*SL',   pack 'SLSLSLSL', 67..90;
753     is("@a", "@b");
754     eval { @a = unpack '(*SL)',   '' };
755     like($@, qr/\(\)-group starts with a count/);
756     eval { @a = unpack '(3SL)',   '' };
757     like($@, qr/\(\)-group starts with a count/);
758     eval { @a = unpack '([3]SL)',   '' };
759     like($@, qr/\(\)-group starts with a count/);
760     eval { @a = pack '(*SL)' };
761     like($@, qr/\(\)-group starts with a count/);
762     @a = unpack '(SL)3 SL',   pack '(SL)4', 67..74;
763     is("@a", "@b");
764     @a = unpack '(SL)3 SL',   pack '(SL)[4]', 67..74;
765     is("@a", "@b");
766     @a = unpack '(SL)3 SL',   pack '(SL)*', 67..74;
767     is("@a", "@b");
768 }
769
770 {  # Repeat count [SUBEXPR]
771    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
772                    s! S! i! I! l! L! j J);
773    my $G;
774    if (eval { pack 'q', 1 } ) {
775      push @codes, qw(q Q);
776    } else {
777      push @codes, qw(c C);      # Keep the count the same
778    }
779    if (eval { pack 'D', 1 } ) {
780      push @codes, 'D';
781    } else {
782      push @codes, 'd';  # Keep the count the same
783    }
784
785    my %val;
786    @val{@codes} = map { / [Xx]  (?{ undef })
787                         | [AZa] (?{ 'something' })
788                         | C     (?{ 214 })
789                         | c     (?{ 114 })
790                         | [Bb]  (?{ '101' })
791                         | [Hh]  (?{ 'b8' })
792                         | [svnSiIlVNLqQjJ]  (?{ 10111 })
793                         | [FfDd]  (?{ 1.36514538e67 })
794                         | [pP]  (?{ "try this buffer" })
795                         /x; $^R } @codes;
796    my @end = (0x12345678, 0x23456781, 0x35465768, 0x15263748);
797    my $end = "N4";
798
799    for my $type (@codes) {
800      my @list = $val{$type};
801      @list = () unless defined $list[0];
802      for my $count ('', '3', '[11]') {
803        my $c = 1;
804        $c = $1 if $count =~ /(\d+)/;
805        my @list1 = @list;
806        @list1 = (@list1) x $c unless $type =~ /[XxAaZBbHhP]/;
807        for my $groupend ('', ')2', ')[8]') {
808            my $groupbegin = ($groupend ? '(' : '');
809            $c = 1;
810            $c = $1 if $groupend =~ /(\d+)/;
811            my @list2 = (@list1) x $c;
812
813            my $junk1 = "$groupbegin $type$count $groupend";
814            # print "# junk1=$junk1\n";
815            my $p = pack $junk1, @list2;
816            my $half = int( (length $p)/2 );
817            for my $move ('', "X$half", "X!$half", 'x1', 'x!8', "x$half") {
818              my $junk = "$junk1 $move";
819              # print "# junk='$junk', list=(@list2)\n";
820              $p = pack "$junk $end", @list2, @end;
821              my @l = unpack "x[$junk] $end", $p;
822              is(scalar @l, scalar @end);
823              is("@l", "@end", "skipping x[$junk]");
824            }
825        }
826      }
827    }
828 }
829
830 # / is recognized after spaces in scalar context
831 # XXXX no spaces are allowed in pack...  In pack only before the slash...
832 is(scalar unpack('A /A Z20', pack 'A/A* Z20', 'bcde', 'xxxxx'), 'bcde');
833 is(scalar unpack('A /A /A Z20', '3004bcde'), 'bcde');
834
835 { # X! and x!
836   my $t = 'C[3]  x!8 C[2]';
837   my @a = (0x73..0x77);
838   my $p = pack($t, @a);
839   is($p, "\x73\x74\x75\0\0\0\0\0\x76\x77");
840   my @b = unpack $t, $p;
841   is(scalar @b, scalar @a);
842   is("@b", "@a", 'x!8');
843   $t = 'x[5] C[6] X!8 C[2]';
844   @a = (0x73..0x7a);
845   $p = pack($t, @a);
846   is($p, "\0\0\0\0\0\x73\x74\x75\x79\x7a");
847   @b = unpack $t, $p;
848   @a = (0x73..0x75, 0x79, 0x7a, 0x79, 0x7a);
849   is(scalar @b, scalar @a);
850   is("@b", "@a");
851 }
852
853 { # struct {char c1; double d; char cc[2];}
854   my $t = 'C x![d] d C[2]';
855   my @a = (173, 1.283476517e-45, 42, 215);
856   my $p = pack $t, @a;
857   ok( length $p);
858   my @b = unpack "$t X[$t] $t", $p;     # Extract, step back, extract again
859   is(scalar @b, 2 * scalar @a);
860   $b = "@b";
861   $b =~ s/(?:17000+|16999+)\d+(e-45) /17$1 /gi; # stringification is gamble
862   is($b, "@a @a");
863
864   my $warning;
865   local $SIG{__WARN__} = sub {
866       $warning = $_[0];
867   };
868   @b = unpack "x[C] x[$t] X[$t] X[C] $t", "$p\0";
869
870   is($warning, undef);
871   is(scalar @b, scalar @a);
872   $b = "@b";
873   $b =~ s/(?:17000+|16999+)\d+(e-45) /17$1 /gi; # stringification is gamble
874   is($b, "@a");
875 }
876
877 is(length(pack("j", 0)), $Config{ivsize});
878 is(length(pack("J", 0)), $Config{uvsize});
879 is(length(pack("F", 0)), $Config{nvsize});
880
881 numbers ('j', -2147483648, -1, 0, 1, 2147483647);
882 numbers ('J', 0, 1, 2147483647, 2147483648, 4294967295);
883 numbers ('F', -(2**34), -1, 0, 1, 2**34);
884 SKIP: {
885     my $t = eval { unpack("D*", pack("D", 12.34)) };
886
887     skip "Long doubles not in use", 56 if $@ =~ /Invalid type in pack/;
888
889     is(length(pack("D", 0)), $Config{longdblsize});
890     numbers ('D', -(2**34), -1, 0, 1, 2**34);
891 }
892