This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
skip trying to constant fold an incomplete op tree
[perl5.git] / t / op / pack.t
CommitLineData
d50dd4e4 1#!./perl -w
a687059c 2
a1a0e61e
TD
3BEGIN {
4 chdir 't' if -d 't';
e99c6025 5 require './test.pl'; require './charset_tools.pl';
43ece5b1 6 set_up_inc(qw '../lib ../dist/Math-BigInt/lib');
b23b8711
MS
7}
8
d9db00a6
NC
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
12cad9bd 15plan tests => 14718;
0b568b5f 16
fa8ec7c1 17use strict;
bd7d4f4d 18use warnings qw(FATAL all);
b23b8711
MS
19use Config;
20
0b568b5f 21my $Perl = which_perl();
1109a392
MHM
22my @valid_errors = (qr/^Invalid type '\w'/);
23
24my $ByteOrder = 'unknown';
25my $maybe_not_avail = '(?:hto[bl]e|[bl]etoh)';
d9db00a6
NC
26if ($no_endianness) {
27 push @valid_errors, qr/^Invalid type '[<>]'/;
28} elsif ($Config{byteorder} =~ /^1234(?:5678)?$/) {
1109a392
MHM
29 $ByteOrder = 'little';
30 $maybe_not_avail = '(?:htobe|betoh)';
31}
32elsif ($Config{byteorder} =~ /^(?:8765)?4321$/) {
33 $ByteOrder = 'big';
34 $maybe_not_avail = '(?:htole|letoh)';
35}
36else {
37 push @valid_errors, qr/^Can't (?:un)?pack (?:big|little)-endian .*? on this platform/;
38}
39
d9db00a6
NC
40if ($no_signedness) {
41 push @valid_errors, qr/^'!' allowed only after types sSiIlLxX in (?:un)?pack/;
42}
43
1109a392 44for my $size ( 16, 32, 64 ) {
49fe901c 45 if (defined $Config{"u${size}size"} and ($Config{"u${size}size"}||0) != ($size >> 3)) {
1109a392
MHM
46 push @valid_errors, qr/^Perl_my_$maybe_not_avail$size\(\) not available/;
47 }
48}
49
50my $IsTwosComplement = pack('i', -1) eq "\xFF" x $Config{intsize};
51print "# \$IsTwosComplement = $IsTwosComplement\n";
52
53sub is_valid_error
54{
55 my $err = shift;
56
57 for my $e (@valid_errors) {
58 $err =~ $e and return 1;
59 }
60
61 return 0;
62}
c274e827 63
b85d93de 64sub encode_list {
9e17a6b8 65 my @result = map {_qq($_)} @_;
b85d93de
NC
66 if (@result == 1) {
67 return @result;
68 }
69 return '(' . join (', ', @result) . ')';
70}
71
a1a0e61e 72
b85d93de
NC
73sub list_eq ($$) {
74 my ($l, $r) = @_;
c8f824eb 75 return 0 unless @$l == @$r;
b85d93de
NC
76 for my $i (0..$#$l) {
77 if (defined $l->[$i]) {
c8f824eb 78 return 0 unless defined ($r->[$i]) && $l->[$i] eq $r->[$i];
b85d93de 79 } else {
c8f824eb 80 return 0 if defined $r->[$i]
b85d93de
NC
81 }
82 }
83 return 1;
84}
85
86##############################################################################
87#
88# Here starteth the tests
89#
90
fa8ec7c1 91{
0b568b5f
MS
92 my $format = "c2 x5 C C x s d i l a6";
93 # Need the expression in here to force ary[5] to be numeric. This avoids
94 # test2 failing because ary2 goes str->numeric->str and ary doesn't.
95 my @ary = (1,-100,127,128,32767,987.654321098 / 100.0,12345,123456,
96 "abcdef");
97 my $foo = pack($format,@ary);
98 my @ary2 = unpack($format,$foo);
99
100 is($#ary, $#ary2);
101
102 my $out1=join(':',@ary);
103 my $out2=join(':',@ary2);
104 # Using long double NVs may introduce greater accuracy than wanted.
105 $out1 =~ s/:9\.87654321097999\d*:/:9.87654321098:/;
106 $out2 =~ s/:9\.87654321097999\d*:/:9.87654321098:/;
107 is($out1, $out2);
108
109 like($foo, qr/def/);
fa8ec7c1 110}
79072805
LW
111# How about counting bits?
112
fa8ec7c1 113{
0b568b5f
MS
114 my $x;
115 is( ($x = unpack("%32B*", "\001\002\004\010\020\040\100\200\377")), 16 );
79072805 116
0b568b5f 117 is( ($x = unpack("%32b69", "\001\002\004\010\020\040\100\200\017")), 12 );
79072805 118
0b568b5f 119 is( ($x = unpack("%32B69", "\001\002\004\010\020\040\100\200\017")), 9 );
fa8ec7c1 120}
79072805 121
fa8ec7c1 122{
0b568b5f 123 my $sum = 129; # ASCII
e99c6025 124 $sum = 103 if $::IS_EBCDIC;
9d116dd7 125
0b568b5f
MS
126 my $x;
127 is( ($x = unpack("%32B*", "Now is the time for all good blurfl")), $sum );
79072805 128
0b568b5f
MS
129 my $foo;
130 open(BIN, $Perl) || die "Can't open $Perl: $!\n";
bd7d4f4d 131 binmode BIN;
0b568b5f
MS
132 sysread BIN, $foo, 8192;
133 close BIN;
79072805 134
0b568b5f
MS
135 $sum = unpack("%32b*", $foo);
136 my $longway = unpack("b*", $foo);
137 is( $sum, $longway =~ tr/1/1/ );
fa8ec7c1 138}
73a1c01a 139
fa8ec7c1
NC
140{
141 my $x;
0b568b5f 142 is( ($x = unpack("I",pack("I", 0xFFFFFFFF))), 0xFFFFFFFF );
fa8ec7c1 143}
def98dd4 144
fa8ec7c1 145{
0b568b5f
MS
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
MS
164 is(scalar(@y), 2);
165 is($y[1], 130);
a6c48a57
UP
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
NC
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
NC
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
NC
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
NC
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
NC
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
NC
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
NC
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
NC
281 eval { $x = unpack "a$mod", 'x'x8 };
282 like ($@, qr/^'$mod' allowed only after types \S+ in unpack/);
283 }
1109a392 284
d9db00a6
NC
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
NC
289 eval { $x = unpack "sI${mod}s", 'x'x16 };
290 like ($@, qr/^Can't use both '<' and '>' after type 'I' in unpack/);
291 }
1109a392
MHM
292 }
293
0258719b
NC
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)
85272d31 298 if (($^O eq 'VMS') && !defined($Config{useieee}) || !$Config{d_double_has_inf});
71f93cb9 299
b987f19e 300 skip("-- $^O has serious fp indigestion on w-packed infinities", 1)
5688dfbf 301 if (
5688dfbf
JH
302 ($^O eq 'ultrix')
303 ||
cd512f8e 304 ($^O =~ /^svr4/ && -f "/etc/issue" && -f "/etc/.relid") # NCR MP-RAS
5688dfbf 305 );
8b571b32 306
1109a392 307 my $inf = eval '2**1000000';
0258719b 308
b987f19e 309 skip("Couldn't generate infinity - got error '$@'", 1)
71b080b8 310 unless defined $inf and $inf == $inf / 2 and $inf + 1 == $inf;
0258719b 311
46ff39aa
PG
312 local our $TODO;
313 $TODO = "VOS needs a fix for posix-1022 to pass this test."
314 if ($^O eq 'vos');
315
0258719b 316 eval { $x = pack 'w', $inf };
0c7df902 317 like ($@, qr/^Cannot compress Inf/, "Cannot compress infinity");
0258719b
NC
318 }
319
320 SKIP: {
71f93cb9 321
b987f19e 322 skip("-- the full range of an IEEE double may not be available in this configuration.", 3)
85272d31 323 if (($^O eq 'VMS') && !defined($Config{useieee}) || !$Config{d_double_style_ieee});
71f93cb9 324
b987f19e 325 skip("-- $^O does not like 2**1023", 3)
ad415dae
JH
326 if (($^O eq 'ultrix'));
327
0258719b
NC
328 # This should be about the biggest thing possible on an IEEE double
329 my $big = eval '2**1023';
330
b987f19e 331 skip("Couldn't generate 2**1023 - got error '$@'", 3)
0258719b
NC
332 unless defined $big and $big != $big / 2;
333
334 eval { $x = pack 'w', $big };
335 is ($@, '', "Should be able to pack 'w', $big # 2**1023");
336
337 my $y = eval {unpack 'w', $x};
338 is ($@, '',
339 "Should be able to unpack 'w' the result of pack 'w', $big # 2**1023");
340
341 # I'm getting about 1e-16 on FreeBSD
342 my $quotient = int (100 * ($y - $big) / $big);
343 ok($quotient < 2 && $quotient > -2,
1109a392 344 "Round trip pack, unpack 'w' of $big is within 1% ($quotient%)");
0258719b
NC
345 }
346
fa8ec7c1 347}
def98dd4 348
40837afc 349print "# test the 'p' template\n";
84902520
TB
350
351# literals
0b568b5f 352is(unpack("p",pack("p","foo")), "foo");
d9db00a6
NC
353SKIP: {
354 skip $no_endianness, 2 if $no_endianness;
355 is(unpack("p<",pack("p<","foo")), "foo");
356 is(unpack("p>",pack("p>","foo")), "foo");
357}
84902520 358# scalars
0b568b5f 359is(unpack("p",pack("p",239)), 239);
d9db00a6
NC
360SKIP: {
361 skip $no_endianness, 2 if $no_endianness;
362 is(unpack("p<",pack("p<",239)), 239);
363 is(unpack("p>",pack("p>",239)), 239);
364}
84902520
TB
365
366# temps
367sub foo { my $a = "a"; return $a . $a++ . $a++ }
368{
bd7d4f4d 369 use warnings qw(NONFATAL all);;
0b568b5f 370 my $warning;
84902520 371 local $SIG{__WARN__} = sub {
0b568b5f 372 $warning = $_[0];
84902520
TB
373 };
374 my $junk = pack("p", &foo);
0b568b5f
MS
375
376 like($warning, qr/temporary val/);
84902520
TB
377}
378
379# undef should give null pointer
1109a392 380like(pack("p", undef), qr/^\0+$/);
d9db00a6
NC
381SKIP: {
382 skip $no_endianness, 2 if $no_endianness;
383 like(pack("p<", undef), qr/^\0+$/);
384 like(pack("p>", undef), qr/^\0+$/);
385}
84902520 386
20408e3c
GS
387# Check for optimizer bug (e.g. Digital Unix GEM cc with -O4 on DU V4.0B gives
388# 4294967295 instead of -1)
389# see #ifdef __osf__ in pp.c pp_unpack
0b568b5f 390is((unpack("i",pack("i",-1))), -1);
20408e3c 391
1109a392
MHM
392print "# test the pack lengths of s S i I l L n N v V + modifiers\n";
393
394my @lengths = (
395 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),
396 's!' => $Config{shortsize}, 'S!' => $Config{shortsize},
397 'i!' => $Config{intsize}, 'I!' => $Config{intsize},
398 'l!' => $Config{longsize}, 'L!' => $Config{longsize},
399);
400
401while (my ($base, $expect) = splice @lengths, 0, 2) {
402 my @formats = ($base);
403 $base =~ /^[nv]/i or push @formats, "$base>", "$base<";
404 for my $format (@formats) {
d9db00a6
NC
405 SKIP: {
406 skip $no_endianness, 1 if $no_endianness && $format =~ m/[<>]/;
407 skip $no_signedness, 1 if $no_signedness && $format =~ /[nNvV]!/;
408 my $len = length(pack($format, 0));
409 if ($expect > 0) {
410 is($expect, $len, "format '$format'");
411 } else {
412 $expect = -$expect;
413 ok ($len >= $expect, "format '$format'") ||
414 print "# format '$format' has length $len, expected >= $expect\n";
415 }
1109a392 416 }
fa8ec7c1
NC
417 }
418}
d4217c7e 419
d4217c7e 420
40837afc
NC
421print "# test unpack-pack lengths\n";
422
f337b084 423my @templates = qw(c C W i I s S l L n N v V f d q Q);
d4217c7e 424
1109a392
MHM
425foreach my $base (@templates) {
426 my @tmpl = ($base);
f337b084 427 $base =~ /^[cwnv]/i or push @tmpl, "$base>", "$base<";
1109a392
MHM
428 foreach my $t (@tmpl) {
429 SKIP: {
430 my @t = eval { unpack("$t*", pack("$t*", 12, 34)) };
0b568b5f 431
1109a392
MHM
432 skip "cannot pack '$t' on this perl", 4
433 if is_valid_error($@);
3020ec7a 434
86704b5f 435 is( $@, '', "Template $t works");
1109a392 436 is(scalar @t, 2);
3020ec7a 437
0b568b5f
MS
438 is($t[0], 12);
439 is($t[1], 34);
440 }
0b568b5f 441 }
d4217c7e 442}
9d116dd7 443
fa8ec7c1 444{
0b568b5f 445 # uuencode/decode
9d116dd7 446
0b568b5f
MS
447 # Note that first uuencoding known 'text' data and then checking the
448 # binary values of the uuencoded version would not be portable between
449 # character sets. Uuencoding is meant for encoding binary data, not
450 # text data.
c4d5f83a 451
0b568b5f 452 my $in = pack 'C*', 0 .. 255;
ba1ac976 453
0b568b5f
MS
454 # just to be anal, we do some random tr/`/ /
455 my $uu = <<'EOUU';
ba1ac976 456M` $"`P0%!@<("0H+# T.#Q`1$A,4%187&!D:&QP='A\@(2(C)"4F)R@I*BLL
9d116dd7
JH
457M+2XO,#$R,S0U-C<X.3H[/#T^/T!!0D-$149'2$E*2TQ-3D]045)35%565UA9
458M6EM<75Y?8&%B8V1E9F=H:6IK;&UN;W!Q<G-T=79W>'EZ>WQ]?G^`@8*#A(6&
459MAXB)BHN,C8Z/D)&2DY25EI>8F9J;G)V>GZ"AHJ.DI::GJ*FJJZRMKJ^PL;*S
460MM+6VM[BYNKN\O;Z_P,'"P\3%QL?(R<K+S,W.S]#1TM/4U=;7V-G:V]S=WM_@
ba1ac976 461?X>+CY.7FY^CIZNOL[>[O\/'R\_3U]O?X^?K[_/W^_P `
9d116dd7
JH
462EOUU
463
0b568b5f
MS
464 $_ = $uu;
465 tr/ /`/;
9d116dd7 466
0b568b5f 467 is(pack('u', $in), $_);
fa8ec7c1 468
0b568b5f 469 is(unpack('u', $uu), $in);
9d116dd7 470
0b568b5f
MS
471 $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";
472 $uu = <<'EOUU';
eddc390b
JH
473M'XL("%C<Q#4"`TI!4%4`\RHM+E%(S,LOR4@M4@A(+<I1*"U-SD])+>("`&1F
474&8%P:````
475EOUU
476
0b568b5f 477 is(unpack('u', $uu), $in);
eddc390b 478
0b568b5f
MS
479# This is identical to the above except that backquotes have been
480# changed to spaces
eddc390b 481
0b568b5f 482 $uu = <<'EOUU';
eddc390b 483M'XL("%C<Q#4" TI!4%4 \RHM+E%(S,LOR4@M4@A(+<I1*"U-SD])+>(" &1F
c4d5f83a 484&8%P:
eddc390b
JH
485EOUU
486
0b568b5f
MS
487 # ' # Grr
488 is(unpack('u', $uu), $in);
ef54e1a4 489
d99ad34e 490}
726ea183 491
0b568b5f 492# test the ascii template types (A, a, Z)
726ea183 493
fa8ec7c1 494foreach (
0b568b5f 495['p', 'A*', "foo\0bar\0 ", "foo\0bar\0 "],
fa8ec7c1 496['p', 'A11', "foo\0bar\0 ", "foo\0bar\0 "],
0b568b5f
MS
497['u', 'A*', "foo\0bar \0", "foo\0bar"],
498['u', 'A8', "foo\0bar \0", "foo\0bar"],
499['p', 'a*', "foo\0bar\0 ", "foo\0bar\0 "],
fa8ec7c1 500['p', 'a11', "foo\0bar\0 ", "foo\0bar\0 \0\0"],
0b568b5f
MS
501['u', 'a*', "foo\0bar \0", "foo\0bar \0"],
502['u', 'a8', "foo\0bar \0", "foo\0bar "],
503['p', 'Z*', "foo\0bar\0 ", "foo\0bar\0 \0"],
fa8ec7c1 504['p', 'Z11', "foo\0bar\0 ", "foo\0bar\0 \0\0"],
0b568b5f
MS
505['p', 'Z3', "foo", "fo\0"],
506['u', 'Z*', "foo\0bar \0", "foo"],
507['u', 'Z8', "foo\0bar \0", "foo"],
28be1210 508)
0b568b5f
MS
509{
510 my ($what, $template, $in, $out) = @$_;
511 my $got = $what eq 'u' ? (unpack $template, $in) : (pack $template, $in);
512 unless (is($got, $out)) {
0b568b5f 513 my $un = $what eq 'u' ? 'un' : '';
9e17a6b8
NC
514 print "# ${un}pack ('$template', "._qq($in).') gave '._qq($out).
515 ' not '._qq($got)."\n";
0b568b5f 516 }
d99ad34e 517}
726ea183 518
40837afc 519print "# packing native shorts/ints/longs\n";
726ea183 520
0b568b5f
MS
521is(length(pack("s!", 0)), $Config{shortsize});
522is(length(pack("i!", 0)), $Config{intsize});
523is(length(pack("l!", 0)), $Config{longsize});
524ok(length(pack("s!", 0)) <= length(pack("i!", 0)));
525ok(length(pack("i!", 0)) <= length(pack("l!", 0)));
526is(length(pack("i!", 0)), length(pack("i", 0)));
726ea183 527
fa8ec7c1 528sub numbers {
1109a392
MHM
529 my $base = shift;
530 my @formats = ($base);
531 $base =~ /^[silqjfdp]/i and push @formats, "$base>", "$base<";
532 for my $format (@formats) {
533 numbers_with_total ($format, undef, @_);
534 }
d99ad34e 535}
726ea183 536
fa8ec7c1
NC
537sub numbers_with_total {
538 my $format = shift;
539 my $total = shift;
540 if (!defined $total) {
541 foreach (@_) {
542 $total += $_;
543 }
544 }
40837afc 545 print "# numbers test for $format\n";
fa8ec7c1 546 foreach (@_) {
0b568b5f
MS
547 SKIP: {
548 my $out = eval {unpack($format, pack($format, $_))};
1109a392
MHM
549 skip "cannot pack '$format' on this perl", 2
550 if is_valid_error($@);
0b568b5f 551
96b96e00
NC
552 is($@, '', "no error");
553 is($out, $_, "unpack pack $format $_");
fa8ec7c1 554 }
fa8ec7c1 555 }
726ea183 556
fa8ec7c1
NC
557 my $skip_if_longer_than = ~0; # "Infinity"
558 if (~0 - 1 == ~0) {
559 # If we're running with -DNO_PERLPRESERVE_IVUV and NVs don't preserve all
560 # UVs (in which case ~0 is NV, ~0-1 will be the same NV) then we can't
561 # correctly in perl calculate UV totals for long checksums, as pp_unpack
562 # is using UV maths, and we've only got NVs.
53133ed1 563 $skip_if_longer_than = $Config{nv_preserves_uv_bits};
fa8ec7c1 564 }
726ea183 565
fa8ec7c1 566 foreach ('', 1, 2, 3, 15, 16, 17, 31, 32, 33, 53, 54, 63, 64, 65) {
0b568b5f
MS
567 SKIP: {
568 my $sum = eval {unpack "%$_$format*", pack "$format*", @_};
569 skip "cannot pack '$format' on this perl", 3
1109a392 570 if is_valid_error($@);
0b568b5f 571
96b96e00
NC
572 is($@, '', "no error");
573 ok(defined $sum, "sum bits $_, format $format defined");
0b568b5f
MS
574
575 my $len = $_; # Copy, so that we can reassign ''
576 $len = 16 unless length $len;
577
578 SKIP: {
579 skip "cannot test checksums over $skip_if_longer_than bits", 1
580 if $len > $skip_if_longer_than;
581
582 # Our problem with testing this portably is that the checksum code in
583 # pp_unpack is able to cast signed to unsigned, and do modulo 2**n
584 # arithmetic in unsigned ints, which perl has no operators to do.
585 # (use integer; does signed ints, which won't wrap on UTS, which is just
586 # fine with ANSI, but not with most people's assumptions.
587 # This is why we need to supply the totals for 'Q' as there's no way in
588 # perl to calculate them, short of unpack '%0Q' (is that documented?)
589 # ** returns NVs; make sure it's IV.
590 my $max = 1 + 2 * (int (2 ** ($len-1))-1); # The max possible checksum
591 my $max_p1 = $max + 1;
592 my ($max_is_integer, $max_p1_is_integer);
593 $max_p1_is_integer = 1 unless $max_p1 + 1 == $max_p1;
594 $max_is_integer = 1 if $max - 1 < ~0;
595
596 my $calc_sum;
597 if (ref $total) {
598 $calc_sum = &$total($len);
599 } else {
600 $calc_sum = $total;
601 # Shift into range by some multiple of the total
53f3fd80 602 my $mult = $max_p1 ? int ($total / $max_p1) : undef;
0b568b5f
MS
603 # Need this to make sure that -1 + (~0+1) is ~0 (ie still integer)
604 $calc_sum = $total - $mult;
605 $calc_sum -= $mult * $max;
606 if ($calc_sum < 0) {
607 $calc_sum += 1;
608 $calc_sum += $max;
609 }
610 }
611 if ($calc_sum == $calc_sum - 1 && $calc_sum == $max_p1) {
612 # we're into floating point (either by getting out of the range of
28be1210 613 # UV arithmetic, or because we're doing a floating point checksum)
0b568b5f
MS
614 # and our calculation of the checksum has become rounded up to
615 # max_checksum + 1
616 $calc_sum = 0;
617 }
618
0dccb3d1 619 if ($calc_sum == $sum) { # HAS to be ==, not eq (so no is()).
96b96e00 620 pass ("unpack '%$_$format' gave $sum");
0b568b5f
MS
621 } else {
622 my $delta = 1.000001;
623 if ($format =~ tr /dDfF//
624 && ($calc_sum <= $sum * $delta && $calc_sum >= $sum / $delta)) {
0dccb3d1 625 pass ("unpack '%$_$format' gave $sum, expected $calc_sum");
0b568b5f
MS
626 } else {
627 my $text = ref $total ? &$total($len) : $total;
628 fail;
629 print "# For list (" . join (", ", @_) . ") (total $text)"
630 . " packed with $format unpack '%$_$format' gave $sum,"
631 . " expected $calc_sum\n";
632 }
633 }
fa8ec7c1 634 }
96b96e00 635 }
2e821511
NC
636 }
637}
638
fa8ec7c1
NC
639numbers ('c', -128, -1, 0, 1, 127);
640numbers ('C', 0, 1, 127, 128, 255);
f337b084 641numbers ('W', 0, 1, 127, 128, 255, 256, 0x7ff, 0x800, 0xfffd);
fa8ec7c1
NC
642numbers ('s', -32768, -1, 0, 1, 32767);
643numbers ('S', 0, 1, 32767, 32768, 65535);
644numbers ('i', -2147483648, -1, 0, 1, 2147483647);
645numbers ('I', 0, 1, 2147483647, 2147483648, 4294967295);
646numbers ('l', -2147483648, -1, 0, 1, 2147483647);
647numbers ('L', 0, 1, 2147483647, 2147483648, 4294967295);
648numbers ('s!', -32768, -1, 0, 1, 32767);
649numbers ('S!', 0, 1, 32767, 32768, 65535);
650numbers ('i!', -2147483648, -1, 0, 1, 2147483647);
651numbers ('I!', 0, 1, 2147483647, 2147483648, 4294967295);
652numbers ('l!', -2147483648, -1, 0, 1, 2147483647);
653numbers ('L!', 0, 1, 2147483647, 2147483648, 4294967295);
654numbers ('n', 0, 1, 32767, 32768, 65535);
655numbers ('v', 0, 1, 32767, 32768, 65535);
656numbers ('N', 0, 1, 2147483647, 2147483648, 4294967295);
657numbers ('V', 0, 1, 2147483647, 2147483648, 4294967295);
068bd2e7
MHM
658numbers ('n!', -32768, -1, 0, 1, 32767);
659numbers ('v!', -32768, -1, 0, 1, 32767);
660numbers ('N!', -2147483648, -1, 0, 1, 2147483647);
661numbers ('V!', -2147483648, -1, 0, 1, 2147483647);
fa8ec7c1
NC
662# All these should have exact binary representations:
663numbers ('f', -1, 0, 0.5, 42, 2**34);
b85d93de
NC
664numbers ('d', -(2**34), -1, 0, 1, 2**34);
665## These don't, but 'd' is NV. XXX wrong, it's double
666#numbers ('d', -1, 0, 1, 1-exp(-1), -exp(1));
fa8ec7c1
NC
667
668numbers_with_total ('q', -1,
669 -9223372036854775808, -1, 0, 1,9223372036854775807);
800e6488 670# This total is icky, but the true total is 2**65-1, and need a way to generate
93f09d7b 671# the expected checksum on any system including those where NVs can preserve
800e6488
JH
672# 65 bits. (long double is 128 bits on sparc, so they certainly can)
673# or where rounding is down not up on binary conversion (crays)
674numbers_with_total ('Q', sub {
675 my $len = shift;
676 $len = 65 if $len > 65; # unmasked total is 2**65-1 here
677 my $total = 1 + 2 * (int (2**($len - 1)) - 1);
678 return 0 if $total == $total - 1; # Overflowed integers
679 return $total; # NVs still accurate to nearest integer
680 },
fa8ec7c1
NC
681 0, 1,9223372036854775807, 9223372036854775808,
682 18446744073709551615);
683
40837afc 684print "# pack nvNV byteorders\n";
fa8ec7c1 685
0b568b5f
MS
686is(pack("n", 0xdead), "\xde\xad");
687is(pack("v", 0xdead), "\xad\xde");
688is(pack("N", 0xdeadbeef), "\xde\xad\xbe\xef");
689is(pack("V", 0xdeadbeef), "\xef\xbe\xad\xde");
43192e07 690
d9db00a6
NC
691SKIP: {
692 skip $no_signedness, 4 if $no_signedness;
693 is(pack("n!", 0xdead), "\xde\xad");
694 is(pack("v!", 0xdead), "\xad\xde");
695 is(pack("N!", 0xdeadbeef), "\xde\xad\xbe\xef");
696 is(pack("V!", 0xdeadbeef), "\xef\xbe\xad\xde");
697}
068bd2e7 698
1109a392
MHM
699print "# test big-/little-endian conversion\n";
700
701sub byteorder
702{
703 my $format = shift;
704 print "# byteorder test for $format\n";
705 for my $value (@_) {
706 SKIP: {
707 my($nat,$be,$le) = eval { map { pack $format.$_, $value } '', '>', '<' };
708 skip "cannot pack '$format' on this perl", 5
709 if is_valid_error($@);
710
90d0f5d9
RGS
711 {
712 use warnings qw(NONFATAL utf8);
713 print "# [$value][$nat][$be][$le][$@]\n";
714 }
1109a392
MHM
715
716 SKIP: {
717 skip "cannot compare native byteorder with big-/little-endian", 1
718 if $ByteOrder eq 'unknown';
719
720 is($nat, $ByteOrder eq 'big' ? $be : $le);
721 }
722 is($be, reverse($le));
723 my @x = eval { unpack "$format$format>$format<", $nat.$be.$le };
724
725 print "# [$value][", join('][', @x), "][$@]\n";
726
727 is($@, '');
728 is($x[0], $x[1]);
729 is($x[0], $x[2]);
730 }
731 }
732}
733
734byteorder('s', -32768, -1, 0, 1, 32767);
735byteorder('S', 0, 1, 32767, 32768, 65535);
736byteorder('i', -2147483648, -1, 0, 1, 2147483647);
737byteorder('I', 0, 1, 2147483647, 2147483648, 4294967295);
738byteorder('l', -2147483648, -1, 0, 1, 2147483647);
739byteorder('L', 0, 1, 2147483647, 2147483648, 4294967295);
740byteorder('j', -2147483648, -1, 0, 1, 2147483647);
741byteorder('J', 0, 1, 2147483647, 2147483648, 4294967295);
742byteorder('s!', -32768, -1, 0, 1, 32767);
743byteorder('S!', 0, 1, 32767, 32768, 65535);
744byteorder('i!', -2147483648, -1, 0, 1, 2147483647);
745byteorder('I!', 0, 1, 2147483647, 2147483648, 4294967295);
746byteorder('l!', -2147483648, -1, 0, 1, 2147483647);
747byteorder('L!', 0, 1, 2147483647, 2147483648, 4294967295);
748byteorder('q', -9223372036854775808, -1, 0, 1, 9223372036854775807);
749byteorder('Q', 0, 1, 9223372036854775807, 9223372036854775808, 18446744073709551615);
750byteorder('f', -1, 0, 0.5, 42, 2**34);
751byteorder('F', -1, 0, 0.5, 42, 2**34);
752byteorder('d', -(2**34), -1, 0, 1, 2**34);
753byteorder('D', -(2**34), -1, 0, 1, 2**34);
754
755print "# test negative numbers\n";
756
757SKIP: {
758 skip "platform is not using two's complement for negative integers", 120
759 unless $IsTwosComplement;
760
761 for my $format (qw(s i l j s! i! l! q)) {
762 SKIP: {
763 my($nat,$be,$le) = eval { map { pack $format.$_, -1 } '', '>', '<' };
764 skip "cannot pack '$format' on this perl", 15
765 if is_valid_error($@);
766
767 my $len = length $nat;
768 is($_, "\xFF"x$len) for $nat, $be, $le;
769
770 my(@val,@ref);
771 if ($len >= 8) {
772 @val = (-2, -81985529216486896, -9223372036854775808);
773 @ref = ("\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFE",
774 "\xFE\xDC\xBA\x98\x76\x54\x32\x10",
775 "\x80\x00\x00\x00\x00\x00\x00\x00");
776 }
777 elsif ($len >= 4) {
778 @val = (-2, -19088744, -2147483648);
779 @ref = ("\xFF\xFF\xFF\xFE",
780 "\xFE\xDC\xBA\x98",
781 "\x80\x00\x00\x00");
782 }
783 else {
784 @val = (-2, -292, -32768);
785 @ref = ("\xFF\xFE",
786 "\xFE\xDC",
787 "\x80\x00");
788 }
789 for my $x (@ref) {
790 if ($len > length $x) {
791 $x = $x . "\xFF" x ($len - length $x);
792 }
793 }
794
795 for my $i (0 .. $#val) {
796 my($nat,$be,$le) = eval { map { pack $format.$_, $val[$i] } '', '>', '<' };
797 is($@, '');
798
799 SKIP: {
800 skip "cannot compare native byteorder with big-/little-endian", 1
801 if $ByteOrder eq 'unknown';
802
803 is($nat, $ByteOrder eq 'big' ? $be : $le);
804 }
805
806 is($be, $ref[$i]);
807 is($be, reverse($le));
808 }
809 }
810 }
811}
812
fa8ec7c1
NC
813{
814 # /
815
21361d07 816 my ($x, $y, $z, @a);
fa8ec7c1 817 eval { ($x) = unpack '/a*','hello' };
49704364 818 like($@, qr!'/' must follow a numeric type!);
72b034c3
NC
819 undef $x;
820 eval { $x = unpack '/a*','hello' };
49704364 821 like($@, qr!'/' must follow a numeric type!);
0b568b5f 822
21361d07
MHM
823 # [perl #60204] Unhelpful error message from unpack
824 eval { @a = unpack 'v/a*','h' };
825 is($@, '');
826 is(scalar @a, 0);
827 eval { $x = unpack 'v/a*','h' };
828 is($@, '');
829 is($x, undef);
830
72b034c3 831 undef $x;
fa8ec7c1 832 eval { ($z,$x,$y) = unpack 'a3/A C/a* C/Z', "003ok \003yes\004z\000abc" };
0b568b5f
MS
833 is($@, '');
834 is($z, 'ok');
835 is($x, 'yes');
836 is($y, 'z');
72b034c3
NC
837 undef $z;
838 eval { $z = unpack 'a3/A C/a* C/Z', "003ok \003yes\004z\000abc" };
839 is($@, '');
840 is($z, 'ok');
841
fa8ec7c1 842
72b034c3 843 undef $x;
fa8ec7c1 844 eval { ($x) = pack '/a*','hello' };
49704364 845 like($@, qr!Invalid type '/'!);
72b034c3
NC
846 undef $x;
847 eval { $x = pack '/a*','hello' };
49704364 848 like($@, qr!Invalid type '/'!);
fa8ec7c1
NC
849
850 $z = pack 'n/a* N/Z* w/A*','string','hi there ','etc';
851 my $expect = "\000\006string\0\0\0\012hi there \000\003etc";
0b568b5f 852 is($z, $expect);
4b5b2118 853
72b034c3 854 undef $x;
b85d93de
NC
855 $expect = 'hello world';
856 eval { ($x) = unpack ("w/a", chr (11) . "hello world!")};
0b568b5f
MS
857 is($x, $expect);
858 is($@, '');
859
72b034c3 860 undef $x;
b85d93de
NC
861 # Doing this in scalar context used to fail.
862 eval { $x = unpack ("w/a", chr (11) . "hello world!")};
0b568b5f
MS
863 is($@, '');
864 is($x, $expect);
b85d93de 865
fa8ec7c1 866 foreach (
0b568b5f
MS
867 ['a/a*/a*', '212ab345678901234567','ab3456789012'],
868 ['a/a*/a*', '3012ab345678901234567', 'ab3456789012'],
e99c6025 869 ['a/a*/b*', '212ab', $::IS_EBCDIC ? '100000010100' : '100001100100'],
28be1210 870 )
0b568b5f 871 {
fa8ec7c1 872 my ($pat, $in, $expect) = @$_;
72b034c3 873 undef $x;
fa8ec7c1 874 eval { ($x) = unpack $pat, $in };
0b568b5f 875 is($@, '');
28be1210 876 is($x, $expect) ||
0b568b5f
MS
877 printf "# list unpack ('$pat', '$in') gave %s, expected '$expect'\n",
878 encode_list ($x);
879
72b034c3 880 undef $x;
b85d93de 881 eval { $x = unpack $pat, $in };
0b568b5f
MS
882 is($@, '');
883 is($x, $expect) ||
884 printf "# scalar unpack ('$pat', '$in') gave %s, expected '$expect'\n",
885 encode_list ($x);
fa8ec7c1 886 }
4b5b2118 887
0b568b5f 888 # / with #
17f4a12d 889
72b034c3 890 my $pattern = <<'EOU';
17f4a12d
IZ
891 a3/A # Count in ASCII
892 C/a* # Count in a C char
893 C/Z # Count in a C char but skip after \0
894EOU
17f4a12d 895
72b034c3
NC
896 $x = $y = $z =undef;
897 eval { ($z,$x,$y) = unpack $pattern, "003ok \003yes\004z\000abc" };
0b568b5f
MS
898 is($@, '');
899 is($z, 'ok');
900 is($x, 'yes');
901 is($y, 'z');
72b034c3
NC
902 undef $x;
903 eval { $z = unpack $pattern, "003ok \003yes\004z\000abc" };
904 is($@, '');
905 is($z, 'ok');
0b568b5f 906
72b034c3 907 $pattern = <<'EOP';
17f4a12d
IZ
908 n/a* # Count as network short
909 w/A* # Count a BER integer
910EOP
fa8ec7c1 911 $expect = "\000\006string\003etc";
72b034c3 912 $z = pack $pattern,'string','etc';
9e17a6b8 913 is($z, $expect);
fa8ec7c1
NC
914}
915
60a99fa7 916
e99c6025
KW
917{
918 is("1.20.300.4000", sprintf "%vd", pack("U*",utf8::native_to_unicode(1),utf8::native_to_unicode(20),300,4000));
919 is("1.20.300.4000", sprintf "%vd", pack(" U*",utf8::native_to_unicode(1),utf8::native_to_unicode(20),300,4000));
60a99fa7 920}
e99c6025 921isnt(v1.20.300.4000, sprintf "%vd", pack("C0U*",utf8::native_to_unicode(1),utf8::native_to_unicode(20),300,4000));
fa8ec7c1 922
e99c6025
KW
923my $rslt = join " ", map { ord } split "", byte_utf8a_to_utf8n("\xc7\xa2");
924# The ASCII UTF-8 of U+1E2 is "\xc7\xa2"
1651fc44 925is(join(" ", unpack("U0 C*", chr(0x1e2))), $rslt);
fa8ec7c1
NC
926
927# does pack U create Unicode?
0b568b5f 928is(ord(pack('U', 300)), 300);
fa8ec7c1
NC
929
930# does unpack U deref Unicode?
0b568b5f 931is((unpack('U', chr(300)))[0], 300);
fa8ec7c1
NC
932
933# is unpack U the reverse of pack U for Unicode string?
0b568b5f 934is("@{[unpack('U*', pack('U*', 100, 200, 300))]}", "100 200 300");
fa8ec7c1
NC
935
936# is unpack U the reverse of pack U for byte string?
0b568b5f
MS
937is("@{[unpack('U*', pack('U*', 100, 200))]}", "100 200");
938
26773d9d 939{
7eed2ccc 940 # does pack U0C create Unicode?
e99c6025
KW
941 my $cp202 = chr(202);
942 utf8::upgrade $cp202;
943 my @bytes202;
944 { # This is portable across character sets
945 use bytes;
946 @bytes202 = map { ord } split "", $cp202;
947 }
26773d9d
KW
948
949 # This test requires the first number to be invariant; 64 is invariant on
950 # ASCII and EBCDIC.
951 is("@{[pack('U0C*', 64, @bytes202)]}", v64.v202);
fa8ec7c1 952
7eed2ccc 953 # does pack C0U create characters?
26773d9d
KW
954 # The U* is expecting Unicode, so convert to that.
955 is("@{[pack('C0U*', map { utf8::native_to_unicode($_) } 64, 202)]}",
956 pack("C*", 64, @bytes202));
fa8ec7c1 957
fd879d93
KW
958 # does unpack U0U on byte data fail?
959 fresh_perl_like('my $bad = pack("U0C", 202); my @null = unpack("U0U", $bad);',
960 qr/^Malformed UTF-8 character: /,
961 {},
962 "pack doesn't return malformed UTF-8");
35bcd338
JH
963}
964
fa8ec7c1
NC
965{
966 my $p = pack 'i*', -2147483648, ~0, 0, 1, 2147483647;
967 my (@a);
968 # bug - % had to be at the start of the pattern, no leading whitespace or
969 # comments. %i! didn't work at all.
970 foreach my $pat ('%32i*', ' %32i*', "# Muhahahaha\n%32i*", '%32i* ',
971 '%32i!*', ' %32i!*', "\n#\n#\n\r \t\f%32i!*", '%32i!*#') {
972 @a = unpack $pat, $p;
0b568b5f 973 is($a[0], 0xFFFFFFFF) || print "# $pat\n";
fa8ec7c1 974 @a = scalar unpack $pat, $p;
0b568b5f 975 is($a[0], 0xFFFFFFFF) || print "# $pat\n";
fa8ec7c1
NC
976 }
977
978
979 $p = pack 'I*', 42, 12;
980 # Multiline patterns in scalar context failed.
981 foreach my $pat ('I', <<EOPOEMSNIPPET, 'I#I', 'I # I', 'I # !!!') {
982# On the Ning Nang Nong
983# Where the Cows go Bong!
984# And the Monkeys all say Boo!
985I
986EOPOEMSNIPPET
0b568b5f
MS
987 @a = unpack $pat, $p;
988 is(scalar @a, 1);
989 is($a[0], 42);
990 @a = scalar unpack $pat, $p;
991 is(scalar @a, 1);
992 is($a[0], 42);
993 }
fa8ec7c1
NC
994
995 # shorts (of all flavours) didn't calculate checksums > 32 bits with floating
996 # point, so a pathologically long pattern would wrap at 32 bits.
997 my $pat = "\xff\xff"x65538; # Start with it long, to save any copying.
998 foreach (4,3,2,1,0) {
999 my $len = 65534 + $_;
0b568b5f 1000 is(unpack ("%33n$len", $pat), 65535 * $len);
fa8ec7c1
NC
1001 }
1002}
b85d93de
NC
1003
1004
1005# pack x X @
1006foreach (
0b568b5f
MS
1007 ['x', "N", "\0"],
1008 ['x4', "N", "\0"x4],
1009 ['xX', "N", ""],
1010 ['xXa*', "Nick", "Nick"],
1011 ['a5Xa5', "cameL", "llama", "camellama"],
1012 ['@4', 'N', "\0"x4],
1013 ['a*@8a*', 'Camel', 'Dromedary', "Camel\0\0\0Dromedary"],
1014 ['a*@4a', 'Perl rules', '!', 'Perl!'],
28be1210 1015)
0b568b5f 1016{
b85d93de
NC
1017 my ($template, @in) = @$_;
1018 my $out = pop @in;
1019 my $got = eval {pack $template, @in};
0b568b5f
MS
1020 is($@, '');
1021 is($out, $got) ||
1022 printf "# pack ('$template', %s) gave %s expected %s\n",
1023 encode_list (@in), encode_list ($got), encode_list ($out);
b85d93de
NC
1024}
1025
1026# unpack x X @
1027foreach (
0b568b5f
MS
1028 ['x', "N"],
1029 ['xX', "N"],
1030 ['xXa*', "Nick", "Nick"],
1031 ['a5Xa5', "camellama", "camel", "llama"],
1032 ['@3', "ice"],
1033 ['@2a2', "water", "te"],
1034 ['a*@1a3', "steam", "steam", "tea"],
28be1210 1035)
0b568b5f 1036{
b85d93de
NC
1037 my ($template, $in, @out) = @$_;
1038 my @got = eval {unpack $template, $in};
0b568b5f 1039 is($@, '');
c8f824eb 1040 ok (list_eq (\@got, \@out)) ||
9e17a6b8
NC
1041 printf "# list unpack ('$template', %s) gave %s expected %s\n",
1042 _qq($in), encode_list (@got), encode_list (@out);
b85d93de
NC
1043
1044 my $got = eval {unpack $template, $in};
0b568b5f
MS
1045 is($@, '');
1046 @out ? is( $got, $out[0] ) # 1 or more items; should get first
1047 : ok( !defined $got ) # 0 items; should get undef
9e17a6b8
NC
1048 or printf "# scalar unpack ('$template', %s) gave %s expected %s\n",
1049 _qq($in), encode_list ($got), encode_list ($out[0]);
b85d93de 1050}
d50dd4e4
JH
1051
1052{
d50dd4e4
JH
1053 my $t = 'Z*Z*';
1054 my ($u, $v) = qw(foo xyzzy);
1055 my $p = pack($t, $u, $v);
1056 my @u = unpack($t, $p);
0b568b5f
MS
1057 is(scalar @u, 2);
1058 is($u[0], $u);
1059 is($u[1], $v);
d50dd4e4 1060}
bf80f5a2
JH
1061
1062{
0b568b5f 1063 is((unpack("w/a*", "\x02abc"))[0], "ab");
bf80f5a2 1064
0b568b5f 1065 # "w/a*" should be seen as one unit
bf80f5a2 1066
0b568b5f 1067 is(scalar unpack("w/a*", "\x02abc"), "ab");
bf80f5a2 1068}
b81060d6 1069
d9db00a6 1070SKIP: {
66c611c5
MHM
1071 print "# group modifiers\n";
1072
d9db00a6
NC
1073 skip $no_endianness, 3 * 2 + 3 * 2 + 1 if $no_endianness;
1074
66c611c5
MHM
1075 for my $t (qw{ (s<)< (sl>s)> (s(l(sl)<l)s)< }) {
1076 print "# testing pattern '$t'\n";
1077 eval { ($_) = unpack($t, 'x'x18); };
1078 is($@, '');
1079 eval { $_ = pack($t, (0)x6); };
1080 is($@, '');
1081 }
1082
1083 for my $t (qw{ (s<)> (sl>s)< (s(l(sl)<l)s)> }) {
1084 print "# testing pattern '$t'\n";
1085 eval { ($_) = unpack($t, 'x'x18); };
1086 like($@, qr/Can't use '[<>]' in a group with different byte-order in unpack/);
1087 eval { $_ = pack($t, (0)x6); };
1088 like($@, qr/Can't use '[<>]' in a group with different byte-order in pack/);
1089 }
1090
d9db00a6
NC
1091 is(pack('L<L>', (0x12345678)x2),
1092 pack('(((L1)1)<)(((L)1)1)>1', (0x12345678)x2));
1093}
1094
1095{
66c611c5
MHM
1096 sub compress_template {
1097 my $t = shift;
1098 for my $mod (qw( < > )) {
1099 $t =~ s/((?:(?:[SILQJFDP]!?$mod|[^SILQJFDP\W]!?)(?:\d+|\*|\[(?:[^]]+)\])?\/?){2,})/
1100 my $x = $1; $x =~ s!$mod!!g ? "($x)$mod" : $x /ieg;
1101 }
1102 return $t;
1103 }
1104
66c611c5
MHM
1105 my %templates = (
1106 's<' => [-42],
1107 's<c2x![S]S<' => [-42, -11, 12, 4711],
1108 '(i<j<[s]l<)3' => [-11, -22, -33, 1000000, 1100, 2201, 3302,
1109 -1000000, 32767, -32768, 1, -123456789 ],
1110 '(I!<4(J<2L<)3)5' => [1 .. 65],
1111 'q<Q<' => [-50000000005, 60000000006],
1112 'f<F<d<' => [3.14159, 111.11, 2222.22],
1113 'D<cCD<' => [1e42, -128, 255, 1e-42],
1114 'n/a*' => ['/usr/bin/perl'],
1115 'C/a*S</A*L</Z*I</a*' => [qw(Just another Perl hacker)],
1116 );
1117
1118 for my $tle (sort keys %templates) {
1119 my @d = @{$templates{$tle}};
1120 my $tbe = $tle;
1121 $tbe =~ y/</>/;
1122 for my $t ($tbe, $tle) {
1123 my $c = compress_template($t);
1124 print "# '$t' -> '$c'\n";
1125 SKIP: {
1126 my $p1 = eval { pack $t, @d };
1127 skip "cannot pack '$t' on this perl", 5 if is_valid_error($@);
1128 my $p2 = eval { pack $c, @d };
1129 is($@, '');
1130 is($p1, $p2);
1131 s!(/[aAZ])\*!$1!g for $t, $c;
1132 my @u1 = eval { unpack $t, $p1 };
1133 is($@, '');
1134 my @u2 = eval { unpack $c, $p2 };
1135 is($@, '');
1136 is(join('!', @u1), join('!', @u2));
1137 }
1138 }
1139 }
1140}
1141
1142{
b81060d6
WL
1143 # from Wolfgang Laun: fix in change #13163
1144
1145 my $s = 'ABC' x 10;
644d52eb
JH
1146 my $t = '*';
1147 my $x = ord($t);
b81060d6
WL
1148 my $buf = pack( 'Z*/A* C', $s, $x );
1149 my $y;
1150
1151 my $h = $buf;
1152 $h =~ s/[^[:print:]]/./g;
1153 ( $s, $y ) = unpack( "Z*/A* C", $buf );
644d52eb 1154 is($h, "30.ABCABCABCABCABCABCABCABCABCABC$t");
0b568b5f
MS
1155 is(length $buf, 34);
1156 is($s, "ABCABCABCABCABCABCABCABCABCABC");
644d52eb 1157 is($y, $x);
b81060d6 1158}
3bf38418
WL
1159
1160{
b223308b 1161 # from Wolfgang Laun: fix in change #13288
3bf38418 1162
b223308b 1163 eval { my $t=unpack("P*", "abc") };
49704364 1164 like($@, qr/'P' must have an explicit size/);
3bf38418 1165}
18529408
IZ
1166
1167{ # Grouping constructs
1168 my (@a, @b);
1169 @a = unpack '(SL)', pack 'SLSLSL', 67..90;
1170 is("@a", "67 68");
1171 @a = unpack '(SL)3', pack 'SLSLSL', 67..90;
1172 @b = (67..72);
1173 is("@a", "@b");
1174 @a = unpack '(SL)3', pack 'SLSLSLSL', 67..90;
1175 is("@a", "@b");
1176 @a = unpack '(SL)[3]', pack 'SLSLSLSL', 67..90;
1177 is("@a", "@b");
1178 @a = unpack '(SL)[2] SL', pack 'SLSLSLSL', 67..90;
1179 is("@a", "@b");
1180 @a = unpack 'A/(SL)', pack 'ASLSLSLSL', 3, 67..90;
1181 is("@a", "@b");
1182 @a = unpack 'A/(SL)SL', pack 'ASLSLSLSL', 2, 67..90;
1183 is("@a", "@b");
1184 @a = unpack '(SL)*', pack 'SLSLSLSL', 67..90;
1185 @b = (67..74);
1186 is("@a", "@b");
1187 @a = unpack '(SL)*SL', pack 'SLSLSLSL', 67..90;
1188 is("@a", "@b");
1189 eval { @a = unpack '(*SL)', '' };
1190 like($@, qr/\(\)-group starts with a count/);
1191 eval { @a = unpack '(3SL)', '' };
1192 like($@, qr/\(\)-group starts with a count/);
1193 eval { @a = unpack '([3]SL)', '' };
1194 like($@, qr/\(\)-group starts with a count/);
1195 eval { @a = pack '(*SL)' };
1196 like($@, qr/\(\)-group starts with a count/);
1197 @a = unpack '(SL)3 SL', pack '(SL)4', 67..74;
1198 is("@a", "@b");
1199 @a = unpack '(SL)3 SL', pack '(SL)[4]', 67..74;
1200 is("@a", "@b");
1201 @a = unpack '(SL)3 SL', pack '(SL)*', 67..74;
1202 is("@a", "@b");
1203}
206947d2 1204
49704364 1205{ # more on grouping (W.Laun)
49704364
WL
1206 # @ absolute within ()-group
1207 my $badc = pack( '(a)*', unpack( '(@1a @0a @2)*', 'abcd' ) );
1208 is( $badc, 'badc' );
1209 my @b = ( 1, 2, 3 );
1210 my $buf = pack( '(@1c)((@2C)@3c)', @b );
1211 is( $buf, "\0\1\0\0\2\3" );
1212 my @a = unpack( '(@1c)((@2c)@3c)', $buf );
1213 is( "@a", "@b" );
1214
28be1210 1215 # various unpack count/code scenarios
49704364
WL
1216 my @Env = ( a => 'AAA', b => 'BBB' );
1217 my $env = pack( 'S(S/A*S/A*)*', @Env/2, @Env );
1218
1219 # unpack full length - ok
1220 my @pup = unpack( 'S/(S/A* S/A*)', $env );
1221 is( "@pup", "@Env" );
1222
1223 # warn when count/code goes beyond end of string
1224 # \0002 \0001 a \0003 AAA \0001 b \0003 BBB
1225 # 2 4 5 7 10 1213
1226 eval { @pup = unpack( 'S/(S/A* S/A*)', substr( $env, 0, 13 ) ) };
1227 like( $@, qr{length/code after end of string} );
28be1210 1228
49704364
WL
1229 # postfix repeat count
1230 $env = pack( '(S/A* S/A*)' . @Env/2, @Env );
1231
1232 # warn when count/code goes beyond end of string
1233 # \0001 a \0003 AAA \0001 b \0003 BBB
1234 # 2 3c 5 8 10 11 13 16
1235 eval { @pup = unpack( '(S/A* S/A*)' . @Env/2, substr( $env, 0, 11 ) ) };
1236 like( $@, qr{length/code after end of string} );
1237
1238 # catch stack overflow/segfault
1239 eval { $_ = pack( ('(' x 105) . 'A' . (')' x 105) ); };
1240 like( $@, qr{Too deeply nested \(\)-groups} );
1241}
1242
1243{ # syntax checks (W.Laun)
bd7d4f4d 1244 use warnings qw(NONFATAL all);;
49704364
WL
1245 my @warning;
1246 local $SIG{__WARN__} = sub {
1247 push( @warning, $_[0] );
1248 };
1249 eval { my $s = pack( 'Ax![4c]A', 1..5 ); };
1250 like( $@, qr{Malformed integer in \[\]} );
1251
1252 eval { my $buf = pack( '(c/*a*)', 'AAA', 'BB' ); };
1253 like( $@, qr{'/' does not take a repeat count} );
1254
1255 eval { my @inf = unpack( 'c/1a', "\x03AAA\x02BB" ); };
1256 like( $@, qr{'/' does not take a repeat count} );
1257
1258 eval { my @inf = unpack( 'c/*a', "\x03AAA\x02BB" ); };
1259 like( $@, qr{'/' does not take a repeat count} );
1260
28be1210 1261 # white space where possible
49704364
WL
1262 my @Env = ( a => 'AAA', b => 'BBB' );
1263 my $env = pack( ' S ( S / A* S / A* )* ', @Env/2, @Env );
1264 my @pup = unpack( ' S / ( S / A* S / A* ) ', $env );
1265 is( "@pup", "@Env" );
1266
1267 # white space in 4 wrong places
1268 for my $temp ( 'A ![4]', 'A [4]', 'A *', 'A 4' ){
1269 eval { my $s = pack( $temp, 'B' ); };
1270 like( $@, qr{Invalid type } );
1271 }
1272
1273 # warning for commas
1274 @warning = ();
1275 my $x = pack( 'I,A', 4, 'X' );
1276 like( $warning[0], qr{Invalid type ','} );
1277
1278 # comma warning only once
1279 @warning = ();
1280 $x = pack( 'C(C,C)C,C', 65..71 );
aaa63dae 1281 cmp_ok( scalar(@warning), '==', 1 );
49704364
WL
1282
1283 # forbidden code in []
1284 eval { my $x = pack( 'A[@4]', 'XXXX' ); };
1285 like( $@, qr{Within \[\]-length '\@' not allowed} );
1286
1287 # @ repeat default 1
1288 my $s = pack( 'AA@A', 'A', 'B', 'C' );
1289 my @c = unpack( 'AA@A', $s );
28be1210
TH
1290 is( $s, 'AC' );
1291 is( "@c", "A C C" );
49704364
WL
1292
1293 # no unpack code after /
1294 eval { my @a = unpack( "C/", "\3" ); };
1295 like( $@, qr{Code missing after '/'} );
1296
d9db00a6
NC
1297 SKIP: {
1298 skip $no_endianness, 6 if $no_endianness;
1299
1300 # modifier warnings
1301 @warning = ();
1302 $x = pack "I>>s!!", 47, 11;
1303 ($x) = unpack "I<<l!>!>", 'x'x20;
1304 is(scalar @warning, 5);
1305 like($warning[0], qr/Duplicate modifier '>' after 'I' in pack/);
1306 like($warning[1], qr/Duplicate modifier '!' after 's' in pack/);
1307 like($warning[2], qr/Duplicate modifier '<' after 'I' in unpack/);
1308 like($warning[3], qr/Duplicate modifier '!' after 'l' in unpack/);
1309 like($warning[4], qr/Duplicate modifier '>' after 'l' in unpack/);
1310 }
49704364
WL
1311}
1312
206947d2 1313{ # Repeat count [SUBEXPR]
f337b084 1314 my @codes = qw( x A Z a c C W B b H h s v n S i I l V N L p P f F d
92d41999
JH
1315 s! S! i! I! l! L! j J);
1316 my $G;
206947d2
IZ
1317 if (eval { pack 'q', 1 } ) {
1318 push @codes, qw(q Q);
1319 } else {
1109a392 1320 push @codes, qw(s S); # Keep the count the same
206947d2 1321 }
92d41999
JH
1322 if (eval { pack 'D', 1 } ) {
1323 push @codes, 'D';
1324 } else {
1325 push @codes, 'd'; # Keep the count the same
1326 }
206947d2 1327
1109a392
MHM
1328 push @codes, map { /^[silqjfdp]/i ? ("$_<", "$_>") : () } @codes;
1329
206947d2
IZ
1330 my %val;
1331 @val{@codes} = map { / [Xx] (?{ undef })
1332 | [AZa] (?{ 'something' })
1333 | C (?{ 214 })
f337b084 1334 | W (?{ 8188 })
206947d2
IZ
1335 | c (?{ 114 })
1336 | [Bb] (?{ '101' })
1337 | [Hh] (?{ 'b8' })
92d41999 1338 | [svnSiIlVNLqQjJ] (?{ 10111 })
15899733 1339 | [FfDd] (?{ 1.36514538e37 })
206947d2
IZ
1340 | [pP] (?{ "try this buffer" })
1341 /x; $^R } @codes;
1342 my @end = (0x12345678, 0x23456781, 0x35465768, 0x15263748);
1343 my $end = "N4";
1344
1345 for my $type (@codes) {
1346 my @list = $val{$type};
1347 @list = () unless defined $list[0];
1348 for my $count ('', '3', '[11]') {
1349 my $c = 1;
1350 $c = $1 if $count =~ /(\d+)/;
1351 my @list1 = @list;
1352 @list1 = (@list1) x $c unless $type =~ /[XxAaZBbHhP]/;
1353 for my $groupend ('', ')2', ')[8]') {
1354 my $groupbegin = ($groupend ? '(' : '');
1355 $c = 1;
1356 $c = $1 if $groupend =~ /(\d+)/;
1357 my @list2 = (@list1) x $c;
1358
1109a392
MHM
1359 SKIP: {
1360 my $junk1 = "$groupbegin $type$count $groupend";
1361 # print "# junk1=$junk1\n";
1362 my $p = eval { pack $junk1, @list2 };
1363 skip "cannot pack '$type' on this perl", 12
1364 if is_valid_error($@);
9b72c5e4 1365 die "pack $junk1 failed: $@" if $@;
1109a392
MHM
1366
1367 my $half = int( (length $p)/2 );
1368 for my $move ('', "X$half", "X!$half", 'x1', 'x!8', "x$half") {
1369 my $junk = "$junk1 $move";
1370 # print "# junk='$junk', list=(@list2)\n";
1371 $p = pack "$junk $end", @list2, @end;
1372 my @l = unpack "x[$junk] $end", $p;
1373 is(scalar @l, scalar @end);
1374 is("@l", "@end", "skipping x[$junk]");
1375 }
1376 }
206947d2
IZ
1377 }
1378 }
1379 }
1380}
1381
1382# / is recognized after spaces in scalar context
1383# XXXX no spaces are allowed in pack... In pack only before the slash...
1384is(scalar unpack('A /A Z20', pack 'A/A* Z20', 'bcde', 'xxxxx'), 'bcde');
1385is(scalar unpack('A /A /A Z20', '3004bcde'), 'bcde');
62f95557
IZ
1386
1387{ # X! and x!
1388 my $t = 'C[3] x!8 C[2]';
1389 my @a = (0x73..0x77);
1390 my $p = pack($t, @a);
1391 is($p, "\x73\x74\x75\0\0\0\0\0\x76\x77");
1392 my @b = unpack $t, $p;
1393 is(scalar @b, scalar @a);
1394 is("@b", "@a", 'x!8');
1395 $t = 'x[5] C[6] X!8 C[2]';
1396 @a = (0x73..0x7a);
1397 $p = pack($t, @a);
1398 is($p, "\0\0\0\0\0\x73\x74\x75\x79\x7a");
1399 @b = unpack $t, $p;
1400 @a = (0x73..0x75, 0x79, 0x7a, 0x79, 0x7a);
1401 is(scalar @b, scalar @a);
1402 is("@b", "@a");
1403}
1404
1405{ # struct {char c1; double d; char cc[2];}
1406 my $t = 'C x![d] d C[2]';
1407 my @a = (173, 1.283476517e-45, 42, 215);
1408 my $p = pack $t, @a;
1409 ok( length $p);
1410 my @b = unpack "$t X[$t] $t", $p; # Extract, step back, extract again
1411 is(scalar @b, 2 * scalar @a);
3f7e3417 1412 $b = "@b";
0e45f487 1413 $b =~ s/(?:17000+|16999+)\d+(e-0?45) /17$1 /gi; # stringification is gamble
3f7e3417 1414 is($b, "@a @a");
62f95557 1415
bd7d4f4d 1416 use warnings qw(NONFATAL all);;
62f95557
IZ
1417 my $warning;
1418 local $SIG{__WARN__} = sub {
1419 $warning = $_[0];
1420 };
1421 @b = unpack "x[C] x[$t] X[$t] X[C] $t", "$p\0";
1422
1423 is($warning, undef);
1424 is(scalar @b, scalar @a);
3f7e3417 1425 $b = "@b";
0e45f487 1426 $b =~ s/(?:17000+|16999+)\d+(e-0?45) /17$1 /gi; # stringification is gamble
3f7e3417 1427 is($b, "@a");
62f95557 1428}
92d41999
JH
1429
1430is(length(pack("j", 0)), $Config{ivsize});
1431is(length(pack("J", 0)), $Config{uvsize});
1432is(length(pack("F", 0)), $Config{nvsize});
1433
1434numbers ('j', -2147483648, -1, 0, 1, 2147483647);
1435numbers ('J', 0, 1, 2147483647, 2147483648, 4294967295);
1436numbers ('F', -(2**34), -1, 0, 1, 2**34);
1437SKIP: {
1438 my $t = eval { unpack("D*", pack("D", 12.34)) };
1439
1109a392 1440 skip "Long doubles not in use", 166 if $@ =~ /Invalid type/;
92d41999
JH
1441
1442 is(length(pack("D", 0)), $Config{longdblsize});
1443 numbers ('D', -(2**34), -1, 0, 1, 2**34);
1444}
1445
c8f824eb
NC
1446# Maybe this knowledge needs to be "global" for all of pack.t
1447# Or a "can checksum" which would effectively be all the number types"
1448my %cant_checksum = map {$_=> 1} qw(A Z u w);
1449# not a b B h H
1450foreach 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)) {
1451 SKIP: {
1452 my $packed = eval {pack "${template}4", 1, 4, 9, 16};
1453 if ($@) {
49704364 1454 die unless $@ =~ /Invalid type '$template'/;
c8f824eb
NC
1455 skip ("$template not supported on this perl",
1456 $cant_checksum{$template} ? 4 : 8);
1457 }
1458 my @unpack4 = unpack "${template}4", $packed;
1459 my @unpack = unpack "${template}*", $packed;
1460 my @unpack1 = unpack "${template}", $packed;
1461 my @unpack1s = scalar unpack "${template}", $packed;
1462 my @unpack4s = scalar unpack "${template}4", $packed;
1463 my @unpacks = scalar unpack "${template}*", $packed;
1464
1465 my @tests = ( ["${template}4 vs ${template}*", \@unpack4, \@unpack],
1466 ["scalar ${template} ${template}", \@unpack1s, \@unpack1],
1467 ["scalar ${template}4 vs ${template}", \@unpack4s, \@unpack1],
1468 ["scalar ${template}* vs ${template}", \@unpacks, \@unpack1],
1469 );
1470
1471 unless ($cant_checksum{$template}) {
1472 my @unpack4_c = unpack "\%${template}4", $packed;
1473 my @unpack_c = unpack "\%${template}*", $packed;
1474 my @unpack1_c = unpack "\%${template}", $packed;
1475 my @unpack1s_c = scalar unpack "\%${template}", $packed;
1476 my @unpack4s_c = scalar unpack "\%${template}4", $packed;
1477 my @unpacks_c = scalar unpack "\%${template}*", $packed;
1478
1479 push @tests,
1480 ( ["% ${template}4 vs ${template}*", \@unpack4_c, \@unpack_c],
1481 ["% scalar ${template} ${template}", \@unpack1s_c, \@unpack1_c],
1482 ["% scalar ${template}4 vs ${template}*", \@unpack4s_c, \@unpack_c],
1483 ["% scalar ${template}* vs ${template}*", \@unpacks_c, \@unpack_c],
1484 );
1485 }
1486 foreach my $test (@tests) {
1487 ok (list_eq ($test->[1], $test->[2]), $test->[0]) ||
1488 printf "# unpack gave %s expected %s\n",
1489 encode_list (@{$test->[1]}), encode_list (@{$test->[2]});
1490 }
1491 }
1492}
9c3dc587
HS
1493
1494ok(pack('u2', 'AA'), "[perl #8026]"); # used to hang and eat RAM in perl 5.7.2
1495
fe581ec7
JH
1496$_ = pack('c', 65); # 'A' would not be EBCDIC-friendly
1497is(unpack('c'), 65, "one-arg unpack (change #18751)"); # defaulting to $_
db37a92e
JH
1498
1499{
250d67eb 1500 my $a = "X\x0901234567\n" x 100; # \t would not be EBCDIC TAB
db37a92e
JH
1501 my @a = unpack("(a1 c/a)*", $a);
1502 is(scalar @a, 200, "[perl #15288]");
1503 is($a[-1], "01234567\n", "[perl #15288]");
1504 is($a[-2], "X", "[perl #15288]");
1505}
0ed7c1bb 1506
f7f98fdf 1507{
bd7d4f4d 1508 use warnings qw(NONFATAL all);;
f7f98fdf
TH
1509 my $warning;
1510 local $SIG{__WARN__} = sub {
1511 $warning = $_[0];
1512 };
e99c6025
KW
1513
1514 # This test is looking for the encoding of the bit pattern "\x66\x6f\x6f",
1515 # which is ASCII "foo"
1516 my $out = pack("u99", native_to_uni("foo") x 99);
f7f98fdf
TH
1517 like($warning, qr/Field too wide in 'u' format in pack at /,
1518 "Warn about too wide uuencode");
1519 is($out, ("_" . "9F]O" x 21 . "\n") x 4 . "M" . "9F]O" x 15 . "\n",
1520 "Use max width in case of too wide uuencode");
1521}
1522
0ed7c1bb
TH
1523# checksums
1524{
1525 # verify that unpack advances correctly wrt a checksum
1526 my (@x) = unpack("b10a", "abcd");
1527 my (@y) = unpack("%b10a", "abcd");
1528 is($x[1], $y[1], "checksum advance ok");
d6d3e8bd 1529
15899733 1530 SKIP: {
85272d31 1531 skip("-- non-IEEE float", 1) if !$Config{d_double_style_ieee};
15899733
JH
1532 # verify that the checksum is not overflowed with C0
1533 is(unpack("C0%128U", "abcd"), unpack("U0%128U", "abcd"), "checksum not overflowed");
1534 }
0ed7c1bb 1535}
0c81e54b 1536
ca114673 1537my $U_1FFC_bytes = byte_utf8a_to_utf8n("\341\277\274");
0c81e54b
TH
1538{
1539 # U0 and C0 must be scoped
ca114673 1540 my (@x) = unpack("a(U0)U", "b$U_1FFC_bytes");
0c81e54b 1541 is($x[0], 'b', 'before scope');
08ca2aa3 1542 is($x[1], 8188, 'after scope');
f337b084 1543
ca114673 1544 is(pack("a(U0)U", "b", 8188), "b$U_1FFC_bytes");
0c81e54b 1545}
21c16052
TH
1546
1547{
1548 # counted length prefixes shouldn't change C0/U0 mode
ca114673
KW
1549 # (note the length is actually 0 in this test, as the C/ is replaced by C0
1550 # due to the \0 in the string)
1551 is(join(',', unpack("aC/UU", "b\0$U_1FFC_bytes")), 'b,8188');
1552 is(join(',', unpack("aC/CU", "b\0$U_1FFC_bytes")), 'b,8188');
26773d9d
KW
1553
1554 # The U expects Unicode, so convert from native
1555 my $first_byte = utf8::native_to_unicode(ord substr($U_1FFC_bytes, 0, 1));
1556
ca114673
KW
1557 is(join(',', unpack("aU0C/UU", "b\0$U_1FFC_bytes")), "b,$first_byte");
1558 is(join(',', unpack("aU0C/CU", "b\0$U_1FFC_bytes")), "b,$first_byte");
21c16052 1559}
f0df5f8b
TH
1560
1561{
1562 # "Z0" (bug #34062)
1563 my (@x) = unpack("C*", pack("CZ0", 1, "b"));
1564 is(join(',', @x), '1', 'pack Z0 doesn\'t destroy the character before');
1565}
f337b084
TH
1566
1567{
1568 # Encoding neutrality
1569 # String we will pull apart and rebuild in several ways:
1570 my $down = "\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff\x05\x06";
1571 my $up = $down;
1572 utf8::upgrade($up);
1573
1574 my %expect =
1575 # [expected result,
1576 # how many chars it should progress,
1577 # (optional) expected result of pack]
1578 (a5 => ["\xf8\xf9\xfa\xfb\xfc", 5],
1579 A5 => ["\xf8\xf9\xfa\xfb\xfc", 5],
1580 Z5 => ["\xf8\xf9\xfa\xfb\xfc", 5, "\xf8\xf9\xfa\xfb\x00\xfd"],
1581 b21 => ["000111111001111101011", 3, "\xf8\xf9\x1a\xfb"],
1582 B21 => ["111110001111100111111", 3, "\xf8\xf9\xf8\xfb"],
1583 H5 => ["f8f9f", 3, "\xf8\xf9\xf0\xfb"],
1584 h5 => ["8f9fa", 3, "\xf8\xf9\x0a\xfb"],
1585 "s<" => [-1544, 2],
1586 "s>" => [-1799, 2],
1587 "S<" => [0xf9f8, 2],
1588 "S>" => [0xf8f9, 2],
1589 "l<" => [-67438088, 4],
1590 "l>" => [-117835013, 4],
1591 "L>" => [0xf8f9fafb, 4],
1592 "L<" => [0xfbfaf9f8, 4],
1593 n => [0xf8f9, 2],
1594 N => [0xf8f9fafb, 4],
1595 v => [63992, 2],
1596 V => [0xfbfaf9f8, 4],
1597 c => [-8, 1],
1598 U0U => [0xf8, 1],
1599 w => ["8715569050387726213", 9],
1600 q => ["-283686952306184", 8],
1601 Q => ["18446460386757245432", 8],
1602 );
1603
1604 for my $string ($down, $up) {
1605 for my $format (sort {lc($a) cmp lc($b) || $a cmp $b } keys %expect) {
1606 SKIP: {
1607 my $expect = $expect{$format};
1608 # unpack upgraded and downgraded string
1609 my @result = eval { unpack("$format C0 W", $string) };
1610 skip "cannot pack/unpack '$format C0 W' on this perl", 5 if
1611 $@ && is_valid_error($@);
1612 is(@result, 2, "Two results from unpack $format C0 W");
1613
1614 # pack to downgraded
1615 my $new = pack("$format C0 W", @result);
1616 is(length($new), $expect->[1]+1,
1617 "pack $format C0 W should give $expect->[1]+1 chars");
1618 is($new, $expect->[2] || substr($string, 0, length $new),
1619 "pack $format C0 W returns expected value");
1620
1621 # pack to upgraded
1622 $new = pack("a0 $format C0 W", chr(256), @result);
1623 is(length($new), $expect->[1]+1,
1624 "pack a0 $format C0 W should give $expect->[1]+1 chars");
1625 is($new, $expect->[2] || substr($string, 0, length $new),
1626 "pack a0 $format C0 W returns expected value");
1627 }
1628 }
1629 }
1630}
1631
1632{
1633 # Encoding neutrality, numbers
1634 my $val = -2.68;
1635 for my $format (qw(s S i I l L j J f d F D q Q
1636 s! S! i! I! l! L! n! N! v! V!)) {
1637 SKIP: {
1638 my $down = eval { pack($format, $val) };
1639 skip "cannot pack/unpack $format on this perl", 9 if
1640 $@ && is_valid_error($@);
1641 ok(!utf8::is_utf8($down), "Simple $format pack doesn't get upgraded");
1642 my $up = pack("a0 $format", chr(256), $val);
1643 ok(utf8::is_utf8($up), "a0 $format with high char leads to upgrade");
1644 is($down, $up, "$format generated strings are equal though");
1645 my @down_expanded = unpack("$format W", $down . chr(0xce));
1646 is(@down_expanded, 2, "Expand to two values");
1647 is($down_expanded[1], 0xce,
1648 "unpack $format left us at the expected position");
1649 my @up_expanded = unpack("$format W", $up . chr(0xce));
1650 is(@up_expanded, 2, "Expand to two values");
1651 is($up_expanded[1], 0xce,
1652 "unpack $format left us at the expected position");
1653 is($down_expanded[0], $up_expanded[0], "$format unpack was neutral");
1654 is(pack($format, $down_expanded[0]), $down, "Pack $format undoes unpack $format");
1655 }
1656 }
1657}
1658
1659{
1651fc44 1660 # C *is* neutral
f337b084
TH
1661 my $down = "\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff\x05\x06";
1662 my $up = $down;
1663 utf8::upgrade($up);
1664 my @down = unpack("C*", $down);
1665 my @expect_down = (0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff, 0x05, 0x06);
1666 is("@down", "@expect_down", "byte expand");
1667 is(pack("C*", @down), $down, "byte join");
1668
1669 my @up = unpack("C*", $up);
1651fc44 1670 my @expect_up = (0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff, 0x05, 0x06);
f337b084
TH
1671 is("@up", "@expect_up", "UTF-8 expand");
1672 is(pack("U0C0C*", @up), $up, "UTF-8 join");
1673}
1674
1675{
1676 # Harder cases for the neutrality test
1677
1678 # u format
1679 my $down = "\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff\x05\x06";
1680 my $up = $down;
1681 utf8::upgrade($up);
1682 is(pack("u", $down), pack("u", $up), "u pack is neutral");
1683 is(unpack("u", pack("u", $down)), $down, "u unpack to downgraded works");
1684 is(unpack("U0C0u", pack("u", $down)), $up, "u unpack to upgraded works");
1685
1686 # p/P format
1687 # This actually only tests something if the address contains a byte >= 0x80
1688 my $str = "abc\xa5\x00\xfede";
1689 $down = pack("p", $str);
1690 is(pack("P", $str), $down);
1691 is(pack("U0C0p", $str), $down);
1692 is(pack("U0C0P", $str), $down);
1693 is(unpack("p", $down), "abc\xa5", "unpack p downgraded");
1694 $up = $down;
1695 utf8::upgrade($up);
1696 is(unpack("p", $up), "abc\xa5", "unpack p upgraded");
1697
1698 is(unpack("P7", $down), "abc\xa5\x00\xfed", "unpack P downgraded");
1699 is(unpack("P7", $up), "abc\xa5\x00\xfed", "unpack P upgraded");
1700
1701 # x, X and @
1702 $down = "\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff\x05\x06";
1703 $up = $down;
1704 utf8::upgrade($up);
1705
1706 is(unpack('@4W', $down), 0xfc, "\@positioning on downgraded string");
1707 is(unpack('@4W', $up), 0xfc, "\@positioning on upgraded string");
1708
1709 is(unpack('@4x2W', $down), 0xfe, "x moving on downgraded string");
1710 is(unpack('@4x2W', $up), 0xfe, "x moving on upgraded string");
1711 is(unpack('@4x!4W', $down), 0xfc, "x! moving on downgraded string");
1712 is(unpack('@4x!4W', $up), 0xfc, "x! moving on upgraded string");
1713 is(unpack('@5x!4W', $down), 0x05, "x! moving on downgraded string");
1714 is(unpack('@5x!4W', $up), 0x05, "x! moving on upgraded string");
1715
1716 is(unpack('@4X2W', $down), 0xfa, "X moving on downgraded string");
1717 is(unpack('@4X2W', $up), 0xfa, "X moving on upgraded string");
1718 is(unpack('@4X!4W', $down), 0xfc, "X! moving on downgraded string");
1719 is(unpack('@4X!4W', $up), 0xfc, "X! moving on upgraded string");
1720 is(unpack('@5X!4W', $down), 0xfc, "X! moving on downgraded string");
1721 is(unpack('@5X!4W', $up), 0xfc, "X! moving on upgraded string");
1722 is(unpack('@5X!8W', $down), 0xf8, "X! moving on downgraded string");
1723 is(unpack('@5X!8W', $up), 0xf8, "X! moving on upgraded string");
1724
1725 is(pack("W2x", 0xfa, 0xe3), "\xfa\xe3\x00", "x on downgraded string");
28be1210 1726 is(pack("W2x!4", 0xfa, 0xe3), "\xfa\xe3\x00\x00",
f337b084
TH
1727 "x! on downgraded string");
1728 is(pack("W2x!2", 0xfa, 0xe3), "\xfa\xe3", "x! on downgraded string");
1729 is(pack("U0C0W2x", 0xfa, 0xe3), "\xfa\xe3\x00", "x on upgraded string");
28be1210 1730 is(pack("U0C0W2x!4", 0xfa, 0xe3), "\xfa\xe3\x00\x00",
f337b084
TH
1731 "x! on upgraded string");
1732 is(pack("U0C0W2x!2", 0xfa, 0xe3), "\xfa\xe3", "x! on upgraded string");
1733 is(pack("W2X", 0xfa, 0xe3), "\xfa", "X on downgraded string");
1734 is(pack("U0C0W2X", 0xfa, 0xe3), "\xfa", "X on upgraded string");
1735 is(pack("W2X!2", 0xfa, 0xe3), "\xfa\xe3", "X! on downgraded string");
1736 is(pack("U0C0W2X!2", 0xfa, 0xe3), "\xfa\xe3", "X! on upgraded string");
1737 is(pack("W3X!2", 0xfa, 0xe3, 0xa6), "\xfa\xe3", "X! on downgraded string");
28be1210 1738 is(pack("U0C0W3X!2", 0xfa, 0xe3, 0xa6), "\xfa\xe3",
f337b084
TH
1739 "X! on upgraded string");
1740
1741 # backward eating through a ( moves the group starting point backwards
28be1210 1742 is(pack("a*(Xa)", "abc", "q"), "abq",
f337b084 1743 "eating before strbeg moves it back");
28be1210 1744 is(pack("a*(Xa)", "ab" . chr(512), "q"), "abq",
f337b084
TH
1745 "eating before strbeg moves it back");
1746
1747 # Check marked_upgrade
1748 is(pack('W(W(Wa@3W)@6W)@9W', 0xa1, 0xa2, 0xa3, "a", 0xa4, 0xa5, 0xa6),
1749 "\xa1\xa2\xa3a\x00\xa4\x00\xa5\x00\xa6");
1750 $up = "a";
1751 utf8::upgrade($up);
1752 is(pack('W(W(Wa@3W)@6W)@9W', 0xa1, 0xa2, 0xa3, $up, 0xa4, 0xa5, 0xa6),
1753 "\xa1\xa2\xa3a\x00\xa4\x00\xa5\x00\xa6", "marked upgrade caused by a");
1754 is(pack('W(W(WW@3W)@6W)@9W', 0xa1, 0xa2, 0xa3, 256, 0xa4, 0xa5, 0xa6),
28be1210 1755 "\xa1\xa2\xa3\x{100}\x00\xa4\x00\xa5\x00\xa6",
f337b084
TH
1756 "marked upgrade caused by W");
1757 is(pack('W(W(WU0aC0@3W)@6W)@9W', 0xa1, 0xa2, 0xa3, "a", 0xa4, 0xa5, 0xa6),
1758 "\xa1\xa2\xa3a\x00\xa4\x00\xa5\x00\xa6", "marked upgrade caused by U0");
1759
1760 # a, A and Z
1761 $down = "\xa4\xa6\xa7";
1762 $up = $down;
1763 utf8::upgrade($up);
1764 utf8::upgrade(my $high = "\xfeb");
1765
1766 for my $format ("a0", "A0", "Z0", "U0a0C0", "U0A0C0", "U0Z0C0") {
28be1210 1767 is(pack("a* $format a*", "ab", $down, "cd"), "abcd",
f337b084
TH
1768 "$format format on plain string");
1769 is(pack("a* $format a*", "ab", $up, "cd"), "abcd",
1770 "$format format on upgraded string");
28be1210 1771 is(pack("a* $format a*", $high, $down, "cd"), "\xfebcd",
f337b084
TH
1772 "$format format on plain string");
1773 is(pack("a* $format a*", $high, $up, "cd"), "\xfebcd",
1774 "$format format on upgraded string");
1775 my @down = unpack("a1 $format a*", "\xfeb");
1776 is("@down", "\xfe b", "unpack $format");
1777 my @up = unpack("a1 $format a*", $high);
1778 is("@up", "\xfe b", "unpack $format");
1779 }
1780 is(pack("a1", $high), "\xfe");
1781 is(pack("A1", $high), "\xfe");
1782 is(pack("Z1", $high), "\x00");
1783 is(pack("a2", $high), "\xfeb");
1784 is(pack("A2", $high), "\xfeb");
1785 is(pack("Z2", $high), "\xfe\x00");
1786 is(pack("a5", $high), "\xfeb\x00\x00\x00");
1787 is(pack("A5", $high), "\xfeb ");
1788 is(pack("Z5", $high), "\xfeb\x00\x00\x00");
1789 is(pack("a*", $high), "\xfeb");
1790 is(pack("A*", $high), "\xfeb");
1791 is(pack("Z*", $high), "\xfeb\x00");
1792
e99c6025
KW
1793 utf8::upgrade($high = byte_utf8a_to_utf8n("\xc3\xbe") . "b");
1794 is(pack("U0a2", $high), uni_to_native("\xfe"));
1795 is(pack("U0A2", $high), uni_to_native("\xfe"));
1796 is(pack("U0Z1", $high), uni_to_native("\x00"));
1797 is(pack("U0a3", $high), uni_to_native("\xfe") . "b");
1798 is(pack("U0A3", $high), uni_to_native("\xfe") . "b");
1799 is(pack("U0Z3", $high), uni_to_native("\xfe\x00"));
1800 is(pack("U0a6", $high), uni_to_native("\xfe") . "b" . uni_to_native("\x00\x00\x00"));
1801 is(pack("U0A6", $high), uni_to_native("\xfe") . "b ");
1802 is(pack("U0Z6", $high), uni_to_native("\xfe") . "b" . uni_to_native("\x00\x00\x00"));
1803 is(pack("U0a*", $high), uni_to_native("\xfe") . "b");
1804 is(pack("U0A*", $high), uni_to_native("\xfe") . "b");
1805 is(pack("U0Z*", $high), uni_to_native("\xfe") . "b" . uni_to_native("\x00"));
f337b084 1806}
246f24af
TH
1807{
1808 # pack /
1809 my @array = 1..14;
1810 my @out = unpack("N/S", pack("N/S", @array) . "abcd");
1811 is("@out", "@array", "pack N/S works");
1812 @out = unpack("N/S*", pack("N/S*", @array) . "abcd");
1813 is("@out", "@array", "pack N/S* works");
1814 @out = unpack("N/S*", pack("N/S14", @array) . "abcd");
1815 is("@out", "@array", "pack N/S14 works");
1816 @out = unpack("N/S*", pack("N/S15", @array) . "abcd");
1817 is("@out", "@array", "pack N/S15 works");
1818 @out = unpack("N/S*", pack("N/S13", @array) . "abcd");
1819 is("@out", "@array[0..12]", "pack N/S13 works");
1820 @out = unpack("N/S*", pack("N/S0", @array) . "abcd");
1821 is("@out", "", "pack N/S0 works");
1822 is(pack("Z*/a0", "abc"), "0\0", "pack Z*/a0 makes a short string");
1823 is(pack("Z*/Z0", "abc"), "0\0", "pack Z*/Z0 makes a short string");
1824 is(pack("Z*/a3", "abc"), "3\0abc", "pack Z*/a3 makes a full string");
1825 is(pack("Z*/Z3", "abc"), "3\0ab\0", "pack Z*/Z3 makes a short string");
1826 is(pack("Z*/a5", "abc"), "5\0abc\0\0", "pack Z*/a5 makes a long string");
1827 is(pack("Z*/Z5", "abc"), "5\0abc\0\0", "pack Z*/Z5 makes a long string");
1828 is(pack("Z*/Z"), "1\0\0", "pack Z*/Z makes an extended string");
1829 is(pack("Z*/Z", ""), "1\0\0", "pack Z*/Z makes an extended string");
1830 is(pack("Z*/a", ""), "0\0", "pack Z*/a makes an extended string");
1831}
18bdf90a
TH
1832{
1833 # unpack("A*", $unicode) strips general unicode spaces
e99c6025 1834 is(unpack("A*", "ab \n" . uni_to_native("\xa0") . " \0"), "ab \n" . uni_to_native("\xa0"),
18bdf90a 1835 'normal A* strip leaves \xa0');
e99c6025 1836 is(unpack("U0C0A*", "ab \n" . uni_to_native("\xa0") . " \0"), "ab \n" . uni_to_native("\xa0"),
18bdf90a
TH
1837 'normal A* strip leaves \xa0 even if it got upgraded for technical reasons');
1838 is(unpack("A*", pack("a*(U0U)a*", "ab \n", 0xa0, " \0")), "ab",
1839 'upgraded strings A* removes \xa0');
1840 is(unpack("A*", pack("a*(U0UU)a*", "ab \n", 0xa0, 0x1680, " \0")), "ab",
1841 'upgraded strings A* removes all unicode whitespace');
1842 is(unpack("A5", pack("a*(U0U)a*", "ab \n", 0x1680, "def", "ab")), "ab",
1843 'upgraded strings A5 removes all unicode whitespace');
1844 is(unpack("A*", pack("U", 0x1680)), "",
1845 'upgraded strings A* with nothing left');
1846}
28be1210
TH
1847{
1848 # Testing unpack . and .!
1849 is(unpack(".", "ABCD"), 0, "offset at start of string is 0");
1850 is(unpack(".", ""), 0, "offset at start of empty string is 0");
1851 is(unpack("x3.", "ABCDEF"), 3, "simple offset works");
1852 is(unpack("x3.", "ABC"), 3, "simple offset at end of string works");
1853 is(unpack("x3.0", "ABC"), 0, "self offset is 0");
1854 is(unpack("x3(x2.)", "ABCDEF"), 2, "offset is relative to inner group");
1855 is(unpack("x3(X2.)", "ABCDEF"), -2,
1856 "negative offset relative to inner group");
1857 is(unpack("x3(X2.2)", "ABCDEF"), 1, "offset is relative to inner group");
1858 is(unpack("x3(x2.0)", "ABCDEF"), 0, "self offset in group is still 0");
1859 is(unpack("x3(x2.2)", "ABCDEF"), 5, "offset counts groups");
1860 is(unpack("x3(x2.*)", "ABCDEF"), 5, "star offset is relative to start");
1861
1862 my $high = chr(8188) x 6;
1863 is(unpack("x3(x2.)", $high), 2, "utf8 offset is relative to inner group");
1864 is(unpack("x3(X2.)", $high), -2,
1865 "utf8 negative offset relative to inner group");
1866 is(unpack("x3(X2.2)", $high), 1, "utf8 offset counts groups");
1867 is(unpack("x3(x2.0)", $high), 0, "utf8 self offset in group is still 0");
1868 is(unpack("x3(x2.2)", $high), 5, "utf8 offset counts groups");
1869 is(unpack("x3(x2.*)", $high), 5, "utf8 star offset is relative to start");
1870
1871 is(unpack("U0x3(x2.)", $high), 2,
1872 "U0 mode utf8 offset is relative to inner group");
1873 is(unpack("U0x3(X2.)", $high), -2,
1874 "U0 mode utf8 negative offset relative to inner group");
1875 is(unpack("U0x3(X2.2)", $high), 1,
1876 "U0 mode utf8 offset counts groups");
1877 is(unpack("U0x3(x2.0)", $high), 0,
1878 "U0 mode utf8 self offset in group is still 0");
1879 is(unpack("U0x3(x2.2)", $high), 5,
1880 "U0 mode utf8 offset counts groups");
1881 is(unpack("U0x3(x2.*)", $high), 5,
1882 "U0 mode utf8 star offset is relative to start");
1883
1884 is(unpack("x3(x2.!)", $high), 2*3,
1885 "utf8 offset is relative to inner group");
1886 is(unpack("x3(X2.!)", $high), -2*3,
1887 "utf8 negative offset relative to inner group");
1888 is(unpack("x3(X2.!2)", $high), 1*3,
1889 "utf8 offset counts groups");
1890 is(unpack("x3(x2.!0)", $high), 0,
1891 "utf8 self offset in group is still 0");
1892 is(unpack("x3(x2.!2)", $high), 5*3,
1893 "utf8 offset counts groups");
1894 is(unpack("x3(x2.!*)", $high), 5*3,
1895 "utf8 star offset is relative to start");
1896
1897 is(unpack("U0x3(x2.!)", $high), 2,
1898 "U0 mode utf8 offset is relative to inner group");
1899 is(unpack("U0x3(X2.!)", $high), -2,
1900 "U0 mode utf8 negative offset relative to inner group");
1901 is(unpack("U0x3(X2.!2)", $high), 1,
1902 "U0 mode utf8 offset counts groups");
1903 is(unpack("U0x3(x2.!0)", $high), 0,
1904 "U0 mode utf8 self offset in group is still 0");
1905 is(unpack("U0x3(x2.!2)", $high), 5,
1906 "U0 mode utf8 offset counts groups");
1907 is(unpack("U0x3(x2.!*)", $high), 5,
1908 "U0 mode utf8 star offset is relative to start");
1909}
1910{
1911 # Testing pack . and .!
1912 is(pack("(a)5 .", 1..5, 3), "123", ". relative to string start, shorten");
1913 eval { () = pack("(a)5 .", 1..5, -3) };
1914 like($@, qr{'\.' outside of string in pack}, "Proper error message");
1915 is(pack("(a)5 .", 1..5, 8), "12345\x00\x00\x00",
1916 ". relative to string start, extend");
1917 is(pack("(a)5 .", 1..5, 5), "12345", ". relative to string start, keep");
1918
1919 is(pack("(a)5 .0", 1..5, -3), "12",
1920 ". relative to string current, shorten");
1921 is(pack("(a)5 .0", 1..5, 2), "12345\x00\x00",
1922 ". relative to string current, extend");
1923 is(pack("(a)5 .0", 1..5, 0), "12345",
1924 ". relative to string current, keep");
1925
1926 is(pack("(a)5 (.)", 1..5, -3), "12",
1927 ". relative to group, shorten");
1928 is(pack("(a)5 (.)", 1..5, 2), "12345\x00\x00",
1929 ". relative to group, extend");
1930 is(pack("(a)5 (.)", 1..5, 0), "12345",
1931 ". relative to group, keep");
1932
1933 is(pack("(a)3 ((a)2 .)", 1..5, -2), "1",
1934 ". relative to group, shorten");
1935 is(pack("(a)3 ((a)2 .)", 1..5, 2), "12345",
1936 ". relative to group, keep");
1937 is(pack("(a)3 ((a)2 .)", 1..5, 4), "12345\x00\x00",
1938 ". relative to group, extend");
1939
1940 is(pack("(a)3 ((a)2 .2)", 1..5, 2), "12",
1941 ". relative to counted group, shorten");
1942 is(pack("(a)3 ((a)2 .2)", 1..5, 7), "12345\x00\x00",
1943 ". relative to counted group, extend");
1944 is(pack("(a)3 ((a)2 .2)", 1..5, 5), "12345",
1945 ". relative to counted group, keep");
1946
1947 is(pack("(a)3 ((a)2 .*)", 1..5, 2), "12",
1948 ". relative to start, shorten");
1949 is(pack("(a)3 ((a)2 .*)", 1..5, 7), "12345\x00\x00",
1950 ". relative to start, extend");
1951 is(pack("(a)3 ((a)2 .*)", 1..5, 5), "12345",
1952 ". relative to start, keep");
1953
1954 is(pack('(a)5 (. @2 a)', 1..5, -3, "a"), "12\x00\x00a",
1955 ". based shrink properly updates group starts");
1956
1957 is(pack("(W)3 ((W)2 .)", 0x301..0x305, -2), "\x{301}",
1958 "utf8 . relative to group, shorten");
1959 is(pack("(W)3 ((W)2 .)", 0x301..0x305, 2),
1960 "\x{301}\x{302}\x{303}\x{304}\x{305}",
1961 "utf8 . relative to group, keep");
1962 is(pack("(W)3 ((W)2 .)", 0x301..0x305, 4),
1963 "\x{301}\x{302}\x{303}\x{304}\x{305}\x00\x00",
1964 "utf8 . relative to group, extend");
1965
1966 is(pack("(W)3 ((W)2 .!)", 0x301..0x305, -2), "\x{301}\x{302}",
1967 "utf8 . relative to group, shorten");
1968 is(pack("(W)3 ((W)2 .!)", 0x301..0x305, 4),
1969 "\x{301}\x{302}\x{303}\x{304}\x{305}",
1970 "utf8 . relative to group, keep");
1971 is(pack("(W)3 ((W)2 .!)", 0x301..0x305, 6),
1972 "\x{301}\x{302}\x{303}\x{304}\x{305}\x00\x00",
1973 "utf8 . relative to group, extend");
1974
1975 is(pack('(W)5 (. @2 a)', 0x301..0x305, -3, "a"),
1976 "\x{301}\x{302}\x00\x00a",
1977 "utf8 . based shrink properly updates group starts");
1978}
1979{
1980 # Testing @!
1981 is(pack('a* @3', "abcde"), "abc", 'Test basic @');
1982 is(pack('a* @!3', "abcde"), "abc", 'Test basic @!');
1983 is(pack('a* @2', "\x{301}\x{302}\x{303}\x{304}\x{305}"), "\x{301}\x{302}",
1984 'Test basic utf8 @');
1985 is(pack('a* @!2', "\x{301}\x{302}\x{303}\x{304}\x{305}"), "\x{301}",
1986 'Test basic utf8 @!');
1987
1988 is(unpack('@4 a*', "abcde"), "e", 'Test basic @');
1989 is(unpack('@!4 a*', "abcde"), "e", 'Test basic @!');
1990 is(unpack('@4 a*', "\x{301}\x{302}\x{303}\x{304}\x{305}"), "\x{305}",
1991 'Test basic utf8 @');
1992 is(unpack('@!4 a*', "\x{301}\x{302}\x{303}\x{304}\x{305}"),
1993 "\x{303}\x{304}\x{305}", 'Test basic utf8 @!');
1994}
c6f750d1
NC
1995{
1996 #50256
e99c6025
KW
1997 # This test is for the bit pattern "\x61\x62", which is ASCII "ab"
1998 my ($v) = split //, unpack ('(B)*', native_to_uni('ab'));
c6f750d1
NC
1999 is($v, 0); # Doesn't SEGV :-)
2000}
858fe5e1
TC
2001{
2002 #73814
2003 my $x = runperl( prog => 'print split( /,/, unpack(q(%2H*), q(hello world))), qq(\n)' );
2004 is($x, "0\n", "split /a/, unpack('%2H*'...) didn't crash");
2005
2006 my $y = runperl( prog => 'print split( /,/, unpack(q(%32u*), q(#,3,Q)), qq(\n)), qq(\n)' );
2007 is($y, "0\n", "split /a/, unpack('%32u*'...) didn't crash");
2008}
c5333953
FC
2009
2010#90160
2011is(eval { () = unpack "C0 U*", ""; "ok" }, "ok",
2012 'medial U* on empty string');
93f6e112
FC
2013
2014package o {
2015 use overload
2016 '""' => sub { ++$o::str; "42" },
2017 '0+' => sub { ++$o::num; 42 };
2018}
2019is pack("c", bless [], "o"), chr(42), 'overloading called';
2020is $o::str, undef, 'pack "c" does not call string overloading';
2021is $o::num, 1, 'pack "c" does call num overloading';
fc1bb3f2
HS
2022
2023#[perl #123874]: argument underflow leads to corrupt length
2024eval q{ pack "pi/x" };
2025ok(1, "argument underflow did not crash");
0403a1ad
TC
2026
2027{
2028 # [perl #126325] pack [hH] with a unicode string
2029 # the hex encoders would read past the end of the string, using
2030 # invalid source bytes
2031 my $twenty_nuls = "\0" x 20;
2032 # This is the case that failed
2033 is(pack("WH40", 0x100, ""), "\x{100}$twenty_nuls",
2034 "check pack H zero fills (utf8 target)");
2035 my $up_nul = "\0";
2036
2037 utf8::upgrade($up_nul);
2038 # check the other combinations too
2039 is(pack("WH40", 0x100, $up_nul), "\x{100}$twenty_nuls",
2040 "check pack H zero fills (utf8 target/source)");
2041 is(pack("H40", ""), $twenty_nuls,
2042 "check pack H zero fills (utf8 none)");
2043 is(pack("H40", $up_nul), $twenty_nuls,
2044 "check pack H zero fills (utf8 source)");
2045}
bf4a926a 2046
30be69c8 2047SKIP:
bf4a926a
TC
2048{
2049 # [perl #129149] the code below would write one past the end of the output
2050 # buffer, only detected by ASAN, not by valgrind
60531871 2051 skip "ASCII-centric test",1 if $::IS_EBCDIC;
bf4a926a
TC
2052 $Config{ivsize} >= 8
2053 or skip "[perl #129149] need 64-bit for this test", 1;
2054 fresh_perl_is(<<'EOS', "ok\n", { stderr => 1 }, "pack W overflow");
2055print pack("ucW", "0000", 0, 140737488355327) eq "\$,#`P,```\n\0\x{7fffffffffff}"
2056 ? "ok\n" : "not ok\n";
2057EOS
2058}
f17fed50
TC
2059
2060SKIP:
2061{
2062 # [perl #131844] pointer addition overflow
2063 $Config{ptrsize} == 4
2064 or skip "[perl #131844] need 32-bit build for this test", 4;
2065 # prevent ASAN just crashing on the allocation failure
2066 local $ENV{ASAN_OPTIONS} = $ENV{ASAN_OPTIONS};
2067 $ENV{ASAN_OPTIONS} .= ",allocator_may_return_null=1";
2068 fresh_perl_like('pack "f999999999"', qr/Out of memory during pack/, { stderr => 1 },
2069 "pointer addition overflow");
2070
2071 # integer (STRLEN) overflow from addition of glen to current length
2072 fresh_perl_like('pack "c10f1073741823"', qr/Out of memory during pack/, { stderr => 1 },
2073 "integer overflow calculating allocation (addition)");
2074
2075 fresh_perl_like('pack "W10f536870913", 256', qr/Out of memory during pack/, { stderr => 1 },
2076 "integer overflow calculating allocation (utf8)");
2077
2078 fresh_perl_like('pack "c10f1073741824"', qr/Out of memory during pack/, { stderr => 1 },
2079 "integer overflow calculating allocation (multiply)");
2080}
12cad9bd
TC
2081
2082{
2083 # [perl #132655] heap-buffer-overflow READ of size 11
2084 # only expect failure under ASAN (and maybe valgrind)
2085 fresh_perl_is('0.0 + unpack("u", "ab")', "", { stderr => 1 },
2086 "ensure unpack u of invalid data nul terminates result");
2087}