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