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