byte-order modifiers for (un)pack templates
[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
1109a392 9plan tests => 13576;
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();
1109a392 17my @valid_errors = (qr/^Invalid type '\w'/);
18
19my $ByteOrder = 'unknown';
20my $maybe_not_avail = '(?:hto[bl]e|[bl]etoh)';
21if ($Config{byteorder} =~ /^1234(?:5678)?$/) {
22 $ByteOrder = 'little';
23 $maybe_not_avail = '(?:htobe|betoh)';
24}
25elsif ($Config{byteorder} =~ /^(?:8765)?4321$/) {
26 $ByteOrder = 'big';
27 $maybe_not_avail = '(?:htole|letoh)';
28}
29else {
30 push @valid_errors, qr/^Can't (?:un)?pack (?:big|little)-endian .*? on this platform/;
31}
32
33for my $size ( 16, 32, 64 ) {
34 if (exists $Config{"u${size}size"} and $Config{"u${size}size"} != ($size >> 3)) {
35 push @valid_errors, qr/^Perl_my_$maybe_not_avail$size\(\) not available/;
36 }
37}
38
39my $IsTwosComplement = pack('i', -1) eq "\xFF" x $Config{intsize};
40print "# \$IsTwosComplement = $IsTwosComplement\n";
41
42sub is_valid_error
43{
44 my $err = shift;
45
46 for my $e (@valid_errors) {
47 $err =~ $e and return 1;
48 }
49
50 return 0;
51}
c274e827 52
b85d93de 53sub encode_list {
9e17a6b8 54 my @result = map {_qq($_)} @_;
b85d93de 55 if (@result == 1) {
56 return @result;
57 }
58 return '(' . join (', ', @result) . ')';
59}
60
a1a0e61e 61
b85d93de 62sub list_eq ($$) {
63 my ($l, $r) = @_;
c8f824eb 64 return 0 unless @$l == @$r;
b85d93de 65 for my $i (0..$#$l) {
66 if (defined $l->[$i]) {
c8f824eb 67 return 0 unless defined ($r->[$i]) && $l->[$i] eq $r->[$i];
b85d93de 68 } else {
c8f824eb 69 return 0 if defined $r->[$i]
b85d93de 70 }
71 }
72 return 1;
73}
74
75##############################################################################
76#
77# Here starteth the tests
78#
79
fa8ec7c1 80{
0b568b5f 81 my $format = "c2 x5 C C x s d i l a6";
82 # Need the expression in here to force ary[5] to be numeric. This avoids
83 # test2 failing because ary2 goes str->numeric->str and ary doesn't.
84 my @ary = (1,-100,127,128,32767,987.654321098 / 100.0,12345,123456,
85 "abcdef");
86 my $foo = pack($format,@ary);
87 my @ary2 = unpack($format,$foo);
88
89 is($#ary, $#ary2);
90
91 my $out1=join(':',@ary);
92 my $out2=join(':',@ary2);
93 # Using long double NVs may introduce greater accuracy than wanted.
94 $out1 =~ s/:9\.87654321097999\d*:/:9.87654321098:/;
95 $out2 =~ s/:9\.87654321097999\d*:/:9.87654321098:/;
96 is($out1, $out2);
97
98 like($foo, qr/def/);
fa8ec7c1 99}
79072805 100# How about counting bits?
101
fa8ec7c1 102{
0b568b5f 103 my $x;
104 is( ($x = unpack("%32B*", "\001\002\004\010\020\040\100\200\377")), 16 );
79072805 105
0b568b5f 106 is( ($x = unpack("%32b69", "\001\002\004\010\020\040\100\200\017")), 12 );
79072805 107
0b568b5f 108 is( ($x = unpack("%32B69", "\001\002\004\010\020\040\100\200\017")), 9 );
fa8ec7c1 109}
79072805 110
fa8ec7c1 111{
0b568b5f 112 my $sum = 129; # ASCII
113 $sum = 103 if $Is_EBCDIC;
9d116dd7 114
0b568b5f 115 my $x;
116 is( ($x = unpack("%32B*", "Now is the time for all good blurfl")), $sum );
79072805 117
0b568b5f 118 my $foo;
119 open(BIN, $Perl) || die "Can't open $Perl: $!\n";
120 sysread BIN, $foo, 8192;
121 close BIN;
79072805 122
0b568b5f 123 $sum = unpack("%32b*", $foo);
124 my $longway = unpack("b*", $foo);
125 is( $sum, $longway =~ tr/1/1/ );
fa8ec7c1 126}
73a1c01a 127
fa8ec7c1 128{
129 my $x;
0b568b5f 130 is( ($x = unpack("I",pack("I", 0xFFFFFFFF))), 0xFFFFFFFF );
fa8ec7c1 131}
def98dd4 132
fa8ec7c1 133{
0b568b5f 134 # check 'w'
135 my @x = (5,130,256,560,32000,3097152,268435455,1073741844, 2**33,
136 '4503599627365785','23728385234614992549757750638446');
137 my $x = pack('w*', @x);
138 my $y = pack 'H*', '0581028200843081fa0081bd8440ffffff7f8480808014A0808'.
139 '0800087ffffffffffdb19caefe8e1eeeea0c2e1e3e8ede1ee6e';
140
141 is($x, $y);
142
143 my @y = unpack('w*', $y);
144 my $a;
145 while ($a = pop @x) {
146 my $b = pop @y;
147 is($a, $b);
148 }
def98dd4 149
0b568b5f 150 @y = unpack('w2', $x);
def98dd4 151
0b568b5f 152 is(scalar(@y), 2);
153 is($y[1], 130);
a6c48a57 154 $x = pack('w*', 5000000000); $y = '';
155 eval {
156 use Math::BigInt;
157 $y = pack('w*', Math::BigInt::->new(5000000000));
158 };
159 is($x, $y);
196b62db 160
161 $x = pack 'w', ~0;
162 $y = pack 'w', (~0).'';
163 is($x, $y);
164 is(unpack ('w',$x), ~0);
165 is(unpack ('w',$y), ~0);
166
167 $x = pack 'w', ~0 - 1;
168 $y = pack 'w', (~0) - 2;
169
170 if (~0 - 1 == (~0) - 2) {
171 is($x, $y, "NV arithmetic");
172 } else {
173 isnt($x, $y, "IV/NV arithmetic");
174 }
175 cmp_ok(unpack ('w',$x), '==', ~0 - 1);
176 cmp_ok(unpack ('w',$y), '==', ~0 - 2);
203d3f29 177
178 # These should spot that pack 'w' is using NV, not double, on platforms
179 # where IVs are smaller than doubles, and harmlessly pass elsewhere.
180 # (tests for change 16861)
181 my $x0 = 2**54+3;
182 my $y0 = 2**54-2;
183
184 $x = pack 'w', $x0;
185 $y = pack 'w', $y0;
186
187 if ($x0 == $y0) {
188 is($x, $y, "NV arithmetic");
189 } else {
190 isnt($x, $y, "IV/NV arithmetic");
191 }
192 cmp_ok(unpack ('w',$x), '==', $x0);
193 cmp_ok(unpack ('w',$y), '==', $y0);
fa8ec7c1 194}
def98dd4 195
0b568b5f 196
fa8ec7c1 197{
40837afc 198 print "# test exceptions\n";
fa8ec7c1 199 my $x;
200 eval { $x = unpack 'w', pack 'C*', 0xff, 0xff};
0b568b5f 201 like($@, qr/^Unterminated compressed integer/);
def98dd4 202
fa8ec7c1 203 eval { $x = unpack 'w', pack 'C*', 0xff, 0xff, 0xff, 0xff};
0b568b5f 204 like($@, qr/^Unterminated compressed integer/);
def98dd4 205
fa8ec7c1 206 eval { $x = unpack 'w', pack 'C*', 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff};
0b568b5f 207 like($@, qr/^Unterminated compressed integer/);
0258719b 208
209 eval { $x = pack 'w', -1 };
210 like ($@, qr/^Cannot compress negative numbers/);
211
212 eval { $x = pack 'w', '1'x(1 + length ~0) . 'e0' };
213 like ($@, qr/^Can only compress unsigned integers/);
214
1109a392 215 for my $mod (qw( ! < > )) {
216 eval { $x = pack "a$mod", 42 };
217 like ($@, qr/^'$mod' allowed only after types \w+ in pack/);
218
219 eval { $x = unpack "a$mod", 'x'x8 };
220 like ($@, qr/^'$mod' allowed only after types \w+ in unpack/);
221 }
222
223 for my $mod (qw( <> >< !<> !>< <!> >!< <>! ><! )) {
224 eval { $x = pack "sI${mod}s", 42, 47, 11 };
225 like ($@, qr/^Can't use both '<' and '>' after type 'I' in pack/);
226
227 eval { $x = unpack "sI${mod}s", 'x'x16 };
228 like ($@, qr/^Can't use both '<' and '>' after type 'I' in unpack/);
229 }
230
0258719b 231 SKIP: {
232 # Is this a stupid thing to do on VMS, VOS and other unusual platforms?
71f93cb9 233
b987f19e 234 skip("-- the IEEE infinity model is unavailable in this configuration.", 1)
71f93cb9 235 if (($^O eq 'VMS') && !defined($Config{useieee}));
236
b987f19e 237 skip("-- $^O has serious fp indigestion on w-packed infinities", 1)
5688dfbf 238 if (
239 ($^O eq 'mpeix')
240 ||
241 ($^O eq 'ultrix')
242 ||
cd512f8e 243 ($^O =~ /^svr4/ && -f "/etc/issue" && -f "/etc/.relid") # NCR MP-RAS
5688dfbf 244 );
8b571b32 245
1109a392 246 my $inf = eval '2**1000000';
0258719b 247
b987f19e 248 skip("Couldn't generate infinity - got error '$@'", 1)
71b080b8 249 unless defined $inf and $inf == $inf / 2 and $inf + 1 == $inf;
0258719b 250
46ff39aa 251 local our $TODO;
252 $TODO = "VOS needs a fix for posix-1022 to pass this test."
253 if ($^O eq 'vos');
254
0258719b 255 eval { $x = pack 'w', $inf };
46ff39aa 256 like ($@, qr/^Cannot compress integer/, "Cannot compress integer");
0258719b 257 }
258
259 SKIP: {
71f93cb9 260
b987f19e 261 skip("-- the full range of an IEEE double may not be available in this configuration.", 3)
71f93cb9 262 if (($^O eq 'VMS') && !defined($Config{useieee}));
263
b987f19e 264 skip("-- $^O does not like 2**1023", 3)
ad415dae 265 if (($^O eq 'ultrix'));
266
0258719b 267 # This should be about the biggest thing possible on an IEEE double
268 my $big = eval '2**1023';
269
b987f19e 270 skip("Couldn't generate 2**1023 - got error '$@'", 3)
0258719b 271 unless defined $big and $big != $big / 2;
272
273 eval { $x = pack 'w', $big };
274 is ($@, '', "Should be able to pack 'w', $big # 2**1023");
275
276 my $y = eval {unpack 'w', $x};
277 is ($@, '',
278 "Should be able to unpack 'w' the result of pack 'w', $big # 2**1023");
279
280 # I'm getting about 1e-16 on FreeBSD
281 my $quotient = int (100 * ($y - $big) / $big);
282 ok($quotient < 2 && $quotient > -2,
1109a392 283 "Round trip pack, unpack 'w' of $big is within 1% ($quotient%)");
0258719b 284 }
285
fa8ec7c1 286}
def98dd4 287
40837afc 288print "# test the 'p' template\n";
84902520 289
290# literals
0b568b5f 291is(unpack("p",pack("p","foo")), "foo");
1109a392 292is(unpack("p<",pack("p<","foo")), "foo");
293is(unpack("p>",pack("p>","foo")), "foo");
84902520 294
295# scalars
0b568b5f 296is(unpack("p",pack("p",239)), 239);
1109a392 297is(unpack("p<",pack("p<",239)), 239);
298is(unpack("p>",pack("p>",239)), 239);
84902520 299
300# temps
301sub foo { my $a = "a"; return $a . $a++ . $a++ }
302{
9f1b1f2d 303 use warnings;
0b568b5f 304 my $warning;
84902520 305 local $SIG{__WARN__} = sub {
0b568b5f 306 $warning = $_[0];
84902520 307 };
308 my $junk = pack("p", &foo);
0b568b5f 309
310 like($warning, qr/temporary val/);
84902520 311}
312
313# undef should give null pointer
1109a392 314like(pack("p", undef), qr/^\0+$/);
315like(pack("p<", undef), qr/^\0+$/);
316like(pack("p>", undef), qr/^\0+$/);
84902520 317
20408e3c 318# Check for optimizer bug (e.g. Digital Unix GEM cc with -O4 on DU V4.0B gives
319# 4294967295 instead of -1)
320# see #ifdef __osf__ in pp.c pp_unpack
0b568b5f 321is((unpack("i",pack("i",-1))), -1);
20408e3c 322
1109a392 323print "# test the pack lengths of s S i I l L n N v V + modifiers\n";
324
325my @lengths = (
326 qw(s 2 S 2 i -4 I -4 l 4 L 4 n 2 N 4 v 2 V 4 n! 2 N! 4 v! 2 V! 4),
327 's!' => $Config{shortsize}, 'S!' => $Config{shortsize},
328 'i!' => $Config{intsize}, 'I!' => $Config{intsize},
329 'l!' => $Config{longsize}, 'L!' => $Config{longsize},
330);
331
332while (my ($base, $expect) = splice @lengths, 0, 2) {
333 my @formats = ($base);
334 $base =~ /^[nv]/i or push @formats, "$base>", "$base<";
335 for my $format (@formats) {
336 my $len = length(pack($format, 0));
337 if ($expect > 0) {
338 is($expect, $len, "format '$format'");
339 } else {
340 $expect = -$expect;
341 ok ($len >= $expect, "format '$format'") ||
342 print "# format '$format' has length $len, expected >= $expect\n";
343 }
fa8ec7c1 344 }
345}
d4217c7e 346
d4217c7e 347
40837afc 348print "# test unpack-pack lengths\n";
349
0b568b5f 350my @templates = qw(c C i I s S l L n N v V f d q Q);
d4217c7e 351
1109a392 352foreach my $base (@templates) {
353 my @tmpl = ($base);
354 $base =~ /^[cnv]/i or push @tmpl, "$base>", "$base<";
355 foreach my $t (@tmpl) {
356 SKIP: {
357 my @t = eval { unpack("$t*", pack("$t*", 12, 34)) };
0b568b5f 358
1109a392 359 skip "cannot pack '$t' on this perl", 4
360 if is_valid_error($@);
3020ec7a 361
1109a392 362 is( $@, '' );
363 is(scalar @t, 2);
3020ec7a 364
0b568b5f 365 is($t[0], 12);
366 is($t[1], 34);
367 }
0b568b5f 368 }
d4217c7e 369}
9d116dd7 370
fa8ec7c1 371{
0b568b5f 372 # uuencode/decode
9d116dd7 373
0b568b5f 374 # Note that first uuencoding known 'text' data and then checking the
375 # binary values of the uuencoded version would not be portable between
376 # character sets. Uuencoding is meant for encoding binary data, not
377 # text data.
c4d5f83a 378
0b568b5f 379 my $in = pack 'C*', 0 .. 255;
ba1ac976 380
0b568b5f 381 # just to be anal, we do some random tr/`/ /
382 my $uu = <<'EOUU';
ba1ac976 383M` $"`P0%!@<("0H+# T.#Q`1$A,4%187&!D:&QP='A\@(2(C)"4F)R@I*BLL
9d116dd7 384M+2XO,#$R,S0U-C<X.3H[/#T^/T!!0D-$149'2$E*2TQ-3D]045)35%565UA9
385M6EM<75Y?8&%B8V1E9F=H:6IK;&UN;W!Q<G-T=79W>'EZ>WQ]?G^`@8*#A(6&
386MAXB)BHN,C8Z/D)&2DY25EI>8F9J;G)V>GZ"AHJ.DI::GJ*FJJZRMKJ^PL;*S
387MM+6VM[BYNKN\O;Z_P,'"P\3%QL?(R<K+S,W.S]#1TM/4U=;7V-G:V]S=WM_@
ba1ac976 388?X>+CY.7FY^CIZNOL[>[O\/'R\_3U]O?X^?K[_/W^_P `
9d116dd7 389EOUU
390
0b568b5f 391 $_ = $uu;
392 tr/ /`/;
9d116dd7 393
0b568b5f 394 is(pack('u', $in), $_);
fa8ec7c1 395
0b568b5f 396 is(unpack('u', $uu), $in);
9d116dd7 397
0b568b5f 398 $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";
399 $uu = <<'EOUU';
eddc390b 400M'XL("%C<Q#4"`TI!4%4`\RHM+E%(S,LOR4@M4@A(+<I1*"U-SD])+>("`&1F
401&8%P:````
402EOUU
403
0b568b5f 404 is(unpack('u', $uu), $in);
eddc390b 405
0b568b5f 406# This is identical to the above except that backquotes have been
407# changed to spaces
eddc390b 408
0b568b5f 409 $uu = <<'EOUU';
eddc390b 410M'XL("%C<Q#4" TI!4%4 \RHM+E%(S,LOR4@M4@A(+<I1*"U-SD])+>(" &1F
c4d5f83a 411&8%P:
eddc390b 412EOUU
413
0b568b5f 414 # ' # Grr
415 is(unpack('u', $uu), $in);
ef54e1a4 416
d99ad34e 417}
726ea183 418
0b568b5f 419# test the ascii template types (A, a, Z)
726ea183 420
fa8ec7c1 421foreach (
0b568b5f 422['p', 'A*', "foo\0bar\0 ", "foo\0bar\0 "],
fa8ec7c1 423['p', 'A11', "foo\0bar\0 ", "foo\0bar\0 "],
0b568b5f 424['u', 'A*', "foo\0bar \0", "foo\0bar"],
425['u', 'A8', "foo\0bar \0", "foo\0bar"],
426['p', 'a*', "foo\0bar\0 ", "foo\0bar\0 "],
fa8ec7c1 427['p', 'a11', "foo\0bar\0 ", "foo\0bar\0 \0\0"],
0b568b5f 428['u', 'a*', "foo\0bar \0", "foo\0bar \0"],
429['u', 'a8', "foo\0bar \0", "foo\0bar "],
430['p', 'Z*', "foo\0bar\0 ", "foo\0bar\0 \0"],
fa8ec7c1 431['p', 'Z11', "foo\0bar\0 ", "foo\0bar\0 \0\0"],
0b568b5f 432['p', 'Z3', "foo", "fo\0"],
433['u', 'Z*', "foo\0bar \0", "foo"],
434['u', 'Z8', "foo\0bar \0", "foo"],
435)
436{
437 my ($what, $template, $in, $out) = @$_;
438 my $got = $what eq 'u' ? (unpack $template, $in) : (pack $template, $in);
439 unless (is($got, $out)) {
0b568b5f 440 my $un = $what eq 'u' ? 'un' : '';
9e17a6b8 441 print "# ${un}pack ('$template', "._qq($in).') gave '._qq($out).
442 ' not '._qq($got)."\n";
0b568b5f 443 }
d99ad34e 444}
726ea183 445
40837afc 446print "# packing native shorts/ints/longs\n";
726ea183 447
0b568b5f 448is(length(pack("s!", 0)), $Config{shortsize});
449is(length(pack("i!", 0)), $Config{intsize});
450is(length(pack("l!", 0)), $Config{longsize});
451ok(length(pack("s!", 0)) <= length(pack("i!", 0)));
452ok(length(pack("i!", 0)) <= length(pack("l!", 0)));
453is(length(pack("i!", 0)), length(pack("i", 0)));
726ea183 454
fa8ec7c1 455sub numbers {
1109a392 456 my $base = shift;
457 my @formats = ($base);
458 $base =~ /^[silqjfdp]/i and push @formats, "$base>", "$base<";
459 for my $format (@formats) {
460 numbers_with_total ($format, undef, @_);
461 }
d99ad34e 462}
726ea183 463
fa8ec7c1 464sub numbers_with_total {
465 my $format = shift;
466 my $total = shift;
467 if (!defined $total) {
468 foreach (@_) {
469 $total += $_;
470 }
471 }
40837afc 472 print "# numbers test for $format\n";
fa8ec7c1 473 foreach (@_) {
0b568b5f 474 SKIP: {
475 my $out = eval {unpack($format, pack($format, $_))};
1109a392 476 skip "cannot pack '$format' on this perl", 2
477 if is_valid_error($@);
0b568b5f 478
479 is($@, '');
480 is($out, $_);
fa8ec7c1 481 }
fa8ec7c1 482 }
726ea183 483
fa8ec7c1 484 my $skip_if_longer_than = ~0; # "Infinity"
485 if (~0 - 1 == ~0) {
486 # If we're running with -DNO_PERLPRESERVE_IVUV and NVs don't preserve all
487 # UVs (in which case ~0 is NV, ~0-1 will be the same NV) then we can't
488 # correctly in perl calculate UV totals for long checksums, as pp_unpack
489 # is using UV maths, and we've only got NVs.
53133ed1 490 $skip_if_longer_than = $Config{nv_preserves_uv_bits};
fa8ec7c1 491 }
726ea183 492
fa8ec7c1 493 foreach ('', 1, 2, 3, 15, 16, 17, 31, 32, 33, 53, 54, 63, 64, 65) {
0b568b5f 494 SKIP: {
495 my $sum = eval {unpack "%$_$format*", pack "$format*", @_};
496 skip "cannot pack '$format' on this perl", 3
1109a392 497 if is_valid_error($@);
0b568b5f 498
499 is($@, '');
500 ok(defined $sum);
501
502 my $len = $_; # Copy, so that we can reassign ''
503 $len = 16 unless length $len;
504
505 SKIP: {
506 skip "cannot test checksums over $skip_if_longer_than bits", 1
507 if $len > $skip_if_longer_than;
508
509 # Our problem with testing this portably is that the checksum code in
510 # pp_unpack is able to cast signed to unsigned, and do modulo 2**n
511 # arithmetic in unsigned ints, which perl has no operators to do.
512 # (use integer; does signed ints, which won't wrap on UTS, which is just
513 # fine with ANSI, but not with most people's assumptions.
514 # This is why we need to supply the totals for 'Q' as there's no way in
515 # perl to calculate them, short of unpack '%0Q' (is that documented?)
516 # ** returns NVs; make sure it's IV.
517 my $max = 1 + 2 * (int (2 ** ($len-1))-1); # The max possible checksum
518 my $max_p1 = $max + 1;
519 my ($max_is_integer, $max_p1_is_integer);
520 $max_p1_is_integer = 1 unless $max_p1 + 1 == $max_p1;
521 $max_is_integer = 1 if $max - 1 < ~0;
522
523 my $calc_sum;
524 if (ref $total) {
525 $calc_sum = &$total($len);
526 } else {
527 $calc_sum = $total;
528 # Shift into range by some multiple of the total
53f3fd80 529 my $mult = $max_p1 ? int ($total / $max_p1) : undef;
0b568b5f 530 # Need this to make sure that -1 + (~0+1) is ~0 (ie still integer)
531 $calc_sum = $total - $mult;
532 $calc_sum -= $mult * $max;
533 if ($calc_sum < 0) {
534 $calc_sum += 1;
535 $calc_sum += $max;
536 }
537 }
538 if ($calc_sum == $calc_sum - 1 && $calc_sum == $max_p1) {
539 # we're into floating point (either by getting out of the range of
540 # UV arithmetic, or because we're doing a floating point checksum)
541 # and our calculation of the checksum has become rounded up to
542 # max_checksum + 1
543 $calc_sum = 0;
544 }
545
0dccb3d1 546 if ($calc_sum == $sum) { # HAS to be ==, not eq (so no is()).
547 ok ("unpack '%$_$format' gave $sum");
0b568b5f 548 } else {
549 my $delta = 1.000001;
550 if ($format =~ tr /dDfF//
551 && ($calc_sum <= $sum * $delta && $calc_sum >= $sum / $delta)) {
0dccb3d1 552 pass ("unpack '%$_$format' gave $sum, expected $calc_sum");
0b568b5f 553 } else {
554 my $text = ref $total ? &$total($len) : $total;
555 fail;
556 print "# For list (" . join (", ", @_) . ") (total $text)"
557 . " packed with $format unpack '%$_$format' gave $sum,"
558 . " expected $calc_sum\n";
559 }
560 }
fa8ec7c1 561 }
0b568b5f 562 }
2e821511 563 }
564}
565
fa8ec7c1 566numbers ('c', -128, -1, 0, 1, 127);
567numbers ('C', 0, 1, 127, 128, 255);
568numbers ('s', -32768, -1, 0, 1, 32767);
569numbers ('S', 0, 1, 32767, 32768, 65535);
570numbers ('i', -2147483648, -1, 0, 1, 2147483647);
571numbers ('I', 0, 1, 2147483647, 2147483648, 4294967295);
572numbers ('l', -2147483648, -1, 0, 1, 2147483647);
573numbers ('L', 0, 1, 2147483647, 2147483648, 4294967295);
574numbers ('s!', -32768, -1, 0, 1, 32767);
575numbers ('S!', 0, 1, 32767, 32768, 65535);
576numbers ('i!', -2147483648, -1, 0, 1, 2147483647);
577numbers ('I!', 0, 1, 2147483647, 2147483648, 4294967295);
578numbers ('l!', -2147483648, -1, 0, 1, 2147483647);
579numbers ('L!', 0, 1, 2147483647, 2147483648, 4294967295);
580numbers ('n', 0, 1, 32767, 32768, 65535);
581numbers ('v', 0, 1, 32767, 32768, 65535);
582numbers ('N', 0, 1, 2147483647, 2147483648, 4294967295);
583numbers ('V', 0, 1, 2147483647, 2147483648, 4294967295);
068bd2e7 584numbers ('n!', -32768, -1, 0, 1, 32767);
585numbers ('v!', -32768, -1, 0, 1, 32767);
586numbers ('N!', -2147483648, -1, 0, 1, 2147483647);
587numbers ('V!', -2147483648, -1, 0, 1, 2147483647);
fa8ec7c1 588# All these should have exact binary representations:
589numbers ('f', -1, 0, 0.5, 42, 2**34);
b85d93de 590numbers ('d', -(2**34), -1, 0, 1, 2**34);
591## These don't, but 'd' is NV. XXX wrong, it's double
592#numbers ('d', -1, 0, 1, 1-exp(-1), -exp(1));
fa8ec7c1 593
594numbers_with_total ('q', -1,
595 -9223372036854775808, -1, 0, 1,9223372036854775807);
800e6488 596# This total is icky, but the true total is 2**65-1, and need a way to generate
597# the epxected checksum on any system including those where NVs can preserve
598# 65 bits. (long double is 128 bits on sparc, so they certainly can)
599# or where rounding is down not up on binary conversion (crays)
600numbers_with_total ('Q', sub {
601 my $len = shift;
602 $len = 65 if $len > 65; # unmasked total is 2**65-1 here
603 my $total = 1 + 2 * (int (2**($len - 1)) - 1);
604 return 0 if $total == $total - 1; # Overflowed integers
605 return $total; # NVs still accurate to nearest integer
606 },
fa8ec7c1 607 0, 1,9223372036854775807, 9223372036854775808,
608 18446744073709551615);
609
40837afc 610print "# pack nvNV byteorders\n";
fa8ec7c1 611
0b568b5f 612is(pack("n", 0xdead), "\xde\xad");
613is(pack("v", 0xdead), "\xad\xde");
614is(pack("N", 0xdeadbeef), "\xde\xad\xbe\xef");
615is(pack("V", 0xdeadbeef), "\xef\xbe\xad\xde");
43192e07 616
068bd2e7 617is(pack("n!", 0xdead), "\xde\xad");
618is(pack("v!", 0xdead), "\xad\xde");
619is(pack("N!", 0xdeadbeef), "\xde\xad\xbe\xef");
620is(pack("V!", 0xdeadbeef), "\xef\xbe\xad\xde");
621
1109a392 622print "# test big-/little-endian conversion\n";
623
624sub byteorder
625{
626 my $format = shift;
627 print "# byteorder test for $format\n";
628 for my $value (@_) {
629 SKIP: {
630 my($nat,$be,$le) = eval { map { pack $format.$_, $value } '', '>', '<' };
631 skip "cannot pack '$format' on this perl", 5
632 if is_valid_error($@);
633
634 print "# [$value][$nat][$be][$le][$@]\n";
635
636 SKIP: {
637 skip "cannot compare native byteorder with big-/little-endian", 1
638 if $ByteOrder eq 'unknown';
639
640 is($nat, $ByteOrder eq 'big' ? $be : $le);
641 }
642 is($be, reverse($le));
643 my @x = eval { unpack "$format$format>$format<", $nat.$be.$le };
644
645 print "# [$value][", join('][', @x), "][$@]\n";
646
647 is($@, '');
648 is($x[0], $x[1]);
649 is($x[0], $x[2]);
650 }
651 }
652}
653
654byteorder('s', -32768, -1, 0, 1, 32767);
655byteorder('S', 0, 1, 32767, 32768, 65535);
656byteorder('i', -2147483648, -1, 0, 1, 2147483647);
657byteorder('I', 0, 1, 2147483647, 2147483648, 4294967295);
658byteorder('l', -2147483648, -1, 0, 1, 2147483647);
659byteorder('L', 0, 1, 2147483647, 2147483648, 4294967295);
660byteorder('j', -2147483648, -1, 0, 1, 2147483647);
661byteorder('J', 0, 1, 2147483647, 2147483648, 4294967295);
662byteorder('s!', -32768, -1, 0, 1, 32767);
663byteorder('S!', 0, 1, 32767, 32768, 65535);
664byteorder('i!', -2147483648, -1, 0, 1, 2147483647);
665byteorder('I!', 0, 1, 2147483647, 2147483648, 4294967295);
666byteorder('l!', -2147483648, -1, 0, 1, 2147483647);
667byteorder('L!', 0, 1, 2147483647, 2147483648, 4294967295);
668byteorder('q', -9223372036854775808, -1, 0, 1, 9223372036854775807);
669byteorder('Q', 0, 1, 9223372036854775807, 9223372036854775808, 18446744073709551615);
670byteorder('f', -1, 0, 0.5, 42, 2**34);
671byteorder('F', -1, 0, 0.5, 42, 2**34);
672byteorder('d', -(2**34), -1, 0, 1, 2**34);
673byteorder('D', -(2**34), -1, 0, 1, 2**34);
674
675print "# test negative numbers\n";
676
677SKIP: {
678 skip "platform is not using two's complement for negative integers", 120
679 unless $IsTwosComplement;
680
681 for my $format (qw(s i l j s! i! l! q)) {
682 SKIP: {
683 my($nat,$be,$le) = eval { map { pack $format.$_, -1 } '', '>', '<' };
684 skip "cannot pack '$format' on this perl", 15
685 if is_valid_error($@);
686
687 my $len = length $nat;
688 is($_, "\xFF"x$len) for $nat, $be, $le;
689
690 my(@val,@ref);
691 if ($len >= 8) {
692 @val = (-2, -81985529216486896, -9223372036854775808);
693 @ref = ("\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFE",
694 "\xFE\xDC\xBA\x98\x76\x54\x32\x10",
695 "\x80\x00\x00\x00\x00\x00\x00\x00");
696 }
697 elsif ($len >= 4) {
698 @val = (-2, -19088744, -2147483648);
699 @ref = ("\xFF\xFF\xFF\xFE",
700 "\xFE\xDC\xBA\x98",
701 "\x80\x00\x00\x00");
702 }
703 else {
704 @val = (-2, -292, -32768);
705 @ref = ("\xFF\xFE",
706 "\xFE\xDC",
707 "\x80\x00");
708 }
709 for my $x (@ref) {
710 if ($len > length $x) {
711 $x = $x . "\xFF" x ($len - length $x);
712 }
713 }
714
715 for my $i (0 .. $#val) {
716 my($nat,$be,$le) = eval { map { pack $format.$_, $val[$i] } '', '>', '<' };
717 is($@, '');
718
719 SKIP: {
720 skip "cannot compare native byteorder with big-/little-endian", 1
721 if $ByteOrder eq 'unknown';
722
723 is($nat, $ByteOrder eq 'big' ? $be : $le);
724 }
725
726 is($be, $ref[$i]);
727 is($be, reverse($le));
728 }
729 }
730 }
731}
732
fa8ec7c1 733{
734 # /
735
736 my ($x, $y, $z);
737 eval { ($x) = unpack '/a*','hello' };
49704364 738 like($@, qr!'/' must follow a numeric type!);
72b034c3 739 undef $x;
740 eval { $x = unpack '/a*','hello' };
49704364 741 like($@, qr!'/' must follow a numeric type!);
0b568b5f 742
72b034c3 743 undef $x;
fa8ec7c1 744 eval { ($z,$x,$y) = unpack 'a3/A C/a* C/Z', "003ok \003yes\004z\000abc" };
0b568b5f 745 is($@, '');
746 is($z, 'ok');
747 is($x, 'yes');
748 is($y, 'z');
72b034c3 749 undef $z;
750 eval { $z = unpack 'a3/A C/a* C/Z', "003ok \003yes\004z\000abc" };
751 is($@, '');
752 is($z, 'ok');
753
fa8ec7c1 754
72b034c3 755 undef $x;
fa8ec7c1 756 eval { ($x) = pack '/a*','hello' };
49704364 757 like($@, qr!Invalid type '/'!);
72b034c3 758 undef $x;
759 eval { $x = pack '/a*','hello' };
49704364 760 like($@, qr!Invalid type '/'!);
fa8ec7c1 761
762 $z = pack 'n/a* N/Z* w/A*','string','hi there ','etc';
763 my $expect = "\000\006string\0\0\0\012hi there \000\003etc";
0b568b5f 764 is($z, $expect);
4b5b2118 765
72b034c3 766 undef $x;
b85d93de 767 $expect = 'hello world';
768 eval { ($x) = unpack ("w/a", chr (11) . "hello world!")};
0b568b5f 769 is($x, $expect);
770 is($@, '');
771
72b034c3 772 undef $x;
b85d93de 773 # Doing this in scalar context used to fail.
774 eval { $x = unpack ("w/a", chr (11) . "hello world!")};
0b568b5f 775 is($@, '');
776 is($x, $expect);
b85d93de 777
fa8ec7c1 778 foreach (
0b568b5f 779 ['a/a*/a*', '212ab345678901234567','ab3456789012'],
780 ['a/a*/a*', '3012ab345678901234567', 'ab3456789012'],
781 ['a/a*/b*', '212ab', $Is_EBCDIC ? '100000010100' : '100001100100'],
782 )
783 {
fa8ec7c1 784 my ($pat, $in, $expect) = @$_;
72b034c3 785 undef $x;
fa8ec7c1 786 eval { ($x) = unpack $pat, $in };
0b568b5f 787 is($@, '');
788 is($x, $expect) ||
789 printf "# list unpack ('$pat', '$in') gave %s, expected '$expect'\n",
790 encode_list ($x);
791
72b034c3 792 undef $x;
b85d93de 793 eval { $x = unpack $pat, $in };
0b568b5f 794 is($@, '');
795 is($x, $expect) ||
796 printf "# scalar unpack ('$pat', '$in') gave %s, expected '$expect'\n",
797 encode_list ($x);
fa8ec7c1 798 }
4b5b2118 799
0b568b5f 800 # / with #
17f4a12d 801
72b034c3 802 my $pattern = <<'EOU';
17f4a12d 803 a3/A # Count in ASCII
804 C/a* # Count in a C char
805 C/Z # Count in a C char but skip after \0
806EOU
17f4a12d 807
72b034c3 808 $x = $y = $z =undef;
809 eval { ($z,$x,$y) = unpack $pattern, "003ok \003yes\004z\000abc" };
0b568b5f 810 is($@, '');
811 is($z, 'ok');
812 is($x, 'yes');
813 is($y, 'z');
72b034c3 814 undef $x;
815 eval { $z = unpack $pattern, "003ok \003yes\004z\000abc" };
816 is($@, '');
817 is($z, 'ok');
0b568b5f 818
72b034c3 819 $pattern = <<'EOP';
17f4a12d 820 n/a* # Count as network short
821 w/A* # Count a BER integer
822EOP
fa8ec7c1 823 $expect = "\000\006string\003etc";
72b034c3 824 $z = pack $pattern,'string','etc';
9e17a6b8 825 is($z, $expect);
fa8ec7c1 826}
827
60a99fa7 828
829SKIP: {
830 skip("(EBCDIC and) version strings are bad idea", 2) if $Is_EBCDIC;
831
832 is("1.20.300.4000", sprintf "%vd", pack("U*",1,20,300,4000));
833 is("1.20.300.4000", sprintf "%vd", pack(" U*",1,20,300,4000));
834}
0b568b5f 835isnt(v1.20.300.4000, sprintf "%vd", pack("C0U*",1,20,300,4000));
fa8ec7c1 836
0b568b5f 837my $rslt = $Is_EBCDIC ? "156 67" : "199 162";
838is(join(" ", unpack("C*", chr(0x1e2))), $rslt);
fa8ec7c1 839
840# does pack U create Unicode?
0b568b5f 841is(ord(pack('U', 300)), 300);
fa8ec7c1 842
843# does unpack U deref Unicode?
0b568b5f 844is((unpack('U', chr(300)))[0], 300);
fa8ec7c1 845
846# is unpack U the reverse of pack U for Unicode string?
0b568b5f 847is("@{[unpack('U*', pack('U*', 100, 200, 300))]}", "100 200 300");
fa8ec7c1 848
849# is unpack U the reverse of pack U for byte string?
0b568b5f 850is("@{[unpack('U*', pack('U*', 100, 200))]}", "100 200");
851
852
853SKIP: {
854 skip "Not for EBCDIC", 4 if $Is_EBCDIC;
fa8ec7c1 855
7eed2ccc 856 # does unpack C unravel pack U?
0b568b5f 857 is("@{[unpack('C*', pack('U*', 100, 200))]}", "100 195 136");
fa8ec7c1 858
7eed2ccc 859 # does pack U0C create Unicode?
0b568b5f 860 is("@{[pack('U0C*', 100, 195, 136)]}", v100.v200);
fa8ec7c1 861
7eed2ccc 862 # does pack C0U create characters?
0b568b5f 863 is("@{[pack('C0U*', 100, 200)]}", pack("C*", 100, 195, 136));
fa8ec7c1 864
2dcec3fe 865 # does unpack U0U on byte data warn?
866 {
867 local $SIG{__WARN__} = sub { $@ = "@_" };
868 my @null = unpack('U0U', chr(255));
1109a392 869 like($@, qr/^Malformed UTF-8 character /);
2dcec3fe 870 }
35bcd338 871}
872
fa8ec7c1 873{
874 my $p = pack 'i*', -2147483648, ~0, 0, 1, 2147483647;
875 my (@a);
876 # bug - % had to be at the start of the pattern, no leading whitespace or
877 # comments. %i! didn't work at all.
878 foreach my $pat ('%32i*', ' %32i*', "# Muhahahaha\n%32i*", '%32i* ',
879 '%32i!*', ' %32i!*', "\n#\n#\n\r \t\f%32i!*", '%32i!*#') {
880 @a = unpack $pat, $p;
0b568b5f 881 is($a[0], 0xFFFFFFFF) || print "# $pat\n";
fa8ec7c1 882 @a = scalar unpack $pat, $p;
0b568b5f 883 is($a[0], 0xFFFFFFFF) || print "# $pat\n";
fa8ec7c1 884 }
885
886
887 $p = pack 'I*', 42, 12;
888 # Multiline patterns in scalar context failed.
889 foreach my $pat ('I', <<EOPOEMSNIPPET, 'I#I', 'I # I', 'I # !!!') {
890# On the Ning Nang Nong
891# Where the Cows go Bong!
892# And the Monkeys all say Boo!
893I
894EOPOEMSNIPPET
0b568b5f 895 @a = unpack $pat, $p;
896 is(scalar @a, 1);
897 is($a[0], 42);
898 @a = scalar unpack $pat, $p;
899 is(scalar @a, 1);
900 is($a[0], 42);
901 }
fa8ec7c1 902
903 # shorts (of all flavours) didn't calculate checksums > 32 bits with floating
904 # point, so a pathologically long pattern would wrap at 32 bits.
905 my $pat = "\xff\xff"x65538; # Start with it long, to save any copying.
906 foreach (4,3,2,1,0) {
907 my $len = 65534 + $_;
0b568b5f 908 is(unpack ("%33n$len", $pat), 65535 * $len);
fa8ec7c1 909 }
910}
b85d93de 911
912
913# pack x X @
914foreach (
0b568b5f 915 ['x', "N", "\0"],
916 ['x4', "N", "\0"x4],
917 ['xX', "N", ""],
918 ['xXa*', "Nick", "Nick"],
919 ['a5Xa5', "cameL", "llama", "camellama"],
920 ['@4', 'N', "\0"x4],
921 ['a*@8a*', 'Camel', 'Dromedary', "Camel\0\0\0Dromedary"],
922 ['a*@4a', 'Perl rules', '!', 'Perl!'],
923)
924{
b85d93de 925 my ($template, @in) = @$_;
926 my $out = pop @in;
927 my $got = eval {pack $template, @in};
0b568b5f 928 is($@, '');
929 is($out, $got) ||
930 printf "# pack ('$template', %s) gave %s expected %s\n",
931 encode_list (@in), encode_list ($got), encode_list ($out);
b85d93de 932}
933
934# unpack x X @
935foreach (
0b568b5f 936 ['x', "N"],
937 ['xX', "N"],
938 ['xXa*', "Nick", "Nick"],
939 ['a5Xa5', "camellama", "camel", "llama"],
940 ['@3', "ice"],
941 ['@2a2', "water", "te"],
942 ['a*@1a3', "steam", "steam", "tea"],
943)
944{
b85d93de 945 my ($template, $in, @out) = @$_;
946 my @got = eval {unpack $template, $in};
0b568b5f 947 is($@, '');
c8f824eb 948 ok (list_eq (\@got, \@out)) ||
9e17a6b8 949 printf "# list unpack ('$template', %s) gave %s expected %s\n",
950 _qq($in), encode_list (@got), encode_list (@out);
b85d93de 951
952 my $got = eval {unpack $template, $in};
0b568b5f 953 is($@, '');
954 @out ? is( $got, $out[0] ) # 1 or more items; should get first
955 : ok( !defined $got ) # 0 items; should get undef
9e17a6b8 956 or printf "# scalar unpack ('$template', %s) gave %s expected %s\n",
957 _qq($in), encode_list ($got), encode_list ($out[0]);
b85d93de 958}
d50dd4e4 959
960{
d50dd4e4 961 my $t = 'Z*Z*';
962 my ($u, $v) = qw(foo xyzzy);
963 my $p = pack($t, $u, $v);
964 my @u = unpack($t, $p);
0b568b5f 965 is(scalar @u, 2);
966 is($u[0], $u);
967 is($u[1], $v);
d50dd4e4 968}
bf80f5a2 969
970{
0b568b5f 971 is((unpack("w/a*", "\x02abc"))[0], "ab");
bf80f5a2 972
0b568b5f 973 # "w/a*" should be seen as one unit
bf80f5a2 974
0b568b5f 975 is(scalar unpack("w/a*", "\x02abc"), "ab");
bf80f5a2 976}
b81060d6 977
978{
b81060d6 979 # from Wolfgang Laun: fix in change #13163
980
981 my $s = 'ABC' x 10;
644d52eb 982 my $t = '*';
983 my $x = ord($t);
b81060d6 984 my $buf = pack( 'Z*/A* C', $s, $x );
985 my $y;
986
987 my $h = $buf;
988 $h =~ s/[^[:print:]]/./g;
989 ( $s, $y ) = unpack( "Z*/A* C", $buf );
644d52eb 990 is($h, "30.ABCABCABCABCABCABCABCABCABCABC$t");
0b568b5f 991 is(length $buf, 34);
992 is($s, "ABCABCABCABCABCABCABCABCABCABC");
644d52eb 993 is($y, $x);
b81060d6 994}
3bf38418 995
996{
b223308b 997 # from Wolfgang Laun: fix in change #13288
3bf38418 998
b223308b 999 eval { my $t=unpack("P*", "abc") };
49704364 1000 like($@, qr/'P' must have an explicit size/);
3bf38418 1001}
18529408 1002
1003{ # Grouping constructs
1004 my (@a, @b);
1005 @a = unpack '(SL)', pack 'SLSLSL', 67..90;
1006 is("@a", "67 68");
1007 @a = unpack '(SL)3', pack 'SLSLSL', 67..90;
1008 @b = (67..72);
1009 is("@a", "@b");
1010 @a = unpack '(SL)3', pack 'SLSLSLSL', 67..90;
1011 is("@a", "@b");
1012 @a = unpack '(SL)[3]', pack 'SLSLSLSL', 67..90;
1013 is("@a", "@b");
1014 @a = unpack '(SL)[2] SL', pack 'SLSLSLSL', 67..90;
1015 is("@a", "@b");
1016 @a = unpack 'A/(SL)', pack 'ASLSLSLSL', 3, 67..90;
1017 is("@a", "@b");
1018 @a = unpack 'A/(SL)SL', pack 'ASLSLSLSL', 2, 67..90;
1019 is("@a", "@b");
1020 @a = unpack '(SL)*', pack 'SLSLSLSL', 67..90;
1021 @b = (67..74);
1022 is("@a", "@b");
1023 @a = unpack '(SL)*SL', pack 'SLSLSLSL', 67..90;
1024 is("@a", "@b");
1025 eval { @a = unpack '(*SL)', '' };
1026 like($@, qr/\(\)-group starts with a count/);
1027 eval { @a = unpack '(3SL)', '' };
1028 like($@, qr/\(\)-group starts with a count/);
1029 eval { @a = unpack '([3]SL)', '' };
1030 like($@, qr/\(\)-group starts with a count/);
1031 eval { @a = pack '(*SL)' };
1032 like($@, qr/\(\)-group starts with a count/);
1033 @a = unpack '(SL)3 SL', pack '(SL)4', 67..74;
1034 is("@a", "@b");
1035 @a = unpack '(SL)3 SL', pack '(SL)[4]', 67..74;
1036 is("@a", "@b");
1037 @a = unpack '(SL)3 SL', pack '(SL)*', 67..74;
1038 is("@a", "@b");
1039}
206947d2 1040
49704364 1041{ # more on grouping (W.Laun)
1042 use warnings;
1043 my $warning;
1044 local $SIG{__WARN__} = sub {
1045 $warning = $_[0];
1046 };
1047 # @ absolute within ()-group
1048 my $badc = pack( '(a)*', unpack( '(@1a @0a @2)*', 'abcd' ) );
1049 is( $badc, 'badc' );
1050 my @b = ( 1, 2, 3 );
1051 my $buf = pack( '(@1c)((@2C)@3c)', @b );
1052 is( $buf, "\0\1\0\0\2\3" );
1053 my @a = unpack( '(@1c)((@2c)@3c)', $buf );
1054 is( "@a", "@b" );
1055
1056 # various unpack count/code scenarios
1057 my @Env = ( a => 'AAA', b => 'BBB' );
1058 my $env = pack( 'S(S/A*S/A*)*', @Env/2, @Env );
1059
1060 # unpack full length - ok
1061 my @pup = unpack( 'S/(S/A* S/A*)', $env );
1062 is( "@pup", "@Env" );
1063
1064 # warn when count/code goes beyond end of string
1065 # \0002 \0001 a \0003 AAA \0001 b \0003 BBB
1066 # 2 4 5 7 10 1213
1067 eval { @pup = unpack( 'S/(S/A* S/A*)', substr( $env, 0, 13 ) ) };
1068 like( $@, qr{length/code after end of string} );
1069
1070 # postfix repeat count
1071 $env = pack( '(S/A* S/A*)' . @Env/2, @Env );
1072
1073 # warn when count/code goes beyond end of string
1074 # \0001 a \0003 AAA \0001 b \0003 BBB
1075 # 2 3c 5 8 10 11 13 16
1076 eval { @pup = unpack( '(S/A* S/A*)' . @Env/2, substr( $env, 0, 11 ) ) };
1077 like( $@, qr{length/code after end of string} );
1078
1079 # catch stack overflow/segfault
1080 eval { $_ = pack( ('(' x 105) . 'A' . (')' x 105) ); };
1081 like( $@, qr{Too deeply nested \(\)-groups} );
1082}
1083
1084{ # syntax checks (W.Laun)
1085 use warnings;
1086 my @warning;
1087 local $SIG{__WARN__} = sub {
1088 push( @warning, $_[0] );
1089 };
1090 eval { my $s = pack( 'Ax![4c]A', 1..5 ); };
1091 like( $@, qr{Malformed integer in \[\]} );
1092
1093 eval { my $buf = pack( '(c/*a*)', 'AAA', 'BB' ); };
1094 like( $@, qr{'/' does not take a repeat count} );
1095
1096 eval { my @inf = unpack( 'c/1a', "\x03AAA\x02BB" ); };
1097 like( $@, qr{'/' does not take a repeat count} );
1098
1099 eval { my @inf = unpack( 'c/*a', "\x03AAA\x02BB" ); };
1100 like( $@, qr{'/' does not take a repeat count} );
1101
1102 # white space where possible
1103 my @Env = ( a => 'AAA', b => 'BBB' );
1104 my $env = pack( ' S ( S / A* S / A* )* ', @Env/2, @Env );
1105 my @pup = unpack( ' S / ( S / A* S / A* ) ', $env );
1106 is( "@pup", "@Env" );
1107
1108 # white space in 4 wrong places
1109 for my $temp ( 'A ![4]', 'A [4]', 'A *', 'A 4' ){
1110 eval { my $s = pack( $temp, 'B' ); };
1111 like( $@, qr{Invalid type } );
1112 }
1113
1114 # warning for commas
1115 @warning = ();
1116 my $x = pack( 'I,A', 4, 'X' );
1117 like( $warning[0], qr{Invalid type ','} );
1118
1119 # comma warning only once
1120 @warning = ();
1121 $x = pack( 'C(C,C)C,C', 65..71 );
1122 like( scalar @warning, 1 );
1123
1124 # forbidden code in []
1125 eval { my $x = pack( 'A[@4]', 'XXXX' ); };
1126 like( $@, qr{Within \[\]-length '\@' not allowed} );
1127
1128 # @ repeat default 1
1129 my $s = pack( 'AA@A', 'A', 'B', 'C' );
1130 my @c = unpack( 'AA@A', $s );
1131 is( $s, 'AC' );
1132 is( "@c", "A C C" );
1133
1134 # no unpack code after /
1135 eval { my @a = unpack( "C/", "\3" ); };
1136 like( $@, qr{Code missing after '/'} );
1137
1109a392 1138 # modifier warnings
1139 @warning = ();
1140 $x = pack "I>>s!!", 47, 11;
1141 ($x) = unpack "I<<l!>!>", 'x'x20;
1142 is(scalar @warning, 5);
1143 like($warning[0], qr/Duplicate modifier '>' after 'I' in pack/);
1144 like($warning[1], qr/Duplicate modifier '!' after 's' in pack/);
1145 like($warning[2], qr/Duplicate modifier '<' after 'I' in unpack/);
1146 like($warning[3], qr/Duplicate modifier '!' after 'l' in unpack/);
1147 like($warning[4], qr/Duplicate modifier '>' after 'l' in unpack/);
49704364 1148}
1149
206947d2 1150{ # Repeat count [SUBEXPR]
92d41999 1151 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
1152 s! S! i! I! l! L! j J);
1153 my $G;
206947d2 1154 if (eval { pack 'q', 1 } ) {
1155 push @codes, qw(q Q);
1156 } else {
1109a392 1157 push @codes, qw(s S); # Keep the count the same
206947d2 1158 }
92d41999 1159 if (eval { pack 'D', 1 } ) {
1160 push @codes, 'D';
1161 } else {
1162 push @codes, 'd'; # Keep the count the same
1163 }
206947d2 1164
1109a392 1165 push @codes, map { /^[silqjfdp]/i ? ("$_<", "$_>") : () } @codes;
1166
206947d2 1167 my %val;
1168 @val{@codes} = map { / [Xx] (?{ undef })
1169 | [AZa] (?{ 'something' })
1170 | C (?{ 214 })
1171 | c (?{ 114 })
1172 | [Bb] (?{ '101' })
1173 | [Hh] (?{ 'b8' })
92d41999 1174 | [svnSiIlVNLqQjJ] (?{ 10111 })
206947d2 1175 | [FfDd] (?{ 1.36514538e67 })
1176 | [pP] (?{ "try this buffer" })
1177 /x; $^R } @codes;
1178 my @end = (0x12345678, 0x23456781, 0x35465768, 0x15263748);
1179 my $end = "N4";
1180
1181 for my $type (@codes) {
1182 my @list = $val{$type};
1183 @list = () unless defined $list[0];
1184 for my $count ('', '3', '[11]') {
1185 my $c = 1;
1186 $c = $1 if $count =~ /(\d+)/;
1187 my @list1 = @list;
1188 @list1 = (@list1) x $c unless $type =~ /[XxAaZBbHhP]/;
1189 for my $groupend ('', ')2', ')[8]') {
1190 my $groupbegin = ($groupend ? '(' : '');
1191 $c = 1;
1192 $c = $1 if $groupend =~ /(\d+)/;
1193 my @list2 = (@list1) x $c;
1194
1109a392 1195 SKIP: {
1196 my $junk1 = "$groupbegin $type$count $groupend";
1197 # print "# junk1=$junk1\n";
1198 my $p = eval { pack $junk1, @list2 };
1199 skip "cannot pack '$type' on this perl", 12
1200 if is_valid_error($@);
1201
1202 my $half = int( (length $p)/2 );
1203 for my $move ('', "X$half", "X!$half", 'x1', 'x!8', "x$half") {
1204 my $junk = "$junk1 $move";
1205 # print "# junk='$junk', list=(@list2)\n";
1206 $p = pack "$junk $end", @list2, @end;
1207 my @l = unpack "x[$junk] $end", $p;
1208 is(scalar @l, scalar @end);
1209 is("@l", "@end", "skipping x[$junk]");
1210 }
1211 }
206947d2 1212 }
1213 }
1214 }
1215}
1216
1217# / is recognized after spaces in scalar context
1218# XXXX no spaces are allowed in pack... In pack only before the slash...
1219is(scalar unpack('A /A Z20', pack 'A/A* Z20', 'bcde', 'xxxxx'), 'bcde');
1220is(scalar unpack('A /A /A Z20', '3004bcde'), 'bcde');
62f95557 1221
1222{ # X! and x!
1223 my $t = 'C[3] x!8 C[2]';
1224 my @a = (0x73..0x77);
1225 my $p = pack($t, @a);
1226 is($p, "\x73\x74\x75\0\0\0\0\0\x76\x77");
1227 my @b = unpack $t, $p;
1228 is(scalar @b, scalar @a);
1229 is("@b", "@a", 'x!8');
1230 $t = 'x[5] C[6] X!8 C[2]';
1231 @a = (0x73..0x7a);
1232 $p = pack($t, @a);
1233 is($p, "\0\0\0\0\0\x73\x74\x75\x79\x7a");
1234 @b = unpack $t, $p;
1235 @a = (0x73..0x75, 0x79, 0x7a, 0x79, 0x7a);
1236 is(scalar @b, scalar @a);
1237 is("@b", "@a");
1238}
1239
1240{ # struct {char c1; double d; char cc[2];}
1241 my $t = 'C x![d] d C[2]';
1242 my @a = (173, 1.283476517e-45, 42, 215);
1243 my $p = pack $t, @a;
1244 ok( length $p);
1245 my @b = unpack "$t X[$t] $t", $p; # Extract, step back, extract again
1246 is(scalar @b, 2 * scalar @a);
3f7e3417 1247 $b = "@b";
1248 $b =~ s/(?:17000+|16999+)\d+(e-45) /17$1 /gi; # stringification is gamble
1249 is($b, "@a @a");
62f95557 1250
1251 my $warning;
1252 local $SIG{__WARN__} = sub {
1253 $warning = $_[0];
1254 };
1255 @b = unpack "x[C] x[$t] X[$t] X[C] $t", "$p\0";
1256
1257 is($warning, undef);
1258 is(scalar @b, scalar @a);
3f7e3417 1259 $b = "@b";
1260 $b =~ s/(?:17000+|16999+)\d+(e-45) /17$1 /gi; # stringification is gamble
1261 is($b, "@a");
62f95557 1262}
92d41999 1263
1264is(length(pack("j", 0)), $Config{ivsize});
1265is(length(pack("J", 0)), $Config{uvsize});
1266is(length(pack("F", 0)), $Config{nvsize});
1267
1268numbers ('j', -2147483648, -1, 0, 1, 2147483647);
1269numbers ('J', 0, 1, 2147483647, 2147483648, 4294967295);
1270numbers ('F', -(2**34), -1, 0, 1, 2**34);
1271SKIP: {
1272 my $t = eval { unpack("D*", pack("D", 12.34)) };
1273
1109a392 1274 skip "Long doubles not in use", 166 if $@ =~ /Invalid type/;
92d41999 1275
1276 is(length(pack("D", 0)), $Config{longdblsize});
1277 numbers ('D', -(2**34), -1, 0, 1, 2**34);
1278}
1279
c8f824eb 1280# Maybe this knowledge needs to be "global" for all of pack.t
1281# Or a "can checksum" which would effectively be all the number types"
1282my %cant_checksum = map {$_=> 1} qw(A Z u w);
1283# not a b B h H
1284foreach 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)) {
1285 SKIP: {
1286 my $packed = eval {pack "${template}4", 1, 4, 9, 16};
1287 if ($@) {
49704364 1288 die unless $@ =~ /Invalid type '$template'/;
c8f824eb 1289 skip ("$template not supported on this perl",
1290 $cant_checksum{$template} ? 4 : 8);
1291 }
1292 my @unpack4 = unpack "${template}4", $packed;
1293 my @unpack = unpack "${template}*", $packed;
1294 my @unpack1 = unpack "${template}", $packed;
1295 my @unpack1s = scalar unpack "${template}", $packed;
1296 my @unpack4s = scalar unpack "${template}4", $packed;
1297 my @unpacks = scalar unpack "${template}*", $packed;
1298
1299 my @tests = ( ["${template}4 vs ${template}*", \@unpack4, \@unpack],
1300 ["scalar ${template} ${template}", \@unpack1s, \@unpack1],
1301 ["scalar ${template}4 vs ${template}", \@unpack4s, \@unpack1],
1302 ["scalar ${template}* vs ${template}", \@unpacks, \@unpack1],
1303 );
1304
1305 unless ($cant_checksum{$template}) {
1306 my @unpack4_c = unpack "\%${template}4", $packed;
1307 my @unpack_c = unpack "\%${template}*", $packed;
1308 my @unpack1_c = unpack "\%${template}", $packed;
1309 my @unpack1s_c = scalar unpack "\%${template}", $packed;
1310 my @unpack4s_c = scalar unpack "\%${template}4", $packed;
1311 my @unpacks_c = scalar unpack "\%${template}*", $packed;
1312
1313 push @tests,
1314 ( ["% ${template}4 vs ${template}*", \@unpack4_c, \@unpack_c],
1315 ["% scalar ${template} ${template}", \@unpack1s_c, \@unpack1_c],
1316 ["% scalar ${template}4 vs ${template}*", \@unpack4s_c, \@unpack_c],
1317 ["% scalar ${template}* vs ${template}*", \@unpacks_c, \@unpack_c],
1318 );
1319 }
1320 foreach my $test (@tests) {
1321 ok (list_eq ($test->[1], $test->[2]), $test->[0]) ||
1322 printf "# unpack gave %s expected %s\n",
1323 encode_list (@{$test->[1]}), encode_list (@{$test->[2]});
1324 }
1325 }
1326}
9c3dc587 1327
1328ok(pack('u2', 'AA'), "[perl #8026]"); # used to hang and eat RAM in perl 5.7.2
1329
fe581ec7 1330$_ = pack('c', 65); # 'A' would not be EBCDIC-friendly
1331is(unpack('c'), 65, "one-arg unpack (change #18751)"); # defaulting to $_
db37a92e 1332
1333{
1334 my $a = "X\t01234567\n" x 100;
1335 my @a = unpack("(a1 c/a)*", $a);
1336 is(scalar @a, 200, "[perl #15288]");
1337 is($a[-1], "01234567\n", "[perl #15288]");
1338 is($a[-2], "X", "[perl #15288]");
1339}