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