This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Hexadecimal float sprintf, for perl #122219
[perl5.git] / t / op / sprintf2.t
CommitLineData
1d917b39
RGS
1#!./perl -w
2
6715405f
FC
3# Tests for sprintf that do not fit the format of sprintf.t.
4
1d917b39
RGS
5BEGIN {
6 chdir 't' if -d 't';
7 @INC = '../lib';
8 require './test.pl';
9}
10
43d7f0da
AB
11# We'll run 12 extra tests (see below) if $Q is false.
12eval { my $q = pack "q", 0 };
13my $Q = $@ eq '';
14
40bca5ae
JH
15# %a and %A depend on the floating point config
16# This totally doesn't test non-IEEE-754 float formats.
17my @hexfloat;
18print "# uvsize = $Config{uvsize}\n";
19print "# nvsize = $Config{nvsize}\n";
20print "# nv_preserves_uv_bits = $Config{nv_preserves_uv_bits}\n";
21print "# d_quad = $Config{d_quad}\n";
22if ($Config{nvsize} == 8 &&
23 (
24 # IEEE-754, we hope, the most common out there.
25 ($Config{uvsize} == 8 && $Config{nv_preserves_uv_bits} == 53)
26 ||
27 # If we have a quad we get still get the mantissa bits.
28 ($Config{uvsize} == 4&& $Config{d_quad})
29 )
30 ) {
31 @hexfloat = (
32 [ '%a', '0', '0x0p+0' ],
33 [ '%a', '1', '0x1p+0' ],
34 [ '%a', '1.0', '0x1p+0' ],
35 [ '%a', '0.5', '0x1p-1' ],
36 [ '%a', '0.25', '0x1p-2' ],
37 [ '%a', '0.75', '0x1.8p-1' ],
38 [ '%a', '3.14', '0x1.91eb851eb851fp+1' ],
39 [ '%a', '-1.0', '-0x1p+0' ],
40 [ '%a', '-3.14', '-0x1.91eb851eb851fp+1' ],
41 [ '%a', '0.1', '0x1.999999999999ap-4' ],
42 [ '%a', '1/7', '0x1.2492492492492p-3' ],
43 [ '%a', 'sqrt(2)', '0x1.6a09e667f3bcdp+0' ],
44 [ '%a', 'exp(1)', '0x1.5bf0a8b145769p+1' ],
45 [ '%a', '2**-10', '0x1p-10' ],
46 [ '%a', '2**10', '0x1p+10' ],
47 [ '%a', '1e-9', '0x1.12e0be826d695p-30' ],
48 [ '%a', '1e9', '0x1.dcd65p+29' ],
49
50 [ '%#a', '1', '0x1.p+0' ],
51 [ '%+a', '1', '+0x1p+0' ],
52 [ '%+a', '-1', '-0x1p+0' ],
53 [ '% a', ' 1', ' 0x1p+0' ],
54 [ '% a', '-1', '-0x1p+0' ],
55
56 [ '%8a', '3.14', '0x1.91eb851eb851fp+1' ],
57 [ '%13a', '3.14', '0x1.91eb851eb851fp+1' ],
58 [ '%20a', '3.14', '0x1.91eb851eb851fp+1' ],
59 [ '%.4a', '3.14', '0x1.91ecp+1' ],
60 [ '%.5a', '3.14', '0x1.91eb8p+1' ],
61 [ '%.6a', '3.14', '0x1.91eb85p+1' ],
62 [ '%.20a', '3.14', '0x1.91eb851eb851f0000000p+1' ],
63 [ '%20.10a', '3.14', ' 0x1.91eb851eb8p+1' ],
64 [ '%20.15a', '3.14', '0x1.91eb851eb851f00p+1' ],
65 [ '% 20.10a', '3.14', ' 0x1.91eb851eb8p+1' ],
66 [ '%020.10a', '3.14', '0x0001.91eb851eb8p+1' ],
67
68 [ '%30a', '3.14', ' 0x1.91eb851eb851fp+1' ],
69 [ '%-30a', '3.14', '0x1.91eb851eb851fp+1 ' ],
70 [ '%030a', '3.14', '0x00000000001.91eb851eb851fp+1' ],
71 [ '%-030a', '3.14', '0x1.91eb851eb851fp+1 ' ],
72
73 [ '%A', '3.14', '0X1.91EB851EB851FP+1' ],
74 );
75} elsif ($Config{nvsize} == 16 || $Config{nvsize} == 12) {
76 # x86 long double, at least
77 @hexfloat = (
78 [ '%a', '0', '0x0p+0' ],
79 [ '%a', '1', '0x8p-3' ],
80 [ '%a', '1.0', '0x8p-3' ],
81 [ '%a', '0.5', '0x8p-4' ],
82 [ '%a', '0.25', '0x8p-5' ],
83 [ '%a', '0.75', '0xcp-4' ],
84 [ '%a', '3.14', '0xc.8f5c28f5c28f5c3p-2' ],
85 [ '%a', '-1.0', '-0x8p-3' ],
86 [ '%a', '-3.14', '-0xc.8f5c28f5c28f5c3p-2' ],
87 [ '%a', '0.1', '0xc.ccccccccccccccdp-7' ],
88 [ '%a', '1/7', '0x9.249249249249249p-6' ],
89 [ '%a', 'sqrt(2)', '0xb.504f333f9de6484p-3' ],
90 [ '%a', 'exp(1)', '0xa.df85458a2bb4a9bp-2' ],
91 [ '%a', '2**-10', '0x8p-13' ],
92 [ '%a', '2**10', '0x8p+7' ],
93 [ '%a', '1e-9', '0x8.9705f4136b4a597p-33' ],
94 [ '%a', '1e9', '0xe.e6b28p+26' ],
95
96 [ '%#a', '1', '0x8.p-3' ],
97 [ '%+a', '1', '+0x8p-3' ],
98 [ '%+a', '-1', '-0x8p-3' ],
99 [ '% a', ' 1', ' 0x8p-3' ],
100 [ '% a', '-1', '-0x8p-3' ],
101
102 [ '%8a', '3.14', '0xc.8f5c28f5c28f5c3p-2' ],
103 [ '%13a', '3.14', '0xc.8f5c28f5c28f5c3p-2' ],
104 [ '%20a', '3.14', '0xc.8f5c28f5c28f5c3p-2' ],
105 [ '%.4a', '3.14', '0xc.8f5cp-2' ],
106 [ '%.5a', '3.14', '0xc.8f5c3p-2' ],
107 [ '%.6a', '3.14', '0xc.8f5c29p-2' ],
108 [ '%.20a', '3.14', '0xc.8f5c28f5c28f5c300000p-2' ],
109 [ '%20.10a', '3.14', ' 0xc.8f5c28f5c3p-2' ],
110 [ '%20.15a', '3.14', '0xc.8f5c28f5c28f5c3p-2' ],
111 [ '% 20.10a', '3.14', ' 0xc.8f5c28f5c3p-2' ],
112 [ '%020.10a', '3.14', '0x000c.8f5c28f5c3p-2' ],
113
114 [ '%30a', '3.14', ' 0xc.8f5c28f5c28f5c3p-2' ],
115 [ '%-30a', '3.14', '0xc.8f5c28f5c28f5c3p-2 ' ],
116 [ '%030a', '3.14', '0x00000000c.8f5c28f5c28f5c3p-2' ],
117 [ '%-030a', '3.14', '0xc.8f5c28f5c28f5c3p-2 ' ],
118
119 [ '%A', '3.14', '0XC.8F5C28F5C28F5C3P-2' ],
120 );
121} else {
122 print "# no hexfloat tests\n";
123}
124
125plan tests => 1406 + ($Q ? 0 : 12) + @hexfloat;
53f65a9e
HS
126
127use strict;
128use Config;
1d917b39
RGS
129
130is(
131 sprintf("%.40g ",0.01),
132 sprintf("%.40g", 0.01)." ",
133 q(the sprintf "%.<number>g" optimization)
134);
135is(
136 sprintf("%.40f ",0.01),
137 sprintf("%.40f", 0.01)." ",
138 q(the sprintf "%.<number>f" optimization)
139);
cc61b222
ST
140
141# cases of $i > 1 are against [perl #39126]
142for my $i (1, 5, 10, 20, 50, 100) {
143 chop(my $utf8_format = "%-*s\x{100}");
144 my $string = "\xB4"x$i; # latin1 ACUTE or ebcdic COPYRIGHT
145 my $expect = $string." "x$i; # followed by 2*$i spaces
146 is(sprintf($utf8_format, 3*$i, $string), $expect,
147 "width calculation under utf8 upgrade, length=$i");
6c94ec8b 148}
fc7325bb 149
59b61096
AV
150# check simultaneous width & precision with wide characters
151for my $i (1, 3, 5, 10) {
152 my $string = "\x{0410}"x($i+10); # cyrillic capital A
153 my $expect = "\x{0410}"x$i; # cut down to exactly $i characters
154 my $format = "%$i.${i}s";
155 is(sprintf($format, $string), $expect,
156 "width & precision interplay with utf8 strings, length=$i");
157}
158
fc7325bb 159# Used to mangle PL_sv_undef
7baa4690 160fresh_perl_like(
fc7325bb 161 'print sprintf "xxx%n\n"; print undef',
aaa63dae 162 qr/Modification of a read-only value attempted at - line 1\./,
fc7325bb
GA
163 { switches => [ '-w' ] },
164 q(%n should not be able to modify read-only constants),
863811b2
DM
165);
166
2fba7546 167# check overflows
45e52d63 168for (int(~0/2+1), ~0, "9999999999999999999") {
2fba7546
GA
169 is(eval {sprintf "%${_}d", 0}, undef, "no sprintf result expected %${_}d");
170 like($@, qr/^Integer overflow in format string for sprintf /, "overflow in sprintf");
171 is(eval {printf "%${_}d\n", 0}, undef, "no printf result expected %${_}d");
94bbb3f4 172 like($@, qr/^Integer overflow in format string for printf /, "overflow in printf");
2fba7546 173}
863811b2 174
2fba7546 175# check %NNN$ for range bounds
863811b2
DM
176{
177 my ($warn, $bad) = (0,0);
178 local $SIG{__WARN__} = sub {
7baa4690 179 if ($_[0] =~ /missing argument/i) {
863811b2
DM
180 $warn++
181 }
182 else {
183 $bad++
184 }
185 };
2fba7546 186
45e52d63 187 my $fmt = join('', map("%$_\$s%" . ((1 << 31)-$_) . '$s', 1..20));
2fba7546
GA
188 my $result = sprintf $fmt, qw(a b c d);
189 is($result, "abcd", "only four valid values in $fmt");
863811b2
DM
190 is($warn, 36, "expected warnings");
191 is($bad, 0, "unexpected warnings");
192}
193
4077a6bc
AB
194# Tests for "missing argument" and "redundant argument" warnings
195{
196 my ($warn_missing, $warn_redundant, $warn_bad) = (0,0,0);
197 local $SIG{__WARN__} = sub {
198 if ($_[0] =~ /missing argument/i) {
199 $warn_missing++
200 }
201 elsif ($_[0] =~ /redundant argument/i) {
202 $warn_redundant++
203 }
204 else {
205 $warn_bad++
206 }
207 };
208
209 my @tests = (
210 # The "", "%s", and "%-p" formats have special-case handling
211 # in sv.c
212 {
213 fmt => "",
214 args => [ qw( x ) ],
215 res => "",
216 m => 0,
217 r => 1,
218 },
219 {
220 fmt => "%s",
221 args => [ qw( x y ) ],
222 res => "x",
223 m => 0,
224 r => 1,
225 },
226 {
227 fmt => "%-p",
228 args => [ qw( x y ) ],
229 res => qr/^[0-9a-f]+$/as,
230 m => 0,
231 r => 1,
232 },
233 # Other non-specialcased patterns
234 {
235 fmt => "%s : %s",
236 args => [ qw( a b c ) ],
237 res => "a : b",
238 m => 0,
239 r => 1,
240 },
241 {
242 fmt => "%s : %s : %s",
243 args => [ qw( a b c d e ) ],
244 res => "a : b : c",
245 m => 0,
246 # Note how we'll only warn about redundant arguments once,
247 # even though both "d" and "e" are redundant...
248 r => 1,
249 },
250 {
251 fmt => "%s : %s : %s",
252 args => [ ],
253 res => " : : ",
254 # ...But when arguments are missing we'll warn about every
255 # missing argument. This difference between the two
256 # warnings is a feature.
257 m => 3,
258 r => 0,
259 },
260
261 # Tests for format parameter indexes.
262 #
263 # Deciding what to do about these is a bit tricky, and so is
264 # "correctly" warning about missing arguments on them.
265 #
266 # Should we warn if you supply 4 arguments but only use
267 # argument 1,3 & 4? Or only if you supply 5 arguments and your
268 # highest used argument is 4?
269 #
270 # For some uses of this printf feature (e.g. i18n systems)
271 # it's a always a logic error to not print out every provided
272 # argument, but for some other uses skipping some might be a
273 # feature (although you could argue that then printf should be
274 # called as e.g:
275 #
276 # printf q[%1$s %3$s], x(), undef, z();
277 #
278 # Instead of:
279 #
280 # printf q[%1$s %3$s], x(), y(), z();
281 #
282 # Since calling the (possibly expensive) y() function is
283 # completely redundant there.
284 #
285 # We deal with all these potential problems by not even
286 # trying. If the pattern contains any format parameter indexes
287 # whatsoever we'll never warn about redundant arguments.
288 {
289 fmt => '%1$s : %2$s',
290 args => [ qw( x y z ) ],
291 res => "x : y",
292 m => 0,
293 r => 0,
294 },
295 {
296 fmt => '%2$s : %4$s : %5$s',
297 args => [ qw( a b c d )],
298 res => "b : d : ",
299 m => 1,
300 r => 0,
301 },
302 {
303 fmt => '%s : %1$s : %s',
304 args => [ qw( x y z ) ],
305 res => "x : x : y",
306 m => 0,
307 r => 0,
308 },
309
310 );
311
312 for my $i (0..$#tests) {
313 my $test = $tests[$i];
314 my $result = sprintf $test->{fmt}, @{$test->{args}};
315
316 my $prefix = "For format '$test->{fmt}' and arguments/result '@{$test->{args}}'/'$result'";
317 if (ref $test->{res} eq 'Regexp') {
318 like($result, $test->{res}, "$prefix got the right result");
319 } else {
320 is($result, $test->{res}, "$prefix got the right result");
321 }
322 is($warn_missing, $test->{m}, "$prefix got '$test->{m}' 'missing argument' warnings");
323 is($warn_redundant, $test->{r}, "$prefix got '$test->{r}' 'redundant argument' warnings");
324 is($warn_bad, 0, "$prefix No unknown warnings");
325
326 ($warn_missing, $warn_redundant, $warn_bad) = (0,0,0);
327 }
328}
329
343ef749
NC
330{
331 foreach my $ord (0 .. 255) {
332 my $bad = 0;
333 local $SIG{__WARN__} = sub {
334 if ($_[0] !~ /^Invalid conversion in sprintf/) {
335 warn $_[0];
336 $bad++;
337 }
338 };
339 my $r = eval {sprintf '%v' . chr $ord};
340 is ($bad, 0, "pattern '%v' . chr $ord");
341 }
342}
9911cee9
ST
343
344sub mysprintf_int_flags {
345 my ($fmt, $num) = @_;
346 die "wrong format $fmt" if $fmt !~ /^%([-+ 0]+)([1-9][0-9]*)d\z/;
347 my $flag = $1;
348 my $width = $2;
349 my $sign = $num < 0 ? '-' :
350 $flag =~ /\+/ ? '+' :
351 $flag =~ /\ / ? ' ' :
352 '';
353 my $abs = abs($num);
354 my $padlen = $width - length($sign.$abs);
355 return
356 $flag =~ /0/ && $flag !~ /-/ # do zero padding
357 ? $sign . '0' x $padlen . $abs
358 : $flag =~ /-/ # left or right
359 ? $sign . $abs . ' ' x $padlen
360 : ' ' x $padlen . $sign . $abs;
361}
362
363# Whole tests for "%4d" with 2 to 4 flags;
364# total counts: 3 * (4**2 + 4**3 + 4**4) == 1008
365
366my @flags = ("-", "+", " ", "0");
367for my $num (0, -1, 1) {
368 for my $f1 (@flags) {
369 for my $f2 (@flags) {
370 for my $f3 ('', @flags) { # '' for doubled flags
371 my $flag = $f1.$f2.$f3;
372 my $width = 4;
373 my $fmt = '%'."${flag}${width}d";
374 my $result = sprintf($fmt, $num);
375 my $expect = mysprintf_int_flags($fmt, $num);
376 is($result, $expect, qq/sprintf("$fmt",$num)/);
377
378 next if $f3 eq '';
379
380 for my $f4 (@flags) { # quadrupled flags
381 my $flag = $f1.$f2.$f3.$f4;
382 my $fmt = '%'."${flag}${width}d";
383 my $result = sprintf($fmt, $num);
384 my $expect = mysprintf_int_flags($fmt, $num);
385 is($result, $expect, qq/sprintf("$fmt",$num)/);
386 }
387 }
388 }
389 }
390}
391
9c2a5cfe
B
392# test that %f doesn't panic with +Inf, -Inf, NaN [perl #45383]
393foreach my $n (2**1e100, -2**1e100, 2**1e100/2**1e100) { # +Inf, -Inf, NaN
394 eval { my $f = sprintf("%f", $n); };
395 is $@, "", "sprintf(\"%f\", $n)";
396}
53f65a9e
HS
397
398# test %ll formats with and without HAS_QUAD
53f65a9e 399my @tests = (
8ff953de
MHM
400 [ '%lld' => [qw( 4294967296 -100000000000000 )] ],
401 [ '%lli' => [qw( 4294967296 -100000000000000 )] ],
402 [ '%llu' => [qw( 4294967296 100000000000000 )] ],
403 [ '%Ld' => [qw( 4294967296 -100000000000000 )] ],
404 [ '%Li' => [qw( 4294967296 -100000000000000 )] ],
405 [ '%Lu' => [qw( 4294967296 100000000000000 )] ],
53f65a9e
HS
406);
407
408for my $t (@tests) {
8ff953de
MHM
409 my($fmt, $nums) = @$t;
410 for my $num (@$nums) {
826af139
AB
411 my $w = '';
412 local $SIG{__WARN__} = sub { $w .= shift };
413 my $sprintf_got = sprintf($fmt, $num);
414 if ($Q) {
415 is($sprintf_got, $num, "quad: $fmt -> $num");
416 is($w, '', "no warnings for: $fmt -> $num");
417 } else {
418 is($sprintf_got, $fmt, "quad unsupported: $fmt -> $fmt");
419 like($w, qr/Invalid conversion in sprintf: "$fmt"/, "got warning about invalid conversion from fmt : $fmt");
3101bb05 420 like($w, qr/Redundant argument in sprintf/, "got warning about redundant argument in sprintf from fmt : $fmt");
826af139 421 }
53f65a9e
HS
422 }
423}
424
9ef5ed94
AV
425# Check unicode vs byte length
426for my $width (1,2,3,4,5,6,7) {
427 for my $precis (1,2,3,4,5,6,7) {
428 my $v = "\x{20ac}\x{20ac}";
429 my $format = "%" . $width . "." . $precis . "s";
430 my $chars = ($precis > 2 ? 2 : $precis);
431 my $space = ($width < 2 ? 0 : $width - $chars);
432 fresh_perl_is(
433 'my $v = "\x{20ac}\x{20ac}"; my $x = sprintf "'.$format.'", $v; $x =~ /^(\s*)(\S*)$/; print "$_" for map {length} $1, $2',
434 "$space$chars",
435 {},
436 q(sprintf ").$format.q(", "\x{20ac}\x{20ac}"),
437 );
438 }
439}
667f6f15
FC
440
441# Overload count
442package o { use overload '""', sub { ++our $count; $_[0][0]; } }
443my $o = bless ["\x{100}"], o::;
444() = sprintf "%1s", $o;
445is $o::count, '1', 'sprinf %1s overload count';
446$o::count = 0;
447() = sprintf "%.1s", $o;
448is $o::count, '1', 'sprinf %.1s overload count';
40bca5ae
JH
449
450for my $t (@hexfloat) {
451 my ($format, $arg, $expected) = @$t;
452 $arg = eval $arg;
453 my $result = sprintf($format, $arg);
454 is($result, $expected, "'$format' '$arg' -> '$result' cf '$expected'");
455}