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