f32ee38fec6e5be78c54f48aa548be281f216d92
[p5sagit/p5-mst-13.2.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 # 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";
14
15 plan tests => 13679;
16
17 use strict;
18 use warnings;
19 use Config;
20
21 my $Is_EBCDIC = (defined $Config{ebcdic} && $Config{ebcdic} eq 'define');
22 my $Perl = which_perl();
23 my @valid_errors = (qr/^Invalid type '\w'/);
24
25 my $ByteOrder = 'unknown';
26 my $maybe_not_avail = '(?:hto[bl]e|[bl]etoh)';
27 if ($no_endianness) {
28   push @valid_errors, qr/^Invalid type '[<>]'/;
29 } elsif ($Config{byteorder} =~ /^1234(?:5678)?$/) {
30   $ByteOrder = 'little';
31   $maybe_not_avail = '(?:htobe|betoh)';
32 }
33 elsif ($Config{byteorder} =~ /^(?:8765)?4321$/) {
34   $ByteOrder = 'big';
35   $maybe_not_avail = '(?:htole|letoh)';
36 }
37 else {
38   push @valid_errors, qr/^Can't (?:un)?pack (?:big|little)-endian .*? on this platform/;
39 }
40
41 if ($no_signedness) {
42   push @valid_errors, qr/^'!' allowed only after types sSiIlLxX in (?:un)?pack/;
43 }
44
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/;
48   }
49 }
50
51 my $IsTwosComplement = pack('i', -1) eq "\xFF" x $Config{intsize};
52 print "# \$IsTwosComplement = $IsTwosComplement\n";
53
54 sub is_valid_error
55 {
56   my $err = shift;
57
58   for my $e (@valid_errors) {
59     $err =~ $e and return 1;
60   }
61
62   return 0;
63 }
64
65 sub encode_list {
66   my @result = map {_qq($_)} @_;
67   if (@result == 1) {
68     return @result;
69   }
70   return '(' . join (', ', @result) . ')';
71 }
72
73
74 sub list_eq ($$) {
75   my ($l, $r) = @_;
76   return 0 unless @$l == @$r;
77   for my $i (0..$#$l) {
78     if (defined $l->[$i]) {
79       return 0 unless defined ($r->[$i]) && $l->[$i] eq $r->[$i];
80     } else {
81       return 0 if defined $r->[$i]
82     }
83   }
84   return 1;
85 }
86
87 ##############################################################################
88 #
89 # Here starteth the tests
90 #
91
92 {
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,
97                "abcdef");
98     my $foo = pack($format,@ary);
99     my @ary2 = unpack($format,$foo);
100
101     is($#ary, $#ary2);
102
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:/;
108     is($out1, $out2);
109
110     like($foo, qr/def/);
111 }
112 # How about counting bits?
113
114 {
115     my $x;
116     is( ($x = unpack("%32B*", "\001\002\004\010\020\040\100\200\377")), 16 );
117
118     is( ($x = unpack("%32b69", "\001\002\004\010\020\040\100\200\017")), 12 );
119
120     is( ($x = unpack("%32B69", "\001\002\004\010\020\040\100\200\017")), 9 );
121 }
122
123 {
124     my $sum = 129; # ASCII
125     $sum = 103 if $Is_EBCDIC;
126
127     my $x;
128     is( ($x = unpack("%32B*", "Now is the time for all good blurfl")), $sum );
129
130     my $foo;
131     open(BIN, $Perl) || die "Can't open $Perl: $!\n";
132     sysread BIN, $foo, 8192;
133     close BIN;
134
135     $sum = unpack("%32b*", $foo);
136     my $longway = unpack("b*", $foo);
137     is( $sum, $longway =~ tr/1/1/ );
138 }
139
140 {
141   my $x;
142   is( ($x = unpack("I",pack("I", 0xFFFFFFFF))), 0xFFFFFFFF );
143 }
144
145 {
146     # check 'w'
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';
152
153     is($x, $y);
154
155     my @y = unpack('w*', $y);
156     my $a;
157     while ($a = pop @x) {
158         my $b = pop @y;
159         is($a, $b);
160     }
161
162     @y = unpack('w2', $x);
163
164     is(scalar(@y), 2);
165     is($y[1], 130);
166     $x = pack('w*', 5000000000); $y = '';
167     eval {
168     use Math::BigInt;
169     $y = pack('w*', Math::BigInt::->new(5000000000));
170     };
171     is($x, $y);
172
173     $x = pack 'w', ~0;
174     $y = pack 'w', (~0).'';
175     is($x, $y);
176     is(unpack ('w',$x), ~0);
177     is(unpack ('w',$y), ~0);
178
179     $x = pack 'w', ~0 - 1;
180     $y = pack 'w', (~0) - 2;
181
182     if (~0 - 1 == (~0) - 2) {
183         is($x, $y, "NV arithmetic");
184     } else {
185         isnt($x, $y, "IV/NV arithmetic");
186     }
187     cmp_ok(unpack ('w',$x), '==', ~0 - 1);
188     cmp_ok(unpack ('w',$y), '==', ~0 - 2);
189
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)
193     my $x0 = 2**54+3;
194     my $y0 = 2**54-2;
195
196     $x = pack 'w', $x0;
197     $y = pack 'w', $y0;
198
199     if ($x0 == $y0) {
200         is($x, $y, "NV arithmetic");
201     } else {
202         isnt($x, $y, "IV/NV arithmetic");
203     }
204     cmp_ok(unpack ('w',$x), '==', $x0);
205     cmp_ok(unpack ('w',$y), '==', $y0);
206 }
207
208
209 {
210   print "# test exceptions\n";
211   my $x;
212   eval { $x = unpack 'w', pack 'C*', 0xff, 0xff};
213   like($@, qr/^Unterminated compressed integer/);
214
215   eval { $x = unpack 'w', pack 'C*', 0xff, 0xff, 0xff, 0xff};
216   like($@, qr/^Unterminated compressed integer/);
217
218   eval { $x = unpack 'w', pack 'C*', 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff};
219   like($@, qr/^Unterminated compressed integer/);
220
221   eval { $x = pack 'w', -1 };
222   like ($@, qr/^Cannot compress negative numbers/);
223
224   eval { $x = pack 'w', '1'x(1 + length ~0) . 'e0' };
225   like ($@, qr/^Can only compress unsigned integers/);
226
227  SKIP: {
228     skip $no_endianness, 2*3 + 2*8 if $no_endianness;
229     for my $mod (qw( ! < > )) {
230       eval { $x = pack "a$mod", 42 };
231       like ($@, qr/^'$mod' allowed only after types \S+ in pack/);
232
233       eval { $x = unpack "a$mod", 'x'x8 };
234       like ($@, qr/^'$mod' allowed only after types \S+ in unpack/);
235     }
236
237     for my $mod (qw( <> >< !<> !>< <!> >!< <>! ><! )) {
238       eval { $x = pack "sI${mod}s", 42, 47, 11 };
239       like ($@, qr/^Can't use both '<' and '>' after type 'I' in pack/);
240
241       eval { $x = unpack "sI${mod}s", 'x'x16 };
242       like ($@, qr/^Can't use both '<' and '>' after type 'I' in unpack/);
243     }
244   }
245
246  SKIP: {
247     # Is this a stupid thing to do on VMS, VOS and other unusual platforms?
248
249     skip("-- the IEEE infinity model is unavailable in this configuration.", 1)
250        if (($^O eq 'VMS') && !defined($Config{useieee}));
251
252     skip("-- $^O has serious fp indigestion on w-packed infinities", 1)
253        if (
254            ($^O eq 'mpeix')
255            ||
256            ($^O eq 'ultrix')
257            ||
258            ($^O =~ /^svr4/ && -f "/etc/issue" && -f "/etc/.relid") # NCR MP-RAS
259            );
260
261     my $inf = eval '2**1000000';
262
263     skip("Couldn't generate infinity - got error '$@'", 1)
264       unless defined $inf and $inf == $inf / 2 and $inf + 1 == $inf;
265
266     local our $TODO;
267     $TODO = "VOS needs a fix for posix-1022 to pass this test."
268       if ($^O eq 'vos');
269
270     eval { $x = pack 'w', $inf };
271     like ($@, qr/^Cannot compress integer/, "Cannot compress integer");
272   }
273
274  SKIP: {
275
276     skip("-- the full range of an IEEE double may not be available in this configuration.", 3)
277        if (($^O eq 'VMS') && !defined($Config{useieee}));
278
279     skip("-- $^O does not like 2**1023", 3)
280        if (($^O eq 'ultrix'));
281
282     # This should be about the biggest thing possible on an IEEE double
283     my $big = eval '2**1023';
284
285     skip("Couldn't generate 2**1023 - got error '$@'", 3)
286       unless defined $big and $big != $big / 2;
287
288     eval { $x = pack 'w', $big };
289     is ($@, '', "Should be able to pack 'w', $big # 2**1023");
290
291     my $y = eval {unpack 'w', $x};
292     is ($@, '',
293         "Should be able to unpack 'w' the result of pack 'w', $big # 2**1023");
294
295     # I'm getting about 1e-16 on FreeBSD
296     my $quotient = int (100 * ($y - $big) / $big);
297     ok($quotient < 2 && $quotient > -2,
298        "Round trip pack, unpack 'w' of $big is within 1% ($quotient%)");
299   }
300
301 }
302
303 print "# test the 'p' template\n";
304
305 # literals
306 is(unpack("p",pack("p","foo")), "foo");
307 SKIP: {
308   skip $no_endianness, 2 if $no_endianness;
309   is(unpack("p<",pack("p<","foo")), "foo");
310   is(unpack("p>",pack("p>","foo")), "foo");
311 }
312 # scalars
313 is(unpack("p",pack("p",239)), 239);
314 SKIP: {
315   skip $no_endianness, 2 if $no_endianness;
316   is(unpack("p<",pack("p<",239)), 239);
317   is(unpack("p>",pack("p>",239)), 239);
318 }
319
320 # temps
321 sub foo { my $a = "a"; return $a . $a++ . $a++ }
322 {
323   use warnings;
324   my $warning;
325   local $SIG{__WARN__} = sub {
326       $warning = $_[0];
327   };
328   my $junk = pack("p", &foo);
329
330   like($warning, qr/temporary val/);
331 }
332
333 # undef should give null pointer
334 like(pack("p", undef), qr/^\0+$/);
335 SKIP: {
336   skip $no_endianness, 2 if $no_endianness;
337   like(pack("p<", undef), qr/^\0+$/);
338   like(pack("p>", undef), qr/^\0+$/);
339 }
340
341 # Check for optimizer bug (e.g.  Digital Unix GEM cc with -O4 on DU V4.0B gives
342 #                                4294967295 instead of -1)
343 #                                see #ifdef __osf__ in pp.c pp_unpack
344 is((unpack("i",pack("i",-1))), -1);
345
346 print "# test the pack lengths of s S i I l L n N v V + modifiers\n";
347
348 my @lengths = (
349   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),
350   's!'  => $Config{shortsize}, 'S!'  => $Config{shortsize},
351   'i!'  => $Config{intsize},   'I!'  => $Config{intsize},
352   'l!'  => $Config{longsize},  'L!'  => $Config{longsize},
353 );
354
355 while (my ($base, $expect) = splice @lengths, 0, 2) {
356   my @formats = ($base);
357   $base =~ /^[nv]/i or push @formats, "$base>", "$base<";
358   for my $format (@formats) {
359   SKIP: {
360       skip $no_endianness, 1 if $no_endianness && $format =~ m/[<>]/;
361       skip $no_signedness, 1 if $no_signedness && $format =~ /[nNvV]!/;
362       my $len = length(pack($format, 0));
363       if ($expect > 0) {
364         is($expect, $len, "format '$format'");
365       } else {
366         $expect = -$expect;
367         ok ($len >= $expect, "format '$format'") ||
368           print "# format '$format' has length $len, expected >= $expect\n";
369       }
370     }
371   }
372 }
373
374
375 print "# test unpack-pack lengths\n";
376
377 my @templates = qw(c C i I s S l L n N v V f d q Q);
378
379 foreach my $base (@templates) {
380     my @tmpl = ($base);
381     $base =~ /^[cnv]/i or push @tmpl, "$base>", "$base<";
382     foreach my $t (@tmpl) {
383         SKIP: {
384             my @t = eval { unpack("$t*", pack("$t*", 12, 34)) };
385
386             skip "cannot pack '$t' on this perl", 4
387               if is_valid_error($@);
388
389             is( $@, '', "Template $t works");
390             is(scalar @t, 2);
391
392             is($t[0], 12);
393             is($t[1], 34);
394         }
395     }
396 }
397
398 {
399     # uuencode/decode
400
401     # Note that first uuencoding known 'text' data and then checking the
402     # binary values of the uuencoded version would not be portable between
403     # character sets.  Uuencoding is meant for encoding binary data, not
404     # text data.
405
406     my $in = pack 'C*', 0 .. 255;
407
408     # just to be anal, we do some random tr/`/ /
409     my $uu = <<'EOUU';
410 M` $"`P0%!@<("0H+# T.#Q`1$A,4%187&!D:&QP='A\@(2(C)"4F)R@I*BLL
411 M+2XO,#$R,S0U-C<X.3H[/#T^/T!!0D-$149'2$E*2TQ-3D]045)35%565UA9
412 M6EM<75Y?8&%B8V1E9F=H:6IK;&UN;W!Q<G-T=79W>'EZ>WQ]?G^`@8*#A(6&
413 MAXB)BHN,C8Z/D)&2DY25EI>8F9J;G)V>GZ"AHJ.DI::GJ*FJJZRMKJ^PL;*S
414 MM+6VM[BYNKN\O;Z_P,'"P\3%QL?(R<K+S,W.S]#1TM/4U=;7V-G:V]S=WM_@
415 ?X>+CY.7FY^CIZNOL[>[O\/'R\_3U]O?X^?K[_/W^_P `
416 EOUU
417
418     $_ = $uu;
419     tr/ /`/;
420
421     is(pack('u', $in), $_);
422
423     is(unpack('u', $uu), $in);
424
425     $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";
426     $uu = <<'EOUU';
427 M'XL("%C<Q#4"`TI!4%4`\RHM+E%(S,LOR4@M4@A(+<I1*"U-SD])+>("`&1F
428 &8%P:````
429 EOUU
430
431     is(unpack('u', $uu), $in);
432
433 # This is identical to the above except that backquotes have been
434 # changed to spaces
435
436     $uu = <<'EOUU';
437 M'XL("%C<Q#4" TI!4%4 \RHM+E%(S,LOR4@M4@A(+<I1*"U-SD])+>(" &1F
438 &8%P:
439 EOUU
440
441     # ' # Grr
442     is(unpack('u', $uu), $in);
443
444 }
445
446 # test the ascii template types (A, a, Z)
447
448 foreach (
449 ['p', 'A*',  "foo\0bar\0 ", "foo\0bar\0 "],
450 ['p', 'A11', "foo\0bar\0 ", "foo\0bar\0   "],
451 ['u', 'A*',  "foo\0bar \0", "foo\0bar"],
452 ['u', 'A8',  "foo\0bar \0", "foo\0bar"],
453 ['p', 'a*',  "foo\0bar\0 ", "foo\0bar\0 "],
454 ['p', 'a11', "foo\0bar\0 ", "foo\0bar\0 \0\0"],
455 ['u', 'a*',  "foo\0bar \0", "foo\0bar \0"],
456 ['u', 'a8',  "foo\0bar \0", "foo\0bar "],
457 ['p', 'Z*',  "foo\0bar\0 ", "foo\0bar\0 \0"],
458 ['p', 'Z11', "foo\0bar\0 ", "foo\0bar\0 \0\0"],
459 ['p', 'Z3',  "foo",         "fo\0"],
460 ['u', 'Z*',  "foo\0bar \0", "foo"],
461 ['u', 'Z8',  "foo\0bar \0", "foo"],
462
463 {
464     my ($what, $template, $in, $out) = @$_;
465     my $got = $what eq 'u' ? (unpack $template, $in) : (pack $template, $in);
466     unless (is($got, $out)) {
467         my $un = $what eq 'u' ? 'un' : '';
468         print "# ${un}pack ('$template', "._qq($in).') gave '._qq($out).
469             ' not '._qq($got)."\n";
470     }
471 }
472
473 print "# packing native shorts/ints/longs\n";
474
475 is(length(pack("s!", 0)), $Config{shortsize});
476 is(length(pack("i!", 0)), $Config{intsize});
477 is(length(pack("l!", 0)), $Config{longsize});
478 ok(length(pack("s!", 0)) <= length(pack("i!", 0)));
479 ok(length(pack("i!", 0)) <= length(pack("l!", 0)));
480 is(length(pack("i!", 0)), length(pack("i", 0)));
481
482 sub numbers {
483   my $base = shift;
484   my @formats = ($base);
485   $base =~ /^[silqjfdp]/i and push @formats, "$base>", "$base<";
486   for my $format (@formats) {
487     numbers_with_total ($format, undef, @_);
488   }
489 }
490
491 sub numbers_with_total {
492   my $format = shift;
493   my $total = shift;
494   if (!defined $total) {
495     foreach (@_) {
496       $total += $_;
497     }
498   }
499   print "# numbers test for $format\n";
500   foreach (@_) {
501     SKIP: {
502         my $out = eval {unpack($format, pack($format, $_))};
503         skip "cannot pack '$format' on this perl", 2
504           if is_valid_error($@);
505
506         is($@, '', "no error");
507         is($out, $_, "unpack pack $format $_");
508     }
509   }
510
511   my $skip_if_longer_than = ~0; # "Infinity"
512   if (~0 - 1 == ~0) {
513     # If we're running with -DNO_PERLPRESERVE_IVUV and NVs don't preserve all
514     # UVs (in which case ~0 is NV, ~0-1 will be the same NV) then we can't
515     # correctly in perl calculate UV totals for long checksums, as pp_unpack
516     # is using UV maths, and we've only got NVs.
517     $skip_if_longer_than = $Config{nv_preserves_uv_bits};
518   }
519
520   foreach ('', 1, 2, 3, 15, 16, 17, 31, 32, 33, 53, 54, 63, 64, 65) {
521     SKIP: {
522       my $sum = eval {unpack "%$_$format*", pack "$format*", @_};
523       skip "cannot pack '$format' on this perl", 3
524         if is_valid_error($@);
525
526       is($@, '', "no error");
527       ok(defined $sum, "sum bits $_, format $format defined");
528
529       my $len = $_; # Copy, so that we can reassign ''
530       $len = 16 unless length $len;
531
532       SKIP: {
533         skip "cannot test checksums over $skip_if_longer_than bits", 1
534           if $len > $skip_if_longer_than;
535
536         # Our problem with testing this portably is that the checksum code in
537         # pp_unpack is able to cast signed to unsigned, and do modulo 2**n
538         # arithmetic in unsigned ints, which perl has no operators to do.
539         # (use integer; does signed ints, which won't wrap on UTS, which is just
540         # fine with ANSI, but not with most people's assumptions.
541         # This is why we need to supply the totals for 'Q' as there's no way in
542         # perl to calculate them, short of unpack '%0Q' (is that documented?)
543         # ** returns NVs; make sure it's IV.
544         my $max = 1 + 2 * (int (2 ** ($len-1))-1); # The max possible checksum
545         my $max_p1 = $max + 1;
546         my ($max_is_integer, $max_p1_is_integer);
547         $max_p1_is_integer = 1 unless $max_p1 + 1 == $max_p1;
548         $max_is_integer = 1 if $max - 1 < ~0;
549
550         my $calc_sum;
551         if (ref $total) {
552             $calc_sum = &$total($len);
553         } else {
554             $calc_sum = $total;
555             # Shift into range by some multiple of the total
556             my $mult = $max_p1 ? int ($total / $max_p1) : undef;
557             # Need this to make sure that -1 + (~0+1) is ~0 (ie still integer)
558             $calc_sum = $total - $mult;
559             $calc_sum -= $mult * $max;
560             if ($calc_sum < 0) {
561                 $calc_sum += 1;
562                 $calc_sum += $max;
563             }
564         }
565         if ($calc_sum == $calc_sum - 1 && $calc_sum == $max_p1) {
566             # we're into floating point (either by getting out of the range of
567             # UV arithmetic, or because we're doing a floating point checksum) 
568             # and our calculation of the checksum has become rounded up to
569             # max_checksum + 1
570             $calc_sum = 0;
571         }
572
573         if ($calc_sum == $sum) { # HAS to be ==, not eq (so no is()).
574             pass ("unpack '%$_$format' gave $sum");
575         } else {
576             my $delta = 1.000001;
577             if ($format =~ tr /dDfF//
578                 && ($calc_sum <= $sum * $delta && $calc_sum >= $sum / $delta)) {
579                 pass ("unpack '%$_$format' gave $sum, expected $calc_sum");
580             } else {
581                 my $text = ref $total ? &$total($len) : $total;
582                 fail;
583                 print "# For list (" . join (", ", @_) . ") (total $text)"
584                     . " packed with $format unpack '%$_$format' gave $sum,"
585                     . " expected $calc_sum\n";
586             }
587         }
588       }
589     }
590   }
591 }
592
593 numbers ('c', -128, -1, 0, 1, 127);
594 numbers ('C', 0, 1, 127, 128, 255);
595 numbers ('s', -32768, -1, 0, 1, 32767);
596 numbers ('S', 0, 1, 32767, 32768, 65535);
597 numbers ('i', -2147483648, -1, 0, 1, 2147483647);
598 numbers ('I', 0, 1, 2147483647, 2147483648, 4294967295);
599 numbers ('l', -2147483648, -1, 0, 1, 2147483647);
600 numbers ('L', 0, 1, 2147483647, 2147483648, 4294967295);
601 numbers ('s!', -32768, -1, 0, 1, 32767);
602 numbers ('S!', 0, 1, 32767, 32768, 65535);
603 numbers ('i!', -2147483648, -1, 0, 1, 2147483647);
604 numbers ('I!', 0, 1, 2147483647, 2147483648, 4294967295);
605 numbers ('l!', -2147483648, -1, 0, 1, 2147483647);
606 numbers ('L!', 0, 1, 2147483647, 2147483648, 4294967295);
607 numbers ('n', 0, 1, 32767, 32768, 65535);
608 numbers ('v', 0, 1, 32767, 32768, 65535);
609 numbers ('N', 0, 1, 2147483647, 2147483648, 4294967295);
610 numbers ('V', 0, 1, 2147483647, 2147483648, 4294967295);
611 numbers ('n!', -32768, -1, 0, 1, 32767);
612 numbers ('v!', -32768, -1, 0, 1, 32767);
613 numbers ('N!', -2147483648, -1, 0, 1, 2147483647);
614 numbers ('V!', -2147483648, -1, 0, 1, 2147483647);
615 # All these should have exact binary representations:
616 numbers ('f', -1, 0, 0.5, 42, 2**34);
617 numbers ('d', -(2**34), -1, 0, 1, 2**34);
618 ## These don't, but 'd' is NV.  XXX wrong, it's double
619 #numbers ('d', -1, 0, 1, 1-exp(-1), -exp(1));
620
621 numbers_with_total ('q', -1,
622                     -9223372036854775808, -1, 0, 1,9223372036854775807);
623 # This total is icky, but the true total is 2**65-1, and need a way to generate
624 # the epxected checksum on any system including those where NVs can preserve
625 # 65 bits. (long double is 128 bits on sparc, so they certainly can)
626 # or where rounding is down not up on binary conversion (crays)
627 numbers_with_total ('Q', sub {
628                       my $len = shift;
629                       $len = 65 if $len > 65; # unmasked total is 2**65-1 here
630                       my $total = 1 + 2 * (int (2**($len - 1)) - 1);
631                       return 0 if $total == $total - 1; # Overflowed integers
632                       return $total; # NVs still accurate to nearest integer
633                     },
634                     0, 1,9223372036854775807, 9223372036854775808,
635                     18446744073709551615);
636
637 print "# pack nvNV byteorders\n";
638
639 is(pack("n", 0xdead), "\xde\xad");
640 is(pack("v", 0xdead), "\xad\xde");
641 is(pack("N", 0xdeadbeef), "\xde\xad\xbe\xef");
642 is(pack("V", 0xdeadbeef), "\xef\xbe\xad\xde");
643
644 SKIP: {
645   skip $no_signedness, 4 if $no_signedness;
646   is(pack("n!", 0xdead), "\xde\xad");
647   is(pack("v!", 0xdead), "\xad\xde");
648   is(pack("N!", 0xdeadbeef), "\xde\xad\xbe\xef");
649   is(pack("V!", 0xdeadbeef), "\xef\xbe\xad\xde");
650 }
651
652 print "# test big-/little-endian conversion\n";
653
654 sub byteorder
655 {
656   my $format = shift;
657   print "# byteorder test for $format\n";
658   for my $value (@_) {
659     SKIP: {
660       my($nat,$be,$le) = eval { map { pack $format.$_, $value } '', '>', '<' };
661       skip "cannot pack '$format' on this perl", 5
662         if is_valid_error($@);
663
664       print "# [$value][$nat][$be][$le][$@]\n";
665
666       SKIP: {
667         skip "cannot compare native byteorder with big-/little-endian", 1
668             if $ByteOrder eq 'unknown';
669
670         is($nat, $ByteOrder eq 'big' ? $be : $le);
671       }
672       is($be, reverse($le));
673       my @x = eval { unpack "$format$format>$format<", $nat.$be.$le };
674
675       print "# [$value][", join('][', @x), "][$@]\n";
676
677       is($@, '');
678       is($x[0], $x[1]);
679       is($x[0], $x[2]);
680     }
681   }
682 }
683
684 byteorder('s', -32768, -1, 0, 1, 32767);
685 byteorder('S', 0, 1, 32767, 32768, 65535);
686 byteorder('i', -2147483648, -1, 0, 1, 2147483647);
687 byteorder('I', 0, 1, 2147483647, 2147483648, 4294967295);
688 byteorder('l', -2147483648, -1, 0, 1, 2147483647);
689 byteorder('L', 0, 1, 2147483647, 2147483648, 4294967295);
690 byteorder('j', -2147483648, -1, 0, 1, 2147483647);
691 byteorder('J', 0, 1, 2147483647, 2147483648, 4294967295);
692 byteorder('s!', -32768, -1, 0, 1, 32767);
693 byteorder('S!', 0, 1, 32767, 32768, 65535);
694 byteorder('i!', -2147483648, -1, 0, 1, 2147483647);
695 byteorder('I!', 0, 1, 2147483647, 2147483648, 4294967295);
696 byteorder('l!', -2147483648, -1, 0, 1, 2147483647);
697 byteorder('L!', 0, 1, 2147483647, 2147483648, 4294967295);
698 byteorder('q', -9223372036854775808, -1, 0, 1, 9223372036854775807);
699 byteorder('Q', 0, 1, 9223372036854775807, 9223372036854775808, 18446744073709551615);
700 byteorder('f', -1, 0, 0.5, 42, 2**34);
701 byteorder('F', -1, 0, 0.5, 42, 2**34);
702 byteorder('d', -(2**34), -1, 0, 1, 2**34);
703 byteorder('D', -(2**34), -1, 0, 1, 2**34);
704
705 print "# test negative numbers\n";
706
707 SKIP: {
708   skip "platform is not using two's complement for negative integers", 120
709     unless $IsTwosComplement;
710
711   for my $format (qw(s i l j s! i! l! q)) {
712     SKIP: {
713       my($nat,$be,$le) = eval { map { pack $format.$_, -1 } '', '>', '<' };
714       skip "cannot pack '$format' on this perl", 15
715         if is_valid_error($@);
716
717       my $len = length $nat;
718       is($_, "\xFF"x$len) for $nat, $be, $le;
719
720       my(@val,@ref);
721       if ($len >= 8) {
722         @val = (-2, -81985529216486896, -9223372036854775808);
723         @ref = ("\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFE",
724                 "\xFE\xDC\xBA\x98\x76\x54\x32\x10",
725                 "\x80\x00\x00\x00\x00\x00\x00\x00");
726       }
727       elsif ($len >= 4) {
728         @val = (-2, -19088744, -2147483648);
729         @ref = ("\xFF\xFF\xFF\xFE",
730                 "\xFE\xDC\xBA\x98",
731                 "\x80\x00\x00\x00");
732       }
733       else {
734         @val = (-2, -292, -32768);
735         @ref = ("\xFF\xFE",
736                 "\xFE\xDC",
737                 "\x80\x00");
738       }
739       for my $x (@ref) {
740         if ($len > length $x) {
741           $x = $x . "\xFF" x ($len - length $x);
742         }
743       }
744
745       for my $i (0 .. $#val) {
746         my($nat,$be,$le) = eval { map { pack $format.$_, $val[$i] } '', '>', '<' };
747         is($@, '');
748
749         SKIP: {
750           skip "cannot compare native byteorder with big-/little-endian", 1
751               if $ByteOrder eq 'unknown';
752
753           is($nat, $ByteOrder eq 'big' ? $be : $le);
754         }
755
756         is($be, $ref[$i]);
757         is($be, reverse($le));
758       }
759     }
760   }
761 }
762
763 {
764   # /
765
766   my ($x, $y, $z);
767   eval { ($x) = unpack '/a*','hello' };
768   like($@, qr!'/' must follow a numeric type!);
769   undef $x;
770   eval { $x = unpack '/a*','hello' };
771   like($@, qr!'/' must follow a numeric type!);
772
773   undef $x;
774   eval { ($z,$x,$y) = unpack 'a3/A C/a* C/Z', "003ok \003yes\004z\000abc" };
775   is($@, '');
776   is($z, 'ok');
777   is($x, 'yes');
778   is($y, 'z');
779   undef $z;
780   eval { $z = unpack 'a3/A C/a* C/Z', "003ok \003yes\004z\000abc" };
781   is($@, '');
782   is($z, 'ok');
783
784
785   undef $x;
786   eval { ($x) = pack '/a*','hello' };
787   like($@,  qr!Invalid type '/'!);
788   undef $x;
789   eval { $x = pack '/a*','hello' };
790   like($@,  qr!Invalid type '/'!);
791
792   $z = pack 'n/a* N/Z* w/A*','string','hi there ','etc';
793   my $expect = "\000\006string\0\0\0\012hi there \000\003etc";
794   is($z, $expect);
795
796   undef $x;
797   $expect = 'hello world';
798   eval { ($x) = unpack ("w/a", chr (11) . "hello world!")};
799   is($x, $expect);
800   is($@, '');
801
802   undef $x;
803   # Doing this in scalar context used to fail.
804   eval { $x = unpack ("w/a", chr (11) . "hello world!")};
805   is($@, '');
806   is($x, $expect);
807
808   foreach (
809            ['a/a*/a*', '212ab345678901234567','ab3456789012'],
810            ['a/a*/a*', '3012ab345678901234567', 'ab3456789012'],
811            ['a/a*/b*', '212ab', $Is_EBCDIC ? '100000010100' : '100001100100'],
812   ) 
813   {
814     my ($pat, $in, $expect) = @$_;
815     undef $x;
816     eval { ($x) = unpack $pat, $in };
817     is($@, '');
818     is($x, $expect) || 
819       printf "# list unpack ('$pat', '$in') gave %s, expected '$expect'\n",
820              encode_list ($x);
821
822     undef $x;
823     eval { $x = unpack $pat, $in };
824     is($@, '');
825     is($x, $expect) ||
826       printf "# scalar unpack ('$pat', '$in') gave %s, expected '$expect'\n",
827              encode_list ($x);
828   }
829
830   # / with #
831
832   my $pattern = <<'EOU';
833  a3/A                   # Count in ASCII
834  C/a*                   # Count in a C char
835  C/Z                    # Count in a C char but skip after \0
836 EOU
837
838   $x = $y = $z =undef;
839   eval { ($z,$x,$y) = unpack $pattern, "003ok \003yes\004z\000abc" };
840   is($@, '');
841   is($z, 'ok');
842   is($x, 'yes');
843   is($y, 'z');
844   undef $x;
845   eval { $z = unpack $pattern, "003ok \003yes\004z\000abc" };
846   is($@, '');
847   is($z, 'ok');
848
849   $pattern = <<'EOP';
850   n/a*                  # Count as network short
851   w/A*                  # Count a  BER integer
852 EOP
853   $expect = "\000\006string\003etc";
854   $z = pack $pattern,'string','etc';
855   is($z, $expect);
856 }
857
858
859 SKIP: {
860     skip("(EBCDIC and) version strings are bad idea", 2) if $Is_EBCDIC;
861
862     is("1.20.300.4000", sprintf "%vd", pack("U*",1,20,300,4000));
863     is("1.20.300.4000", sprintf "%vd", pack("  U*",1,20,300,4000));
864 }
865 isnt(v1.20.300.4000, sprintf "%vd", pack("C0U*",1,20,300,4000));
866
867 my $rslt = $Is_EBCDIC ? "156 67" : "199 162";
868 is(join(" ", unpack("C*", chr(0x1e2))), $rslt);
869
870 # does pack U create Unicode?
871 is(ord(pack('U', 300)), 300);
872
873 # does unpack U deref Unicode?
874 is((unpack('U', chr(300)))[0], 300);
875
876 # is unpack U the reverse of pack U for Unicode string?
877 is("@{[unpack('U*', pack('U*', 100, 200, 300))]}", "100 200 300");
878
879 # is unpack U the reverse of pack U for byte string?
880 is("@{[unpack('U*', pack('U*', 100, 200))]}", "100 200");
881
882
883 SKIP: {
884     skip "Not for EBCDIC", 4 if $Is_EBCDIC;
885
886     # does unpack C unravel pack U?
887     is("@{[unpack('C*', pack('U*', 100, 200))]}", "100 195 136");
888
889     # does pack U0C create Unicode?
890     is("@{[pack('U0C*', 100, 195, 136)]}", v100.v200);
891
892     # does pack C0U create characters?
893     is("@{[pack('C0U*', 100, 200)]}", pack("C*", 100, 195, 136));
894
895     # does unpack U0U on byte data warn?
896     {
897         local $SIG{__WARN__} = sub { $@ = "@_" };
898         my @null = unpack('U0U', chr(255));
899         like($@, qr/^Malformed UTF-8 character /);
900     }
901 }
902
903 {
904   my $p = pack 'i*', -2147483648, ~0, 0, 1, 2147483647;
905   my (@a);
906   # bug - % had to be at the start of the pattern, no leading whitespace or
907   # comments. %i! didn't work at all.
908   foreach my $pat ('%32i*', ' %32i*', "# Muhahahaha\n%32i*", '%32i*  ',
909                    '%32i!*', ' %32i!*', "\n#\n#\n\r \t\f%32i!*", '%32i!*#') {
910     @a = unpack $pat, $p;
911     is($a[0], 0xFFFFFFFF) || print "# $pat\n";
912     @a = scalar unpack $pat, $p;
913     is($a[0], 0xFFFFFFFF) || print "# $pat\n";
914   }
915
916
917   $p = pack 'I*', 42, 12;
918   # Multiline patterns in scalar context failed.
919   foreach my $pat ('I', <<EOPOEMSNIPPET, 'I#I', 'I # I', 'I # !!!') {
920 # On the Ning Nang Nong
921 # Where the Cows go Bong!
922 # And the Monkeys all say Boo!
923 I
924 EOPOEMSNIPPET
925     @a = unpack $pat, $p;
926     is(scalar @a, 1);
927     is($a[0], 42);
928     @a = scalar unpack $pat, $p;
929     is(scalar @a, 1);
930     is($a[0], 42);
931   }
932
933   # shorts (of all flavours) didn't calculate checksums > 32 bits with floating
934   # point, so a pathologically long pattern would wrap at 32 bits.
935   my $pat = "\xff\xff"x65538; # Start with it long, to save any copying.
936   foreach (4,3,2,1,0) {
937     my $len = 65534 + $_;
938     is(unpack ("%33n$len", $pat), 65535 * $len);
939   }
940 }
941
942
943 # pack x X @
944 foreach (
945          ['x', "N", "\0"],
946          ['x4', "N", "\0"x4],
947          ['xX', "N", ""],
948          ['xXa*', "Nick", "Nick"],
949          ['a5Xa5', "cameL", "llama", "camellama"],
950          ['@4', 'N', "\0"x4],
951          ['a*@8a*', 'Camel', 'Dromedary', "Camel\0\0\0Dromedary"],
952          ['a*@4a', 'Perl rules', '!', 'Perl!'],
953
954 {
955   my ($template, @in) = @$_;
956   my $out = pop @in;
957   my $got = eval {pack $template, @in};
958   is($@, '');
959   is($out, $got) ||
960     printf "# pack ('$template', %s) gave %s expected %s\n",
961            encode_list (@in), encode_list ($got), encode_list ($out);
962 }
963
964 # unpack x X @
965 foreach (
966          ['x', "N"],
967          ['xX', "N"],
968          ['xXa*', "Nick", "Nick"],
969          ['a5Xa5', "camellama", "camel", "llama"],
970          ['@3', "ice"],
971          ['@2a2', "water", "te"],
972          ['a*@1a3', "steam", "steam", "tea"],
973
974 {
975   my ($template, $in, @out) = @$_;
976   my @got = eval {unpack $template, $in};
977   is($@, '');
978   ok (list_eq (\@got, \@out)) ||
979     printf "# list unpack ('$template', %s) gave %s expected %s\n",
980            _qq($in), encode_list (@got), encode_list (@out);
981
982   my $got = eval {unpack $template, $in};
983   is($@, '');
984   @out ? is( $got, $out[0] ) # 1 or more items; should get first
985        : ok( !defined $got ) # 0 items; should get undef
986     or printf "# scalar unpack ('$template', %s) gave %s expected %s\n",
987               _qq($in), encode_list ($got), encode_list ($out[0]);
988 }
989
990 {
991     my $t = 'Z*Z*';
992     my ($u, $v) = qw(foo xyzzy);
993     my $p = pack($t, $u, $v);
994     my @u = unpack($t, $p);
995     is(scalar @u, 2);
996     is($u[0], $u);
997     is($u[1], $v);
998 }
999
1000 {
1001     is((unpack("w/a*", "\x02abc"))[0], "ab");
1002
1003     # "w/a*" should be seen as one unit
1004
1005     is(scalar unpack("w/a*", "\x02abc"), "ab");
1006 }
1007
1008 SKIP: {
1009   print "# group modifiers\n";
1010
1011   skip $no_endianness, 3 * 2 + 3 * 2 + 1 if $no_endianness;
1012
1013   for my $t (qw{ (s<)< (sl>s)> (s(l(sl)<l)s)< }) {
1014     print "# testing pattern '$t'\n";
1015     eval { ($_) = unpack($t, 'x'x18); };
1016     is($@, '');
1017     eval { $_ = pack($t, (0)x6); };
1018     is($@, '');
1019   }
1020
1021   for my $t (qw{ (s<)> (sl>s)< (s(l(sl)<l)s)> }) {
1022     print "# testing pattern '$t'\n";
1023     eval { ($_) = unpack($t, 'x'x18); };
1024     like($@, qr/Can't use '[<>]' in a group with different byte-order in unpack/);
1025     eval { $_ = pack($t, (0)x6); };
1026     like($@, qr/Can't use '[<>]' in a group with different byte-order in pack/);
1027   }
1028
1029   is(pack('L<L>', (0x12345678)x2),
1030      pack('(((L1)1)<)(((L)1)1)>1', (0x12345678)x2));
1031 }
1032
1033 {
1034   sub compress_template {
1035     my $t = shift;
1036     for my $mod (qw( < > )) {
1037       $t =~ s/((?:(?:[SILQJFDP]!?$mod|[^SILQJFDP\W]!?)(?:\d+|\*|\[(?:[^]]+)\])?\/?){2,})/
1038               my $x = $1; $x =~ s!$mod!!g ? "($x)$mod" : $x /ieg;
1039     }
1040     return $t;
1041   }
1042
1043   my %templates = (
1044     's<'                  => [-42],
1045     's<c2x![S]S<'         => [-42, -11, 12, 4711],
1046     '(i<j<[s]l<)3'        => [-11, -22, -33, 1000000, 1100, 2201, 3302,
1047                               -1000000, 32767, -32768, 1, -123456789 ],
1048     '(I!<4(J<2L<)3)5'     => [1 .. 65],
1049     'q<Q<'                => [-50000000005, 60000000006],
1050     'f<F<d<'              => [3.14159, 111.11, 2222.22],
1051     'D<cCD<'              => [1e42, -128, 255, 1e-42],
1052     'n/a*'                => ['/usr/bin/perl'],
1053     'C/a*S</A*L</Z*I</a*' => [qw(Just another Perl hacker)],
1054   );
1055
1056   for my $tle (sort keys %templates) {
1057     my @d = @{$templates{$tle}};
1058     my $tbe = $tle;
1059     $tbe =~ y/</>/;
1060     for my $t ($tbe, $tle) {
1061       my $c = compress_template($t);
1062       print "# '$t' -> '$c'\n";
1063       SKIP: {
1064         my $p1 = eval { pack $t, @d };
1065         skip "cannot pack '$t' on this perl", 5 if is_valid_error($@);
1066         my $p2 = eval { pack $c, @d };
1067         is($@, '');
1068         is($p1, $p2);
1069         s!(/[aAZ])\*!$1!g for $t, $c;
1070         my @u1 = eval { unpack $t, $p1 };
1071         is($@, '');
1072         my @u2 = eval { unpack $c, $p2 };
1073         is($@, '');
1074         is(join('!', @u1), join('!', @u2));
1075       }
1076     }
1077   }
1078 }
1079
1080 {
1081     # from Wolfgang Laun: fix in change #13163
1082
1083     my $s = 'ABC' x 10;
1084     my $t = '*';
1085     my $x = ord($t);
1086     my $buf = pack( 'Z*/A* C',  $s, $x );
1087     my $y;
1088
1089     my $h = $buf;
1090     $h =~ s/[^[:print:]]/./g;
1091     ( $s, $y ) = unpack( "Z*/A* C", $buf );
1092     is($h, "30.ABCABCABCABCABCABCABCABCABCABC$t");
1093     is(length $buf, 34);
1094     is($s, "ABCABCABCABCABCABCABCABCABCABC");
1095     is($y, $x);
1096 }
1097
1098 {
1099     # from Wolfgang Laun: fix in change #13288
1100
1101     eval { my $t=unpack("P*", "abc") };
1102     like($@, qr/'P' must have an explicit size/);
1103 }
1104
1105 {   # Grouping constructs
1106     my (@a, @b);
1107     @a = unpack '(SL)',   pack 'SLSLSL', 67..90;
1108     is("@a", "67 68");
1109     @a = unpack '(SL)3',   pack 'SLSLSL', 67..90;
1110     @b = (67..72);
1111     is("@a", "@b");
1112     @a = unpack '(SL)3',   pack 'SLSLSLSL', 67..90;
1113     is("@a", "@b");
1114     @a = unpack '(SL)[3]', pack 'SLSLSLSL', 67..90;
1115     is("@a", "@b");
1116     @a = unpack '(SL)[2] SL', pack 'SLSLSLSL', 67..90;
1117     is("@a", "@b");
1118     @a = unpack 'A/(SL)',  pack 'ASLSLSLSL', 3, 67..90;
1119     is("@a", "@b");
1120     @a = unpack 'A/(SL)SL',  pack 'ASLSLSLSL', 2, 67..90;
1121     is("@a", "@b");
1122     @a = unpack '(SL)*',   pack 'SLSLSLSL', 67..90;
1123     @b = (67..74);
1124     is("@a", "@b");
1125     @a = unpack '(SL)*SL',   pack 'SLSLSLSL', 67..90;
1126     is("@a", "@b");
1127     eval { @a = unpack '(*SL)',   '' };
1128     like($@, qr/\(\)-group starts with a count/);
1129     eval { @a = unpack '(3SL)',   '' };
1130     like($@, qr/\(\)-group starts with a count/);
1131     eval { @a = unpack '([3]SL)',   '' };
1132     like($@, qr/\(\)-group starts with a count/);
1133     eval { @a = pack '(*SL)' };
1134     like($@, qr/\(\)-group starts with a count/);
1135     @a = unpack '(SL)3 SL',   pack '(SL)4', 67..74;
1136     is("@a", "@b");
1137     @a = unpack '(SL)3 SL',   pack '(SL)[4]', 67..74;
1138     is("@a", "@b");
1139     @a = unpack '(SL)3 SL',   pack '(SL)*', 67..74;
1140     is("@a", "@b");
1141 }
1142
1143 {  # more on grouping (W.Laun)
1144   use warnings;
1145   my $warning;
1146   local $SIG{__WARN__} = sub {
1147       $warning = $_[0];
1148   };
1149   # @ absolute within ()-group
1150   my $badc = pack( '(a)*', unpack( '(@1a @0a @2)*', 'abcd' ) );
1151   is( $badc, 'badc' );
1152   my @b = ( 1, 2, 3 );
1153   my $buf = pack( '(@1c)((@2C)@3c)', @b );
1154   is( $buf, "\0\1\0\0\2\3" );
1155   my @a = unpack( '(@1c)((@2c)@3c)', $buf );
1156   is( "@a", "@b" );
1157
1158   # various unpack count/code scenarios 
1159   my @Env = ( a => 'AAA', b => 'BBB' );
1160   my $env = pack( 'S(S/A*S/A*)*', @Env/2, @Env );
1161
1162   # unpack full length - ok
1163   my @pup = unpack( 'S/(S/A* S/A*)', $env );
1164   is( "@pup", "@Env" );
1165
1166   # warn when count/code goes beyond end of string
1167   # \0002 \0001 a \0003 AAA \0001 b \0003 BBB
1168   #     2     4 5     7  10    1213
1169   eval { @pup = unpack( 'S/(S/A* S/A*)', substr( $env, 0, 13 ) ) };
1170   like( $@, qr{length/code after end of string} );
1171   
1172   # postfix repeat count
1173   $env = pack( '(S/A* S/A*)' . @Env/2, @Env );
1174
1175   # warn when count/code goes beyond end of string
1176   # \0001 a \0003 AAA \0001  b \0003 BBB
1177   #     2 3c    5   8    10 11    13  16
1178   eval { @pup = unpack( '(S/A* S/A*)' . @Env/2, substr( $env, 0, 11 ) ) };
1179   like( $@, qr{length/code after end of string} );
1180
1181   # catch stack overflow/segfault
1182   eval { $_ = pack( ('(' x 105) . 'A' . (')' x 105) ); };
1183   like( $@, qr{Too deeply nested \(\)-groups} );
1184 }
1185
1186 { # syntax checks (W.Laun)
1187   use warnings;
1188   my @warning;
1189   local $SIG{__WARN__} = sub {
1190       push( @warning, $_[0] );
1191   };
1192   eval { my $s = pack( 'Ax![4c]A', 1..5 ); };
1193   like( $@, qr{Malformed integer in \[\]} );
1194
1195   eval { my $buf = pack( '(c/*a*)', 'AAA', 'BB' ); };
1196   like( $@, qr{'/' does not take a repeat count} );
1197
1198   eval { my @inf = unpack( 'c/1a', "\x03AAA\x02BB" ); };
1199   like( $@, qr{'/' does not take a repeat count} );
1200
1201   eval { my @inf = unpack( 'c/*a', "\x03AAA\x02BB" ); };
1202   like( $@, qr{'/' does not take a repeat count} );
1203
1204   # white space where possible 
1205   my @Env = ( a => 'AAA', b => 'BBB' );
1206   my $env = pack( ' S ( S / A*   S / A* )* ', @Env/2, @Env );
1207   my @pup = unpack( ' S / ( S / A*   S / A* ) ', $env );
1208   is( "@pup", "@Env" );
1209
1210   # white space in 4 wrong places
1211   for my $temp (  'A ![4]', 'A [4]', 'A *', 'A 4' ){
1212       eval { my $s = pack( $temp, 'B' ); };
1213       like( $@, qr{Invalid type } );
1214   }
1215
1216   # warning for commas
1217   @warning = ();
1218   my $x = pack( 'I,A', 4, 'X' );
1219   like( $warning[0], qr{Invalid type ','} );
1220
1221   # comma warning only once
1222   @warning = ();
1223   $x = pack( 'C(C,C)C,C', 65..71  );
1224   like( scalar @warning, 1 );
1225
1226   # forbidden code in []
1227   eval { my $x = pack( 'A[@4]', 'XXXX' ); };
1228   like( $@, qr{Within \[\]-length '\@' not allowed} );
1229
1230   # @ repeat default 1
1231   my $s = pack( 'AA@A', 'A', 'B', 'C' );
1232   my @c = unpack( 'AA@A', $s );
1233   is( $s, 'AC' ); 
1234   is( "@c", "A C C" ); 
1235
1236   # no unpack code after /
1237   eval { my @a = unpack( "C/", "\3" ); };
1238   like( $@, qr{Code missing after '/'} );
1239
1240  SKIP: {
1241     skip $no_endianness, 6 if $no_endianness;
1242
1243     # modifier warnings
1244     @warning = ();
1245     $x = pack "I>>s!!", 47, 11;
1246     ($x) = unpack "I<<l!>!>", 'x'x20;
1247     is(scalar @warning, 5);
1248     like($warning[0], qr/Duplicate modifier '>' after 'I' in pack/);
1249     like($warning[1], qr/Duplicate modifier '!' after 's' in pack/);
1250     like($warning[2], qr/Duplicate modifier '<' after 'I' in unpack/);
1251     like($warning[3], qr/Duplicate modifier '!' after 'l' in unpack/);
1252     like($warning[4], qr/Duplicate modifier '>' after 'l' in unpack/);
1253   }
1254 }
1255
1256 {  # Repeat count [SUBEXPR]
1257    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
1258                    s! S! i! I! l! L! j J);
1259    my $G;
1260    if (eval { pack 'q', 1 } ) {
1261      push @codes, qw(q Q);
1262    } else {
1263      push @codes, qw(s S);      # Keep the count the same
1264    }
1265    if (eval { pack 'D', 1 } ) {
1266      push @codes, 'D';
1267    } else {
1268      push @codes, 'd';  # Keep the count the same
1269    }
1270
1271    push @codes, map { /^[silqjfdp]/i ? ("$_<", "$_>") : () } @codes;
1272
1273    my %val;
1274    @val{@codes} = map { / [Xx]  (?{ undef })
1275                         | [AZa] (?{ 'something' })
1276                         | C     (?{ 214 })
1277                         | c     (?{ 114 })
1278                         | [Bb]  (?{ '101' })
1279                         | [Hh]  (?{ 'b8' })
1280                         | [svnSiIlVNLqQjJ]  (?{ 10111 })
1281                         | [FfDd]  (?{ 1.36514538e67 })
1282                         | [pP]  (?{ "try this buffer" })
1283                         /x; $^R } @codes;
1284    my @end = (0x12345678, 0x23456781, 0x35465768, 0x15263748);
1285    my $end = "N4";
1286
1287    for my $type (@codes) {
1288      my @list = $val{$type};
1289      @list = () unless defined $list[0];
1290      for my $count ('', '3', '[11]') {
1291        my $c = 1;
1292        $c = $1 if $count =~ /(\d+)/;
1293        my @list1 = @list;
1294        @list1 = (@list1) x $c unless $type =~ /[XxAaZBbHhP]/;
1295        for my $groupend ('', ')2', ')[8]') {
1296            my $groupbegin = ($groupend ? '(' : '');
1297            $c = 1;
1298            $c = $1 if $groupend =~ /(\d+)/;
1299            my @list2 = (@list1) x $c;
1300
1301            SKIP: {
1302              my $junk1 = "$groupbegin $type$count $groupend";
1303              # print "# junk1=$junk1\n";
1304              my $p = eval { pack $junk1, @list2 };
1305              skip "cannot pack '$type' on this perl", 12
1306                if is_valid_error($@);
1307
1308              my $half = int( (length $p)/2 );
1309              for my $move ('', "X$half", "X!$half", 'x1', 'x!8', "x$half") {
1310                my $junk = "$junk1 $move";
1311                # print "# junk='$junk', list=(@list2)\n";
1312                $p = pack "$junk $end", @list2, @end;
1313                my @l = unpack "x[$junk] $end", $p;
1314                is(scalar @l, scalar @end);
1315                is("@l", "@end", "skipping x[$junk]");
1316              }
1317            }
1318        }
1319      }
1320    }
1321 }
1322
1323 # / is recognized after spaces in scalar context
1324 # XXXX no spaces are allowed in pack...  In pack only before the slash...
1325 is(scalar unpack('A /A Z20', pack 'A/A* Z20', 'bcde', 'xxxxx'), 'bcde');
1326 is(scalar unpack('A /A /A Z20', '3004bcde'), 'bcde');
1327
1328 { # X! and x!
1329   my $t = 'C[3]  x!8 C[2]';
1330   my @a = (0x73..0x77);
1331   my $p = pack($t, @a);
1332   is($p, "\x73\x74\x75\0\0\0\0\0\x76\x77");
1333   my @b = unpack $t, $p;
1334   is(scalar @b, scalar @a);
1335   is("@b", "@a", 'x!8');
1336   $t = 'x[5] C[6] X!8 C[2]';
1337   @a = (0x73..0x7a);
1338   $p = pack($t, @a);
1339   is($p, "\0\0\0\0\0\x73\x74\x75\x79\x7a");
1340   @b = unpack $t, $p;
1341   @a = (0x73..0x75, 0x79, 0x7a, 0x79, 0x7a);
1342   is(scalar @b, scalar @a);
1343   is("@b", "@a");
1344 }
1345
1346 { # struct {char c1; double d; char cc[2];}
1347   my $t = 'C x![d] d C[2]';
1348   my @a = (173, 1.283476517e-45, 42, 215);
1349   my $p = pack $t, @a;
1350   ok( length $p);
1351   my @b = unpack "$t X[$t] $t", $p;     # Extract, step back, extract again
1352   is(scalar @b, 2 * scalar @a);
1353   $b = "@b";
1354   $b =~ s/(?:17000+|16999+)\d+(e-45) /17$1 /gi; # stringification is gamble
1355   is($b, "@a @a");
1356
1357   my $warning;
1358   local $SIG{__WARN__} = sub {
1359       $warning = $_[0];
1360   };
1361   @b = unpack "x[C] x[$t] X[$t] X[C] $t", "$p\0";
1362
1363   is($warning, undef);
1364   is(scalar @b, scalar @a);
1365   $b = "@b";
1366   $b =~ s/(?:17000+|16999+)\d+(e-45) /17$1 /gi; # stringification is gamble
1367   is($b, "@a");
1368 }
1369
1370 is(length(pack("j", 0)), $Config{ivsize});
1371 is(length(pack("J", 0)), $Config{uvsize});
1372 is(length(pack("F", 0)), $Config{nvsize});
1373
1374 numbers ('j', -2147483648, -1, 0, 1, 2147483647);
1375 numbers ('J', 0, 1, 2147483647, 2147483648, 4294967295);
1376 numbers ('F', -(2**34), -1, 0, 1, 2**34);
1377 SKIP: {
1378     my $t = eval { unpack("D*", pack("D", 12.34)) };
1379
1380     skip "Long doubles not in use", 166 if $@ =~ /Invalid type/;
1381
1382     is(length(pack("D", 0)), $Config{longdblsize});
1383     numbers ('D', -(2**34), -1, 0, 1, 2**34);
1384 }
1385
1386 # Maybe this knowledge needs to be "global" for all of pack.t
1387 # Or a "can checksum" which would effectively be all the number types"
1388 my %cant_checksum = map {$_=> 1} qw(A Z u w);
1389 # not a b B h H
1390 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)) {
1391   SKIP: {
1392     my $packed = eval {pack "${template}4", 1, 4, 9, 16};
1393     if ($@) {
1394       die unless $@ =~ /Invalid type '$template'/;
1395       skip ("$template not supported on this perl",
1396             $cant_checksum{$template} ? 4 : 8);
1397     }
1398     my @unpack4 = unpack "${template}4", $packed;
1399     my @unpack = unpack "${template}*", $packed;
1400     my @unpack1 = unpack "${template}", $packed;
1401     my @unpack1s = scalar unpack "${template}", $packed;
1402     my @unpack4s = scalar unpack "${template}4", $packed;
1403     my @unpacks = scalar unpack "${template}*", $packed;
1404
1405     my @tests = ( ["${template}4 vs ${template}*", \@unpack4, \@unpack],
1406                   ["scalar ${template} ${template}", \@unpack1s, \@unpack1],
1407                   ["scalar ${template}4 vs ${template}", \@unpack4s, \@unpack1],
1408                   ["scalar ${template}* vs ${template}", \@unpacks, \@unpack1],
1409                 );
1410
1411     unless ($cant_checksum{$template}) {
1412       my @unpack4_c = unpack "\%${template}4", $packed;
1413       my @unpack_c = unpack "\%${template}*", $packed;
1414       my @unpack1_c = unpack "\%${template}", $packed;
1415       my @unpack1s_c = scalar unpack "\%${template}", $packed;
1416       my @unpack4s_c = scalar unpack "\%${template}4", $packed;
1417       my @unpacks_c = scalar unpack "\%${template}*", $packed;
1418
1419       push @tests,
1420         ( ["% ${template}4 vs ${template}*", \@unpack4_c, \@unpack_c],
1421           ["% scalar ${template} ${template}", \@unpack1s_c, \@unpack1_c],
1422           ["% scalar ${template}4 vs ${template}*", \@unpack4s_c, \@unpack_c],
1423           ["% scalar ${template}* vs ${template}*", \@unpacks_c, \@unpack_c],
1424         );
1425     }
1426     foreach my $test (@tests) {
1427       ok (list_eq ($test->[1], $test->[2]), $test->[0]) ||
1428         printf "# unpack gave %s expected %s\n",
1429           encode_list (@{$test->[1]}), encode_list (@{$test->[2]});
1430     }
1431   }
1432 }
1433
1434 ok(pack('u2', 'AA'), "[perl #8026]"); # used to hang and eat RAM in perl 5.7.2
1435
1436 $_ = pack('c', 65); # 'A' would not be EBCDIC-friendly
1437 is(unpack('c'), 65, "one-arg unpack (change #18751)"); # defaulting to $_
1438
1439 {
1440     my $a = "X\t01234567\n" x 100;
1441     my @a = unpack("(a1 c/a)*", $a);
1442     is(scalar @a, 200,       "[perl #15288]");
1443     is($a[-1], "01234567\n", "[perl #15288]");
1444     is($a[-2], "X",          "[perl #15288]");
1445 }