Skip to content

HTTPS clone URL

Subversion checkout URL

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