This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Update Encode to CPAN version 2.78
[perl5.git] / t / op / pack.t
1 #!./perl -w
2
3 BEGIN {
4     chdir 't' if -d 't';
5     require './test.pl'; require './charset_tools.pl';
6     set_up_inc(qw '../lib ../dist/Math-BigInt/lib');
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 => 14708;
16
17 use strict;
18 use warnings qw(FATAL all);
19 use Config;
20
21 my $Perl = which_perl();
22 my @valid_errors = (qr/^Invalid type '\w'/);
23
24 my $ByteOrder = 'unknown';
25 my $maybe_not_avail = '(?:hto[bl]e|[bl]etoh)';
26 if ($no_endianness) {
27   push @valid_errors, qr/^Invalid type '[<>]'/;
28 } elsif ($Config{byteorder} =~ /^1234(?:5678)?$/) {
29   $ByteOrder = 'little';
30   $maybe_not_avail = '(?:htobe|betoh)';
31 }
32 elsif ($Config{byteorder} =~ /^(?:8765)?4321$/) {
33   $ByteOrder = 'big';
34   $maybe_not_avail = '(?:htole|letoh)';
35 }
36 else {
37   push @valid_errors, qr/^Can't (?:un)?pack (?:big|little)-endian .*? on this platform/;
38 }
39
40 if ($no_signedness) {
41   push @valid_errors, qr/^'!' allowed only after types sSiIlLxX in (?:un)?pack/;
42 }
43
44 for my $size ( 16, 32, 64 ) {
45   if (defined $Config{"u${size}size"} and ($Config{"u${size}size"}||0) != ($size >> 3)) {
46     push @valid_errors, qr/^Perl_my_$maybe_not_avail$size\(\) not available/;
47   }
48 }
49
50 my $IsTwosComplement = pack('i', -1) eq "\xFF" x $Config{intsize};
51 print "# \$IsTwosComplement = $IsTwosComplement\n";
52
53 sub is_valid_error
54 {
55   my $err = shift;
56
57   for my $e (@valid_errors) {
58     $err =~ $e and return 1;
59   }
60
61   return 0;
62 }
63
64 sub encode_list {
65   my @result = map {_qq($_)} @_;
66   if (@result == 1) {
67     return @result;
68   }
69   return '(' . join (', ', @result) . ')';
70 }
71
72
73 sub list_eq ($$) {
74   my ($l, $r) = @_;
75   return 0 unless @$l == @$r;
76   for my $i (0..$#$l) {
77     if (defined $l->[$i]) {
78       return 0 unless defined ($r->[$i]) && $l->[$i] eq $r->[$i];
79     } else {
80       return 0 if defined $r->[$i]
81     }
82   }
83   return 1;
84 }
85
86 ##############################################################################
87 #
88 # Here starteth the tests
89 #
90
91 {
92     my $format = "c2 x5 C C x s d i l a6";
93     # Need the expression in here to force ary[5] to be numeric.  This avoids
94     # test2 failing because ary2 goes str->numeric->str and ary doesn't.
95     my @ary = (1,-100,127,128,32767,987.654321098 / 100.0,12345,123456,
96                "abcdef");
97     my $foo = pack($format,@ary);
98     my @ary2 = unpack($format,$foo);
99
100     is($#ary, $#ary2);
101
102     my $out1=join(':',@ary);
103     my $out2=join(':',@ary2);
104     # Using long double NVs may introduce greater accuracy than wanted.
105     $out1 =~ s/:9\.87654321097999\d*:/:9.87654321098:/;
106     $out2 =~ s/:9\.87654321097999\d*:/:9.87654321098:/;
107     is($out1, $out2);
108
109     like($foo, qr/def/);
110 }
111 # How about counting bits?
112
113 {
114     my $x;
115     is( ($x = unpack("%32B*", "\001\002\004\010\020\040\100\200\377")), 16 );
116
117     is( ($x = unpack("%32b69", "\001\002\004\010\020\040\100\200\017")), 12 );
118
119     is( ($x = unpack("%32B69", "\001\002\004\010\020\040\100\200\017")), 9 );
120 }
121
122 {
123     my $sum = 129; # ASCII
124     $sum = 103 if $::IS_EBCDIC;
125
126     my $x;
127     is( ($x = unpack("%32B*", "Now is the time for all good blurfl")), $sum );
128
129     my $foo;
130     open(BIN, $Perl) || die "Can't open $Perl: $!\n";
131     binmode BIN;
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   # Check that the warning behaviour on the modifiers !, < and > is as we
228   # expect it for this perl.
229   my $can_endian = $no_endianness ? '' : 'sSiIlLqQjJfFdDpP';
230   my $can_shriek = 'sSiIlL';
231   $can_shriek .= 'nNvV' unless $no_signedness;
232   # h and H can't do either, so act as sanity checks in blead
233   foreach my $base (split '', 'hHsSiIlLqQjJfFdDpPnNvV') {
234     foreach my $mod ('', '<', '>', '!', '<!', '>!', '!<', '!>') {
235     SKIP: {
236         # Avoid void context warnings.
237         my $a = eval {pack "$base$mod"};
238         skip "pack can't $base", 1 if $@ =~ /^Invalid type '\w'/;
239         # Which error you get when 2 would be possible seems to be emergent
240         # behaviour of pack's format parser.
241
242         my $fails_shriek = $mod =~ /!/ && index ($can_shriek, $base) == -1;
243         my $fails_endian = $mod =~ /[<>]/ && index ($can_endian, $base) == -1;
244         my $shriek_first = $mod =~ /^!/;
245
246         if ($no_endianness and ($mod eq '<!' or $mod eq '>!')) {
247           # The ! isn't seem as part of $base. Instead it's seen as a modifier
248           # on > or <
249           $fails_shriek = 1;
250           undef $fails_endian;
251         } elsif ($fails_shriek and $fails_endian) {
252           if ($shriek_first) {
253             undef $fails_endian;
254           }
255         }
256
257         if ($fails_endian) {
258           if ($no_endianness) {
259             # < and > are seen as pattern letters, not modifiers
260             like ($@, qr/^Invalid type '[<>]'/, "pack can't $base$mod");
261           } else {
262             like ($@, qr/^'[<>]' allowed only after types/,
263                   "pack can't $base$mod");
264           }
265         } elsif ($fails_shriek) {
266           like ($@, qr/^'!' allowed only after types/,
267                 "pack can't $base$mod");
268         } else {
269           is ($@, '', "pack can $base$mod");
270         }
271       }
272     }
273   }
274
275  SKIP: {
276     skip $no_endianness, 2*3 + 2*8 if $no_endianness;
277     for my $mod (qw( ! < > )) {
278       eval { $x = pack "a$mod", 42 };
279       like ($@, qr/^'$mod' allowed only after types \S+ in pack/);
280
281       eval { $x = unpack "a$mod", 'x'x8 };
282       like ($@, qr/^'$mod' allowed only after types \S+ in unpack/);
283     }
284
285     for my $mod (qw( <> >< !<> !>< <!> >!< <>! ><! )) {
286       eval { $x = pack "sI${mod}s", 42, 47, 11 };
287       like ($@, qr/^Can't use both '<' and '>' after type 'I' in pack/);
288
289       eval { $x = unpack "sI${mod}s", 'x'x16 };
290       like ($@, qr/^Can't use both '<' and '>' after type 'I' in unpack/);
291     }
292   }
293
294  SKIP: {
295     # Is this a stupid thing to do on VMS, VOS and other unusual platforms?
296
297     skip("-- the IEEE infinity model is unavailable in this configuration.", 1)
298        if (($^O eq 'VMS') && !defined($Config{useieee}));
299
300     skip("-- $^O has serious fp indigestion on w-packed infinities", 1)
301        if (
302            ($^O eq 'ultrix')
303            ||
304            ($^O =~ /^svr4/ && -f "/etc/issue" && -f "/etc/.relid") # NCR MP-RAS
305            );
306
307     my $inf = eval '2**1000000';
308
309     skip("Couldn't generate infinity - got error '$@'", 1)
310       unless defined $inf and $inf == $inf / 2 and $inf + 1 == $inf;
311
312     local our $TODO;
313     $TODO = "VOS needs a fix for posix-1022 to pass this test."
314       if ($^O eq 'vos');
315
316     eval { $x = pack 'w', $inf };
317     like ($@, qr/^Cannot compress Inf/, "Cannot compress infinity");
318   }
319
320  SKIP: {
321
322     skip("-- the full range of an IEEE double may not be available in this configuration.", 3)
323        if (($^O eq 'VMS') && !defined($Config{useieee}));
324
325     skip("-- $^O does not like 2**1023", 3)
326        if (($^O eq 'ultrix'));
327
328     # This should be about the biggest thing possible on an IEEE double
329     my $big = eval '2**1023';
330
331     skip("Couldn't generate 2**1023 - got error '$@'", 3)
332       unless defined $big and $big != $big / 2;
333
334     eval { $x = pack 'w', $big };
335     is ($@, '', "Should be able to pack 'w', $big # 2**1023");
336
337     my $y = eval {unpack 'w', $x};
338     is ($@, '',
339         "Should be able to unpack 'w' the result of pack 'w', $big # 2**1023");
340
341     # I'm getting about 1e-16 on FreeBSD
342     my $quotient = int (100 * ($y - $big) / $big);
343     ok($quotient < 2 && $quotient > -2,
344        "Round trip pack, unpack 'w' of $big is within 1% ($quotient%)");
345   }
346
347 }
348
349 print "# test the 'p' template\n";
350
351 # literals
352 is(unpack("p",pack("p","foo")), "foo");
353 SKIP: {
354   skip $no_endianness, 2 if $no_endianness;
355   is(unpack("p<",pack("p<","foo")), "foo");
356   is(unpack("p>",pack("p>","foo")), "foo");
357 }
358 # scalars
359 is(unpack("p",pack("p",239)), 239);
360 SKIP: {
361   skip $no_endianness, 2 if $no_endianness;
362   is(unpack("p<",pack("p<",239)), 239);
363   is(unpack("p>",pack("p>",239)), 239);
364 }
365
366 # temps
367 sub foo { my $a = "a"; return $a . $a++ . $a++ }
368 {
369   use warnings qw(NONFATAL all);;
370   my $warning;
371   local $SIG{__WARN__} = sub {
372       $warning = $_[0];
373   };
374   my $junk = pack("p", &foo);
375
376   like($warning, qr/temporary val/);
377 }
378
379 # undef should give null pointer
380 like(pack("p", undef), qr/^\0+$/);
381 SKIP: {
382   skip $no_endianness, 2 if $no_endianness;
383   like(pack("p<", undef), qr/^\0+$/);
384   like(pack("p>", undef), qr/^\0+$/);
385 }
386
387 # Check for optimizer bug (e.g.  Digital Unix GEM cc with -O4 on DU V4.0B gives
388 #                                4294967295 instead of -1)
389 #                                see #ifdef __osf__ in pp.c pp_unpack
390 is((unpack("i",pack("i",-1))), -1);
391
392 print "# test the pack lengths of s S i I l L n N v V + modifiers\n";
393
394 my @lengths = (
395   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),
396   's!'  => $Config{shortsize}, 'S!'  => $Config{shortsize},
397   'i!'  => $Config{intsize},   'I!'  => $Config{intsize},
398   'l!'  => $Config{longsize},  'L!'  => $Config{longsize},
399 );
400
401 while (my ($base, $expect) = splice @lengths, 0, 2) {
402   my @formats = ($base);
403   $base =~ /^[nv]/i or push @formats, "$base>", "$base<";
404   for my $format (@formats) {
405   SKIP: {
406       skip $no_endianness, 1 if $no_endianness && $format =~ m/[<>]/;
407       skip $no_signedness, 1 if $no_signedness && $format =~ /[nNvV]!/;
408       my $len = length(pack($format, 0));
409       if ($expect > 0) {
410         is($expect, $len, "format '$format'");
411       } else {
412         $expect = -$expect;
413         ok ($len >= $expect, "format '$format'") ||
414           print "# format '$format' has length $len, expected >= $expect\n";
415       }
416     }
417   }
418 }
419
420
421 print "# test unpack-pack lengths\n";
422
423 my @templates = qw(c C W i I s S l L n N v V f d q Q);
424
425 foreach my $base (@templates) {
426     my @tmpl = ($base);
427     $base =~ /^[cwnv]/i or push @tmpl, "$base>", "$base<";
428     foreach my $t (@tmpl) {
429         SKIP: {
430             my @t = eval { unpack("$t*", pack("$t*", 12, 34)) };
431
432             skip "cannot pack '$t' on this perl", 4
433               if is_valid_error($@);
434
435             is( $@, '', "Template $t works");
436             is(scalar @t, 2);
437
438             is($t[0], 12);
439             is($t[1], 34);
440         }
441     }
442 }
443
444 {
445     # uuencode/decode
446
447     # Note that first uuencoding known 'text' data and then checking the
448     # binary values of the uuencoded version would not be portable between
449     # character sets.  Uuencoding is meant for encoding binary data, not
450     # text data.
451
452     my $in = pack 'C*', 0 .. 255;
453
454     # just to be anal, we do some random tr/`/ /
455     my $uu = <<'EOUU';
456 M` $"`P0%!@<("0H+# T.#Q`1$A,4%187&!D:&QP='A\@(2(C)"4F)R@I*BLL
457 M+2XO,#$R,S0U-C<X.3H[/#T^/T!!0D-$149'2$E*2TQ-3D]045)35%565UA9
458 M6EM<75Y?8&%B8V1E9F=H:6IK;&UN;W!Q<G-T=79W>'EZ>WQ]?G^`@8*#A(6&
459 MAXB)BHN,C8Z/D)&2DY25EI>8F9J;G)V>GZ"AHJ.DI::GJ*FJJZRMKJ^PL;*S
460 MM+6VM[BYNKN\O;Z_P,'"P\3%QL?(R<K+S,W.S]#1TM/4U=;7V-G:V]S=WM_@
461 ?X>+CY.7FY^CIZNOL[>[O\/'R\_3U]O?X^?K[_/W^_P `
462 EOUU
463
464     $_ = $uu;
465     tr/ /`/;
466
467     is(pack('u', $in), $_);
468
469     is(unpack('u', $uu), $in);
470
471     $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";
472     $uu = <<'EOUU';
473 M'XL("%C<Q#4"`TI!4%4`\RHM+E%(S,LOR4@M4@A(+<I1*"U-SD])+>("`&1F
474 &8%P:````
475 EOUU
476
477     is(unpack('u', $uu), $in);
478
479 # This is identical to the above except that backquotes have been
480 # changed to spaces
481
482     $uu = <<'EOUU';
483 M'XL("%C<Q#4" TI!4%4 \RHM+E%(S,LOR4@M4@A(+<I1*"U-SD])+>(" &1F
484 &8%P:
485 EOUU
486
487     # ' # Grr
488     is(unpack('u', $uu), $in);
489
490 }
491
492 # test the ascii template types (A, a, Z)
493
494 foreach (
495 ['p', 'A*',  "foo\0bar\0 ", "foo\0bar\0 "],
496 ['p', 'A11', "foo\0bar\0 ", "foo\0bar\0   "],
497 ['u', 'A*',  "foo\0bar \0", "foo\0bar"],
498 ['u', 'A8',  "foo\0bar \0", "foo\0bar"],
499 ['p', 'a*',  "foo\0bar\0 ", "foo\0bar\0 "],
500 ['p', 'a11', "foo\0bar\0 ", "foo\0bar\0 \0\0"],
501 ['u', 'a*',  "foo\0bar \0", "foo\0bar \0"],
502 ['u', 'a8',  "foo\0bar \0", "foo\0bar "],
503 ['p', 'Z*',  "foo\0bar\0 ", "foo\0bar\0 \0"],
504 ['p', 'Z11', "foo\0bar\0 ", "foo\0bar\0 \0\0"],
505 ['p', 'Z3',  "foo",         "fo\0"],
506 ['u', 'Z*',  "foo\0bar \0", "foo"],
507 ['u', 'Z8',  "foo\0bar \0", "foo"],
508 )
509 {
510     my ($what, $template, $in, $out) = @$_;
511     my $got = $what eq 'u' ? (unpack $template, $in) : (pack $template, $in);
512     unless (is($got, $out)) {
513         my $un = $what eq 'u' ? 'un' : '';
514         print "# ${un}pack ('$template', "._qq($in).') gave '._qq($out).
515             ' not '._qq($got)."\n";
516     }
517 }
518
519 print "# packing native shorts/ints/longs\n";
520
521 is(length(pack("s!", 0)), $Config{shortsize});
522 is(length(pack("i!", 0)), $Config{intsize});
523 is(length(pack("l!", 0)), $Config{longsize});
524 ok(length(pack("s!", 0)) <= length(pack("i!", 0)));
525 ok(length(pack("i!", 0)) <= length(pack("l!", 0)));
526 is(length(pack("i!", 0)), length(pack("i", 0)));
527
528 sub numbers {
529   my $base = shift;
530   my @formats = ($base);
531   $base =~ /^[silqjfdp]/i and push @formats, "$base>", "$base<";
532   for my $format (@formats) {
533     numbers_with_total ($format, undef, @_);
534   }
535 }
536
537 sub numbers_with_total {
538   my $format = shift;
539   my $total = shift;
540   if (!defined $total) {
541     foreach (@_) {
542       $total += $_;
543     }
544   }
545   print "# numbers test for $format\n";
546   foreach (@_) {
547     SKIP: {
548         my $out = eval {unpack($format, pack($format, $_))};
549         skip "cannot pack '$format' on this perl", 2
550           if is_valid_error($@);
551
552         is($@, '', "no error");
553         is($out, $_, "unpack pack $format $_");
554     }
555   }
556
557   my $skip_if_longer_than = ~0; # "Infinity"
558   if (~0 - 1 == ~0) {
559     # If we're running with -DNO_PERLPRESERVE_IVUV and NVs don't preserve all
560     # UVs (in which case ~0 is NV, ~0-1 will be the same NV) then we can't
561     # correctly in perl calculate UV totals for long checksums, as pp_unpack
562     # is using UV maths, and we've only got NVs.
563     $skip_if_longer_than = $Config{nv_preserves_uv_bits};
564   }
565
566   foreach ('', 1, 2, 3, 15, 16, 17, 31, 32, 33, 53, 54, 63, 64, 65) {
567     SKIP: {
568       my $sum = eval {unpack "%$_$format*", pack "$format*", @_};
569       skip "cannot pack '$format' on this perl", 3
570         if is_valid_error($@);
571
572       is($@, '', "no error");
573       ok(defined $sum, "sum bits $_, format $format defined");
574
575       my $len = $_; # Copy, so that we can reassign ''
576       $len = 16 unless length $len;
577
578       SKIP: {
579         skip "cannot test checksums over $skip_if_longer_than bits", 1
580           if $len > $skip_if_longer_than;
581
582         # Our problem with testing this portably is that the checksum code in
583         # pp_unpack is able to cast signed to unsigned, and do modulo 2**n
584         # arithmetic in unsigned ints, which perl has no operators to do.
585         # (use integer; does signed ints, which won't wrap on UTS, which is just
586         # fine with ANSI, but not with most people's assumptions.
587         # This is why we need to supply the totals for 'Q' as there's no way in
588         # perl to calculate them, short of unpack '%0Q' (is that documented?)
589         # ** returns NVs; make sure it's IV.
590         my $max = 1 + 2 * (int (2 ** ($len-1))-1); # The max possible checksum
591         my $max_p1 = $max + 1;
592         my ($max_is_integer, $max_p1_is_integer);
593         $max_p1_is_integer = 1 unless $max_p1 + 1 == $max_p1;
594         $max_is_integer = 1 if $max - 1 < ~0;
595
596         my $calc_sum;
597         if (ref $total) {
598             $calc_sum = &$total($len);
599         } else {
600             $calc_sum = $total;
601             # Shift into range by some multiple of the total
602             my $mult = $max_p1 ? int ($total / $max_p1) : undef;
603             # Need this to make sure that -1 + (~0+1) is ~0 (ie still integer)
604             $calc_sum = $total - $mult;
605             $calc_sum -= $mult * $max;
606             if ($calc_sum < 0) {
607                 $calc_sum += 1;
608                 $calc_sum += $max;
609             }
610         }
611         if ($calc_sum == $calc_sum - 1 && $calc_sum == $max_p1) {
612             # we're into floating point (either by getting out of the range of
613             # UV arithmetic, or because we're doing a floating point checksum)
614             # and our calculation of the checksum has become rounded up to
615             # max_checksum + 1
616             $calc_sum = 0;
617         }
618
619         if ($calc_sum == $sum) { # HAS to be ==, not eq (so no is()).
620             pass ("unpack '%$_$format' gave $sum");
621         } else {
622             my $delta = 1.000001;
623             if ($format =~ tr /dDfF//
624                 && ($calc_sum <= $sum * $delta && $calc_sum >= $sum / $delta)) {
625                 pass ("unpack '%$_$format' gave $sum, expected $calc_sum");
626             } else {
627                 my $text = ref $total ? &$total($len) : $total;
628                 fail;
629                 print "# For list (" . join (", ", @_) . ") (total $text)"
630                     . " packed with $format unpack '%$_$format' gave $sum,"
631                     . " expected $calc_sum\n";
632             }
633         }
634       }
635     }
636   }
637 }
638
639 numbers ('c', -128, -1, 0, 1, 127);
640 numbers ('C', 0, 1, 127, 128, 255);
641 numbers ('W', 0, 1, 127, 128, 255, 256, 0x7ff, 0x800, 0xfffd);
642 numbers ('s', -32768, -1, 0, 1, 32767);
643 numbers ('S', 0, 1, 32767, 32768, 65535);
644 numbers ('i', -2147483648, -1, 0, 1, 2147483647);
645 numbers ('I', 0, 1, 2147483647, 2147483648, 4294967295);
646 numbers ('l', -2147483648, -1, 0, 1, 2147483647);
647 numbers ('L', 0, 1, 2147483647, 2147483648, 4294967295);
648 numbers ('s!', -32768, -1, 0, 1, 32767);
649 numbers ('S!', 0, 1, 32767, 32768, 65535);
650 numbers ('i!', -2147483648, -1, 0, 1, 2147483647);
651 numbers ('I!', 0, 1, 2147483647, 2147483648, 4294967295);
652 numbers ('l!', -2147483648, -1, 0, 1, 2147483647);
653 numbers ('L!', 0, 1, 2147483647, 2147483648, 4294967295);
654 numbers ('n', 0, 1, 32767, 32768, 65535);
655 numbers ('v', 0, 1, 32767, 32768, 65535);
656 numbers ('N', 0, 1, 2147483647, 2147483648, 4294967295);
657 numbers ('V', 0, 1, 2147483647, 2147483648, 4294967295);
658 numbers ('n!', -32768, -1, 0, 1, 32767);
659 numbers ('v!', -32768, -1, 0, 1, 32767);
660 numbers ('N!', -2147483648, -1, 0, 1, 2147483647);
661 numbers ('V!', -2147483648, -1, 0, 1, 2147483647);
662 # All these should have exact binary representations:
663 numbers ('f', -1, 0, 0.5, 42, 2**34);
664 numbers ('d', -(2**34), -1, 0, 1, 2**34);
665 ## These don't, but 'd' is NV.  XXX wrong, it's double
666 #numbers ('d', -1, 0, 1, 1-exp(-1), -exp(1));
667
668 numbers_with_total ('q', -1,
669                     -9223372036854775808, -1, 0, 1,9223372036854775807);
670 # This total is icky, but the true total is 2**65-1, and need a way to generate
671 # the expected checksum on any system including those where NVs can preserve
672 # 65 bits. (long double is 128 bits on sparc, so they certainly can)
673 # or where rounding is down not up on binary conversion (crays)
674 numbers_with_total ('Q', sub {
675                       my $len = shift;
676                       $len = 65 if $len > 65; # unmasked total is 2**65-1 here
677                       my $total = 1 + 2 * (int (2**($len - 1)) - 1);
678                       return 0 if $total == $total - 1; # Overflowed integers
679                       return $total; # NVs still accurate to nearest integer
680                     },
681                     0, 1,9223372036854775807, 9223372036854775808,
682                     18446744073709551615);
683
684 print "# pack nvNV byteorders\n";
685
686 is(pack("n", 0xdead), "\xde\xad");
687 is(pack("v", 0xdead), "\xad\xde");
688 is(pack("N", 0xdeadbeef), "\xde\xad\xbe\xef");
689 is(pack("V", 0xdeadbeef), "\xef\xbe\xad\xde");
690
691 SKIP: {
692   skip $no_signedness, 4 if $no_signedness;
693   is(pack("n!", 0xdead), "\xde\xad");
694   is(pack("v!", 0xdead), "\xad\xde");
695   is(pack("N!", 0xdeadbeef), "\xde\xad\xbe\xef");
696   is(pack("V!", 0xdeadbeef), "\xef\xbe\xad\xde");
697 }
698
699 print "# test big-/little-endian conversion\n";
700
701 sub byteorder
702 {
703   my $format = shift;
704   print "# byteorder test for $format\n";
705   for my $value (@_) {
706     SKIP: {
707       my($nat,$be,$le) = eval { map { pack $format.$_, $value } '', '>', '<' };
708       skip "cannot pack '$format' on this perl", 5
709         if is_valid_error($@);
710
711       {
712         use warnings qw(NONFATAL utf8);
713         print "# [$value][$nat][$be][$le][$@]\n";
714       }
715
716       SKIP: {
717         skip "cannot compare native byteorder with big-/little-endian", 1
718             if $ByteOrder eq 'unknown';
719
720         is($nat, $ByteOrder eq 'big' ? $be : $le);
721       }
722       is($be, reverse($le));
723       my @x = eval { unpack "$format$format>$format<", $nat.$be.$le };
724
725       print "# [$value][", join('][', @x), "][$@]\n";
726
727       is($@, '');
728       is($x[0], $x[1]);
729       is($x[0], $x[2]);
730     }
731   }
732 }
733
734 byteorder('s', -32768, -1, 0, 1, 32767);
735 byteorder('S', 0, 1, 32767, 32768, 65535);
736 byteorder('i', -2147483648, -1, 0, 1, 2147483647);
737 byteorder('I', 0, 1, 2147483647, 2147483648, 4294967295);
738 byteorder('l', -2147483648, -1, 0, 1, 2147483647);
739 byteorder('L', 0, 1, 2147483647, 2147483648, 4294967295);
740 byteorder('j', -2147483648, -1, 0, 1, 2147483647);
741 byteorder('J', 0, 1, 2147483647, 2147483648, 4294967295);
742 byteorder('s!', -32768, -1, 0, 1, 32767);
743 byteorder('S!', 0, 1, 32767, 32768, 65535);
744 byteorder('i!', -2147483648, -1, 0, 1, 2147483647);
745 byteorder('I!', 0, 1, 2147483647, 2147483648, 4294967295);
746 byteorder('l!', -2147483648, -1, 0, 1, 2147483647);
747 byteorder('L!', 0, 1, 2147483647, 2147483648, 4294967295);
748 byteorder('q', -9223372036854775808, -1, 0, 1, 9223372036854775807);
749 byteorder('Q', 0, 1, 9223372036854775807, 9223372036854775808, 18446744073709551615);
750 byteorder('f', -1, 0, 0.5, 42, 2**34);
751 byteorder('F', -1, 0, 0.5, 42, 2**34);
752 byteorder('d', -(2**34), -1, 0, 1, 2**34);
753 byteorder('D', -(2**34), -1, 0, 1, 2**34);
754
755 print "# test negative numbers\n";
756
757 SKIP: {
758   skip "platform is not using two's complement for negative integers", 120
759     unless $IsTwosComplement;
760
761   for my $format (qw(s i l j s! i! l! q)) {
762     SKIP: {
763       my($nat,$be,$le) = eval { map { pack $format.$_, -1 } '', '>', '<' };
764       skip "cannot pack '$format' on this perl", 15
765         if is_valid_error($@);
766
767       my $len = length $nat;
768       is($_, "\xFF"x$len) for $nat, $be, $le;
769
770       my(@val,@ref);
771       if ($len >= 8) {
772         @val = (-2, -81985529216486896, -9223372036854775808);
773         @ref = ("\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFE",
774                 "\xFE\xDC\xBA\x98\x76\x54\x32\x10",
775                 "\x80\x00\x00\x00\x00\x00\x00\x00");
776       }
777       elsif ($len >= 4) {
778         @val = (-2, -19088744, -2147483648);
779         @ref = ("\xFF\xFF\xFF\xFE",
780                 "\xFE\xDC\xBA\x98",
781                 "\x80\x00\x00\x00");
782       }
783       else {
784         @val = (-2, -292, -32768);
785         @ref = ("\xFF\xFE",
786                 "\xFE\xDC",
787                 "\x80\x00");
788       }
789       for my $x (@ref) {
790         if ($len > length $x) {
791           $x = $x . "\xFF" x ($len - length $x);
792         }
793       }
794
795       for my $i (0 .. $#val) {
796         my($nat,$be,$le) = eval { map { pack $format.$_, $val[$i] } '', '>', '<' };
797         is($@, '');
798
799         SKIP: {
800           skip "cannot compare native byteorder with big-/little-endian", 1
801               if $ByteOrder eq 'unknown';
802
803           is($nat, $ByteOrder eq 'big' ? $be : $le);
804         }
805
806         is($be, $ref[$i]);
807         is($be, reverse($le));
808       }
809     }
810   }
811 }
812
813 {
814   # /
815
816   my ($x, $y, $z, @a);
817   eval { ($x) = unpack '/a*','hello' };
818   like($@, qr!'/' must follow a numeric type!);
819   undef $x;
820   eval { $x = unpack '/a*','hello' };
821   like($@, qr!'/' must follow a numeric type!);
822
823   # [perl #60204] Unhelpful error message from unpack
824   eval { @a = unpack 'v/a*','h' };
825   is($@, '');
826   is(scalar @a, 0);
827   eval { $x = unpack 'v/a*','h' };
828   is($@, '');
829   is($x, undef);
830
831   undef $x;
832   eval { ($z,$x,$y) = unpack 'a3/A C/a* C/Z', "003ok \003yes\004z\000abc" };
833   is($@, '');
834   is($z, 'ok');
835   is($x, 'yes');
836   is($y, 'z');
837   undef $z;
838   eval { $z = unpack 'a3/A C/a* C/Z', "003ok \003yes\004z\000abc" };
839   is($@, '');
840   is($z, 'ok');
841
842
843   undef $x;
844   eval { ($x) = pack '/a*','hello' };
845   like($@,  qr!Invalid type '/'!);
846   undef $x;
847   eval { $x = pack '/a*','hello' };
848   like($@,  qr!Invalid type '/'!);
849
850   $z = pack 'n/a* N/Z* w/A*','string','hi there ','etc';
851   my $expect = "\000\006string\0\0\0\012hi there \000\003etc";
852   is($z, $expect);
853
854   undef $x;
855   $expect = 'hello world';
856   eval { ($x) = unpack ("w/a", chr (11) . "hello world!")};
857   is($x, $expect);
858   is($@, '');
859
860   undef $x;
861   # Doing this in scalar context used to fail.
862   eval { $x = unpack ("w/a", chr (11) . "hello world!")};
863   is($@, '');
864   is($x, $expect);
865
866   foreach (
867            ['a/a*/a*', '212ab345678901234567','ab3456789012'],
868            ['a/a*/a*', '3012ab345678901234567', 'ab3456789012'],
869            ['a/a*/b*', '212ab', $::IS_EBCDIC ? '100000010100' : '100001100100'],
870   )
871   {
872     my ($pat, $in, $expect) = @$_;
873     undef $x;
874     eval { ($x) = unpack $pat, $in };
875     is($@, '');
876     is($x, $expect) ||
877       printf "# list unpack ('$pat', '$in') gave %s, expected '$expect'\n",
878              encode_list ($x);
879
880     undef $x;
881     eval { $x = unpack $pat, $in };
882     is($@, '');
883     is($x, $expect) ||
884       printf "# scalar unpack ('$pat', '$in') gave %s, expected '$expect'\n",
885              encode_list ($x);
886   }
887
888   # / with #
889
890   my $pattern = <<'EOU';
891  a3/A                   # Count in ASCII
892  C/a*                   # Count in a C char
893  C/Z                    # Count in a C char but skip after \0
894 EOU
895
896   $x = $y = $z =undef;
897   eval { ($z,$x,$y) = unpack $pattern, "003ok \003yes\004z\000abc" };
898   is($@, '');
899   is($z, 'ok');
900   is($x, 'yes');
901   is($y, 'z');
902   undef $x;
903   eval { $z = unpack $pattern, "003ok \003yes\004z\000abc" };
904   is($@, '');
905   is($z, 'ok');
906
907   $pattern = <<'EOP';
908   n/a*                  # Count as network short
909   w/A*                  # Count a  BER integer
910 EOP
911   $expect = "\000\006string\003etc";
912   $z = pack $pattern,'string','etc';
913   is($z, $expect);
914 }
915
916
917 {
918     is("1.20.300.4000", sprintf "%vd", pack("U*",utf8::native_to_unicode(1),utf8::native_to_unicode(20),300,4000));
919     is("1.20.300.4000", sprintf "%vd", pack("  U*",utf8::native_to_unicode(1),utf8::native_to_unicode(20),300,4000));
920 }
921 isnt(v1.20.300.4000, sprintf "%vd", pack("C0U*",utf8::native_to_unicode(1),utf8::native_to_unicode(20),300,4000));
922
923 my $rslt = join " ", map { ord } split "", byte_utf8a_to_utf8n("\xc7\xa2");
924 # The ASCII UTF-8 of U+1E2 is "\xc7\xa2"
925 is(join(" ", unpack("U0 C*", chr(0x1e2))), $rslt);
926
927 # does pack U create Unicode?
928 is(ord(pack('U', 300)), 300);
929
930 # does unpack U deref Unicode?
931 is((unpack('U', chr(300)))[0], 300);
932
933 # is unpack U the reverse of pack U for Unicode string?
934 is("@{[unpack('U*', pack('U*', 100, 200, 300))]}", "100 200 300");
935
936 # is unpack U the reverse of pack U for byte string?
937 is("@{[unpack('U*', pack('U*', 100, 200))]}", "100 200");
938
939
940 SKIP: {
941     skip "Two of these still fail on EBCDIC; investigate in v5.23", 3 if $::IS_EBCDIC;
942
943     # does pack U0C create Unicode?
944     my $cp202 = chr(202);
945     utf8::upgrade $cp202;
946     my @bytes202;
947     {   # This is portable across character sets
948         use bytes;
949         @bytes202 = map { ord } split "", $cp202;
950     }
951     is("@{[pack('U0C*', 100, @bytes202)]}", v100.v202);
952
953     # does pack C0U create characters?
954     is("@{[pack('C0U*', 100, 202)]}", pack("C*", 100, @bytes202));
955
956     # does unpack U0U on byte data warn?
957     {
958         use warnings qw(NONFATAL all);;
959
960         my $bad = pack("U0C", 202);
961         local $SIG{__WARN__} = sub { $@ = "@_" };
962         my @null = unpack('U0U', $bad);
963         like($@, qr/^Malformed UTF-8 character /);
964     }
965 }
966
967 {
968   my $p = pack 'i*', -2147483648, ~0, 0, 1, 2147483647;
969   my (@a);
970   # bug - % had to be at the start of the pattern, no leading whitespace or
971   # comments. %i! didn't work at all.
972   foreach my $pat ('%32i*', ' %32i*', "# Muhahahaha\n%32i*", '%32i*  ',
973                    '%32i!*', ' %32i!*', "\n#\n#\n\r \t\f%32i!*", '%32i!*#') {
974     @a = unpack $pat, $p;
975     is($a[0], 0xFFFFFFFF) || print "# $pat\n";
976     @a = scalar unpack $pat, $p;
977     is($a[0], 0xFFFFFFFF) || print "# $pat\n";
978   }
979
980
981   $p = pack 'I*', 42, 12;
982   # Multiline patterns in scalar context failed.
983   foreach my $pat ('I', <<EOPOEMSNIPPET, 'I#I', 'I # I', 'I # !!!') {
984 # On the Ning Nang Nong
985 # Where the Cows go Bong!
986 # And the Monkeys all say Boo!
987 I
988 EOPOEMSNIPPET
989     @a = unpack $pat, $p;
990     is(scalar @a, 1);
991     is($a[0], 42);
992     @a = scalar unpack $pat, $p;
993     is(scalar @a, 1);
994     is($a[0], 42);
995   }
996
997   # shorts (of all flavours) didn't calculate checksums > 32 bits with floating
998   # point, so a pathologically long pattern would wrap at 32 bits.
999   my $pat = "\xff\xff"x65538; # Start with it long, to save any copying.
1000   foreach (4,3,2,1,0) {
1001     my $len = 65534 + $_;
1002     is(unpack ("%33n$len", $pat), 65535 * $len);
1003   }
1004 }
1005
1006
1007 # pack x X @
1008 foreach (
1009          ['x', "N", "\0"],
1010          ['x4', "N", "\0"x4],
1011          ['xX', "N", ""],
1012          ['xXa*', "Nick", "Nick"],
1013          ['a5Xa5', "cameL", "llama", "camellama"],
1014          ['@4', 'N', "\0"x4],
1015          ['a*@8a*', 'Camel', 'Dromedary', "Camel\0\0\0Dromedary"],
1016          ['a*@4a', 'Perl rules', '!', 'Perl!'],
1017 )
1018 {
1019   my ($template, @in) = @$_;
1020   my $out = pop @in;
1021   my $got = eval {pack $template, @in};
1022   is($@, '');
1023   is($out, $got) ||
1024     printf "# pack ('$template', %s) gave %s expected %s\n",
1025            encode_list (@in), encode_list ($got), encode_list ($out);
1026 }
1027
1028 # unpack x X @
1029 foreach (
1030          ['x', "N"],
1031          ['xX', "N"],
1032          ['xXa*', "Nick", "Nick"],
1033          ['a5Xa5', "camellama", "camel", "llama"],
1034          ['@3', "ice"],
1035          ['@2a2', "water", "te"],
1036          ['a*@1a3', "steam", "steam", "tea"],
1037 )
1038 {
1039   my ($template, $in, @out) = @$_;
1040   my @got = eval {unpack $template, $in};
1041   is($@, '');
1042   ok (list_eq (\@got, \@out)) ||
1043     printf "# list unpack ('$template', %s) gave %s expected %s\n",
1044            _qq($in), encode_list (@got), encode_list (@out);
1045
1046   my $got = eval {unpack $template, $in};
1047   is($@, '');
1048   @out ? is( $got, $out[0] ) # 1 or more items; should get first
1049        : ok( !defined $got ) # 0 items; should get undef
1050     or printf "# scalar unpack ('$template', %s) gave %s expected %s\n",
1051               _qq($in), encode_list ($got), encode_list ($out[0]);
1052 }
1053
1054 {
1055     my $t = 'Z*Z*';
1056     my ($u, $v) = qw(foo xyzzy);
1057     my $p = pack($t, $u, $v);
1058     my @u = unpack($t, $p);
1059     is(scalar @u, 2);
1060     is($u[0], $u);
1061     is($u[1], $v);
1062 }
1063
1064 {
1065     is((unpack("w/a*", "\x02abc"))[0], "ab");
1066
1067     # "w/a*" should be seen as one unit
1068
1069     is(scalar unpack("w/a*", "\x02abc"), "ab");
1070 }
1071
1072 SKIP: {
1073   print "# group modifiers\n";
1074
1075   skip $no_endianness, 3 * 2 + 3 * 2 + 1 if $no_endianness;
1076
1077   for my $t (qw{ (s<)< (sl>s)> (s(l(sl)<l)s)< }) {
1078     print "# testing pattern '$t'\n";
1079     eval { ($_) = unpack($t, 'x'x18); };
1080     is($@, '');
1081     eval { $_ = pack($t, (0)x6); };
1082     is($@, '');
1083   }
1084
1085   for my $t (qw{ (s<)> (sl>s)< (s(l(sl)<l)s)> }) {
1086     print "# testing pattern '$t'\n";
1087     eval { ($_) = unpack($t, 'x'x18); };
1088     like($@, qr/Can't use '[<>]' in a group with different byte-order in unpack/);
1089     eval { $_ = pack($t, (0)x6); };
1090     like($@, qr/Can't use '[<>]' in a group with different byte-order in pack/);
1091   }
1092
1093   is(pack('L<L>', (0x12345678)x2),
1094      pack('(((L1)1)<)(((L)1)1)>1', (0x12345678)x2));
1095 }
1096
1097 {
1098   sub compress_template {
1099     my $t = shift;
1100     for my $mod (qw( < > )) {
1101       $t =~ s/((?:(?:[SILQJFDP]!?$mod|[^SILQJFDP\W]!?)(?:\d+|\*|\[(?:[^]]+)\])?\/?){2,})/
1102               my $x = $1; $x =~ s!$mod!!g ? "($x)$mod" : $x /ieg;
1103     }
1104     return $t;
1105   }
1106
1107   my %templates = (
1108     's<'                  => [-42],
1109     's<c2x![S]S<'         => [-42, -11, 12, 4711],
1110     '(i<j<[s]l<)3'        => [-11, -22, -33, 1000000, 1100, 2201, 3302,
1111                               -1000000, 32767, -32768, 1, -123456789 ],
1112     '(I!<4(J<2L<)3)5'     => [1 .. 65],
1113     'q<Q<'                => [-50000000005, 60000000006],
1114     'f<F<d<'              => [3.14159, 111.11, 2222.22],
1115     'D<cCD<'              => [1e42, -128, 255, 1e-42],
1116     'n/a*'                => ['/usr/bin/perl'],
1117     'C/a*S</A*L</Z*I</a*' => [qw(Just another Perl hacker)],
1118   );
1119
1120   for my $tle (sort keys %templates) {
1121     my @d = @{$templates{$tle}};
1122     my $tbe = $tle;
1123     $tbe =~ y/</>/;
1124     for my $t ($tbe, $tle) {
1125       my $c = compress_template($t);
1126       print "# '$t' -> '$c'\n";
1127       SKIP: {
1128         my $p1 = eval { pack $t, @d };
1129         skip "cannot pack '$t' on this perl", 5 if is_valid_error($@);
1130         my $p2 = eval { pack $c, @d };
1131         is($@, '');
1132         is($p1, $p2);
1133         s!(/[aAZ])\*!$1!g for $t, $c;
1134         my @u1 = eval { unpack $t, $p1 };
1135         is($@, '');
1136         my @u2 = eval { unpack $c, $p2 };
1137         is($@, '');
1138         is(join('!', @u1), join('!', @u2));
1139       }
1140     }
1141   }
1142 }
1143
1144 {
1145     # from Wolfgang Laun: fix in change #13163
1146
1147     my $s = 'ABC' x 10;
1148     my $t = '*';
1149     my $x = ord($t);
1150     my $buf = pack( 'Z*/A* C',  $s, $x );
1151     my $y;
1152
1153     my $h = $buf;
1154     $h =~ s/[^[:print:]]/./g;
1155     ( $s, $y ) = unpack( "Z*/A* C", $buf );
1156     is($h, "30.ABCABCABCABCABCABCABCABCABCABC$t");
1157     is(length $buf, 34);
1158     is($s, "ABCABCABCABCABCABCABCABCABCABC");
1159     is($y, $x);
1160 }
1161
1162 {
1163     # from Wolfgang Laun: fix in change #13288
1164
1165     eval { my $t=unpack("P*", "abc") };
1166     like($@, qr/'P' must have an explicit size/);
1167 }
1168
1169 {   # Grouping constructs
1170     my (@a, @b);
1171     @a = unpack '(SL)',   pack 'SLSLSL', 67..90;
1172     is("@a", "67 68");
1173     @a = unpack '(SL)3',   pack 'SLSLSL', 67..90;
1174     @b = (67..72);
1175     is("@a", "@b");
1176     @a = unpack '(SL)3',   pack 'SLSLSLSL', 67..90;
1177     is("@a", "@b");
1178     @a = unpack '(SL)[3]', pack 'SLSLSLSL', 67..90;
1179     is("@a", "@b");
1180     @a = unpack '(SL)[2] SL', pack 'SLSLSLSL', 67..90;
1181     is("@a", "@b");
1182     @a = unpack 'A/(SL)',  pack 'ASLSLSLSL', 3, 67..90;
1183     is("@a", "@b");
1184     @a = unpack 'A/(SL)SL',  pack 'ASLSLSLSL', 2, 67..90;
1185     is("@a", "@b");
1186     @a = unpack '(SL)*',   pack 'SLSLSLSL', 67..90;
1187     @b = (67..74);
1188     is("@a", "@b");
1189     @a = unpack '(SL)*SL',   pack 'SLSLSLSL', 67..90;
1190     is("@a", "@b");
1191     eval { @a = unpack '(*SL)',   '' };
1192     like($@, qr/\(\)-group starts with a count/);
1193     eval { @a = unpack '(3SL)',   '' };
1194     like($@, qr/\(\)-group starts with a count/);
1195     eval { @a = unpack '([3]SL)',   '' };
1196     like($@, qr/\(\)-group starts with a count/);
1197     eval { @a = pack '(*SL)' };
1198     like($@, qr/\(\)-group starts with a count/);
1199     @a = unpack '(SL)3 SL',   pack '(SL)4', 67..74;
1200     is("@a", "@b");
1201     @a = unpack '(SL)3 SL',   pack '(SL)[4]', 67..74;
1202     is("@a", "@b");
1203     @a = unpack '(SL)3 SL',   pack '(SL)*', 67..74;
1204     is("@a", "@b");
1205 }
1206
1207 {  # more on grouping (W.Laun)
1208   # @ absolute within ()-group
1209   my $badc = pack( '(a)*', unpack( '(@1a @0a @2)*', 'abcd' ) );
1210   is( $badc, 'badc' );
1211   my @b = ( 1, 2, 3 );
1212   my $buf = pack( '(@1c)((@2C)@3c)', @b );
1213   is( $buf, "\0\1\0\0\2\3" );
1214   my @a = unpack( '(@1c)((@2c)@3c)', $buf );
1215   is( "@a", "@b" );
1216
1217   # various unpack count/code scenarios
1218   my @Env = ( a => 'AAA', b => 'BBB' );
1219   my $env = pack( 'S(S/A*S/A*)*', @Env/2, @Env );
1220
1221   # unpack full length - ok
1222   my @pup = unpack( 'S/(S/A* S/A*)', $env );
1223   is( "@pup", "@Env" );
1224
1225   # warn when count/code goes beyond end of string
1226   # \0002 \0001 a \0003 AAA \0001 b \0003 BBB
1227   #     2     4 5     7  10    1213
1228   eval { @pup = unpack( 'S/(S/A* S/A*)', substr( $env, 0, 13 ) ) };
1229   like( $@, qr{length/code after end of string} );
1230
1231   # postfix repeat count
1232   $env = pack( '(S/A* S/A*)' . @Env/2, @Env );
1233
1234   # warn when count/code goes beyond end of string
1235   # \0001 a \0003 AAA \0001  b \0003 BBB
1236   #     2 3c    5   8    10 11    13  16
1237   eval { @pup = unpack( '(S/A* S/A*)' . @Env/2, substr( $env, 0, 11 ) ) };
1238   like( $@, qr{length/code after end of string} );
1239
1240   # catch stack overflow/segfault
1241   eval { $_ = pack( ('(' x 105) . 'A' . (')' x 105) ); };
1242   like( $@, qr{Too deeply nested \(\)-groups} );
1243 }
1244
1245 { # syntax checks (W.Laun)
1246   use warnings qw(NONFATAL all);;
1247   my @warning;
1248   local $SIG{__WARN__} = sub {
1249       push( @warning, $_[0] );
1250   };
1251   eval { my $s = pack( 'Ax![4c]A', 1..5 ); };
1252   like( $@, qr{Malformed integer in \[\]} );
1253
1254   eval { my $buf = pack( '(c/*a*)', 'AAA', 'BB' ); };
1255   like( $@, qr{'/' does not take a repeat count} );
1256
1257   eval { my @inf = unpack( 'c/1a', "\x03AAA\x02BB" ); };
1258   like( $@, qr{'/' does not take a repeat count} );
1259
1260   eval { my @inf = unpack( 'c/*a', "\x03AAA\x02BB" ); };
1261   like( $@, qr{'/' does not take a repeat count} );
1262
1263   # white space where possible
1264   my @Env = ( a => 'AAA', b => 'BBB' );
1265   my $env = pack( ' S ( S / A*   S / A* )* ', @Env/2, @Env );
1266   my @pup = unpack( ' S / ( S / A*   S / A* ) ', $env );
1267   is( "@pup", "@Env" );
1268
1269   # white space in 4 wrong places
1270   for my $temp (  'A ![4]', 'A [4]', 'A *', 'A 4' ){
1271       eval { my $s = pack( $temp, 'B' ); };
1272       like( $@, qr{Invalid type } );
1273   }
1274
1275   # warning for commas
1276   @warning = ();
1277   my $x = pack( 'I,A', 4, 'X' );
1278   like( $warning[0], qr{Invalid type ','} );
1279
1280   # comma warning only once
1281   @warning = ();
1282   $x = pack( 'C(C,C)C,C', 65..71  );
1283   cmp_ok( scalar(@warning), '==', 1 );
1284
1285   # forbidden code in []
1286   eval { my $x = pack( 'A[@4]', 'XXXX' ); };
1287   like( $@, qr{Within \[\]-length '\@' not allowed} );
1288
1289   # @ repeat default 1
1290   my $s = pack( 'AA@A', 'A', 'B', 'C' );
1291   my @c = unpack( 'AA@A', $s );
1292   is( $s, 'AC' );
1293   is( "@c", "A C C" );
1294
1295   # no unpack code after /
1296   eval { my @a = unpack( "C/", "\3" ); };
1297   like( $@, qr{Code missing after '/'} );
1298
1299  SKIP: {
1300     skip $no_endianness, 6 if $no_endianness;
1301
1302     # modifier warnings
1303     @warning = ();
1304     $x = pack "I>>s!!", 47, 11;
1305     ($x) = unpack "I<<l!>!>", 'x'x20;
1306     is(scalar @warning, 5);
1307     like($warning[0], qr/Duplicate modifier '>' after 'I' in pack/);
1308     like($warning[1], qr/Duplicate modifier '!' after 's' in pack/);
1309     like($warning[2], qr/Duplicate modifier '<' after 'I' in unpack/);
1310     like($warning[3], qr/Duplicate modifier '!' after 'l' in unpack/);
1311     like($warning[4], qr/Duplicate modifier '>' after 'l' in unpack/);
1312   }
1313 }
1314
1315 {  # Repeat count [SUBEXPR]
1316    my @codes = qw( x A Z a c C W B b H h s v n S i I l V N L p P f F d
1317                    s! S! i! I! l! L! j J);
1318    my $G;
1319    if (eval { pack 'q', 1 } ) {
1320      push @codes, qw(q Q);
1321    } else {
1322      push @codes, qw(s S);      # Keep the count the same
1323    }
1324    if (eval { pack 'D', 1 } ) {
1325      push @codes, 'D';
1326    } else {
1327      push @codes, 'd';  # Keep the count the same
1328    }
1329
1330    push @codes, map { /^[silqjfdp]/i ? ("$_<", "$_>") : () } @codes;
1331
1332    my %val;
1333    @val{@codes} = map { / [Xx]  (?{ undef })
1334                         | [AZa] (?{ 'something' })
1335                         | C     (?{ 214 })
1336                         | W     (?{ 8188 })
1337                         | c     (?{ 114 })
1338                         | [Bb]  (?{ '101' })
1339                         | [Hh]  (?{ 'b8' })
1340                         | [svnSiIlVNLqQjJ]  (?{ 10111 })
1341                         | [FfDd]  (?{ 1.36514538e67 })
1342                         | [pP]  (?{ "try this buffer" })
1343                         /x; $^R } @codes;
1344    my @end = (0x12345678, 0x23456781, 0x35465768, 0x15263748);
1345    my $end = "N4";
1346
1347    for my $type (@codes) {
1348      my @list = $val{$type};
1349      @list = () unless defined $list[0];
1350      for my $count ('', '3', '[11]') {
1351        my $c = 1;
1352        $c = $1 if $count =~ /(\d+)/;
1353        my @list1 = @list;
1354        @list1 = (@list1) x $c unless $type =~ /[XxAaZBbHhP]/;
1355        for my $groupend ('', ')2', ')[8]') {
1356            my $groupbegin = ($groupend ? '(' : '');
1357            $c = 1;
1358            $c = $1 if $groupend =~ /(\d+)/;
1359            my @list2 = (@list1) x $c;
1360
1361            SKIP: {
1362              my $junk1 = "$groupbegin $type$count $groupend";
1363              # print "# junk1=$junk1\n";
1364              my $p = eval { pack $junk1, @list2 };
1365              skip "cannot pack '$type' on this perl", 12
1366                if is_valid_error($@);
1367              die "pack $junk1 failed: $@" if $@;
1368
1369              my $half = int( (length $p)/2 );
1370              for my $move ('', "X$half", "X!$half", 'x1', 'x!8', "x$half") {
1371                my $junk = "$junk1 $move";
1372                # print "# junk='$junk', list=(@list2)\n";
1373                $p = pack "$junk $end", @list2, @end;
1374                my @l = unpack "x[$junk] $end", $p;
1375                is(scalar @l, scalar @end);
1376                is("@l", "@end", "skipping x[$junk]");
1377              }
1378            }
1379        }
1380      }
1381    }
1382 }
1383
1384 # / is recognized after spaces in scalar context
1385 # XXXX no spaces are allowed in pack...  In pack only before the slash...
1386 is(scalar unpack('A /A Z20', pack 'A/A* Z20', 'bcde', 'xxxxx'), 'bcde');
1387 is(scalar unpack('A /A /A Z20', '3004bcde'), 'bcde');
1388
1389 { # X! and x!
1390   my $t = 'C[3]  x!8 C[2]';
1391   my @a = (0x73..0x77);
1392   my $p = pack($t, @a);
1393   is($p, "\x73\x74\x75\0\0\0\0\0\x76\x77");
1394   my @b = unpack $t, $p;
1395   is(scalar @b, scalar @a);
1396   is("@b", "@a", 'x!8');
1397   $t = 'x[5] C[6] X!8 C[2]';
1398   @a = (0x73..0x7a);
1399   $p = pack($t, @a);
1400   is($p, "\0\0\0\0\0\x73\x74\x75\x79\x7a");
1401   @b = unpack $t, $p;
1402   @a = (0x73..0x75, 0x79, 0x7a, 0x79, 0x7a);
1403   is(scalar @b, scalar @a);
1404   is("@b", "@a");
1405 }
1406
1407 { # struct {char c1; double d; char cc[2];}
1408   my $t = 'C x![d] d C[2]';
1409   my @a = (173, 1.283476517e-45, 42, 215);
1410   my $p = pack $t, @a;
1411   ok( length $p);
1412   my @b = unpack "$t X[$t] $t", $p;     # Extract, step back, extract again
1413   is(scalar @b, 2 * scalar @a);
1414   $b = "@b";
1415   $b =~ s/(?:17000+|16999+)\d+(e-45) /17$1 /gi; # stringification is gamble
1416   is($b, "@a @a");
1417
1418   use warnings qw(NONFATAL all);;
1419   my $warning;
1420   local $SIG{__WARN__} = sub {
1421       $warning = $_[0];
1422   };
1423   @b = unpack "x[C] x[$t] X[$t] X[C] $t", "$p\0";
1424
1425   is($warning, undef);
1426   is(scalar @b, scalar @a);
1427   $b = "@b";
1428   $b =~ s/(?:17000+|16999+)\d+(e-45) /17$1 /gi; # stringification is gamble
1429   is($b, "@a");
1430 }
1431
1432 is(length(pack("j", 0)), $Config{ivsize});
1433 is(length(pack("J", 0)), $Config{uvsize});
1434 is(length(pack("F", 0)), $Config{nvsize});
1435
1436 numbers ('j', -2147483648, -1, 0, 1, 2147483647);
1437 numbers ('J', 0, 1, 2147483647, 2147483648, 4294967295);
1438 numbers ('F', -(2**34), -1, 0, 1, 2**34);
1439 SKIP: {
1440     my $t = eval { unpack("D*", pack("D", 12.34)) };
1441
1442     skip "Long doubles not in use", 166 if $@ =~ /Invalid type/;
1443
1444     is(length(pack("D", 0)), $Config{longdblsize});
1445     numbers ('D', -(2**34), -1, 0, 1, 2**34);
1446 }
1447
1448 # Maybe this knowledge needs to be "global" for all of pack.t
1449 # Or a "can checksum" which would effectively be all the number types"
1450 my %cant_checksum = map {$_=> 1} qw(A Z u w);
1451 # not a b B h H
1452 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)) {
1453   SKIP: {
1454     my $packed = eval {pack "${template}4", 1, 4, 9, 16};
1455     if ($@) {
1456       die unless $@ =~ /Invalid type '$template'/;
1457       skip ("$template not supported on this perl",
1458             $cant_checksum{$template} ? 4 : 8);
1459     }
1460     my @unpack4 = unpack "${template}4", $packed;
1461     my @unpack = unpack "${template}*", $packed;
1462     my @unpack1 = unpack "${template}", $packed;
1463     my @unpack1s = scalar unpack "${template}", $packed;
1464     my @unpack4s = scalar unpack "${template}4", $packed;
1465     my @unpacks = scalar unpack "${template}*", $packed;
1466
1467     my @tests = ( ["${template}4 vs ${template}*", \@unpack4, \@unpack],
1468                   ["scalar ${template} ${template}", \@unpack1s, \@unpack1],
1469                   ["scalar ${template}4 vs ${template}", \@unpack4s, \@unpack1],
1470                   ["scalar ${template}* vs ${template}", \@unpacks, \@unpack1],
1471                 );
1472
1473     unless ($cant_checksum{$template}) {
1474       my @unpack4_c = unpack "\%${template}4", $packed;
1475       my @unpack_c = unpack "\%${template}*", $packed;
1476       my @unpack1_c = unpack "\%${template}", $packed;
1477       my @unpack1s_c = scalar unpack "\%${template}", $packed;
1478       my @unpack4s_c = scalar unpack "\%${template}4", $packed;
1479       my @unpacks_c = scalar unpack "\%${template}*", $packed;
1480
1481       push @tests,
1482         ( ["% ${template}4 vs ${template}*", \@unpack4_c, \@unpack_c],
1483           ["% scalar ${template} ${template}", \@unpack1s_c, \@unpack1_c],
1484           ["% scalar ${template}4 vs ${template}*", \@unpack4s_c, \@unpack_c],
1485           ["% scalar ${template}* vs ${template}*", \@unpacks_c, \@unpack_c],
1486         );
1487     }
1488     foreach my $test (@tests) {
1489       ok (list_eq ($test->[1], $test->[2]), $test->[0]) ||
1490         printf "# unpack gave %s expected %s\n",
1491           encode_list (@{$test->[1]}), encode_list (@{$test->[2]});
1492     }
1493   }
1494 }
1495
1496 ok(pack('u2', 'AA'), "[perl #8026]"); # used to hang and eat RAM in perl 5.7.2
1497
1498 $_ = pack('c', 65); # 'A' would not be EBCDIC-friendly
1499 is(unpack('c'), 65, "one-arg unpack (change #18751)"); # defaulting to $_
1500
1501 {
1502     my $a = "X\x0901234567\n" x 100; # \t would not be EBCDIC TAB
1503     my @a = unpack("(a1 c/a)*", $a);
1504     is(scalar @a, 200,       "[perl #15288]");
1505     is($a[-1], "01234567\n", "[perl #15288]");
1506     is($a[-2], "X",          "[perl #15288]");
1507 }
1508
1509 {
1510     use warnings qw(NONFATAL all);;
1511     my $warning;
1512     local $SIG{__WARN__} = sub {
1513         $warning = $_[0];
1514     };
1515
1516     # This test is looking for the encoding of the bit pattern "\x66\x6f\x6f",
1517     # which is ASCII "foo"
1518     my $out = pack("u99", native_to_uni("foo") x 99);
1519     like($warning, qr/Field too wide in 'u' format in pack at /,
1520          "Warn about too wide uuencode");
1521     is($out, ("_" . "9F]O" x 21 . "\n") x 4 . "M" . "9F]O" x 15 . "\n",
1522        "Use max width in case of too wide uuencode");
1523 }
1524
1525 # checksums
1526 {
1527     # verify that unpack advances correctly wrt a checksum
1528     my (@x) = unpack("b10a", "abcd");
1529     my (@y) = unpack("%b10a", "abcd");
1530     is($x[1], $y[1], "checksum advance ok");
1531
1532     # verify that the checksum is not overflowed with C0
1533     is(unpack("C0%128U", "abcd"), unpack("U0%128U", "abcd"), "checksum not overflowed");
1534 }
1535
1536 my $U_1FFC_utf8 = byte_utf8a_to_utf8n("\341\277\274");
1537 my $first_byte = ord uni_to_native("\341");
1538 {
1539     # U0 and C0 must be scoped
1540     my (@x) = unpack("a(U0)U", "b$U_1FFC_utf8");
1541     is($x[0], 'b', 'before scope');
1542     is($x[1], 8188, 'after scope');
1543
1544     is(pack("a(U0)U", "b", 8188), "b$U_1FFC_utf8");
1545 }
1546
1547 SKIP:
1548 {
1549     # counted length prefixes shouldn't change C0/U0 mode
1550     # (note the length is actually 0 in this test)
1551     is(join(',', unpack("aC/UU",   "b\0$U_1FFC_utf8")), 'b,8188');
1552     is(join(',', unpack("aC/CU",   "b\0$U_1FFC_utf8")), 'b,8188');
1553     skip "These two still fail on EBCDIC; investigate in v5.23", 2 if $::IS_EBCDIC;
1554     is(join(',', unpack("aU0C/UU", "b\0$U_1FFC_utf8")), "b,$first_byte");
1555     is(join(',', unpack("aU0C/CU", "b\0$U_1FFC_utf8")), "b,$first_byte");
1556 }
1557
1558 {
1559     # "Z0" (bug #34062)
1560     my (@x) = unpack("C*", pack("CZ0", 1, "b"));
1561     is(join(',', @x), '1', 'pack Z0 doesn\'t destroy the character before');
1562 }
1563
1564 {
1565     # Encoding neutrality
1566     # String we will pull apart and rebuild in several ways:
1567     my $down = "\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff\x05\x06";
1568     my $up   = $down;
1569     utf8::upgrade($up);
1570
1571     my %expect =
1572         # [expected result,
1573         #  how many chars it should progress,
1574         #  (optional) expected result of pack]
1575         (a5 => ["\xf8\xf9\xfa\xfb\xfc", 5],
1576          A5 => ["\xf8\xf9\xfa\xfb\xfc", 5],
1577          Z5 => ["\xf8\xf9\xfa\xfb\xfc", 5, "\xf8\xf9\xfa\xfb\x00\xfd"],
1578          b21 => ["000111111001111101011", 3, "\xf8\xf9\x1a\xfb"],
1579          B21 => ["111110001111100111111", 3, "\xf8\xf9\xf8\xfb"],
1580          H5 => ["f8f9f", 3, "\xf8\xf9\xf0\xfb"],
1581          h5 => ["8f9fa", 3, "\xf8\xf9\x0a\xfb"],
1582          "s<"  => [-1544, 2],
1583          "s>"  => [-1799, 2],
1584          "S<"  => [0xf9f8, 2],
1585          "S>"  => [0xf8f9, 2],
1586          "l<"  => [-67438088, 4],
1587          "l>"  => [-117835013, 4],
1588          "L>"  => [0xf8f9fafb, 4],
1589          "L<"  => [0xfbfaf9f8, 4],
1590          n     => [0xf8f9, 2],
1591          N     => [0xf8f9fafb, 4],
1592          v     => [63992, 2],
1593          V     => [0xfbfaf9f8, 4],
1594          c     => [-8, 1],
1595          U0U   => [0xf8, 1],
1596          w     => ["8715569050387726213", 9],
1597          q     => ["-283686952306184", 8],
1598          Q     => ["18446460386757245432", 8],
1599          );
1600
1601     for my $string ($down, $up) {
1602         for my $format (sort {lc($a) cmp lc($b) || $a cmp $b } keys %expect) {
1603           SKIP: {
1604               my $expect = $expect{$format};
1605               # unpack upgraded and downgraded string
1606               my @result = eval { unpack("$format C0 W", $string) };
1607               skip "cannot pack/unpack '$format C0 W' on this perl", 5 if
1608                   $@ && is_valid_error($@);
1609               is(@result, 2, "Two results from unpack $format C0 W");
1610
1611               # pack to downgraded
1612               my $new = pack("$format C0 W", @result);
1613               is(length($new), $expect->[1]+1,
1614                  "pack $format C0 W should give $expect->[1]+1 chars");
1615               is($new, $expect->[2] || substr($string, 0, length $new),
1616                  "pack $format C0 W returns expected value");
1617
1618               # pack to upgraded
1619               $new = pack("a0 $format C0 W", chr(256), @result);
1620               is(length($new), $expect->[1]+1,
1621                  "pack a0 $format C0 W should give $expect->[1]+1 chars");
1622               is($new, $expect->[2] || substr($string, 0, length $new),
1623                  "pack a0 $format C0 W returns expected value");
1624           }
1625         }
1626     }
1627 }
1628
1629 {
1630     # Encoding neutrality, numbers
1631     my $val = -2.68;
1632     for my $format (qw(s S i I l L j J f d F D q Q
1633                        s! S! i! I! l! L! n! N! v! V!)) {
1634       SKIP: {
1635           my $down = eval { pack($format, $val) };
1636           skip "cannot pack/unpack $format on this perl", 9 if
1637               $@ && is_valid_error($@);
1638           ok(!utf8::is_utf8($down), "Simple $format pack doesn't get upgraded");
1639           my $up = pack("a0 $format", chr(256), $val);
1640           ok(utf8::is_utf8($up), "a0 $format with high char leads to upgrade");
1641           is($down, $up, "$format generated strings are equal though");
1642           my @down_expanded = unpack("$format W", $down . chr(0xce));
1643           is(@down_expanded, 2, "Expand to two values");
1644           is($down_expanded[1], 0xce,
1645              "unpack $format left us at the expected position");
1646           my @up_expanded   = unpack("$format W", $up   . chr(0xce));
1647           is(@up_expanded, 2, "Expand to two values");
1648           is($up_expanded[1], 0xce,
1649              "unpack $format left us at the expected position");
1650           is($down_expanded[0], $up_expanded[0], "$format unpack was neutral");
1651           is(pack($format, $down_expanded[0]), $down, "Pack $format undoes unpack $format");
1652       }
1653     }
1654 }
1655
1656 {
1657     # C *is* neutral
1658     my $down = "\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff\x05\x06";
1659     my $up   = $down;
1660     utf8::upgrade($up);
1661     my @down = unpack("C*", $down);
1662     my @expect_down = (0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff, 0x05, 0x06);
1663     is("@down", "@expect_down", "byte expand");
1664     is(pack("C*", @down), $down, "byte join");
1665
1666     my @up   = unpack("C*", $up);
1667     my @expect_up = (0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff, 0x05, 0x06);
1668     is("@up", "@expect_up", "UTF-8 expand");
1669     is(pack("U0C0C*", @up), $up, "UTF-8 join");
1670 }
1671
1672 {
1673     # Harder cases for the neutrality test
1674
1675     # u format
1676     my $down = "\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff\x05\x06";
1677     my $up   = $down;
1678     utf8::upgrade($up);
1679     is(pack("u", $down), pack("u", $up), "u pack is neutral");
1680     is(unpack("u", pack("u", $down)), $down, "u unpack to downgraded works");
1681     is(unpack("U0C0u", pack("u", $down)), $up, "u unpack to upgraded works");
1682
1683     # p/P format
1684     # This actually only tests something if the address contains a byte >= 0x80
1685     my $str = "abc\xa5\x00\xfede";
1686     $down = pack("p", $str);
1687     is(pack("P", $str), $down);
1688     is(pack("U0C0p", $str), $down);
1689     is(pack("U0C0P", $str), $down);
1690     is(unpack("p", $down), "abc\xa5", "unpack p downgraded");
1691     $up   = $down;
1692     utf8::upgrade($up);
1693     is(unpack("p", $up), "abc\xa5", "unpack p upgraded");
1694
1695     is(unpack("P7", $down), "abc\xa5\x00\xfed", "unpack P downgraded");
1696     is(unpack("P7", $up),   "abc\xa5\x00\xfed", "unpack P upgraded");
1697
1698     # x, X and @
1699     $down = "\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff\x05\x06";
1700     $up   = $down;
1701     utf8::upgrade($up);
1702
1703     is(unpack('@4W', $down), 0xfc, "\@positioning on downgraded string");
1704     is(unpack('@4W', $up),   0xfc, "\@positioning on upgraded string");
1705
1706     is(unpack('@4x2W', $down), 0xfe, "x moving on downgraded string");
1707     is(unpack('@4x2W', $up),   0xfe, "x moving on upgraded string");
1708     is(unpack('@4x!4W', $down), 0xfc, "x! moving on downgraded string");
1709     is(unpack('@4x!4W', $up),   0xfc, "x! moving on upgraded string");
1710     is(unpack('@5x!4W', $down), 0x05, "x! moving on downgraded string");
1711     is(unpack('@5x!4W', $up),   0x05, "x! moving on upgraded string");
1712
1713     is(unpack('@4X2W', $down), 0xfa, "X moving on downgraded string");
1714     is(unpack('@4X2W', $up),   0xfa, "X moving on upgraded string");
1715     is(unpack('@4X!4W', $down), 0xfc, "X! moving on downgraded string");
1716     is(unpack('@4X!4W', $up),   0xfc, "X! moving on upgraded string");
1717     is(unpack('@5X!4W', $down), 0xfc, "X! moving on downgraded string");
1718     is(unpack('@5X!4W', $up),   0xfc, "X! moving on upgraded string");
1719     is(unpack('@5X!8W', $down), 0xf8, "X! moving on downgraded string");
1720     is(unpack('@5X!8W', $up),   0xf8, "X! moving on upgraded string");
1721
1722     is(pack("W2x", 0xfa, 0xe3), "\xfa\xe3\x00", "x on downgraded string");
1723     is(pack("W2x!4", 0xfa, 0xe3), "\xfa\xe3\x00\x00",
1724        "x! on downgraded string");
1725     is(pack("W2x!2", 0xfa, 0xe3), "\xfa\xe3", "x! on downgraded string");
1726     is(pack("U0C0W2x", 0xfa, 0xe3), "\xfa\xe3\x00", "x on upgraded string");
1727     is(pack("U0C0W2x!4", 0xfa, 0xe3), "\xfa\xe3\x00\x00",
1728        "x! on upgraded string");
1729     is(pack("U0C0W2x!2", 0xfa, 0xe3), "\xfa\xe3", "x! on upgraded string");
1730     is(pack("W2X", 0xfa, 0xe3), "\xfa", "X on downgraded string");
1731     is(pack("U0C0W2X", 0xfa, 0xe3), "\xfa", "X on upgraded string");
1732     is(pack("W2X!2", 0xfa, 0xe3), "\xfa\xe3", "X! on downgraded string");
1733     is(pack("U0C0W2X!2", 0xfa, 0xe3), "\xfa\xe3", "X! on upgraded string");
1734     is(pack("W3X!2", 0xfa, 0xe3, 0xa6), "\xfa\xe3", "X! on downgraded string");
1735     is(pack("U0C0W3X!2", 0xfa, 0xe3, 0xa6), "\xfa\xe3",
1736        "X! on upgraded string");
1737
1738     # backward eating through a ( moves the group starting point backwards
1739     is(pack("a*(Xa)", "abc", "q"), "abq",
1740        "eating before strbeg moves it back");
1741     is(pack("a*(Xa)", "ab" . chr(512), "q"), "abq",
1742        "eating before strbeg moves it back");
1743
1744     # Check marked_upgrade
1745     is(pack('W(W(Wa@3W)@6W)@9W', 0xa1, 0xa2, 0xa3, "a", 0xa4, 0xa5, 0xa6),
1746        "\xa1\xa2\xa3a\x00\xa4\x00\xa5\x00\xa6");
1747     $up = "a";
1748     utf8::upgrade($up);
1749     is(pack('W(W(Wa@3W)@6W)@9W', 0xa1, 0xa2, 0xa3, $up, 0xa4, 0xa5, 0xa6),
1750        "\xa1\xa2\xa3a\x00\xa4\x00\xa5\x00\xa6", "marked upgrade caused by a");
1751     is(pack('W(W(WW@3W)@6W)@9W', 0xa1, 0xa2, 0xa3, 256, 0xa4, 0xa5, 0xa6),
1752        "\xa1\xa2\xa3\x{100}\x00\xa4\x00\xa5\x00\xa6",
1753        "marked upgrade caused by W");
1754     is(pack('W(W(WU0aC0@3W)@6W)@9W', 0xa1, 0xa2, 0xa3, "a", 0xa4, 0xa5, 0xa6),
1755        "\xa1\xa2\xa3a\x00\xa4\x00\xa5\x00\xa6", "marked upgrade caused by U0");
1756
1757     # a, A and Z
1758     $down = "\xa4\xa6\xa7";
1759     $up   = $down;
1760     utf8::upgrade($up);
1761     utf8::upgrade(my $high = "\xfeb");
1762
1763     for my $format ("a0", "A0", "Z0", "U0a0C0", "U0A0C0", "U0Z0C0") {
1764         is(pack("a* $format a*", "ab", $down, "cd"), "abcd",
1765            "$format format on plain string");
1766         is(pack("a* $format a*", "ab", $up,   "cd"), "abcd",
1767            "$format format on upgraded string");
1768         is(pack("a* $format a*", $high, $down, "cd"), "\xfebcd",
1769            "$format format on plain string");
1770         is(pack("a* $format a*", $high, $up,   "cd"), "\xfebcd",
1771            "$format format on upgraded string");
1772         my @down = unpack("a1 $format a*", "\xfeb");
1773         is("@down", "\xfe  b", "unpack $format");
1774         my @up = unpack("a1 $format a*", $high);
1775         is("@up", "\xfe  b", "unpack $format");
1776     }
1777     is(pack("a1", $high), "\xfe");
1778     is(pack("A1", $high), "\xfe");
1779     is(pack("Z1", $high), "\x00");
1780     is(pack("a2", $high), "\xfeb");
1781     is(pack("A2", $high), "\xfeb");
1782     is(pack("Z2", $high), "\xfe\x00");
1783     is(pack("a5", $high), "\xfeb\x00\x00\x00");
1784     is(pack("A5", $high), "\xfeb   ");
1785     is(pack("Z5", $high), "\xfeb\x00\x00\x00");
1786     is(pack("a*", $high), "\xfeb");
1787     is(pack("A*", $high), "\xfeb");
1788     is(pack("Z*", $high), "\xfeb\x00");
1789
1790     utf8::upgrade($high = byte_utf8a_to_utf8n("\xc3\xbe") . "b");
1791     is(pack("U0a2", $high), uni_to_native("\xfe"));
1792     is(pack("U0A2", $high), uni_to_native("\xfe"));
1793     is(pack("U0Z1", $high), uni_to_native("\x00"));
1794     is(pack("U0a3", $high), uni_to_native("\xfe") . "b");
1795     is(pack("U0A3", $high), uni_to_native("\xfe") . "b");
1796     is(pack("U0Z3", $high), uni_to_native("\xfe\x00"));
1797     is(pack("U0a6", $high), uni_to_native("\xfe") . "b" . uni_to_native("\x00\x00\x00"));
1798     is(pack("U0A6", $high), uni_to_native("\xfe") . "b   ");
1799     is(pack("U0Z6", $high), uni_to_native("\xfe") . "b" . uni_to_native("\x00\x00\x00"));
1800     is(pack("U0a*", $high), uni_to_native("\xfe") . "b");
1801     is(pack("U0A*", $high), uni_to_native("\xfe") . "b");
1802     is(pack("U0Z*", $high), uni_to_native("\xfe") . "b" . uni_to_native("\x00"));
1803 }
1804 {
1805     # pack /
1806     my @array = 1..14;
1807     my @out = unpack("N/S", pack("N/S", @array) . "abcd");
1808     is("@out", "@array", "pack N/S works");
1809     @out = unpack("N/S*", pack("N/S*", @array) . "abcd");
1810     is("@out", "@array", "pack N/S* works");
1811     @out = unpack("N/S*", pack("N/S14", @array) . "abcd");
1812     is("@out", "@array", "pack N/S14 works");
1813     @out = unpack("N/S*", pack("N/S15", @array) . "abcd");
1814     is("@out", "@array", "pack N/S15 works");
1815     @out = unpack("N/S*", pack("N/S13", @array) . "abcd");
1816     is("@out", "@array[0..12]", "pack N/S13 works");
1817     @out = unpack("N/S*", pack("N/S0", @array) . "abcd");
1818     is("@out", "", "pack N/S0 works");
1819     is(pack("Z*/a0", "abc"), "0\0", "pack Z*/a0 makes a short string");
1820     is(pack("Z*/Z0", "abc"), "0\0", "pack Z*/Z0 makes a short string");
1821     is(pack("Z*/a3", "abc"), "3\0abc", "pack Z*/a3 makes a full string");
1822     is(pack("Z*/Z3", "abc"), "3\0ab\0", "pack Z*/Z3 makes a short string");
1823     is(pack("Z*/a5", "abc"), "5\0abc\0\0", "pack Z*/a5 makes a long string");
1824     is(pack("Z*/Z5", "abc"), "5\0abc\0\0", "pack Z*/Z5 makes a long string");
1825     is(pack("Z*/Z"), "1\0\0", "pack Z*/Z makes an extended string");
1826     is(pack("Z*/Z", ""), "1\0\0", "pack Z*/Z makes an extended string");
1827     is(pack("Z*/a", ""), "0\0", "pack Z*/a makes an extended string");
1828 }
1829 {
1830     # unpack("A*", $unicode) strips general unicode spaces
1831     is(unpack("A*", "ab \n" . uni_to_native("\xa0") . " \0"), "ab \n" . uni_to_native("\xa0"),
1832        'normal A* strip leaves \xa0');
1833     is(unpack("U0C0A*", "ab \n" . uni_to_native("\xa0") . " \0"), "ab \n" . uni_to_native("\xa0"),
1834        'normal A* strip leaves \xa0 even if it got upgraded for technical reasons');
1835     is(unpack("A*", pack("a*(U0U)a*", "ab \n", 0xa0, " \0")), "ab",
1836        'upgraded strings A* removes \xa0');
1837     is(unpack("A*", pack("a*(U0UU)a*", "ab \n", 0xa0, 0x1680, " \0")), "ab",
1838        'upgraded strings A* removes all unicode whitespace');
1839     is(unpack("A5", pack("a*(U0U)a*", "ab \n", 0x1680, "def", "ab")), "ab",
1840        'upgraded strings A5 removes all unicode whitespace');
1841     is(unpack("A*", pack("U", 0x1680)), "",
1842        'upgraded strings A* with nothing left');
1843 }
1844 {
1845     # Testing unpack . and .!
1846     is(unpack(".", "ABCD"), 0, "offset at start of string is 0");
1847     is(unpack(".", ""), 0, "offset at start of empty string is 0");
1848     is(unpack("x3.", "ABCDEF"), 3, "simple offset works");
1849     is(unpack("x3.", "ABC"), 3, "simple offset at end of string works");
1850     is(unpack("x3.0", "ABC"), 0, "self offset is 0");
1851     is(unpack("x3(x2.)", "ABCDEF"), 2, "offset is relative to inner group");
1852     is(unpack("x3(X2.)", "ABCDEF"), -2,
1853        "negative offset relative to inner group");
1854     is(unpack("x3(X2.2)", "ABCDEF"), 1, "offset is relative to inner group");
1855     is(unpack("x3(x2.0)", "ABCDEF"), 0, "self offset in group is still 0");
1856     is(unpack("x3(x2.2)", "ABCDEF"), 5, "offset counts groups");
1857     is(unpack("x3(x2.*)", "ABCDEF"), 5, "star offset is relative to start");
1858
1859     my $high = chr(8188) x 6;
1860     is(unpack("x3(x2.)", $high), 2, "utf8 offset is relative to inner group");
1861     is(unpack("x3(X2.)", $high), -2,
1862        "utf8 negative offset relative to inner group");
1863     is(unpack("x3(X2.2)", $high), 1, "utf8 offset counts groups");
1864     is(unpack("x3(x2.0)", $high), 0, "utf8 self offset in group is still 0");
1865     is(unpack("x3(x2.2)", $high), 5, "utf8 offset counts groups");
1866     is(unpack("x3(x2.*)", $high), 5, "utf8 star offset is relative to start");
1867
1868     is(unpack("U0x3(x2.)", $high), 2,
1869        "U0 mode utf8 offset is relative to inner group");
1870     is(unpack("U0x3(X2.)", $high), -2,
1871        "U0 mode utf8 negative offset relative to inner group");
1872     is(unpack("U0x3(X2.2)", $high), 1,
1873        "U0 mode utf8 offset counts groups");
1874     is(unpack("U0x3(x2.0)", $high), 0,
1875        "U0 mode utf8 self offset in group is still 0");
1876     is(unpack("U0x3(x2.2)", $high), 5,
1877        "U0 mode utf8 offset counts groups");
1878     is(unpack("U0x3(x2.*)", $high), 5,
1879        "U0 mode utf8 star offset is relative to start");
1880
1881     is(unpack("x3(x2.!)", $high), 2*3,
1882        "utf8 offset is relative to inner group");
1883     is(unpack("x3(X2.!)", $high), -2*3,
1884        "utf8 negative offset relative to inner group");
1885     is(unpack("x3(X2.!2)", $high), 1*3,
1886        "utf8 offset counts groups");
1887     is(unpack("x3(x2.!0)", $high), 0,
1888        "utf8 self offset in group is still 0");
1889     is(unpack("x3(x2.!2)", $high), 5*3,
1890        "utf8 offset counts groups");
1891     is(unpack("x3(x2.!*)", $high), 5*3,
1892        "utf8 star offset is relative to start");
1893
1894     is(unpack("U0x3(x2.!)", $high), 2,
1895        "U0 mode utf8 offset is relative to inner group");
1896     is(unpack("U0x3(X2.!)", $high), -2,
1897        "U0 mode utf8 negative offset relative to inner group");
1898     is(unpack("U0x3(X2.!2)", $high), 1,
1899        "U0 mode utf8 offset counts groups");
1900     is(unpack("U0x3(x2.!0)", $high), 0,
1901        "U0 mode utf8 self offset in group is still 0");
1902     is(unpack("U0x3(x2.!2)", $high), 5,
1903        "U0 mode utf8 offset counts groups");
1904     is(unpack("U0x3(x2.!*)", $high), 5,
1905        "U0 mode utf8 star offset is relative to start");
1906 }
1907 {
1908     # Testing pack . and .!
1909     is(pack("(a)5 .", 1..5, 3), "123", ". relative to string start, shorten");
1910     eval { () = pack("(a)5 .", 1..5, -3) };
1911     like($@, qr{'\.' outside of string in pack}, "Proper error message");
1912     is(pack("(a)5 .", 1..5, 8), "12345\x00\x00\x00",
1913        ". relative to string start, extend");
1914     is(pack("(a)5 .", 1..5, 5), "12345", ". relative to string start, keep");
1915
1916     is(pack("(a)5 .0", 1..5, -3), "12",
1917        ". relative to string current, shorten");
1918     is(pack("(a)5 .0", 1..5, 2), "12345\x00\x00",
1919        ". relative to string current, extend");
1920     is(pack("(a)5 .0", 1..5, 0), "12345",
1921        ". relative to string current, keep");
1922
1923     is(pack("(a)5 (.)", 1..5, -3), "12",
1924        ". relative to group, shorten");
1925     is(pack("(a)5 (.)", 1..5, 2), "12345\x00\x00",
1926        ". relative to group, extend");
1927     is(pack("(a)5 (.)", 1..5, 0), "12345",
1928        ". relative to group, keep");
1929
1930     is(pack("(a)3 ((a)2 .)", 1..5, -2), "1",
1931        ". relative to group, shorten");
1932     is(pack("(a)3 ((a)2 .)", 1..5, 2), "12345",
1933        ". relative to group, keep");
1934     is(pack("(a)3 ((a)2 .)", 1..5, 4), "12345\x00\x00",
1935        ". relative to group, extend");
1936
1937     is(pack("(a)3 ((a)2 .2)", 1..5, 2), "12",
1938        ". relative to counted group, shorten");
1939     is(pack("(a)3 ((a)2 .2)", 1..5, 7), "12345\x00\x00",
1940        ". relative to counted group, extend");
1941     is(pack("(a)3 ((a)2 .2)", 1..5, 5), "12345",
1942        ". relative to counted group, keep");
1943
1944     is(pack("(a)3 ((a)2 .*)", 1..5, 2), "12",
1945        ". relative to start, shorten");
1946     is(pack("(a)3 ((a)2 .*)", 1..5, 7), "12345\x00\x00",
1947        ". relative to start, extend");
1948     is(pack("(a)3 ((a)2 .*)", 1..5, 5), "12345",
1949        ". relative to start, keep");
1950
1951     is(pack('(a)5 (. @2 a)', 1..5, -3, "a"), "12\x00\x00a",
1952        ". based shrink properly updates group starts");
1953
1954     is(pack("(W)3 ((W)2 .)", 0x301..0x305, -2), "\x{301}",
1955        "utf8 . relative to group, shorten");
1956     is(pack("(W)3 ((W)2 .)", 0x301..0x305, 2),
1957        "\x{301}\x{302}\x{303}\x{304}\x{305}",
1958        "utf8 . relative to group, keep");
1959     is(pack("(W)3 ((W)2 .)", 0x301..0x305, 4),
1960        "\x{301}\x{302}\x{303}\x{304}\x{305}\x00\x00",
1961        "utf8 . relative to group, extend");
1962
1963     is(pack("(W)3 ((W)2 .!)", 0x301..0x305, -2), "\x{301}\x{302}",
1964        "utf8 . relative to group, shorten");
1965     is(pack("(W)3 ((W)2 .!)", 0x301..0x305, 4),
1966        "\x{301}\x{302}\x{303}\x{304}\x{305}",
1967        "utf8 . relative to group, keep");
1968     is(pack("(W)3 ((W)2 .!)", 0x301..0x305, 6),
1969        "\x{301}\x{302}\x{303}\x{304}\x{305}\x00\x00",
1970        "utf8 . relative to group, extend");
1971
1972     is(pack('(W)5 (. @2 a)', 0x301..0x305, -3, "a"),
1973        "\x{301}\x{302}\x00\x00a",
1974        "utf8 . based shrink properly updates group starts");
1975 }
1976 {
1977     # Testing @!
1978     is(pack('a* @3',  "abcde"), "abc", 'Test basic @');
1979     is(pack('a* @!3', "abcde"), "abc", 'Test basic @!');
1980     is(pack('a* @2', "\x{301}\x{302}\x{303}\x{304}\x{305}"), "\x{301}\x{302}",
1981        'Test basic utf8 @');
1982     is(pack('a* @!2', "\x{301}\x{302}\x{303}\x{304}\x{305}"), "\x{301}",
1983        'Test basic utf8 @!');
1984
1985     is(unpack('@4 a*',  "abcde"), "e", 'Test basic @');
1986     is(unpack('@!4 a*', "abcde"), "e", 'Test basic @!');
1987     is(unpack('@4 a*',  "\x{301}\x{302}\x{303}\x{304}\x{305}"), "\x{305}",
1988        'Test basic utf8 @');
1989     is(unpack('@!4 a*', "\x{301}\x{302}\x{303}\x{304}\x{305}"),
1990        "\x{303}\x{304}\x{305}", 'Test basic utf8 @!');
1991 }
1992 {
1993     #50256
1994     # This test is for the bit pattern "\x61\x62", which is ASCII "ab"
1995     my ($v) = split //, unpack ('(B)*', native_to_uni('ab'));
1996     is($v, 0); # Doesn't SEGV :-)
1997 }
1998 {
1999     #73814
2000     my $x = runperl( prog => 'print split( /,/, unpack(q(%2H*), q(hello world))), qq(\n)' );
2001     is($x, "0\n", "split /a/, unpack('%2H*'...) didn't crash");
2002
2003     my $y = runperl( prog => 'print split( /,/, unpack(q(%32u*), q(#,3,Q)), qq(\n)), qq(\n)' );
2004     is($y, "0\n", "split /a/, unpack('%32u*'...) didn't crash");
2005 }
2006
2007 #90160
2008 is(eval { () = unpack "C0 U*", ""; "ok" }, "ok",
2009   'medial U* on empty string');
2010
2011 package o {
2012     use overload
2013         '""' => sub { ++$o::str; "42" },
2014         '0+' => sub { ++$o::num; 42 };
2015 }
2016 is pack("c", bless [], "o"), chr(42), 'overloading called';
2017 is $o::str, undef, 'pack "c" does not call string overloading';
2018 is $o::num, 1,     'pack "c" does call num overloading';
2019
2020 #[perl #123874]: argument underflow leads to corrupt length
2021 eval q{ pack "pi/x" };
2022 ok(1, "argument underflow did not crash");