This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
question about fs.t
[perl5.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 => 1477;
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 unless @$l == @$r;
30   for my $i (0..$#$l) {
31     if (defined $l->[$i]) {
32       return unless defined ($r->[$i]) && $l->[$i] eq $r->[$i];
33     } else {
34       return 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
127
128 {
129   # test exeptions
130   my $x;
131   eval { $x = unpack 'w', pack 'C*', 0xff, 0xff};
132   like($@, qr/^Unterminated compressed integer/);
133
134   eval { $x = unpack 'w', pack 'C*', 0xff, 0xff, 0xff, 0xff};
135   like($@, qr/^Unterminated compressed integer/);
136
137   eval { $x = unpack 'w', pack 'C*', 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff};
138   like($@, qr/^Unterminated compressed integer/);
139 }
140
141 #
142 # test the "p" template
143
144 # literals
145 is(unpack("p",pack("p","foo")), "foo");
146
147 # scalars
148 is(unpack("p",pack("p",239)), 239);
149
150 # temps
151 sub foo { my $a = "a"; return $a . $a++ . $a++ }
152 {
153   use warnings;
154   my $warning;
155   local $SIG{__WARN__} = sub {
156       $warning = $_[0];
157   };
158   my $junk = pack("p", &foo);
159
160   like($warning, qr/temporary val/);
161 }
162
163 # undef should give null pointer
164 like(pack("p", undef), qr/^\0+/);
165
166 # Check for optimizer bug (e.g.  Digital Unix GEM cc with -O4 on DU V4.0B gives
167 #                                4294967295 instead of -1)
168 #                                see #ifdef __osf__ in pp.c pp_unpack
169 is((unpack("i",pack("i",-1))), -1);
170
171 # test the pack lengths of s S i I l L
172 # test the pack lengths of n N v V
173 my @lengths = qw(s 2 S 2 i -4 I -4 l 4 L 4 n 2 N 4 v 2 V 4);
174 while (my ($format, $expect) = splice @lengths, 0, 2) {
175   my $len = length(pack($format, 0));
176   if ($expect > 0) {
177     is($expect, $len, "format '$format'");
178   } else {
179     $expect = -$expect;
180     ok ($len >= $expect, "format '$format'") ||
181       print "# format '$format' has length $len, expected >= $expect\n";
182   }
183 }
184
185
186 # test unpack-pack lengths
187 my @templates = qw(c C i I s S l L n N v V f d q Q);
188
189 foreach my $t (@templates) {
190     SKIP: {
191         my @t = eval { unpack("$t*", pack("$t*", 12, 34)) };
192
193         # quads not supported everywhere
194         skip "Quads not supported", 4 if $@ =~ /Invalid type in pack/;
195         is( $@, '' );
196
197         is(scalar @t, 2);
198
199         SKIP: {
200             skip "$t not expected to work for some reason", 2 if $t =~ /[nv]/i;
201
202             is($t[0], 12);
203             is($t[1], 34);
204         }
205     }
206 }
207
208 {
209     # uuencode/decode
210
211     # Note that first uuencoding known 'text' data and then checking the
212     # binary values of the uuencoded version would not be portable between
213     # character sets.  Uuencoding is meant for encoding binary data, not
214     # text data.
215
216     my $in = pack 'C*', 0 .. 255;
217
218     # just to be anal, we do some random tr/`/ /
219     my $uu = <<'EOUU';
220 M` $"`P0%!@<("0H+# T.#Q`1$A,4%187&!D:&QP='A\@(2(C)"4F)R@I*BLL
221 M+2XO,#$R,S0U-C<X.3H[/#T^/T!!0D-$149'2$E*2TQ-3D]045)35%565UA9
222 M6EM<75Y?8&%B8V1E9F=H:6IK;&UN;W!Q<G-T=79W>'EZ>WQ]?G^`@8*#A(6&
223 MAXB)BHN,C8Z/D)&2DY25EI>8F9J;G)V>GZ"AHJ.DI::GJ*FJJZRMKJ^PL;*S
224 MM+6VM[BYNKN\O;Z_P,'"P\3%QL?(R<K+S,W.S]#1TM/4U=;7V-G:V]S=WM_@
225 ?X>+CY.7FY^CIZNOL[>[O\/'R\_3U]O?X^?K[_/W^_P `
226 EOUU
227
228     $_ = $uu;
229     tr/ /`/;
230
231     is(pack('u', $in), $_);
232
233     is(unpack('u', $uu), $in);
234
235     $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";
236     $uu = <<'EOUU';
237 M'XL("%C<Q#4"`TI!4%4`\RHM+E%(S,LOR4@M4@A(+<I1*"U-SD])+>("`&1F
238 &8%P:````
239 EOUU
240
241     is(unpack('u', $uu), $in);
242
243 # This is identical to the above except that backquotes have been
244 # changed to spaces
245
246     $uu = <<'EOUU';
247 M'XL("%C<Q#4" TI!4%4 \RHM+E%(S,LOR4@M4@A(+<I1*"U-SD])+>(" &1F
248 &8%P:
249 EOUU
250
251     # ' # Grr
252     is(unpack('u', $uu), $in);
253
254 }
255
256 # test the ascii template types (A, a, Z)
257
258 foreach (
259 ['p', 'A*',  "foo\0bar\0 ", "foo\0bar\0 "],
260 ['p', 'A11', "foo\0bar\0 ", "foo\0bar\0   "],
261 ['u', 'A*',  "foo\0bar \0", "foo\0bar"],
262 ['u', 'A8',  "foo\0bar \0", "foo\0bar"],
263 ['p', 'a*',  "foo\0bar\0 ", "foo\0bar\0 "],
264 ['p', 'a11', "foo\0bar\0 ", "foo\0bar\0 \0\0"],
265 ['u', 'a*',  "foo\0bar \0", "foo\0bar \0"],
266 ['u', 'a8',  "foo\0bar \0", "foo\0bar "],
267 ['p', 'Z*',  "foo\0bar\0 ", "foo\0bar\0 \0"],
268 ['p', 'Z11', "foo\0bar\0 ", "foo\0bar\0 \0\0"],
269 ['p', 'Z3',  "foo",         "fo\0"],
270 ['u', 'Z*',  "foo\0bar \0", "foo"],
271 ['u', 'Z8',  "foo\0bar \0", "foo"],
272
273 {
274     my ($what, $template, $in, $out) = @$_;
275     my $got = $what eq 'u' ? (unpack $template, $in) : (pack $template, $in);
276     unless (is($got, $out)) {
277         my $un = $what eq 'u' ? 'un' : '';
278         print "# ${un}pack ('$template', "._qq($in).') gave '._qq($out).
279             ' not '._qq($got)."\n";
280     }
281 }
282
283 # packing native shorts/ints/longs
284
285 is(length(pack("s!", 0)), $Config{shortsize});
286 is(length(pack("i!", 0)), $Config{intsize});
287 is(length(pack("l!", 0)), $Config{longsize});
288 ok(length(pack("s!", 0)) <= length(pack("i!", 0)));
289 ok(length(pack("i!", 0)) <= length(pack("l!", 0)));
290 is(length(pack("i!", 0)), length(pack("i", 0)));
291
292 sub numbers {
293   my $format = shift;
294   return numbers_with_total ($format, undef, @_);
295 }
296
297 sub numbers_with_total {
298   my $format = shift;
299   my $total = shift;
300   if (!defined $total) {
301     foreach (@_) {
302       $total += $_;
303     }
304   }
305   foreach (@_) {
306     SKIP: {
307         my $out = eval {unpack($format, pack($format, $_))};
308         skip "cannot pack '$format' on this perl", 2 if
309           $@ =~ /Invalid type in pack: '$format'/;
310
311         is($@, '');
312         is($out, $_);
313     }
314   }
315
316   my $skip_if_longer_than = ~0; # "Infinity"
317   if (~0 - 1 == ~0) {
318     # If we're running with -DNO_PERLPRESERVE_IVUV and NVs don't preserve all
319     # UVs (in which case ~0 is NV, ~0-1 will be the same NV) then we can't
320     # correctly in perl calculate UV totals for long checksums, as pp_unpack
321     # is using UV maths, and we've only got NVs.
322     $skip_if_longer_than = $Config{d_nv_preserves_uv_bits};
323   }
324
325   foreach ('', 1, 2, 3, 15, 16, 17, 31, 32, 33, 53, 54, 63, 64, 65) {
326     SKIP: {
327       my $sum = eval {unpack "%$_$format*", pack "$format*", @_};
328       skip "cannot pack '$format' on this perl", 3
329         if $@ =~ /Invalid type in pack: '$format'/;
330
331       is($@, '');
332       ok(defined $sum);
333
334       my $len = $_; # Copy, so that we can reassign ''
335       $len = 16 unless length $len;
336
337       SKIP: {
338         skip "cannot test checksums over $skip_if_longer_than bits", 1
339           if $len > $skip_if_longer_than;
340
341         # Our problem with testing this portably is that the checksum code in
342         # pp_unpack is able to cast signed to unsigned, and do modulo 2**n
343         # arithmetic in unsigned ints, which perl has no operators to do.
344         # (use integer; does signed ints, which won't wrap on UTS, which is just
345         # fine with ANSI, but not with most people's assumptions.
346         # This is why we need to supply the totals for 'Q' as there's no way in
347         # perl to calculate them, short of unpack '%0Q' (is that documented?)
348         # ** returns NVs; make sure it's IV.
349         my $max = 1 + 2 * (int (2 ** ($len-1))-1); # The max possible checksum
350         my $max_p1 = $max + 1;
351         my ($max_is_integer, $max_p1_is_integer);
352         $max_p1_is_integer = 1 unless $max_p1 + 1 == $max_p1;
353         $max_is_integer = 1 if $max - 1 < ~0;
354
355         my $calc_sum;
356         if (ref $total) {
357             $calc_sum = &$total($len);
358         } else {
359             $calc_sum = $total;
360             # Shift into range by some multiple of the total
361             my $mult = int ($total / $max_p1);
362             # Need this to make sure that -1 + (~0+1) is ~0 (ie still integer)
363             $calc_sum = $total - $mult;
364             $calc_sum -= $mult * $max;
365             if ($calc_sum < 0) {
366                 $calc_sum += 1;
367                 $calc_sum += $max;
368             }
369         }
370         if ($calc_sum == $calc_sum - 1 && $calc_sum == $max_p1) {
371             # we're into floating point (either by getting out of the range of
372             # UV arithmetic, or because we're doing a floating point checksum) 
373             # and our calculation of the checksum has become rounded up to
374             # max_checksum + 1
375             $calc_sum = 0;
376         }
377
378         if ($calc_sum == $sum) { # HAS to be ==, not eq (so no is()).
379             ok ("unpack '%$_$format' gave $sum");
380         } else {
381             my $delta = 1.000001;
382             if ($format =~ tr /dDfF//
383                 && ($calc_sum <= $sum * $delta && $calc_sum >= $sum / $delta)) {
384                 pass ("unpack '%$_$format' gave $sum, expected $calc_sum");
385             } else {
386                 my $text = ref $total ? &$total($len) : $total;
387                 fail;
388                 print "# For list (" . join (", ", @_) . ") (total $text)"
389                     . " packed with $format unpack '%$_$format' gave $sum,"
390                     . " expected $calc_sum\n";
391             }
392         }
393       }
394     }   
395   }
396 }
397
398 numbers ('c', -128, -1, 0, 1, 127);
399 numbers ('C', 0, 1, 127, 128, 255);
400 numbers ('s', -32768, -1, 0, 1, 32767);
401 numbers ('S', 0, 1, 32767, 32768, 65535);
402 numbers ('i', -2147483648, -1, 0, 1, 2147483647);
403 numbers ('I', 0, 1, 2147483647, 2147483648, 4294967295);
404 numbers ('l', -2147483648, -1, 0, 1, 2147483647);
405 numbers ('L', 0, 1, 2147483647, 2147483648, 4294967295);
406 numbers ('s!', -32768, -1, 0, 1, 32767);
407 numbers ('S!', 0, 1, 32767, 32768, 65535);
408 numbers ('i!', -2147483648, -1, 0, 1, 2147483647);
409 numbers ('I!', 0, 1, 2147483647, 2147483648, 4294967295);
410 numbers ('l!', -2147483648, -1, 0, 1, 2147483647);
411 numbers ('L!', 0, 1, 2147483647, 2147483648, 4294967295);
412 numbers ('n', 0, 1, 32767, 32768, 65535);
413 numbers ('v', 0, 1, 32767, 32768, 65535);
414 numbers ('N', 0, 1, 2147483647, 2147483648, 4294967295);
415 numbers ('V', 0, 1, 2147483647, 2147483648, 4294967295);
416 # All these should have exact binary representations:
417 numbers ('f', -1, 0, 0.5, 42, 2**34);
418 numbers ('d', -(2**34), -1, 0, 1, 2**34);
419 ## These don't, but 'd' is NV.  XXX wrong, it's double
420 #numbers ('d', -1, 0, 1, 1-exp(-1), -exp(1));
421
422 numbers_with_total ('q', -1,
423                     -9223372036854775808, -1, 0, 1,9223372036854775807);
424 # This total is icky, but the true total is 2**65-1, and need a way to generate
425 # the epxected checksum on any system including those where NVs can preserve
426 # 65 bits. (long double is 128 bits on sparc, so they certainly can)
427 # or where rounding is down not up on binary conversion (crays)
428 numbers_with_total ('Q', sub {
429                       my $len = shift;
430                       $len = 65 if $len > 65; # unmasked total is 2**65-1 here
431                       my $total = 1 + 2 * (int (2**($len - 1)) - 1);
432                       return 0 if $total == $total - 1; # Overflowed integers
433                       return $total; # NVs still accurate to nearest integer
434                     },
435                     0, 1,9223372036854775807, 9223372036854775808,
436                     18446744073709551615);
437
438 # pack nvNV byteorders
439
440 is(pack("n", 0xdead), "\xde\xad");
441 is(pack("v", 0xdead), "\xad\xde");
442 is(pack("N", 0xdeadbeef), "\xde\xad\xbe\xef");
443 is(pack("V", 0xdeadbeef), "\xef\xbe\xad\xde");
444
445 {
446   # /
447
448   my ($x, $y, $z);
449   eval { ($x) = unpack '/a*','hello' };
450   like($@, qr!/ must follow a numeric type!);
451   undef $x;
452   eval { $x = unpack '/a*','hello' };
453   like($@, qr!/ must follow a numeric type!);
454
455   undef $x;
456   eval { ($z,$x,$y) = unpack 'a3/A C/a* C/Z', "003ok \003yes\004z\000abc" };
457   is($@, '');
458   is($z, 'ok');
459   is($x, 'yes');
460   is($y, 'z');
461   undef $z;
462   eval { $z = unpack 'a3/A C/a* C/Z', "003ok \003yes\004z\000abc" };
463   is($@, '');
464   is($z, 'ok');
465
466
467   undef $x;
468   eval { ($x) = pack '/a*','hello' };
469   like($@,  qr!Invalid type in pack: '/'!);
470   undef $x;
471   eval { $x = pack '/a*','hello' };
472   like($@,  qr!Invalid type in pack: '/'!);
473
474   $z = pack 'n/a* N/Z* w/A*','string','hi there ','etc';
475   my $expect = "\000\006string\0\0\0\012hi there \000\003etc";
476   is($z, $expect);
477
478   undef $x;
479   $expect = 'hello world';
480   eval { ($x) = unpack ("w/a", chr (11) . "hello world!")};
481   is($x, $expect);
482   is($@, '');
483
484   undef $x;
485   # Doing this in scalar context used to fail.
486   eval { $x = unpack ("w/a", chr (11) . "hello world!")};
487   is($@, '');
488   is($x, $expect);
489
490   foreach (
491            ['a/a*/a*', '212ab345678901234567','ab3456789012'],
492            ['a/a*/a*', '3012ab345678901234567', 'ab3456789012'],
493            ['a/a*/b*', '212ab', $Is_EBCDIC ? '100000010100' : '100001100100'],
494   ) 
495   {
496     my ($pat, $in, $expect) = @$_;
497     undef $x;
498     eval { ($x) = unpack $pat, $in };
499     is($@, '');
500     is($x, $expect) || 
501       printf "# list unpack ('$pat', '$in') gave %s, expected '$expect'\n",
502              encode_list ($x);
503
504     undef $x;
505     eval { $x = unpack $pat, $in };
506     is($@, '');
507     is($x, $expect) ||
508       printf "# scalar unpack ('$pat', '$in') gave %s, expected '$expect'\n",
509              encode_list ($x);
510   }
511
512   # / with #
513
514   my $pattern = <<'EOU';
515  a3/A                   # Count in ASCII
516  C/a*                   # Count in a C char
517  C/Z                    # Count in a C char but skip after \0
518 EOU
519
520   $x = $y = $z =undef;
521   eval { ($z,$x,$y) = unpack $pattern, "003ok \003yes\004z\000abc" };
522   is($@, '');
523   is($z, 'ok');
524   is($x, 'yes');
525   is($y, 'z');
526   undef $x;
527   eval { $z = unpack $pattern, "003ok \003yes\004z\000abc" };
528   is($@, '');
529   is($z, 'ok');
530
531   $pattern = <<'EOP';
532   n/a*                  # Count as network short
533   w/A*                  # Count a  BER integer
534 EOP
535   $expect = "\000\006string\003etc";
536   $z = pack $pattern,'string','etc';
537   is($z, $expect);
538 }
539
540
541 SKIP: {
542     skip("(EBCDIC and) version strings are bad idea", 2) if $Is_EBCDIC;
543
544     is("1.20.300.4000", sprintf "%vd", pack("U*",1,20,300,4000));
545     is("1.20.300.4000", sprintf "%vd", pack("  U*",1,20,300,4000));
546 }
547 isnt(v1.20.300.4000, sprintf "%vd", pack("C0U*",1,20,300,4000));
548
549 my $rslt = $Is_EBCDIC ? "156 67" : "199 162";
550 is(join(" ", unpack("C*", chr(0x1e2))), $rslt);
551
552 # does pack U create Unicode?
553 is(ord(pack('U', 300)), 300);
554
555 # does unpack U deref Unicode?
556 is((unpack('U', chr(300)))[0], 300);
557
558 # is unpack U the reverse of pack U for Unicode string?
559 is("@{[unpack('U*', pack('U*', 100, 200, 300))]}", "100 200 300");
560
561 # is unpack U the reverse of pack U for byte string?
562 is("@{[unpack('U*', pack('U*', 100, 200))]}", "100 200");
563
564
565 SKIP: {
566     skip "Not for EBCDIC", 4 if $Is_EBCDIC;
567
568     # does unpack C unravel pack U?
569     is("@{[unpack('C*', pack('U*', 100, 200))]}", "100 195 136");
570
571     # does pack U0C create Unicode?
572     is("@{[pack('U0C*', 100, 195, 136)]}", v100.v200);
573
574     # does pack C0U create characters?
575     is("@{[pack('C0U*', 100, 200)]}", pack("C*", 100, 195, 136));
576
577     # does unpack U0U on byte data warn?
578     {
579         local $SIG{__WARN__} = sub { $@ = "@_" };
580         my @null = unpack('U0U', chr(255));
581         like($@, /^Malformed UTF-8 character /);
582     }
583 }
584
585 {
586   my $p = pack 'i*', -2147483648, ~0, 0, 1, 2147483647;
587   my (@a);
588   # bug - % had to be at the start of the pattern, no leading whitespace or
589   # comments. %i! didn't work at all.
590   foreach my $pat ('%32i*', ' %32i*', "# Muhahahaha\n%32i*", '%32i*  ',
591                    '%32i!*', ' %32i!*', "\n#\n#\n\r \t\f%32i!*", '%32i!*#') {
592     @a = unpack $pat, $p;
593     is($a[0], 0xFFFFFFFF) || print "# $pat\n";
594     @a = scalar unpack $pat, $p;
595     is($a[0], 0xFFFFFFFF) || print "# $pat\n";
596   }
597
598
599   $p = pack 'I*', 42, 12;
600   # Multiline patterns in scalar context failed.
601   foreach my $pat ('I', <<EOPOEMSNIPPET, 'I#I', 'I # I', 'I # !!!') {
602 # On the Ning Nang Nong
603 # Where the Cows go Bong!
604 # And the Monkeys all say Boo!
605 I
606 EOPOEMSNIPPET
607     @a = unpack $pat, $p;
608     is(scalar @a, 1);
609     is($a[0], 42);
610     @a = scalar unpack $pat, $p;
611     is(scalar @a, 1);
612     is($a[0], 42);
613   }
614
615   # shorts (of all flavours) didn't calculate checksums > 32 bits with floating
616   # point, so a pathologically long pattern would wrap at 32 bits.
617   my $pat = "\xff\xff"x65538; # Start with it long, to save any copying.
618   foreach (4,3,2,1,0) {
619     my $len = 65534 + $_;
620     is(unpack ("%33n$len", $pat), 65535 * $len);
621   }
622 }
623
624
625 # pack x X @
626 foreach (
627          ['x', "N", "\0"],
628          ['x4', "N", "\0"x4],
629          ['xX', "N", ""],
630          ['xXa*', "Nick", "Nick"],
631          ['a5Xa5', "cameL", "llama", "camellama"],
632          ['@4', 'N', "\0"x4],
633          ['a*@8a*', 'Camel', 'Dromedary', "Camel\0\0\0Dromedary"],
634          ['a*@4a', 'Perl rules', '!', 'Perl!'],
635
636 {
637   my ($template, @in) = @$_;
638   my $out = pop @in;
639   my $got = eval {pack $template, @in};
640   is($@, '');
641   is($out, $got) ||
642     printf "# pack ('$template', %s) gave %s expected %s\n",
643            encode_list (@in), encode_list ($got), encode_list ($out);
644 }
645
646 # unpack x X @
647 foreach (
648          ['x', "N"],
649          ['xX', "N"],
650          ['xXa*', "Nick", "Nick"],
651          ['a5Xa5', "camellama", "camel", "llama"],
652          ['@3', "ice"],
653          ['@2a2', "water", "te"],
654          ['a*@1a3', "steam", "steam", "tea"],
655
656 {
657   my ($template, $in, @out) = @$_;
658   my @got = eval {unpack $template, $in};
659   is($@, '');
660   list_eq (\@got, \@out) ||
661     printf "# list unpack ('$template', %s) gave %s expected %s\n",
662            _qq($in), encode_list (@got), encode_list (@out);
663
664   my $got = eval {unpack $template, $in};
665   is($@, '');
666   @out ? is( $got, $out[0] ) # 1 or more items; should get first
667        : ok( !defined $got ) # 0 items; should get undef
668     or printf "# scalar unpack ('$template', %s) gave %s expected %s\n",
669               _qq($in), encode_list ($got), encode_list ($out[0]);
670 }
671
672 {
673     my $t = 'Z*Z*';
674     my ($u, $v) = qw(foo xyzzy);
675     my $p = pack($t, $u, $v);
676     my @u = unpack($t, $p);
677     is(scalar @u, 2);
678     is($u[0], $u);
679     is($u[1], $v);
680 }
681
682 {
683     is((unpack("w/a*", "\x02abc"))[0], "ab");
684
685     # "w/a*" should be seen as one unit
686
687     is(scalar unpack("w/a*", "\x02abc"), "ab");
688 }
689
690 {
691     # from Wolfgang Laun: fix in change #13163
692
693     my $s = 'ABC' x 10;
694     my $t = '*';
695     my $x = ord($t);
696     my $buf = pack( 'Z*/A* C',  $s, $x );
697     my $y;
698
699     my $h = $buf;
700     $h =~ s/[^[:print:]]/./g;
701     ( $s, $y ) = unpack( "Z*/A* C", $buf );
702     is($h, "30.ABCABCABCABCABCABCABCABCABCABC$t");
703     is(length $buf, 34);
704     is($s, "ABCABCABCABCABCABCABCABCABCABC");
705     is($y, $x);
706 }
707
708 {
709     # from Wolfgang Laun: fix in change #13288
710
711     eval { my $t=unpack("P*", "abc") };
712     like($@, qr/P must have an explicit size/);
713 }