Many of the feared z/OS failures turned out to be false alarms.
[p5sagit/p5-mst-13.2.git] / t / op / pack.t
CommitLineData
d50dd4e4 1#!./perl -w
a687059c 2
a1a0e61e 3BEGIN {
4 chdir 't' if -d 't';
20822f61 5 @INC = '../lib';
0b568b5f 6 require './test.pl';
b23b8711 7}
8
203d3f29 9plan tests => 5819;
0b568b5f 10
fa8ec7c1 11use strict;
12use warnings;
b23b8711 13use Config;
14
fa8ec7c1 15my $Is_EBCDIC = (defined $Config{ebcdic} && $Config{ebcdic} eq 'define');
0b568b5f 16my $Perl = which_perl();
c274e827 17
b85d93de 18sub encode_list {
9e17a6b8 19 my @result = map {_qq($_)} @_;
b85d93de 20 if (@result == 1) {
21 return @result;
22 }
23 return '(' . join (', ', @result) . ')';
24}
25
a1a0e61e 26
b85d93de 27sub list_eq ($$) {
28 my ($l, $r) = @_;
c8f824eb 29 return 0 unless @$l == @$r;
b85d93de 30 for my $i (0..$#$l) {
31 if (defined $l->[$i]) {
c8f824eb 32 return 0 unless defined ($r->[$i]) && $l->[$i] eq $r->[$i];
b85d93de 33 } else {
c8f824eb 34 return 0 if defined $r->[$i]
b85d93de 35 }
36 }
37 return 1;
38}
39
40##############################################################################
41#
42# Here starteth the tests
43#
44
fa8ec7c1 45{
0b568b5f 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/);
fa8ec7c1 64}
79072805 65# How about counting bits?
66
fa8ec7c1 67{
0b568b5f 68 my $x;
69 is( ($x = unpack("%32B*", "\001\002\004\010\020\040\100\200\377")), 16 );
79072805 70
0b568b5f 71 is( ($x = unpack("%32b69", "\001\002\004\010\020\040\100\200\017")), 12 );
79072805 72
0b568b5f 73 is( ($x = unpack("%32B69", "\001\002\004\010\020\040\100\200\017")), 9 );
fa8ec7c1 74}
79072805 75
fa8ec7c1 76{
0b568b5f 77 my $sum = 129; # ASCII
78 $sum = 103 if $Is_EBCDIC;
9d116dd7 79
0b568b5f 80 my $x;
81 is( ($x = unpack("%32B*", "Now is the time for all good blurfl")), $sum );
79072805 82
0b568b5f 83 my $foo;
84 open(BIN, $Perl) || die "Can't open $Perl: $!\n";
85 sysread BIN, $foo, 8192;
86 close BIN;
79072805 87
0b568b5f 88 $sum = unpack("%32b*", $foo);
89 my $longway = unpack("b*", $foo);
90 is( $sum, $longway =~ tr/1/1/ );
fa8ec7c1 91}
73a1c01a 92
fa8ec7c1 93{
94 my $x;
0b568b5f 95 is( ($x = unpack("I",pack("I", 0xFFFFFFFF))), 0xFFFFFFFF );
fa8ec7c1 96}
def98dd4 97
fa8ec7c1 98{
0b568b5f 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 }
def98dd4 114
0b568b5f 115 @y = unpack('w2', $x);
def98dd4 116
0b568b5f 117 is(scalar(@y), 2);
118 is($y[1], 130);
a6c48a57 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);
196b62db 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);
203d3f29 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);
fa8ec7c1 159}
def98dd4 160
0b568b5f 161
fa8ec7c1 162{
196b62db 163 # test exceptions
fa8ec7c1 164 my $x;
165 eval { $x = unpack 'w', pack 'C*', 0xff, 0xff};
0b568b5f 166 like($@, qr/^Unterminated compressed integer/);
def98dd4 167
fa8ec7c1 168 eval { $x = unpack 'w', pack 'C*', 0xff, 0xff, 0xff, 0xff};
0b568b5f 169 like($@, qr/^Unterminated compressed integer/);
def98dd4 170
fa8ec7c1 171 eval { $x = unpack 'w', pack 'C*', 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff};
0b568b5f 172 like($@, qr/^Unterminated compressed integer/);
fa8ec7c1 173}
def98dd4 174
84902520 175#
176# test the "p" template
177
178# literals
0b568b5f 179is(unpack("p",pack("p","foo")), "foo");
84902520 180
181# scalars
0b568b5f 182is(unpack("p",pack("p",239)), 239);
84902520 183
184# temps
185sub foo { my $a = "a"; return $a . $a++ . $a++ }
186{
9f1b1f2d 187 use warnings;
0b568b5f 188 my $warning;
84902520 189 local $SIG{__WARN__} = sub {
0b568b5f 190 $warning = $_[0];
84902520 191 };
192 my $junk = pack("p", &foo);
0b568b5f 193
194 like($warning, qr/temporary val/);
84902520 195}
196
197# undef should give null pointer
0b568b5f 198like(pack("p", undef), qr/^\0+/);
84902520 199
20408e3c 200# Check for optimizer bug (e.g. Digital Unix GEM cc with -O4 on DU V4.0B gives
201# 4294967295 instead of -1)
202# see #ifdef __osf__ in pp.c pp_unpack
0b568b5f 203is((unpack("i",pack("i",-1))), -1);
20408e3c 204
0b568b5f 205# test the pack lengths of s S i I l L
206# test the pack lengths of n N v V
fa8ec7c1 207my @lengths = qw(s 2 S 2 i -4 I -4 l 4 L 4 n 2 N 4 v 2 V 4);
208while (my ($format, $expect) = splice @lengths, 0, 2) {
209 my $len = length(pack($format, 0));
210 if ($expect > 0) {
0b568b5f 211 is($expect, $len, "format '$format'");
fa8ec7c1 212 } else {
213 $expect = -$expect;
0b568b5f 214 ok ($len >= $expect, "format '$format'") ||
215 print "# format '$format' has length $len, expected >= $expect\n";
fa8ec7c1 216 }
217}
d4217c7e 218
d4217c7e 219
0b568b5f 220# test unpack-pack lengths
221my @templates = qw(c C i I s S l L n N v V f d q Q);
d4217c7e 222
223foreach my $t (@templates) {
0b568b5f 224 SKIP: {
225 my @t = eval { unpack("$t*", pack("$t*", 12, 34)) };
226
227 # quads not supported everywhere
228 skip "Quads not supported", 4 if $@ =~ /Invalid type in pack/;
229 is( $@, '' );
230
231 is(scalar @t, 2);
3020ec7a 232
233 SKIP: {
234 skip "$t not expected to work for some reason", 2 if $t =~ /[nv]/i;
235
0b568b5f 236 is($t[0], 12);
237 is($t[1], 34);
238 }
0b568b5f 239 }
d4217c7e 240}
9d116dd7 241
fa8ec7c1 242{
0b568b5f 243 # uuencode/decode
9d116dd7 244
0b568b5f 245 # Note that first uuencoding known 'text' data and then checking the
246 # binary values of the uuencoded version would not be portable between
247 # character sets. Uuencoding is meant for encoding binary data, not
248 # text data.
c4d5f83a 249
0b568b5f 250 my $in = pack 'C*', 0 .. 255;
ba1ac976 251
0b568b5f 252 # just to be anal, we do some random tr/`/ /
253 my $uu = <<'EOUU';
ba1ac976 254M` $"`P0%!@<("0H+# T.#Q`1$A,4%187&!D:&QP='A\@(2(C)"4F)R@I*BLL
9d116dd7 255M+2XO,#$R,S0U-C<X.3H[/#T^/T!!0D-$149'2$E*2TQ-3D]045)35%565UA9
256M6EM<75Y?8&%B8V1E9F=H:6IK;&UN;W!Q<G-T=79W>'EZ>WQ]?G^`@8*#A(6&
257MAXB)BHN,C8Z/D)&2DY25EI>8F9J;G)V>GZ"AHJ.DI::GJ*FJJZRMKJ^PL;*S
258MM+6VM[BYNKN\O;Z_P,'"P\3%QL?(R<K+S,W.S]#1TM/4U=;7V-G:V]S=WM_@
ba1ac976 259?X>+CY.7FY^CIZNOL[>[O\/'R\_3U]O?X^?K[_/W^_P `
9d116dd7 260EOUU
261
0b568b5f 262 $_ = $uu;
263 tr/ /`/;
9d116dd7 264
0b568b5f 265 is(pack('u', $in), $_);
fa8ec7c1 266
0b568b5f 267 is(unpack('u', $uu), $in);
9d116dd7 268
0b568b5f 269 $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";
270 $uu = <<'EOUU';
eddc390b 271M'XL("%C<Q#4"`TI!4%4`\RHM+E%(S,LOR4@M4@A(+<I1*"U-SD])+>("`&1F
272&8%P:````
273EOUU
274
0b568b5f 275 is(unpack('u', $uu), $in);
eddc390b 276
0b568b5f 277# This is identical to the above except that backquotes have been
278# changed to spaces
eddc390b 279
0b568b5f 280 $uu = <<'EOUU';
eddc390b 281M'XL("%C<Q#4" TI!4%4 \RHM+E%(S,LOR4@M4@A(+<I1*"U-SD])+>(" &1F
c4d5f83a 282&8%P:
eddc390b 283EOUU
284
0b568b5f 285 # ' # Grr
286 is(unpack('u', $uu), $in);
ef54e1a4 287
d99ad34e 288}
726ea183 289
0b568b5f 290# test the ascii template types (A, a, Z)
726ea183 291
fa8ec7c1 292foreach (
0b568b5f 293['p', 'A*', "foo\0bar\0 ", "foo\0bar\0 "],
fa8ec7c1 294['p', 'A11', "foo\0bar\0 ", "foo\0bar\0 "],
0b568b5f 295['u', 'A*', "foo\0bar \0", "foo\0bar"],
296['u', 'A8', "foo\0bar \0", "foo\0bar"],
297['p', 'a*', "foo\0bar\0 ", "foo\0bar\0 "],
fa8ec7c1 298['p', 'a11', "foo\0bar\0 ", "foo\0bar\0 \0\0"],
0b568b5f 299['u', 'a*', "foo\0bar \0", "foo\0bar \0"],
300['u', 'a8', "foo\0bar \0", "foo\0bar "],
301['p', 'Z*', "foo\0bar\0 ", "foo\0bar\0 \0"],
fa8ec7c1 302['p', 'Z11', "foo\0bar\0 ", "foo\0bar\0 \0\0"],
0b568b5f 303['p', 'Z3', "foo", "fo\0"],
304['u', 'Z*', "foo\0bar \0", "foo"],
305['u', 'Z8', "foo\0bar \0", "foo"],
306)
307{
308 my ($what, $template, $in, $out) = @$_;
309 my $got = $what eq 'u' ? (unpack $template, $in) : (pack $template, $in);
310 unless (is($got, $out)) {
0b568b5f 311 my $un = $what eq 'u' ? 'un' : '';
9e17a6b8 312 print "# ${un}pack ('$template', "._qq($in).') gave '._qq($out).
313 ' not '._qq($got)."\n";
0b568b5f 314 }
d99ad34e 315}
726ea183 316
0b568b5f 317# packing native shorts/ints/longs
726ea183 318
0b568b5f 319is(length(pack("s!", 0)), $Config{shortsize});
320is(length(pack("i!", 0)), $Config{intsize});
321is(length(pack("l!", 0)), $Config{longsize});
322ok(length(pack("s!", 0)) <= length(pack("i!", 0)));
323ok(length(pack("i!", 0)) <= length(pack("l!", 0)));
324is(length(pack("i!", 0)), length(pack("i", 0)));
726ea183 325
fa8ec7c1 326sub numbers {
327 my $format = shift;
328 return numbers_with_total ($format, undef, @_);
d99ad34e 329}
726ea183 330
fa8ec7c1 331sub numbers_with_total {
332 my $format = shift;
333 my $total = shift;
334 if (!defined $total) {
335 foreach (@_) {
336 $total += $_;
337 }
338 }
339 foreach (@_) {
0b568b5f 340 SKIP: {
341 my $out = eval {unpack($format, pack($format, $_))};
342 skip "cannot pack '$format' on this perl", 2 if
343 $@ =~ /Invalid type in pack: '$format'/;
344
345 is($@, '');
346 is($out, $_);
fa8ec7c1 347 }
fa8ec7c1 348 }
726ea183 349
fa8ec7c1 350 my $skip_if_longer_than = ~0; # "Infinity"
351 if (~0 - 1 == ~0) {
352 # If we're running with -DNO_PERLPRESERVE_IVUV and NVs don't preserve all
353 # UVs (in which case ~0 is NV, ~0-1 will be the same NV) then we can't
354 # correctly in perl calculate UV totals for long checksums, as pp_unpack
355 # is using UV maths, and we've only got NVs.
53133ed1 356 $skip_if_longer_than = $Config{nv_preserves_uv_bits};
fa8ec7c1 357 }
726ea183 358
fa8ec7c1 359 foreach ('', 1, 2, 3, 15, 16, 17, 31, 32, 33, 53, 54, 63, 64, 65) {
0b568b5f 360 SKIP: {
361 my $sum = eval {unpack "%$_$format*", pack "$format*", @_};
362 skip "cannot pack '$format' on this perl", 3
363 if $@ =~ /Invalid type in pack: '$format'/;
364
365 is($@, '');
366 ok(defined $sum);
367
368 my $len = $_; # Copy, so that we can reassign ''
369 $len = 16 unless length $len;
370
371 SKIP: {
372 skip "cannot test checksums over $skip_if_longer_than bits", 1
373 if $len > $skip_if_longer_than;
374
375 # Our problem with testing this portably is that the checksum code in
376 # pp_unpack is able to cast signed to unsigned, and do modulo 2**n
377 # arithmetic in unsigned ints, which perl has no operators to do.
378 # (use integer; does signed ints, which won't wrap on UTS, which is just
379 # fine with ANSI, but not with most people's assumptions.
380 # This is why we need to supply the totals for 'Q' as there's no way in
381 # perl to calculate them, short of unpack '%0Q' (is that documented?)
382 # ** returns NVs; make sure it's IV.
383 my $max = 1 + 2 * (int (2 ** ($len-1))-1); # The max possible checksum
384 my $max_p1 = $max + 1;
385 my ($max_is_integer, $max_p1_is_integer);
386 $max_p1_is_integer = 1 unless $max_p1 + 1 == $max_p1;
387 $max_is_integer = 1 if $max - 1 < ~0;
388
389 my $calc_sum;
390 if (ref $total) {
391 $calc_sum = &$total($len);
392 } else {
393 $calc_sum = $total;
394 # Shift into range by some multiple of the total
395 my $mult = int ($total / $max_p1);
396 # Need this to make sure that -1 + (~0+1) is ~0 (ie still integer)
397 $calc_sum = $total - $mult;
398 $calc_sum -= $mult * $max;
399 if ($calc_sum < 0) {
400 $calc_sum += 1;
401 $calc_sum += $max;
402 }
403 }
404 if ($calc_sum == $calc_sum - 1 && $calc_sum == $max_p1) {
405 # we're into floating point (either by getting out of the range of
406 # UV arithmetic, or because we're doing a floating point checksum)
407 # and our calculation of the checksum has become rounded up to
408 # max_checksum + 1
409 $calc_sum = 0;
410 }
411
0dccb3d1 412 if ($calc_sum == $sum) { # HAS to be ==, not eq (so no is()).
413 ok ("unpack '%$_$format' gave $sum");
0b568b5f 414 } else {
415 my $delta = 1.000001;
416 if ($format =~ tr /dDfF//
417 && ($calc_sum <= $sum * $delta && $calc_sum >= $sum / $delta)) {
0dccb3d1 418 pass ("unpack '%$_$format' gave $sum, expected $calc_sum");
0b568b5f 419 } else {
420 my $text = ref $total ? &$total($len) : $total;
421 fail;
422 print "# For list (" . join (", ", @_) . ") (total $text)"
423 . " packed with $format unpack '%$_$format' gave $sum,"
424 . " expected $calc_sum\n";
425 }
426 }
fa8ec7c1 427 }
0b568b5f 428 }
2e821511 429 }
430}
431
fa8ec7c1 432numbers ('c', -128, -1, 0, 1, 127);
433numbers ('C', 0, 1, 127, 128, 255);
434numbers ('s', -32768, -1, 0, 1, 32767);
435numbers ('S', 0, 1, 32767, 32768, 65535);
436numbers ('i', -2147483648, -1, 0, 1, 2147483647);
437numbers ('I', 0, 1, 2147483647, 2147483648, 4294967295);
438numbers ('l', -2147483648, -1, 0, 1, 2147483647);
439numbers ('L', 0, 1, 2147483647, 2147483648, 4294967295);
440numbers ('s!', -32768, -1, 0, 1, 32767);
441numbers ('S!', 0, 1, 32767, 32768, 65535);
442numbers ('i!', -2147483648, -1, 0, 1, 2147483647);
443numbers ('I!', 0, 1, 2147483647, 2147483648, 4294967295);
444numbers ('l!', -2147483648, -1, 0, 1, 2147483647);
445numbers ('L!', 0, 1, 2147483647, 2147483648, 4294967295);
446numbers ('n', 0, 1, 32767, 32768, 65535);
447numbers ('v', 0, 1, 32767, 32768, 65535);
448numbers ('N', 0, 1, 2147483647, 2147483648, 4294967295);
449numbers ('V', 0, 1, 2147483647, 2147483648, 4294967295);
450# All these should have exact binary representations:
451numbers ('f', -1, 0, 0.5, 42, 2**34);
b85d93de 452numbers ('d', -(2**34), -1, 0, 1, 2**34);
453## These don't, but 'd' is NV. XXX wrong, it's double
454#numbers ('d', -1, 0, 1, 1-exp(-1), -exp(1));
fa8ec7c1 455
456numbers_with_total ('q', -1,
457 -9223372036854775808, -1, 0, 1,9223372036854775807);
800e6488 458# This total is icky, but the true total is 2**65-1, and need a way to generate
459# the epxected checksum on any system including those where NVs can preserve
460# 65 bits. (long double is 128 bits on sparc, so they certainly can)
461# or where rounding is down not up on binary conversion (crays)
462numbers_with_total ('Q', sub {
463 my $len = shift;
464 $len = 65 if $len > 65; # unmasked total is 2**65-1 here
465 my $total = 1 + 2 * (int (2**($len - 1)) - 1);
466 return 0 if $total == $total - 1; # Overflowed integers
467 return $total; # NVs still accurate to nearest integer
468 },
fa8ec7c1 469 0, 1,9223372036854775807, 9223372036854775808,
470 18446744073709551615);
471
472# pack nvNV byteorders
473
0b568b5f 474is(pack("n", 0xdead), "\xde\xad");
475is(pack("v", 0xdead), "\xad\xde");
476is(pack("N", 0xdeadbeef), "\xde\xad\xbe\xef");
477is(pack("V", 0xdeadbeef), "\xef\xbe\xad\xde");
43192e07 478
fa8ec7c1 479{
480 # /
481
482 my ($x, $y, $z);
483 eval { ($x) = unpack '/a*','hello' };
0b568b5f 484 like($@, qr!/ must follow a numeric type!);
72b034c3 485 undef $x;
486 eval { $x = unpack '/a*','hello' };
487 like($@, qr!/ must follow a numeric type!);
0b568b5f 488
72b034c3 489 undef $x;
fa8ec7c1 490 eval { ($z,$x,$y) = unpack 'a3/A C/a* C/Z', "003ok \003yes\004z\000abc" };
0b568b5f 491 is($@, '');
492 is($z, 'ok');
493 is($x, 'yes');
494 is($y, 'z');
72b034c3 495 undef $z;
496 eval { $z = unpack 'a3/A C/a* C/Z', "003ok \003yes\004z\000abc" };
497 is($@, '');
498 is($z, 'ok');
499
fa8ec7c1 500
72b034c3 501 undef $x;
fa8ec7c1 502 eval { ($x) = pack '/a*','hello' };
0b568b5f 503 like($@, qr!Invalid type in pack: '/'!);
72b034c3 504 undef $x;
505 eval { $x = pack '/a*','hello' };
506 like($@, qr!Invalid type in pack: '/'!);
fa8ec7c1 507
508 $z = pack 'n/a* N/Z* w/A*','string','hi there ','etc';
509 my $expect = "\000\006string\0\0\0\012hi there \000\003etc";
0b568b5f 510 is($z, $expect);
4b5b2118 511
72b034c3 512 undef $x;
b85d93de 513 $expect = 'hello world';
514 eval { ($x) = unpack ("w/a", chr (11) . "hello world!")};
0b568b5f 515 is($x, $expect);
516 is($@, '');
517
72b034c3 518 undef $x;
b85d93de 519 # Doing this in scalar context used to fail.
520 eval { $x = unpack ("w/a", chr (11) . "hello world!")};
0b568b5f 521 is($@, '');
522 is($x, $expect);
b85d93de 523
fa8ec7c1 524 foreach (
0b568b5f 525 ['a/a*/a*', '212ab345678901234567','ab3456789012'],
526 ['a/a*/a*', '3012ab345678901234567', 'ab3456789012'],
527 ['a/a*/b*', '212ab', $Is_EBCDIC ? '100000010100' : '100001100100'],
528 )
529 {
fa8ec7c1 530 my ($pat, $in, $expect) = @$_;
72b034c3 531 undef $x;
fa8ec7c1 532 eval { ($x) = unpack $pat, $in };
0b568b5f 533 is($@, '');
534 is($x, $expect) ||
535 printf "# list unpack ('$pat', '$in') gave %s, expected '$expect'\n",
536 encode_list ($x);
537
72b034c3 538 undef $x;
b85d93de 539 eval { $x = unpack $pat, $in };
0b568b5f 540 is($@, '');
541 is($x, $expect) ||
542 printf "# scalar unpack ('$pat', '$in') gave %s, expected '$expect'\n",
543 encode_list ($x);
fa8ec7c1 544 }
4b5b2118 545
0b568b5f 546 # / with #
17f4a12d 547
72b034c3 548 my $pattern = <<'EOU';
17f4a12d 549 a3/A # Count in ASCII
550 C/a* # Count in a C char
551 C/Z # Count in a C char but skip after \0
552EOU
17f4a12d 553
72b034c3 554 $x = $y = $z =undef;
555 eval { ($z,$x,$y) = unpack $pattern, "003ok \003yes\004z\000abc" };
0b568b5f 556 is($@, '');
557 is($z, 'ok');
558 is($x, 'yes');
559 is($y, 'z');
72b034c3 560 undef $x;
561 eval { $z = unpack $pattern, "003ok \003yes\004z\000abc" };
562 is($@, '');
563 is($z, 'ok');
0b568b5f 564
72b034c3 565 $pattern = <<'EOP';
17f4a12d 566 n/a* # Count as network short
567 w/A* # Count a BER integer
568EOP
fa8ec7c1 569 $expect = "\000\006string\003etc";
72b034c3 570 $z = pack $pattern,'string','etc';
9e17a6b8 571 is($z, $expect);
fa8ec7c1 572}
573
60a99fa7 574
575SKIP: {
576 skip("(EBCDIC and) version strings are bad idea", 2) if $Is_EBCDIC;
577
578 is("1.20.300.4000", sprintf "%vd", pack("U*",1,20,300,4000));
579 is("1.20.300.4000", sprintf "%vd", pack(" U*",1,20,300,4000));
580}
0b568b5f 581isnt(v1.20.300.4000, sprintf "%vd", pack("C0U*",1,20,300,4000));
fa8ec7c1 582
0b568b5f 583my $rslt = $Is_EBCDIC ? "156 67" : "199 162";
584is(join(" ", unpack("C*", chr(0x1e2))), $rslt);
fa8ec7c1 585
586# does pack U create Unicode?
0b568b5f 587is(ord(pack('U', 300)), 300);
fa8ec7c1 588
589# does unpack U deref Unicode?
0b568b5f 590is((unpack('U', chr(300)))[0], 300);
fa8ec7c1 591
592# is unpack U the reverse of pack U for Unicode string?
0b568b5f 593is("@{[unpack('U*', pack('U*', 100, 200, 300))]}", "100 200 300");
fa8ec7c1 594
595# is unpack U the reverse of pack U for byte string?
0b568b5f 596is("@{[unpack('U*', pack('U*', 100, 200))]}", "100 200");
597
598
599SKIP: {
600 skip "Not for EBCDIC", 4 if $Is_EBCDIC;
fa8ec7c1 601
7eed2ccc 602 # does unpack C unravel pack U?
0b568b5f 603 is("@{[unpack('C*', pack('U*', 100, 200))]}", "100 195 136");
fa8ec7c1 604
7eed2ccc 605 # does pack U0C create Unicode?
0b568b5f 606 is("@{[pack('U0C*', 100, 195, 136)]}", v100.v200);
fa8ec7c1 607
7eed2ccc 608 # does pack C0U create characters?
0b568b5f 609 is("@{[pack('C0U*', 100, 200)]}", pack("C*", 100, 195, 136));
fa8ec7c1 610
2dcec3fe 611 # does unpack U0U on byte data warn?
612 {
613 local $SIG{__WARN__} = sub { $@ = "@_" };
614 my @null = unpack('U0U', chr(255));
0b568b5f 615 like($@, /^Malformed UTF-8 character /);
2dcec3fe 616 }
35bcd338 617}
618
fa8ec7c1 619{
620 my $p = pack 'i*', -2147483648, ~0, 0, 1, 2147483647;
621 my (@a);
622 # bug - % had to be at the start of the pattern, no leading whitespace or
623 # comments. %i! didn't work at all.
624 foreach my $pat ('%32i*', ' %32i*', "# Muhahahaha\n%32i*", '%32i* ',
625 '%32i!*', ' %32i!*', "\n#\n#\n\r \t\f%32i!*", '%32i!*#') {
626 @a = unpack $pat, $p;
0b568b5f 627 is($a[0], 0xFFFFFFFF) || print "# $pat\n";
fa8ec7c1 628 @a = scalar unpack $pat, $p;
0b568b5f 629 is($a[0], 0xFFFFFFFF) || print "# $pat\n";
fa8ec7c1 630 }
631
632
633 $p = pack 'I*', 42, 12;
634 # Multiline patterns in scalar context failed.
635 foreach my $pat ('I', <<EOPOEMSNIPPET, 'I#I', 'I # I', 'I # !!!') {
636# On the Ning Nang Nong
637# Where the Cows go Bong!
638# And the Monkeys all say Boo!
639I
640EOPOEMSNIPPET
0b568b5f 641 @a = unpack $pat, $p;
642 is(scalar @a, 1);
643 is($a[0], 42);
644 @a = scalar unpack $pat, $p;
645 is(scalar @a, 1);
646 is($a[0], 42);
647 }
fa8ec7c1 648
649 # shorts (of all flavours) didn't calculate checksums > 32 bits with floating
650 # point, so a pathologically long pattern would wrap at 32 bits.
651 my $pat = "\xff\xff"x65538; # Start with it long, to save any copying.
652 foreach (4,3,2,1,0) {
653 my $len = 65534 + $_;
0b568b5f 654 is(unpack ("%33n$len", $pat), 65535 * $len);
fa8ec7c1 655 }
656}
b85d93de 657
658
659# pack x X @
660foreach (
0b568b5f 661 ['x', "N", "\0"],
662 ['x4', "N", "\0"x4],
663 ['xX', "N", ""],
664 ['xXa*', "Nick", "Nick"],
665 ['a5Xa5', "cameL", "llama", "camellama"],
666 ['@4', 'N', "\0"x4],
667 ['a*@8a*', 'Camel', 'Dromedary', "Camel\0\0\0Dromedary"],
668 ['a*@4a', 'Perl rules', '!', 'Perl!'],
669)
670{
b85d93de 671 my ($template, @in) = @$_;
672 my $out = pop @in;
673 my $got = eval {pack $template, @in};
0b568b5f 674 is($@, '');
675 is($out, $got) ||
676 printf "# pack ('$template', %s) gave %s expected %s\n",
677 encode_list (@in), encode_list ($got), encode_list ($out);
b85d93de 678}
679
680# unpack x X @
681foreach (
0b568b5f 682 ['x', "N"],
683 ['xX', "N"],
684 ['xXa*', "Nick", "Nick"],
685 ['a5Xa5', "camellama", "camel", "llama"],
686 ['@3', "ice"],
687 ['@2a2', "water", "te"],
688 ['a*@1a3', "steam", "steam", "tea"],
689)
690{
b85d93de 691 my ($template, $in, @out) = @$_;
692 my @got = eval {unpack $template, $in};
0b568b5f 693 is($@, '');
c8f824eb 694 ok (list_eq (\@got, \@out)) ||
9e17a6b8 695 printf "# list unpack ('$template', %s) gave %s expected %s\n",
696 _qq($in), encode_list (@got), encode_list (@out);
b85d93de 697
698 my $got = eval {unpack $template, $in};
0b568b5f 699 is($@, '');
700 @out ? is( $got, $out[0] ) # 1 or more items; should get first
701 : ok( !defined $got ) # 0 items; should get undef
9e17a6b8 702 or printf "# scalar unpack ('$template', %s) gave %s expected %s\n",
703 _qq($in), encode_list ($got), encode_list ($out[0]);
b85d93de 704}
d50dd4e4 705
706{
d50dd4e4 707 my $t = 'Z*Z*';
708 my ($u, $v) = qw(foo xyzzy);
709 my $p = pack($t, $u, $v);
710 my @u = unpack($t, $p);
0b568b5f 711 is(scalar @u, 2);
712 is($u[0], $u);
713 is($u[1], $v);
d50dd4e4 714}
bf80f5a2 715
716{
0b568b5f 717 is((unpack("w/a*", "\x02abc"))[0], "ab");
bf80f5a2 718
0b568b5f 719 # "w/a*" should be seen as one unit
bf80f5a2 720
0b568b5f 721 is(scalar unpack("w/a*", "\x02abc"), "ab");
bf80f5a2 722}
b81060d6 723
724{
b81060d6 725 # from Wolfgang Laun: fix in change #13163
726
727 my $s = 'ABC' x 10;
644d52eb 728 my $t = '*';
729 my $x = ord($t);
b81060d6 730 my $buf = pack( 'Z*/A* C', $s, $x );
731 my $y;
732
733 my $h = $buf;
734 $h =~ s/[^[:print:]]/./g;
735 ( $s, $y ) = unpack( "Z*/A* C", $buf );
644d52eb 736 is($h, "30.ABCABCABCABCABCABCABCABCABCABC$t");
0b568b5f 737 is(length $buf, 34);
738 is($s, "ABCABCABCABCABCABCABCABCABCABC");
644d52eb 739 is($y, $x);
b81060d6 740}
3bf38418 741
742{
b223308b 743 # from Wolfgang Laun: fix in change #13288
3bf38418 744
b223308b 745 eval { my $t=unpack("P*", "abc") };
0b568b5f 746 like($@, qr/P must have an explicit size/);
3bf38418 747}
18529408 748
749{ # Grouping constructs
750 my (@a, @b);
751 @a = unpack '(SL)', pack 'SLSLSL', 67..90;
752 is("@a", "67 68");
753 @a = unpack '(SL)3', pack 'SLSLSL', 67..90;
754 @b = (67..72);
755 is("@a", "@b");
756 @a = unpack '(SL)3', pack 'SLSLSLSL', 67..90;
757 is("@a", "@b");
758 @a = unpack '(SL)[3]', pack 'SLSLSLSL', 67..90;
759 is("@a", "@b");
760 @a = unpack '(SL)[2] SL', pack 'SLSLSLSL', 67..90;
761 is("@a", "@b");
762 @a = unpack 'A/(SL)', pack 'ASLSLSLSL', 3, 67..90;
763 is("@a", "@b");
764 @a = unpack 'A/(SL)SL', pack 'ASLSLSLSL', 2, 67..90;
765 is("@a", "@b");
766 @a = unpack '(SL)*', pack 'SLSLSLSL', 67..90;
767 @b = (67..74);
768 is("@a", "@b");
769 @a = unpack '(SL)*SL', pack 'SLSLSLSL', 67..90;
770 is("@a", "@b");
771 eval { @a = unpack '(*SL)', '' };
772 like($@, qr/\(\)-group starts with a count/);
773 eval { @a = unpack '(3SL)', '' };
774 like($@, qr/\(\)-group starts with a count/);
775 eval { @a = unpack '([3]SL)', '' };
776 like($@, qr/\(\)-group starts with a count/);
777 eval { @a = pack '(*SL)' };
778 like($@, qr/\(\)-group starts with a count/);
779 @a = unpack '(SL)3 SL', pack '(SL)4', 67..74;
780 is("@a", "@b");
781 @a = unpack '(SL)3 SL', pack '(SL)[4]', 67..74;
782 is("@a", "@b");
783 @a = unpack '(SL)3 SL', pack '(SL)*', 67..74;
784 is("@a", "@b");
785}
206947d2 786
787{ # Repeat count [SUBEXPR]
92d41999 788 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
789 s! S! i! I! l! L! j J);
790 my $G;
206947d2 791 if (eval { pack 'q', 1 } ) {
792 push @codes, qw(q Q);
793 } else {
794 push @codes, qw(c C); # Keep the count the same
795 }
92d41999 796 if (eval { pack 'D', 1 } ) {
797 push @codes, 'D';
798 } else {
799 push @codes, 'd'; # Keep the count the same
800 }
206947d2 801
802 my %val;
803 @val{@codes} = map { / [Xx] (?{ undef })
804 | [AZa] (?{ 'something' })
805 | C (?{ 214 })
806 | c (?{ 114 })
807 | [Bb] (?{ '101' })
808 | [Hh] (?{ 'b8' })
92d41999 809 | [svnSiIlVNLqQjJ] (?{ 10111 })
206947d2 810 | [FfDd] (?{ 1.36514538e67 })
811 | [pP] (?{ "try this buffer" })
812 /x; $^R } @codes;
813 my @end = (0x12345678, 0x23456781, 0x35465768, 0x15263748);
814 my $end = "N4";
815
816 for my $type (@codes) {
817 my @list = $val{$type};
818 @list = () unless defined $list[0];
819 for my $count ('', '3', '[11]') {
820 my $c = 1;
821 $c = $1 if $count =~ /(\d+)/;
822 my @list1 = @list;
823 @list1 = (@list1) x $c unless $type =~ /[XxAaZBbHhP]/;
824 for my $groupend ('', ')2', ')[8]') {
825 my $groupbegin = ($groupend ? '(' : '');
826 $c = 1;
827 $c = $1 if $groupend =~ /(\d+)/;
828 my @list2 = (@list1) x $c;
829
830 my $junk1 = "$groupbegin $type$count $groupend";
831 # print "# junk1=$junk1\n";
832 my $p = pack $junk1, @list2;
833 my $half = int( (length $p)/2 );
62f95557 834 for my $move ('', "X$half", "X!$half", 'x1', 'x!8', "x$half") {
206947d2 835 my $junk = "$junk1 $move";
62f95557 836 # print "# junk='$junk', list=(@list2)\n";
206947d2 837 $p = pack "$junk $end", @list2, @end;
838 my @l = unpack "x[$junk] $end", $p;
839 is(scalar @l, scalar @end);
840 is("@l", "@end", "skipping x[$junk]");
841 }
842 }
843 }
844 }
845}
846
847# / is recognized after spaces in scalar context
848# XXXX no spaces are allowed in pack... In pack only before the slash...
849is(scalar unpack('A /A Z20', pack 'A/A* Z20', 'bcde', 'xxxxx'), 'bcde');
850is(scalar unpack('A /A /A Z20', '3004bcde'), 'bcde');
62f95557 851
852{ # X! and x!
853 my $t = 'C[3] x!8 C[2]';
854 my @a = (0x73..0x77);
855 my $p = pack($t, @a);
856 is($p, "\x73\x74\x75\0\0\0\0\0\x76\x77");
857 my @b = unpack $t, $p;
858 is(scalar @b, scalar @a);
859 is("@b", "@a", 'x!8');
860 $t = 'x[5] C[6] X!8 C[2]';
861 @a = (0x73..0x7a);
862 $p = pack($t, @a);
863 is($p, "\0\0\0\0\0\x73\x74\x75\x79\x7a");
864 @b = unpack $t, $p;
865 @a = (0x73..0x75, 0x79, 0x7a, 0x79, 0x7a);
866 is(scalar @b, scalar @a);
867 is("@b", "@a");
868}
869
870{ # struct {char c1; double d; char cc[2];}
871 my $t = 'C x![d] d C[2]';
872 my @a = (173, 1.283476517e-45, 42, 215);
873 my $p = pack $t, @a;
874 ok( length $p);
875 my @b = unpack "$t X[$t] $t", $p; # Extract, step back, extract again
876 is(scalar @b, 2 * scalar @a);
3f7e3417 877 $b = "@b";
878 $b =~ s/(?:17000+|16999+)\d+(e-45) /17$1 /gi; # stringification is gamble
879 is($b, "@a @a");
62f95557 880
881 my $warning;
882 local $SIG{__WARN__} = sub {
883 $warning = $_[0];
884 };
885 @b = unpack "x[C] x[$t] X[$t] X[C] $t", "$p\0";
886
887 is($warning, undef);
888 is(scalar @b, scalar @a);
3f7e3417 889 $b = "@b";
890 $b =~ s/(?:17000+|16999+)\d+(e-45) /17$1 /gi; # stringification is gamble
891 is($b, "@a");
62f95557 892}
92d41999 893
894is(length(pack("j", 0)), $Config{ivsize});
895is(length(pack("J", 0)), $Config{uvsize});
896is(length(pack("F", 0)), $Config{nvsize});
897
898numbers ('j', -2147483648, -1, 0, 1, 2147483647);
899numbers ('J', 0, 1, 2147483647, 2147483648, 4294967295);
900numbers ('F', -(2**34), -1, 0, 1, 2**34);
901SKIP: {
902 my $t = eval { unpack("D*", pack("D", 12.34)) };
903
904 skip "Long doubles not in use", 56 if $@ =~ /Invalid type in pack/;
905
906 is(length(pack("D", 0)), $Config{longdblsize});
907 numbers ('D', -(2**34), -1, 0, 1, 2**34);
908}
909
c8f824eb 910# Maybe this knowledge needs to be "global" for all of pack.t
911# Or a "can checksum" which would effectively be all the number types"
912my %cant_checksum = map {$_=> 1} qw(A Z u w);
913# not a b B h H
914foreach 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)) {
915 SKIP: {
916 my $packed = eval {pack "${template}4", 1, 4, 9, 16};
917 if ($@) {
918 die unless $@ =~ /Invalid type in pack: '$template'/;
919 skip ("$template not supported on this perl",
920 $cant_checksum{$template} ? 4 : 8);
921 }
922 my @unpack4 = unpack "${template}4", $packed;
923 my @unpack = unpack "${template}*", $packed;
924 my @unpack1 = unpack "${template}", $packed;
925 my @unpack1s = scalar unpack "${template}", $packed;
926 my @unpack4s = scalar unpack "${template}4", $packed;
927 my @unpacks = scalar unpack "${template}*", $packed;
928
929 my @tests = ( ["${template}4 vs ${template}*", \@unpack4, \@unpack],
930 ["scalar ${template} ${template}", \@unpack1s, \@unpack1],
931 ["scalar ${template}4 vs ${template}", \@unpack4s, \@unpack1],
932 ["scalar ${template}* vs ${template}", \@unpacks, \@unpack1],
933 );
934
935 unless ($cant_checksum{$template}) {
936 my @unpack4_c = unpack "\%${template}4", $packed;
937 my @unpack_c = unpack "\%${template}*", $packed;
938 my @unpack1_c = unpack "\%${template}", $packed;
939 my @unpack1s_c = scalar unpack "\%${template}", $packed;
940 my @unpack4s_c = scalar unpack "\%${template}4", $packed;
941 my @unpacks_c = scalar unpack "\%${template}*", $packed;
942
943 push @tests,
944 ( ["% ${template}4 vs ${template}*", \@unpack4_c, \@unpack_c],
945 ["% scalar ${template} ${template}", \@unpack1s_c, \@unpack1_c],
946 ["% scalar ${template}4 vs ${template}*", \@unpack4s_c, \@unpack_c],
947 ["% scalar ${template}* vs ${template}*", \@unpacks_c, \@unpack_c],
948 );
949 }
950 foreach my $test (@tests) {
951 ok (list_eq ($test->[1], $test->[2]), $test->[0]) ||
952 printf "# unpack gave %s expected %s\n",
953 encode_list (@{$test->[1]}), encode_list (@{$test->[2]});
954 }
955 }
956}