Re: n questions (was Re: 4 questions about pack/unpack)
[p5sagit/p5-mst-13.2.git] / t / op / pack.t
1 #!./perl -Tw
2
3 print "1..581\n";
4
5 BEGIN {
6     chdir 't' if -d 't';
7     @INC = '../lib';
8 }
9
10 use strict;
11 use warnings;
12 use Config;
13
14 my $Is_EBCDIC = (defined $Config{ebcdic} && $Config{ebcdic} eq 'define');
15
16 my $test = 1;
17 # Using Test considered bad plan in op/*.t ?
18
19 sub encode {
20   my @result = @_;
21   s/([[:cntrl:]\177 ])/sprintf "\\%03o", ord $1/ge foreach @result;
22   @result;
23 }
24
25 sub ok {
26   my ($pass, $wrong, $err) = @_;
27   if ($pass) {
28     print "ok $test\n";
29     $test++;
30     return 1;
31   } else {
32     if ($err) {
33       chomp $err;
34       print "not ok $test # \$\@ = $err\n";
35     } else {
36       if (defined $wrong) {
37         $wrong = ", got $wrong";
38       } else {
39         $wrong = '';
40       }
41       printf "not ok $test # line %d$wrong\n", (caller)[2];
42     }
43   }
44   $test++;
45   return;
46 }
47
48 {
49 my $format = "c2 x5 C C x s d i l a6";
50 # Need the expression in here to force ary[5] to be numeric.  This avoids
51 # test2 failing because ary2 goes str->numeric->str and ary doesn't.
52 my @ary = (1,-100,127,128,32767,987.654321098 / 100.0,12345,123456,"abcdef");
53 my $foo = pack($format,@ary);
54 my @ary2 = unpack($format,$foo);
55
56 ok($#ary == $#ary2);
57
58 my $out1=join(':',@ary);
59 my $out2=join(':',@ary2);
60 # Using long double NVs may introduce greater accuracy than wanted.
61 $out1 =~ s/:9\.87654321097999\d*:/:9.87654321098:/;
62 $out2 =~ s/:9\.87654321097999\d*:/:9.87654321098:/;
63 ok($out1 eq $out2);
64
65 ok($foo =~ /def/);
66 }
67 # How about counting bits?
68
69 {
70 my $x;
71 ok( ($x = unpack("%32B*", "\001\002\004\010\020\040\100\200\377")) == 16 );
72
73 ok( ($x = unpack("%32b69", "\001\002\004\010\020\040\100\200\017")) == 12 );
74
75 ok( ($x = unpack("%32B69", "\001\002\004\010\020\040\100\200\017")) == 9 );
76 }
77
78 {
79 my $sum = 129; # ASCII
80 $sum = 103 if $Is_EBCDIC;
81
82 my $x;
83 ok( ($x = unpack("%32B*", "Now is the time for all good blurfl")) == $sum );
84
85 my $foo;
86 open(BIN, "./perl") || open(BIN, "./perl.exe") || open(BIN, $^X)
87     || die "Can't open ../perl or ../perl.exe: $!\n";
88 sysread BIN, $foo, 8192;
89 close BIN;
90
91 $sum = unpack("%32b*", $foo);
92 my $longway = unpack("b*", $foo);
93 ok( $sum == $longway =~ tr/1/1/ );
94 }
95
96 {
97   my $x;
98   ok( ($x = unpack("I",pack("I", 0xFFFFFFFF))) == 0xFFFFFFFF );
99 }
100
101 {
102 # check 'w'
103 my @x = (5,130,256,560,32000,3097152,268435455,1073741844, 2**33,
104          '4503599627365785','23728385234614992549757750638446');
105 my $x = pack('w*', @x);
106 my $y = pack 'H*', '0581028200843081fa0081bd8440ffffff7f8480808014A08080800087ffffffffffdb19caefe8e1eeeea0c2e1e3e8ede1ee6e';
107
108 ok ($x eq $y, unpack 'H*', $x);
109 my @y = unpack('w*', $y);
110 my $a;
111 while ($a = pop @x) {
112   my $b = pop @y;
113   ok ($a eq $b, "\$a='$a' \$b='$b'");
114 }
115
116 @y = unpack('w2', $x);
117
118 ok (scalar(@y) == 2);
119 ok ($y[1] == 130, $y[1]);
120 }
121
122 {
123   # test exeptions
124   my $x;
125   eval { $x = unpack 'w', pack 'C*', 0xff, 0xff};
126   ok ($@ =~ /^Unterminated compressed integer/, undef, $@);
127
128   eval { $x = unpack 'w', pack 'C*', 0xff, 0xff, 0xff, 0xff};
129   ok ($@ =~ /^Unterminated compressed integer/, undef, $@);
130
131   eval { $x = unpack 'w', pack 'C*', 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff};
132   ok ($@ =~ /^Unterminated compressed integer/, undef, $@);
133 }
134
135 #
136 # test the "p" template
137
138 # literals
139 ok(unpack("p",pack("p","foo")) eq "foo");
140
141 # scalars
142 ok(unpack("p",pack("p",$test)) == $test);
143
144 # temps
145 sub foo { my $a = "a"; return $a . $a++ . $a++ }
146 {
147   use warnings;
148   my $last = $test;
149   local $SIG{__WARN__} = sub {
150         print "ok ",$test++,"\n" if $_[0] =~ /temporary val/
151   };
152   my $junk = pack("p", &foo);
153   print "not ok ", $test++, "\n" if $last == $test;
154 }
155
156 # undef should give null pointer
157 ok (pack("p", undef) =~ /^\0+/);
158
159 # Check for optimizer bug (e.g.  Digital Unix GEM cc with -O4 on DU V4.0B gives
160 #                                4294967295 instead of -1)
161 #                                see #ifdef __osf__ in pp.c pp_unpack
162 # Test 30:
163 ok((unpack("i",pack("i",-1))) == -1, "__osf__ like bug seems to exist");
164
165 # 31..36: test the pack lengths of s S i I l L
166 # 37..40: test the pack lengths of n N v V
167 my @lengths = qw(s 2 S 2 i -4 I -4 l 4 L 4 n 2 N 4 v 2 V 4);
168 while (my ($format, $expect) = splice @lengths, 0, 2) {
169   my $len = length(pack($format, 0));
170   if ($expect > 0) {
171     ok ($expect == $len, "format '$format' has length $len, expected $expect");
172   } else {
173     $expect = -$expect;
174     ok ($len >= $expect,
175         "format '$format' has length $len, expected >= $expect");
176   }
177 }
178
179 # 41..56: test unpack-pack lengths
180
181 my @templates = qw(c C i I s S l L n N v V f d);
182
183 # quads not supported everywhere: if not, retest floats/doubles
184 # to preserve the test count...
185 eval { my $q = pack("q",0) };
186 push @templates, $@ !~ /Invalid type in pack/ ? qw(q Q) : qw(f d);
187
188 foreach my $t (@templates) {
189     my @t = unpack("$t*", pack("$t*", 12, 34));
190     ok ((@t == 2 and (($t[0] == 12 and $t[1] == 34) or ($t =~ /[nv]/i))),
191         "unpack-pack length for '$t' failed; \@t=@t");
192 }
193
194 {
195 # 57..60: uuencode/decode
196
197 # Note that first uuencoding known 'text' data and then checking the
198 # binary values of the uuencoded version would not be portable between
199 # character sets.  Uuencoding is meant for encoding binary data, not
200 # text data.
201
202 my $in = pack 'C*', 0 .. 255;
203
204 # just to be anal, we do some random tr/`/ /
205 my $uu = <<'EOUU';
206 M` $"`P0%!@<("0H+# T.#Q`1$A,4%187&!D:&QP='A\@(2(C)"4F)R@I*BLL
207 M+2XO,#$R,S0U-C<X.3H[/#T^/T!!0D-$149'2$E*2TQ-3D]045)35%565UA9
208 M6EM<75Y?8&%B8V1E9F=H:6IK;&UN;W!Q<G-T=79W>'EZ>WQ]?G^`@8*#A(6&
209 MAXB)BHN,C8Z/D)&2DY25EI>8F9J;G)V>GZ"AHJ.DI::GJ*FJJZRMKJ^PL;*S
210 MM+6VM[BYNKN\O;Z_P,'"P\3%QL?(R<K+S,W.S]#1TM/4U=;7V-G:V]S=WM_@
211 ?X>+CY.7FY^CIZNOL[>[O\/'R\_3U]O?X^?K[_/W^_P `
212 EOUU
213
214 $_ = $uu;
215 tr/ /`/;
216
217 ok (pack('u', $in) eq $_);
218
219 ok (unpack('u', $uu) eq $in);
220
221 $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";
222 $uu = <<'EOUU';
223 M'XL("%C<Q#4"`TI!4%4`\RHM+E%(S,LOR4@M4@A(+<I1*"U-SD])+>("`&1F
224 &8%P:````
225 EOUU
226
227 ok unless unpack('u', $uu);
228
229 # 60 identical to 59 except that backquotes have been changed to spaces
230
231 $uu = <<'EOUU';
232 M'XL("%C<Q#4" TI!4%4 \RHM+E%(S,LOR4@M4@A(+<I1*"U-SD])+>(" &1F
233 &8%P:
234 EOUU
235
236 # ' # Grr
237 ok (unpack('u', $uu) eq $in);
238
239 }
240
241 # 61..73: test the ascii template types (A, a, Z)
242
243 foreach (
244 ['p', 'A*', "foo\0bar\0 ", "foo\0bar\0 "],
245 ['p', 'A11', "foo\0bar\0 ", "foo\0bar\0   "],
246 ['u', 'A*', "foo\0bar \0", "foo\0bar"],
247 ['u', 'A8', "foo\0bar \0", "foo\0bar"],
248 ['p', 'a*', "foo\0bar\0 ", "foo\0bar\0 "],
249 ['p', 'a11', "foo\0bar\0 ", "foo\0bar\0 \0\0"],
250 ['u', 'a*', "foo\0bar \0", "foo\0bar \0"],
251 ['u', 'a8', "foo\0bar \0", "foo\0bar "],
252 ['p', 'Z*', "foo\0bar\0 ", "foo\0bar\0 \0"],
253 ['p', 'Z11', "foo\0bar\0 ", "foo\0bar\0 \0\0"],
254 ['p', 'Z3', "foo", "fo\0"],
255 ['u', 'Z*', "foo\0bar \0", "foo"],
256 ['u', 'Z8', "foo\0bar \0", "foo"],
257 ) {
258   my ($what, $template, $in, $out) = @$_;
259   my $got = $what eq 'u' ? (unpack $template, $in) : (pack $template, $in);
260   unless (ok ($got eq $out)) {
261     ($in, $out, $got) = encode ($in, $out, $got);
262     my $un = $what eq 'u' ? 'un' : '';
263     print "# ${un}pack ('$template', \"$in\") gave $out not $got\n";
264   }
265 }
266
267 # 74..79: packing native shorts/ints/longs
268
269 ok (length(pack("s!", 0)) == $Config{shortsize});
270 ok (length(pack("i!", 0)) == $Config{intsize});
271 ok (length(pack("l!", 0)) == $Config{longsize});
272 ok (length(pack("s!", 0)) <= length(pack("i!", 0)));
273 ok (length(pack("i!", 0)) <= length(pack("l!", 0)));
274 ok (length(pack("i!", 0)) == length(pack("i", 0)));
275
276 sub numbers {
277   my $format = shift;
278   return numbers_with_total ($format, undef, @_);
279 }
280
281 sub numbers_with_total {
282   my $format = shift;
283   my $total = shift;
284   if (!defined $total) {
285     foreach (@_) {
286       $total += $_;
287     }
288   }
289   foreach (@_) {
290     my $out = eval {unpack($format, pack($format, $_))};
291     if ($@ =~ /Invalid type in pack: '$format'/) {
292       print "ok $test # skip cannot pack '$format' on this perl\n";
293     } elsif ($out == $_) {
294       print "ok $test\n";
295     } else {
296       print "not ok $test # unpack '$format', pack '$format', $_ gives $out\n";
297       print "# \$\@='$@'\n" if $@;
298     }
299     $test++;
300   }
301
302   my $skip_if_longer_than = ~0; # "Infinity"
303   if (~0 - 1 == ~0) {
304     # If we're running with -DNO_PERLPRESERVE_IVUV and NVs don't preserve all
305     # UVs (in which case ~0 is NV, ~0-1 will be the same NV) then we can't
306     # correctly in perl calculate UV totals for long checksums, as pp_unpack
307     # is using UV maths, and we've only got NVs.
308     $skip_if_longer_than = $Config{d_nv_preserves_uv_bits};
309   }
310
311   foreach ('', 1, 2, 3, 15, 16, 17, 31, 32, 33, 53, 54, 63, 64, 65) {
312     my $sum = eval {unpack "%$_$format*", pack "$format*", @_};
313     if (!defined $sum) {
314       if ($@ =~ /Invalid type in pack: '$format'/) {
315         print "ok $test # skip cannot pack '$format' on this perl\n";
316       } else {
317         print "not ok $test # \$\@='$@'\n" if $@;
318       }
319       next;
320     }
321     my $len = $_; # Copy, so that we can reassign ''
322     $len = 16 unless length $len;
323
324     if ($len > $skip_if_longer_than) {
325       print "ok $test # skip cannot test checksums over $skip_if_longer_than "
326         ."bits for this perl (compiled with -DNO_PERLPRESERVE_IVUV)\n";
327       next;
328     }
329
330     # Our problem with testing this portably is that the checksum code in
331     # pp_unpack is able to cast signed to unsigned, and do modulo 2**n
332     # arithmetic in unsigned ints, which perl has no operators to do.
333     # (use integer; does signed ints, which won't wrap on UTS, which is just
334     # fine with ANSI, but not with most people's assumptions.
335     # This is why we need to supply the totals for 'Q' as there's no way in
336     # perl to calculate them, short of unpack '%0Q' (is that documented?)
337     # ** returns NVs; make sure it's IV.
338     my $max = 1 + 2 * (int (2 ** ($len-1))-1); # The maximum possible checksum
339     my $max_p1 = $max + 1;
340     my ($max_is_integer, $max_p1_is_integer);
341     $max_p1_is_integer = 1 unless $max_p1 + 1 == $max_p1;
342     $max_is_integer = 1 if $max - 1 < ~0;
343
344     my $calc_sum;
345     if ($total =~ /^0b[01]*?([01]{1,$len})/) {
346       no warnings qw(overflow portable);
347       $calc_sum = oct "0b$1";
348     } else {
349       $calc_sum = $total;
350       # Shift into range by some multiple of the total
351       my $mult = int ($total / $max_p1);
352       # Need this to make sure that -1 + (~0+1) is ~0 (ie still integer)
353       $calc_sum = $total - $mult;
354       $calc_sum -= $mult * $max;
355       if ($calc_sum < 0) {
356         $calc_sum += 1;
357         $calc_sum += $max;
358       }
359     }
360     if ($calc_sum == $calc_sum - 1 && $calc_sum == $max_p1) {
361       # we're into floating point (either by getting out of the range of
362       # UV arithmetic, or because we're doing a floating point checksum) and
363       # our calculation of the checksum has become rounded up to
364       # max_checksum + 1
365       $calc_sum = 0;
366     }
367
368     if ($calc_sum == $sum) {
369       print "ok $test # unpack '%$_$format' gave $sum\n";
370     } else {
371       my $delta = 1.000001;
372       if ($format =~ tr /dDfF//
373           && ($calc_sum <= $sum * $delta && $calc_sum >= $sum / $delta)) {
374         print "ok $test # unpack '%$_$format' gave $sum,"
375           . " expected $calc_sum\n";
376       } else {
377         print "not ok $test # For list (" . join (", ", @_) . ") (total $total)"
378           . " packed with $format unpack '%$_$format' gave $sum,"
379             . " expected $calc_sum\n";
380       }
381     }
382   } continue {
383     $test++;
384   }
385 }
386
387 numbers ('c', -128, -1, 0, 1, 127);
388 numbers ('C', 0, 1, 127, 128, 255);
389 numbers ('s', -32768, -1, 0, 1, 32767);
390 numbers ('S', 0, 1, 32767, 32768, 65535);
391 numbers ('i', -2147483648, -1, 0, 1, 2147483647);
392 numbers ('I', 0, 1, 2147483647, 2147483648, 4294967295);
393 numbers ('l', -2147483648, -1, 0, 1, 2147483647);
394 numbers ('L', 0, 1, 2147483647, 2147483648, 4294967295);
395 numbers ('s!', -32768, -1, 0, 1, 32767);
396 numbers ('S!', 0, 1, 32767, 32768, 65535);
397 numbers ('i!', -2147483648, -1, 0, 1, 2147483647);
398 numbers ('I!', 0, 1, 2147483647, 2147483648, 4294967295);
399 numbers ('l!', -2147483648, -1, 0, 1, 2147483647);
400 numbers ('L!', 0, 1, 2147483647, 2147483648, 4294967295);
401 numbers ('n', 0, 1, 32767, 32768, 65535);
402 numbers ('v', 0, 1, 32767, 32768, 65535);
403 numbers ('N', 0, 1, 2147483647, 2147483648, 4294967295);
404 numbers ('V', 0, 1, 2147483647, 2147483648, 4294967295);
405 # All these should have exact binary representations:
406 numbers ('f', -1, 0, 0.5, 42, 2**34);
407 # These don't, but 'd' is NV.
408 numbers ('d', -1, 0, 1, 1-exp(-1), -exp(1));
409
410 numbers_with_total ('q', -1,
411                     -9223372036854775808, -1, 0, 1,9223372036854775807);
412 # This total is icky, but need a way to express 2**65-1 that is going to
413 # work independant of whether NVs can preserve 65 bits.
414 # (long double is 128 bits on sparc, so they certianly can)
415 numbers_with_total ('Q', "0b" . "1" x 65,
416                     0, 1,9223372036854775807, 9223372036854775808,
417                     18446744073709551615);
418
419 # pack nvNV byteorders
420
421 ok (pack("n", 0xdead) eq "\xde\xad");
422 ok (pack("v", 0xdead) eq "\xad\xde");
423 ok (pack("N", 0xdeadbeef) eq "\xde\xad\xbe\xef");
424 ok (pack("V", 0xdeadbeef) eq "\xef\xbe\xad\xde");
425
426 {
427   # /
428
429   my ($x, $y, $z);
430   eval { ($x) = unpack '/a*','hello' };
431   ok ($@ =~ m!/ must follow a numeric type!, undef, $@);
432   eval { ($z,$x,$y) = unpack 'a3/A C/a* C/Z', "003ok \003yes\004z\000abc" };
433   ok ($z eq 'ok');
434   ok ($x eq 'yes');
435   ok ($y eq 'z');
436   ok ($@ eq '', undef, $@);
437
438   eval { ($x) = pack '/a*','hello' };
439   ok ($@ =~ m!Invalid type in pack: '/'!, undef, $@);
440
441   $z = pack 'n/a* N/Z* w/A*','string','hi there ','etc';
442   my $expect = "\000\006string\0\0\0\012hi there \000\003etc";
443   unless (ok ($z eq $expect)) {
444     printf "# got '%s'\n", encode $z;
445   }
446
447   foreach (
448 ['a/a*/a*', '212ab345678901234567','ab3456789012'],
449 ['a/a*/a*', '3012ab345678901234567', 'ab3456789012'],
450 ['a/a*/b*', '212ab', $Is_EBCDIC ? '100000010100' : '100001100100'],
451 ) {
452     my ($pat, $in, $expect) = @$_;
453     eval { ($x) = unpack $pat, $in };
454     unless (ok ($x eq $expect)) {
455       $x = encode $x;
456       print "# pack ('$pat', '$in') gave '$x', expected '$expect'\n";
457     }
458   }
459
460 # / with #
461
462 eval { ($z,$x,$y) = unpack <<EOU, "003ok \003yes\004z\000abc" };
463  a3/A                   # Count in ASCII
464  C/a*                   # Count in a C char
465  C/Z                    # Count in a C char but skip after \0
466 EOU
467   ok ($z eq 'ok');
468   ok ($x eq 'yes');
469   ok ($y eq 'z');
470   ok ($@ eq '', undef, $@);
471
472 $z = pack <<EOP,'string','etc';
473   n/a*                  # Count as network short
474   w/A*                  # Count a  BER integer
475 EOP
476   $expect = "\000\006string\003etc";
477 unless (ok ($z eq $expect)) {
478   $z = encode $z;
479   print "# got '$z', expected '$expect'\n";
480 }
481 }
482
483 ok ("1.20.300.4000" eq sprintf "%vd", pack("U*",1,20,300,4000));
484 ok ("1.20.300.4000" eq sprintf "%vd", pack("  U*",1,20,300,4000));
485 ok (v1.20.300.4000 ne sprintf "%vd", pack("C0U*",1,20,300,4000));
486
487 ok (join(" ", unpack("C*", chr(0x1e2))) eq ((ord("A") == 193) ? "156 67"
488                                             : "199 162"));
489
490 # does pack U create Unicode?
491 ok (ord(pack('U', 300)) == 300);
492
493 # does unpack U deref Unicode?
494 ok ((unpack('U', chr(300)))[0] == 300);
495
496 # is unpack U the reverse of pack U for Unicode string?
497 ok ("@{[unpack('U*', pack('U*', 100, 200, 300))]}" eq "100 200 300");
498
499 # is unpack U the reverse of pack U for byte string?
500 ok ("@{[unpack('U*', pack('U*', 100, 200))]}" eq "100 200");
501
502 # does unpack C unravel pack U?
503 ok ("@{[unpack('C*', pack('U*', 100, 200))]}" eq "100 195 136");
504
505 # does pack U0C create Unicode?
506 ok ("@{[pack('U0C*', 100, 195, 136)]}" eq v100.v200);
507
508 # does pack C0U create characters?
509 ok ("@{[pack('C0U*', 100, 200)]}" eq pack("C*", 100, 195, 136));
510
511 # does unpack U0U on byte data warn?
512 {
513     local $SIG{__WARN__} = sub { $@ = "@_" };
514     my @null = unpack('U0U', chr(255));
515     ok ($@ =~ /^Malformed UTF-8 character /, undef, $@);
516 }
517
518 {
519   my $p = pack 'i*', -2147483648, ~0, 0, 1, 2147483647;
520   my (@a);
521   # bug - % had to be at the start of the pattern, no leading whitespace or
522   # comments. %i! didn't work at all.
523   foreach my $pat ('%32i*', ' %32i*', "# Muhahahaha\n%32i*", '%32i*  ',
524                    '%32i!*', ' %32i!*', "\n#\n#\n\r \t\f%32i!*", '%32i!*#') {
525     @a = unpack $pat, $p;
526     ok ($a[0] == 0xFFFFFFFF, "$pat failed");
527     @a = scalar unpack $pat, $p;
528     ok ($a[0] == 0xFFFFFFFF, "$pat failed in scalar context");
529   }
530
531
532   $p = pack 'I*', 42, 12;
533   # Multiline patterns in scalar context failed.
534   foreach my $pat ('I', <<EOPOEMSNIPPET, 'I#I', 'I # I', 'I # !!!') {
535 # On the Ning Nang Nong
536 # Where the Cows go Bong!
537 # And the Monkeys all say Boo!
538 I
539 EOPOEMSNIPPET
540   @a = unpack $pat, $p;
541   ok (@a == 1 && $a[0] == 42);
542   @a = scalar unpack $pat, $p;
543   ok (@a == 1 && $a[0] == 42);
544 }
545
546   # shorts (of all flavours) didn't calculate checksums > 32 bits with floating
547   # point, so a pathologically long pattern would wrap at 32 bits.
548   my $pat = "\xff\xff"x65538; # Start with it long, to save any copying.
549   foreach (4,3,2,1,0) {
550     my $len = 65534 + $_;
551     ok (unpack ("%33n$len", $pat) == 65535 * $len);
552   }
553 }