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