xref: /openbsd-src/gnu/usr.bin/perl/t/op/sprintf2.t (revision f2da64fbbbf1b03f09f390ab01267c93dfd77c4c)
1#!./perl -w
2
3# Tests for sprintf that do not fit the format of sprintf.t.
4
5BEGIN {
6    chdir 't' if -d 't';
7    @INC = '../lib';
8    require './test.pl';
9}
10
11plan tests => 1370;
12
13use strict;
14use Config;
15
16is(
17    sprintf("%.40g ",0.01),
18    sprintf("%.40g", 0.01)." ",
19    q(the sprintf "%.<number>g" optimization)
20);
21is(
22    sprintf("%.40f ",0.01),
23    sprintf("%.40f", 0.01)." ",
24    q(the sprintf "%.<number>f" optimization)
25);
26
27# cases of $i > 1 are against [perl #39126]
28for my $i (1, 5, 10, 20, 50, 100) {
29    chop(my $utf8_format = "%-*s\x{100}");
30    my $string = "\xB4"x$i;        # latin1 ACUTE or ebcdic COPYRIGHT
31    my $expect = $string."  "x$i;  # followed by 2*$i spaces
32    is(sprintf($utf8_format, 3*$i, $string), $expect,
33       "width calculation under utf8 upgrade, length=$i");
34}
35
36# check simultaneous width & precision with wide characters
37for my $i (1, 3, 5, 10) {
38    my $string = "\x{0410}"x($i+10);   # cyrillic capital A
39    my $expect = "\x{0410}"x$i;        # cut down to exactly $i characters
40    my $format = "%$i.${i}s";
41    is(sprintf($format, $string), $expect,
42       "width & precision interplay with utf8 strings, length=$i");
43}
44
45# Used to mangle PL_sv_undef
46fresh_perl_like(
47    'print sprintf "xxx%n\n"; print undef',
48    'Modification of a read-only value attempted at - line 1\.',
49    { switches => [ '-w' ] },
50    q(%n should not be able to modify read-only constants),
51);
52
53# check overflows
54for (int(~0/2+1), ~0, "9999999999999999999") {
55    is(eval {sprintf "%${_}d", 0}, undef, "no sprintf result expected %${_}d");
56    like($@, qr/^Integer overflow in format string for sprintf /, "overflow in sprintf");
57    is(eval {printf "%${_}d\n", 0}, undef, "no printf result expected %${_}d");
58    like($@, qr/^Integer overflow in format string for printf /, "overflow in printf");
59}
60
61# check %NNN$ for range bounds
62{
63    my ($warn, $bad) = (0,0);
64    local $SIG{__WARN__} = sub {
65	if ($_[0] =~ /missing argument/i) {
66	    $warn++
67	}
68	else {
69	    $bad++
70	}
71    };
72
73    my $fmt = join('', map("%$_\$s%" . ((1 << 31)-$_) . '$s', 1..20));
74    my $result = sprintf $fmt, qw(a b c d);
75    is($result, "abcd", "only four valid values in $fmt");
76    is($warn, 36, "expected warnings");
77    is($bad,   0, "unexpected warnings");
78}
79
80{
81    foreach my $ord (0 .. 255) {
82	my $bad = 0;
83	local $SIG{__WARN__} = sub {
84	    if ($_[0] !~ /^Invalid conversion in sprintf/) {
85		warn $_[0];
86		$bad++;
87	    }
88	};
89	my $r = eval {sprintf '%v' . chr $ord};
90	is ($bad, 0, "pattern '%v' . chr $ord");
91    }
92}
93
94sub mysprintf_int_flags {
95    my ($fmt, $num) = @_;
96    die "wrong format $fmt" if $fmt !~ /^%([-+ 0]+)([1-9][0-9]*)d\z/;
97    my $flag  = $1;
98    my $width = $2;
99    my $sign  = $num < 0 ? '-' :
100		$flag =~ /\+/ ? '+' :
101		$flag =~ /\ / ? ' ' :
102		'';
103    my $abs   = abs($num);
104    my $padlen = $width - length($sign.$abs);
105    return
106	$flag =~ /0/ && $flag !~ /-/ # do zero padding
107	    ? $sign . '0' x $padlen . $abs
108	    : $flag =~ /-/ # left or right
109		? $sign . $abs . ' ' x $padlen
110		: ' ' x $padlen . $sign . $abs;
111}
112
113# Whole tests for "%4d" with 2 to 4 flags;
114# total counts: 3 * (4**2 + 4**3 + 4**4) == 1008
115
116my @flags = ("-", "+", " ", "0");
117for my $num (0, -1, 1) {
118    for my $f1 (@flags) {
119	for my $f2 (@flags) {
120	    for my $f3 ('', @flags) { # '' for doubled flags
121		my $flag = $f1.$f2.$f3;
122		my $width = 4;
123		my $fmt   = '%'."${flag}${width}d";
124		my $result = sprintf($fmt, $num);
125		my $expect = mysprintf_int_flags($fmt, $num);
126		is($result, $expect, qq/sprintf("$fmt",$num)/);
127
128	        next if $f3 eq '';
129
130		for my $f4 (@flags) { # quadrupled flags
131		    my $flag = $f1.$f2.$f3.$f4;
132		    my $fmt   = '%'."${flag}${width}d";
133		    my $result = sprintf($fmt, $num);
134		    my $expect = mysprintf_int_flags($fmt, $num);
135		    is($result, $expect, qq/sprintf("$fmt",$num)/);
136		}
137	    }
138	}
139    }
140}
141
142# test that %f doesn't panic with +Inf, -Inf, NaN [perl #45383]
143foreach my $n (2**1e100, -2**1e100, 2**1e100/2**1e100) { # +Inf, -Inf, NaN
144    eval { my $f = sprintf("%f", $n); };
145    is $@, "", "sprintf(\"%f\", $n)";
146}
147
148# test %ll formats with and without HAS_QUAD
149eval { my $q = pack "q", 0 };
150my $Q = $@ eq '';
151
152my @tests = (
153  [ '%lld' => [qw( 4294967296 -100000000000000 )] ],
154  [ '%lli' => [qw( 4294967296 -100000000000000 )] ],
155  [ '%llu' => [qw( 4294967296  100000000000000 )] ],
156  [ '%Ld'  => [qw( 4294967296 -100000000000000 )] ],
157  [ '%Li'  => [qw( 4294967296 -100000000000000 )] ],
158  [ '%Lu'  => [qw( 4294967296  100000000000000 )] ],
159);
160
161for my $t (@tests) {
162  my($fmt, $nums) = @$t;
163  for my $num (@$nums) {
164    my $w; local $SIG{__WARN__} = sub { $w = shift };
165    is(sprintf($fmt, $num), $Q ? $num : $fmt, "quad: $fmt -> $num");
166    like($w, $Q ? '' : qr/Invalid conversion in sprintf: "$fmt"/, "warning: $fmt");
167  }
168}
169
170# Check unicode vs byte length
171for my $width (1,2,3,4,5,6,7) {
172    for my $precis (1,2,3,4,5,6,7) {
173        my $v = "\x{20ac}\x{20ac}";
174        my $format = "%" . $width . "." . $precis . "s";
175        my $chars = ($precis > 2 ? 2 : $precis);
176        my $space = ($width < 2 ? 0 : $width - $chars);
177        fresh_perl_is(
178            'my $v = "\x{20ac}\x{20ac}"; my $x = sprintf "'.$format.'", $v; $x =~ /^(\s*)(\S*)$/; print "$_" for map {length} $1, $2',
179            "$space$chars",
180            {},
181            q(sprintf ").$format.q(", "\x{20ac}\x{20ac}"),
182        );
183    }
184}
185
186# Overload count
187package o { use overload '""', sub { ++our $count; $_[0][0]; } }
188my $o = bless ["\x{100}"], o::;
189() = sprintf "%1s", $o;
190is $o::count, '1', 'sprinf %1s overload count';
191$o::count = 0;
192() = sprintf "%.1s", $o;
193is $o::count, '1', 'sprinf %.1s overload count';
194