Debian Codegraph @

errors/fmt/fmt_test.go

raw symbols SCIP
1 // Copyright 2009 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 package fmt_test
6
7 import (
8 "bytes"
9 . "golang.org/x/exp/errors/fmt"
10 "io"
11 "math"
12 "reflect"
13 "runtime"
14 "strings"
15 "testing"
16 "time"
17 // "unicode"
18 )
19
20 type (
21 renamedBool bool
22 renamedInt int
23 renamedInt8 int8
24 renamedInt16 int16
25 renamedInt32 int32
26 renamedInt64 int64
27 renamedUint uint
28 renamedUint8 uint8
29 renamedUint16 uint16
30 renamedUint32 uint32
31 renamedUint64 uint64
32 renamedUintptr uintptr
33 renamedString string
34 renamedBytes []byte
35 renamedFloat32 float32
36 renamedFloat64 float64
37 renamedComplex64 complex64
38 renamedComplex128 complex128
39 )
40
41 func TestFmtInterface(t *testing.T) {
42 var i1 interface{}
43 i1 = "abc"
44 s := Sprintf("%s", i1)
45 if s != "abc" {
46 t.Errorf(`Sprintf("%%s", empty("abc")) = %q want %q`, s, "abc")
47 }
48 }
49
50 var (
51 NaN = math.NaN()
52 posInf = math.Inf(1)
53 negInf = math.Inf(-1)
54
55 intVar = 0
56
57 array = [5]int{1, 2, 3, 4, 5}
58 iarray = [4]interface{}{1, "hello", 2.5, nil}
59 slice = array[:]
60 islice = iarray[:]
61 )
62
63 type A struct {
64 i int
65 j uint
66 s string
67 x []int
68 }
69
70 type I int
71
72 func (i I) String() string { return Sprintf("<%d>", int(i)) }
73
74 type B struct {
75 I I
76 j int
77 }
78
79 type C struct {
80 i int
81 B
82 }
83
84 type F int
85
86 func (f F) Format(s State, c rune) {
87 Fprintf(s, "<%c=F(%d)>", c, int(f))
88 }
89
90 type G int
91
92 func (g G) GoString() string {
93 return Sprintf("GoString(%d)", int(g))
94 }
95
96 type S struct {
97 F F // a struct field that Formats
98 G G // a struct field that GoStrings
99 }
100
101 type SI struct {
102 I interface{}
103 }
104
105 // P is a type with a String method with pointer receiver for testing %p.
106 type P int
107
108 var pValue P
109
110 func (p *P) String() string {
111 return "String(p)"
112 }
113
114 var barray = [5]renamedUint8{1, 2, 3, 4, 5}
115 var bslice = barray[:]
116
117 type byteStringer byte
118
119 func (byteStringer) String() string {
120 return "X"
121 }
122
123 var byteStringerSlice = []byteStringer{'h', 'e', 'l', 'l', 'o'}
124
125 type byteFormatter byte
126
127 func (byteFormatter) Format(f State, _ rune) {
128 Fprint(f, "X")
129 }
130
131 var byteFormatterSlice = []byteFormatter{'h', 'e', 'l', 'l', 'o'}
132
133 // Copy of io.stringWriter interface used by writeStringFormatter for type assertion.
134 type stringWriter interface {
135 WriteString(s string) (n int, err error)
136 }
137
138 type writeStringFormatter string
139
140 func (sf writeStringFormatter) Format(f State, c rune) {
141 if sw, ok := f.(stringWriter); ok {
142 sw.WriteString("***" + string(sf) + "***")
143 }
144 }
145
146 var fmtTests = []struct {
147 fmt string
148 val interface{}
149 out string
150 }{
151 {"%d", 12345, "12345"},
152 {"%v", 12345, "12345"},
153 {"%t", true, "true"},
154
155 // basic string
156 {"%s", "abc", "abc"},
157 {"%q", "abc", `"abc"`},
158 {"%x", "abc", "616263"},
159 {"%x", "\xff\xf0\x0f\xff", "fff00fff"},
160 {"%X", "\xff\xf0\x0f\xff", "FFF00FFF"},
161 {"%x", "", ""},
162 {"% x", "", ""},
163 {"%#x", "", ""},
164 {"%# x", "", ""},
165 {"%x", "xyz", "78797a"},
166 {"%X", "xyz", "78797A"},
167 {"% x", "xyz", "78 79 7a"},
168 {"% X", "xyz", "78 79 7A"},
169 {"%#x", "xyz", "0x78797a"},
170 {"%#X", "xyz", "0X78797A"},
171 {"%# x", "xyz", "0x78 0x79 0x7a"},
172 {"%# X", "xyz", "0X78 0X79 0X7A"},
173
174 // basic bytes
175 {"%s", []byte("abc"), "abc"},
176 {"%s", [3]byte{'a', 'b', 'c'}, "abc"},
177 {"%s", &[3]byte{'a', 'b', 'c'}, "&abc"},
178 {"%q", []byte("abc"), `"abc"`},
179 {"%x", []byte("abc"), "616263"},
180 {"%x", []byte("\xff\xf0\x0f\xff"), "fff00fff"},
181 {"%X", []byte("\xff\xf0\x0f\xff"), "FFF00FFF"},
182 {"%x", []byte(""), ""},
183 {"% x", []byte(""), ""},
184 {"%#x", []byte(""), ""},
185 {"%# x", []byte(""), ""},
186 {"%x", []byte("xyz"), "78797a"},
187 {"%X", []byte("xyz"), "78797A"},
188 {"% x", []byte("xyz"), "78 79 7a"},
189 {"% X", []byte("xyz"), "78 79 7A"},
190 {"%#x", []byte("xyz"), "0x78797a"},
191 {"%#X", []byte("xyz"), "0X78797A"},
192 {"%# x", []byte("xyz"), "0x78 0x79 0x7a"},
193 {"%# X", []byte("xyz"), "0X78 0X79 0X7A"},
194
195 // escaped strings
196 {"%q", "", `""`},
197 {"%#q", "", "``"},
198 {"%q", "\"", `"\""`},
199 {"%#q", "\"", "`\"`"},
200 {"%q", "`", `"` + "`" + `"`},
201 {"%#q", "`", `"` + "`" + `"`},
202 {"%q", "\n", `"\n"`},
203 {"%#q", "\n", `"\n"`},
204 {"%q", `\n`, `"\\n"`},
205 {"%#q", `\n`, "`\\n`"},
206 {"%q", "abc", `"abc"`},
207 {"%#q", "abc", "`abc`"},
208 {"%q", "日本語", `"日本語"`},
209 {"%+q", "日本語", `"\u65e5\u672c\u8a9e"`},
210 {"%#q", "日本語", "`日本語`"},
211 {"%#+q", "日本語", "`日本語`"},
212 {"%q", "\a\b\f\n\r\t\v\"\\", `"\a\b\f\n\r\t\v\"\\"`},
213 {"%+q", "\a\b\f\n\r\t\v\"\\", `"\a\b\f\n\r\t\v\"\\"`},
214 {"%#q", "\a\b\f\n\r\t\v\"\\", `"\a\b\f\n\r\t\v\"\\"`},
215 {"%#+q", "\a\b\f\n\r\t\v\"\\", `"\a\b\f\n\r\t\v\"\\"`},
216 {"%q", "☺", `"☺"`},
217 {"% q", "☺", `"☺"`}, // The space modifier should have no effect.
218 {"%+q", "☺", `"\u263a"`},
219 {"%#q", "☺", "`☺`"},
220 {"%#+q", "☺", "`☺`"},
221 {"%10q", "⌘", ` "⌘"`},
222 {"%+10q", "⌘", ` "\u2318"`},
223 {"%-10q", "⌘", `"⌘" `},
224 {"%+-10q", "⌘", `"\u2318" `},
225 {"%010q", "⌘", `0000000"⌘"`},
226 {"%+010q", "⌘", `00"\u2318"`},
227 {"%-010q", "⌘", `"⌘" `}, // 0 has no effect when - is present.
228 {"%+-010q", "⌘", `"\u2318" `},
229 {"%#8q", "\n", ` "\n"`},
230 {"%#+8q", "\r", ` "\r"`},
231 {"%#-8q", "\t", "` ` "},
232 {"%#+-8q", "\b", `"\b" `},
233 {"%q", "abc\xffdef", `"abc\xffdef"`},
234 {"%+q", "abc\xffdef", `"abc\xffdef"`},
235 {"%#q", "abc\xffdef", `"abc\xffdef"`},
236 {"%#+q", "abc\xffdef", `"abc\xffdef"`},
237 // Runes that are not printable.
238 {"%q", "\U0010ffff", `"\U0010ffff"`},
239 {"%+q", "\U0010ffff", `"\U0010ffff"`},
240 {"%#q", "\U0010ffff", "`􏿿`"},
241 {"%#+q", "\U0010ffff", "`􏿿`"},
242 // Runes that are not valid.
243 {"%q", string(rune(0x110000)), `"�"`},
244 {"%+q", string(rune(0x110000)), `"\ufffd"`},
245 {"%#q", string(rune(0x110000)), "`�`"},
246 {"%#+q", string(rune(0x110000)), "`�`"},
247
248 // characters
249 {"%c", uint('x'), "x"},
250 {"%c", 0xe4, "ä"},
251 {"%c", 0x672c, "本"},
252 {"%c", '日', "日"},
253 {"%.0c", '⌘', "⌘"}, // Specifying precision should have no effect.
254 {"%3c", '⌘', " ⌘"},
255 {"%-3c", '⌘', "⌘ "},
256 // Runes that are not printable.
257 {"%c", '\U00000e00', "\u0e00"},
258 {"%c", '\U0010ffff', "\U0010ffff"},
259 // Runes that are not valid.
260 {"%c", -1, "�"},
261 {"%c", 0xDC80, "�"},
262 {"%c", rune(0x110000), "�"},
263 {"%c", int64(0xFFFFFFFFF), "�"},
264 {"%c", uint64(0xFFFFFFFFF), "�"},
265
266 // escaped characters
267 {"%q", uint(0), `'\x00'`},
268 {"%+q", uint(0), `'\x00'`},
269 {"%q", '"', `'"'`},
270 {"%+q", '"', `'"'`},
271 {"%q", '\'', `'\''`},
272 {"%+q", '\'', `'\''`},
273 {"%q", '`', "'`'"},
274 {"%+q", '`', "'`'"},
275 {"%q", 'x', `'x'`},
276 {"%+q", 'x', `'x'`},
277 {"%q", 'ÿ', `'ÿ'`},
278 {"%+q", 'ÿ', `'\u00ff'`},
279 {"%q", '\n', `'\n'`},
280 {"%+q", '\n', `'\n'`},
281 {"%q", '☺', `'☺'`},
282 {"%+q", '☺', `'\u263a'`},
283 {"% q", '☺', `'☺'`}, // The space modifier should have no effect.
284 {"%.0q", '☺', `'☺'`}, // Specifying precision should have no effect.
285 {"%10q", '⌘', ` '⌘'`},
286 {"%+10q", '⌘', ` '\u2318'`},
287 {"%-10q", '⌘', `'⌘' `},
288 {"%+-10q", '⌘', `'\u2318' `},
289 {"%010q", '⌘', `0000000'⌘'`},
290 {"%+010q", '⌘', `00'\u2318'`},
291 {"%-010q", '⌘', `'⌘' `}, // 0 has no effect when - is present.
292 {"%+-010q", '⌘', `'\u2318' `},
293 // Runes that are not printable.
294 {"%q", '\U00000e00', `'\u0e00'`},
295 {"%q", '\U0010ffff', `'\U0010ffff'`},
296 // Runes that are not valid.
297 {"%q", int32(-1), "%!q(int32=-1)"},
298 {"%q", 0xDC80, `'�'`},
299 {"%q", rune(0x110000), "%!q(int32=1114112)"},
300 {"%q", int64(0xFFFFFFFFF), "%!q(int64=68719476735)"},
301 {"%q", uint64(0xFFFFFFFFF), "%!q(uint64=68719476735)"},
302
303 // width
304 {"%5s", "abc", " abc"},
305 {"%2s", "\u263a", " ☺"},
306 {"%-5s", "abc", "abc "},
307 {"%-8q", "abc", `"abc" `},
308 {"%05s", "abc", "00abc"},
309 {"%08q", "abc", `000"abc"`},
310 {"%5s", "abcdefghijklmnopqrstuvwxyz", "abcdefghijklmnopqrstuvwxyz"},
311 {"%.5s", "abcdefghijklmnopqrstuvwxyz", "abcde"},
312 {"%.0s", "日本語日本語", ""},
313 {"%.5s", "日本語日本語", "日本語日本"},
314 {"%.10s", "日本語日本語", "日本語日本語"},
315 {"%.5s", []byte("日本語日本語"), "日本語日本"},
316 {"%.5q", "abcdefghijklmnopqrstuvwxyz", `"abcde"`},
317 {"%.5x", "abcdefghijklmnopqrstuvwxyz", "6162636465"},
318 {"%.5q", []byte("abcdefghijklmnopqrstuvwxyz"), `"abcde"`},
319 {"%.5x", []byte("abcdefghijklmnopqrstuvwxyz"), "6162636465"},
320 {"%.3q", "日本語日本語", `"日本語"`},
321 {"%.3q", []byte("日本語日本語"), `"日本語"`},
322 {"%.1q", "日本語", `"日"`},
323 {"%.1q", []byte("日本語"), `"日"`},
324 {"%.1x", "日本語", "e6"},
325 {"%.1X", []byte("日本語"), "E6"},
326 {"%10.1q", "日本語日本語", ` "日"`},
327 {"%10v", nil, " <nil>"},
328 {"%-10v", nil, "<nil> "},
329
330 // integers
331 {"%d", uint(12345), "12345"},
332 {"%d", int(-12345), "-12345"},
333 {"%d", ^uint8(0), "255"},
334 {"%d", ^uint16(0), "65535"},
335 {"%d", ^uint32(0), "4294967295"},
336 {"%d", ^uint64(0), "18446744073709551615"},
337 {"%d", int8(-1 << 7), "-128"},
338 {"%d", int16(-1 << 15), "-32768"},
339 {"%d", int32(-1 << 31), "-2147483648"},
340 {"%d", int64(-1 << 63), "-9223372036854775808"},
341 {"%.d", 0, ""},
342 {"%.0d", 0, ""},
343 {"%6.0d", 0, " "},
344 {"%06.0d", 0, " "},
345 {"% d", 12345, " 12345"},
346 {"%+d", 12345, "+12345"},
347 {"%+d", -12345, "-12345"},
348 {"%b", 7, "111"},
349 {"%b", -6, "-110"},
350 {"%b", ^uint32(0), "11111111111111111111111111111111"},
351 {"%b", ^uint64(0), "1111111111111111111111111111111111111111111111111111111111111111"},
352 {"%b", int64(-1 << 63), zeroFill("-1", 63, "")},
353 {"%o", 01234, "1234"},
354 {"%#o", 01234, "01234"},
355 {"%o", ^uint32(0), "37777777777"},
356 {"%o", ^uint64(0), "1777777777777777777777"},
357 {"%#X", 0, "0X0"},
358 {"%x", 0x12abcdef, "12abcdef"},
359 {"%X", 0x12abcdef, "12ABCDEF"},
360 {"%x", ^uint32(0), "ffffffff"},
361 {"%X", ^uint64(0), "FFFFFFFFFFFFFFFF"},
362 {"%.20b", 7, "00000000000000000111"},
363 {"%10d", 12345, " 12345"},
364 {"%10d", -12345, " -12345"},
365 {"%+10d", 12345, " +12345"},
366 {"%010d", 12345, "0000012345"},
367 {"%010d", -12345, "-000012345"},
368 {"%20.8d", 1234, " 00001234"},
369 {"%20.8d", -1234, " -00001234"},
370 {"%020.8d", 1234, " 00001234"},
371 {"%020.8d", -1234, " -00001234"},
372 {"%-20.8d", 1234, "00001234 "},
373 {"%-20.8d", -1234, "-00001234 "},
374 {"%-#20.8x", 0x1234abc, "0x01234abc "},
375 {"%-#20.8X", 0x1234abc, "0X01234ABC "},
376 {"%-#20.8o", 01234, "00001234 "},
377
378 // Test correct f.intbuf overflow checks.
379 {"%068d", 1, zeroFill("", 68, "1")},
380 {"%068d", -1, zeroFill("-", 67, "1")},
381 {"%#.68x", 42, zeroFill("0x", 68, "2a")},
382 {"%.68d", -42, zeroFill("-", 68, "42")},
383 {"%+.68d", 42, zeroFill("+", 68, "42")},
384 {"% .68d", 42, zeroFill(" ", 68, "42")},
385 {"% +.68d", 42, zeroFill("+", 68, "42")},
386
387 // unicode format
388 {"%U", 0, "U+0000"},
389 {"%U", -1, "U+FFFFFFFFFFFFFFFF"},
390 {"%U", '\n', `U+000A`},
391 {"%#U", '\n', `U+000A`},
392 {"%+U", 'x', `U+0078`}, // Plus flag should have no effect.
393 {"%# U", 'x', `U+0078 'x'`}, // Space flag should have no effect.
394 {"%#.2U", 'x', `U+0078 'x'`}, // Precisions below 4 should print 4 digits.
395 {"%U", '\u263a', `U+263A`},
396 {"%#U", '\u263a', `U+263A '☺'`},
397 {"%U", '\U0001D6C2', `U+1D6C2`},
398 {"%#U", '\U0001D6C2', `U+1D6C2 '𝛂'`},
399 {"%#14.6U", '⌘', " U+002318 '⌘'"},
400 {"%#-14.6U", '⌘', "U+002318 '⌘' "},
401 {"%#014.6U", '⌘', " U+002318 '⌘'"},
402 {"%#-014.6U", '⌘', "U+002318 '⌘' "},
403 {"%.68U", uint(42), zeroFill("U+", 68, "2A")},
404 {"%#.68U", '日', zeroFill("U+", 68, "65E5") + " '日'"},
405
406 // floats
407 {"%+.3e", 0.0, "+0.000e+00"},
408 {"%+.3e", 1.0, "+1.000e+00"},
409 {"%+.3f", -1.0, "-1.000"},
410 {"%+.3F", -1.0, "-1.000"},
411 {"%+.3F", float32(-1.0), "-1.000"},
412 {"%+07.2f", 1.0, "+001.00"},
413 {"%+07.2f", -1.0, "-001.00"},
414 {"%-07.2f", 1.0, "1.00 "},
415 {"%-07.2f", -1.0, "-1.00 "},
416 {"%+-07.2f", 1.0, "+1.00 "},
417 {"%+-07.2f", -1.0, "-1.00 "},
418 {"%-+07.2f", 1.0, "+1.00 "},
419 {"%-+07.2f", -1.0, "-1.00 "},
420 {"%+10.2f", +1.0, " +1.00"},
421 {"%+10.2f", -1.0, " -1.00"},
422 {"% .3E", -1.0, "-1.000E+00"},
423 {"% .3e", 1.0, " 1.000e+00"},
424 {"%+.3g", 0.0, "+0"},
425 {"%+.3g", 1.0, "+1"},
426 {"%+.3g", -1.0, "-1"},
427 {"% .3g", -1.0, "-1"},
428 {"% .3g", 1.0, " 1"},
429 {"%b", float32(1.0), "8388608p-23"},
430 {"%b", 1.0, "4503599627370496p-52"},
431 // Test sharp flag used with floats.
432 {"%#g", 1e-323, "1.00000e-323"},
433 {"%#g", -1.0, "-1.00000"},
434 {"%#g", 1.1, "1.10000"},
435 {"%#g", 123456.0, "123456."},
436 {"%#g", 1234567.0, "1.234567e+06"},
437 {"%#g", 1230000.0, "1.23000e+06"},
438 {"%#g", 1000000.0, "1.00000e+06"},
439 {"%#.0f", 1.0, "1."},
440 {"%#.0e", 1.0, "1.e+00"},
441 {"%#.0g", 1.0, "1."},
442 {"%#.0g", 1100000.0, "1.e+06"},
443 {"%#.4f", 1.0, "1.0000"},
444 {"%#.4e", 1.0, "1.0000e+00"},
445 {"%#.4g", 1.0, "1.000"},
446 {"%#.4g", 100000.0, "1.000e+05"},
447 {"%#.0f", 123.0, "123."},
448 {"%#.0e", 123.0, "1.e+02"},
449 {"%#.0g", 123.0, "1.e+02"},
450 {"%#.4f", 123.0, "123.0000"},
451 {"%#.4e", 123.0, "1.2300e+02"},
452 {"%#.4g", 123.0, "123.0"},
453 {"%#.4g", 123000.0, "1.230e+05"},
454 {"%#9.4g", 1.0, " 1.000"},
455 // The sharp flag has no effect for binary float format.
456 {"%#b", 1.0, "4503599627370496p-52"},
457 // Precision has no effect for binary float format.
458 {"%.4b", float32(1.0), "8388608p-23"},
459 {"%.4b", -1.0, "-4503599627370496p-52"},
460 // Test correct f.intbuf boundary checks.
461 {"%.68f", 1.0, zeroFill("1.", 68, "")},
462 {"%.68f", -1.0, zeroFill("-1.", 68, "")},
463 // float infinites and NaNs
464 {"%f", posInf, "+Inf"},
465 {"%.1f", negInf, "-Inf"},
466 {"% f", NaN, " NaN"},
467 {"%20f", posInf, " +Inf"},
468 {"% 20F", posInf, " Inf"},
469 {"% 20e", negInf, " -Inf"},
470 {"%+20E", negInf, " -Inf"},
471 {"% +20g", negInf, " -Inf"},
472 {"%+-20G", posInf, "+Inf "},
473 {"%20e", NaN, " NaN"},
474 {"% +20E", NaN, " +NaN"},
475 {"% -20g", NaN, " NaN "},
476 {"%+-20G", NaN, "+NaN "},
477 // Zero padding does not apply to infinities and NaN.
478 {"%+020e", posInf, " +Inf"},
479 {"%-020f", negInf, "-Inf "},
480 {"%-020E", NaN, "NaN "},
481
482 // complex values
483 {"%.f", 0i, "(0+0i)"},
484 {"% .f", 0i, "( 0+0i)"},
485 {"%+.f", 0i, "(+0+0i)"},
486 {"% +.f", 0i, "(+0+0i)"},
487 {"%+.3e", 0i, "(+0.000e+00+0.000e+00i)"},
488 {"%+.3f", 0i, "(+0.000+0.000i)"},
489 {"%+.3g", 0i, "(+0+0i)"},
490 {"%+.3e", 1 + 2i, "(+1.000e+00+2.000e+00i)"},
491 {"%+.3f", 1 + 2i, "(+1.000+2.000i)"},
492 {"%+.3g", 1 + 2i, "(+1+2i)"},
493 {"%.3e", 0i, "(0.000e+00+0.000e+00i)"},
494 {"%.3f", 0i, "(0.000+0.000i)"},
495 {"%.3F", 0i, "(0.000+0.000i)"},
496 {"%.3F", complex64(0i), "(0.000+0.000i)"},
497 {"%.3g", 0i, "(0+0i)"},
498 {"%.3e", 1 + 2i, "(1.000e+00+2.000e+00i)"},
499 {"%.3f", 1 + 2i, "(1.000+2.000i)"},
500 {"%.3g", 1 + 2i, "(1+2i)"},
501 {"%.3e", -1 - 2i, "(-1.000e+00-2.000e+00i)"},
502 {"%.3f", -1 - 2i, "(-1.000-2.000i)"},
503 {"%.3g", -1 - 2i, "(-1-2i)"},
504 {"% .3E", -1 - 2i, "(-1.000E+00-2.000E+00i)"},
505 {"%+.3g", 1 + 2i, "(+1+2i)"},
506 {"%+.3g", complex64(1 + 2i), "(+1+2i)"},
507 {"%#g", 1 + 2i, "(1.00000+2.00000i)"},
508 {"%#g", 123456 + 789012i, "(123456.+789012.i)"},
509 {"%#g", 1e-10i, "(0.00000+1.00000e-10i)"},
510 {"%#g", -1e10 - 1.11e100i, "(-1.00000e+10-1.11000e+100i)"},
511 {"%#.0f", 1.23 + 1.0i, "(1.+1.i)"},
512 {"%#.0e", 1.23 + 1.0i, "(1.e+00+1.e+00i)"},
513 {"%#.0g", 1.23 + 1.0i, "(1.+1.i)"},
514 {"%#.0g", 0 + 100000i, "(0.+1.e+05i)"},
515 {"%#.0g", 1230000 + 0i, "(1.e+06+0.i)"},
516 {"%#.4f", 1 + 1.23i, "(1.0000+1.2300i)"},
517 {"%#.4e", 123 + 1i, "(1.2300e+02+1.0000e+00i)"},
518 {"%#.4g", 123 + 1.23i, "(123.0+1.230i)"},
519 {"%#12.5g", 0 + 100000i, "( 0.0000 +1.0000e+05i)"},
520 {"%#12.5g", 1230000 - 0i, "( 1.2300e+06 +0.0000i)"},
521 {"%b", 1 + 2i, "(4503599627370496p-52+4503599627370496p-51i)"},
522 {"%b", complex64(1 + 2i), "(8388608p-23+8388608p-22i)"},
523 // The sharp flag has no effect for binary complex format.
524 {"%#b", 1 + 2i, "(4503599627370496p-52+4503599627370496p-51i)"},
525 // Precision has no effect for binary complex format.
526 {"%.4b", 1 + 2i, "(4503599627370496p-52+4503599627370496p-51i)"},
527 {"%.4b", complex64(1 + 2i), "(8388608p-23+8388608p-22i)"},
528 // complex infinites and NaNs
529 {"%f", complex(posInf, posInf), "(+Inf+Infi)"},
530 {"%f", complex(negInf, negInf), "(-Inf-Infi)"},
531 {"%f", complex(NaN, NaN), "(NaN+NaNi)"},
532 {"%.1f", complex(posInf, posInf), "(+Inf+Infi)"},
533 {"% f", complex(posInf, posInf), "( Inf+Infi)"},
534 {"% f", complex(negInf, negInf), "(-Inf-Infi)"},
535 {"% f", complex(NaN, NaN), "( NaN+NaNi)"},
536 {"%8e", complex(posInf, posInf), "( +Inf +Infi)"},
537 {"% 8E", complex(posInf, posInf), "( Inf +Infi)"},
538 {"%+8f", complex(negInf, negInf), "( -Inf -Infi)"},
539 {"% +8g", complex(negInf, negInf), "( -Inf -Infi)"},
540 {"% -8G", complex(NaN, NaN), "( NaN +NaN i)"},
541 {"%+-8b", complex(NaN, NaN), "(+NaN +NaN i)"},
542 // Zero padding does not apply to infinities and NaN.
543 {"%08f", complex(posInf, posInf), "( +Inf +Infi)"},
544 {"%-08g", complex(negInf, negInf), "(-Inf -Inf i)"},
545 {"%-08G", complex(NaN, NaN), "(NaN +NaN i)"},
546
547 // old test/fmt_test.go
548 {"%e", 1.0, "1.000000e+00"},
549 {"%e", 1234.5678e3, "1.234568e+06"},
550 {"%e", 1234.5678e-8, "1.234568e-05"},
551 {"%e", -7.0, "-7.000000e+00"},
552 {"%e", -1e-9, "-1.000000e-09"},
553 {"%f", 1234.5678e3, "1234567.800000"},
554 {"%f", 1234.5678e-8, "0.000012"},
555 {"%f", -7.0, "-7.000000"},
556 {"%f", -1e-9, "-0.000000"},
557 {"%g", 1234.5678e3, "1.2345678e+06"},
558 {"%g", float32(1234.5678e3), "1.2345678e+06"},
559 {"%g", 1234.5678e-8, "1.2345678e-05"},
560 {"%g", -7.0, "-7"},
561 {"%g", -1e-9, "-1e-09"},
562 {"%g", float32(-1e-9), "-1e-09"},
563 {"%E", 1.0, "1.000000E+00"},
564 {"%E", 1234.5678e3, "1.234568E+06"},
565 {"%E", 1234.5678e-8, "1.234568E-05"},
566 {"%E", -7.0, "-7.000000E+00"},
567 {"%E", -1e-9, "-1.000000E-09"},
568 {"%G", 1234.5678e3, "1.2345678E+06"},
569 {"%G", float32(1234.5678e3), "1.2345678E+06"},
570 {"%G", 1234.5678e-8, "1.2345678E-05"},
571 {"%G", -7.0, "-7"},
572 {"%G", -1e-9, "-1E-09"},
573 {"%G", float32(-1e-9), "-1E-09"},
574 {"%20.5s", "qwertyuiop", " qwert"},
575 {"%.5s", "qwertyuiop", "qwert"},
576 {"%-20.5s", "qwertyuiop", "qwert "},
577 {"%20c", 'x', " x"},
578 {"%-20c", 'x', "x "},
579 {"%20.6e", 1.2345e3, " 1.234500e+03"},
580 {"%20.6e", 1.2345e-3, " 1.234500e-03"},
581 {"%20e", 1.2345e3, " 1.234500e+03"},
582 {"%20e", 1.2345e-3, " 1.234500e-03"},
583 {"%20.8e", 1.2345e3, " 1.23450000e+03"},
584 {"%20f", 1.23456789e3, " 1234.567890"},
585 {"%20f", 1.23456789e-3, " 0.001235"},
586 {"%20f", 12345678901.23456789, " 12345678901.234568"},
587 {"%-20f", 1.23456789e3, "1234.567890 "},
588 {"%20.8f", 1.23456789e3, " 1234.56789000"},
589 {"%20.8f", 1.23456789e-3, " 0.00123457"},
590 {"%g", 1.23456789e3, "1234.56789"},
591 {"%g", 1.23456789e-3, "0.00123456789"},
592 {"%g", 1.23456789e20, "1.23456789e+20"},
593
594 // arrays
595 {"%v", array, "[1 2 3 4 5]"},
596 {"%v", iarray, "[1 hello 2.5 <nil>]"},
597 {"%v", barray, "[1 2 3 4 5]"},
598 {"%v", &array, "&[1 2 3 4 5]"},
599 {"%v", &iarray, "&[1 hello 2.5 <nil>]"},
600 {"%v", &barray, "&[1 2 3 4 5]"},
601
602 // slices
603 {"%v", slice, "[1 2 3 4 5]"},
604 {"%v", islice, "[1 hello 2.5 <nil>]"},
605 {"%v", bslice, "[1 2 3 4 5]"},
606 {"%v", &slice, "&[1 2 3 4 5]"},
607 {"%v", &islice, "&[1 hello 2.5 <nil>]"},
608 {"%v", &bslice, "&[1 2 3 4 5]"},
609
610 // byte arrays and slices with %b,%c,%d,%o,%U and %v
611 {"%b", [3]byte{65, 66, 67}, "[1000001 1000010 1000011]"},
612 {"%c", [3]byte{65, 66, 67}, "[A B C]"},
613 {"%d", [3]byte{65, 66, 67}, "[65 66 67]"},
614 {"%o", [3]byte{65, 66, 67}, "[101 102 103]"},
615 {"%U", [3]byte{65, 66, 67}, "[U+0041 U+0042 U+0043]"},
616 {"%v", [3]byte{65, 66, 67}, "[65 66 67]"},
617 {"%v", [1]byte{123}, "[123]"},
618 {"%012v", []byte{}, "[]"},
619 {"%#012v", []byte{}, "[]byte{}"},
620 {"%6v", []byte{1, 11, 111}, "[ 1 11 111]"},
621 {"%06v", []byte{1, 11, 111}, "[000001 000011 000111]"},
622 {"%-6v", []byte{1, 11, 111}, "[1 11 111 ]"},
623 {"%-06v", []byte{1, 11, 111}, "[1 11 111 ]"},
624 {"%#v", []byte{1, 11, 111}, "[]byte{0x1, 0xb, 0x6f}"},
625 {"%#6v", []byte{1, 11, 111}, "[]byte{ 0x1, 0xb, 0x6f}"},
626 {"%#06v", []byte{1, 11, 111}, "[]byte{0x000001, 0x00000b, 0x00006f}"},
627 {"%#-6v", []byte{1, 11, 111}, "[]byte{0x1 , 0xb , 0x6f }"},
628 {"%#-06v", []byte{1, 11, 111}, "[]byte{0x1 , 0xb , 0x6f }"},
629 // f.space should and f.plus should not have an effect with %v.
630 {"% v", []byte{1, 11, 111}, "[ 1 11 111]"},
631 {"%+v", [3]byte{1, 11, 111}, "[1 11 111]"},
632 {"%# -6v", []byte{1, 11, 111}, "[]byte{ 0x1 , 0xb , 0x6f }"},
633 {"%#+-6v", [3]byte{1, 11, 111}, "[3]uint8{0x1 , 0xb , 0x6f }"},
634 // f.space and f.plus should have an effect with %d.
635 {"% d", []byte{1, 11, 111}, "[ 1 11 111]"},
636 {"%+d", [3]byte{1, 11, 111}, "[+1 +11 +111]"},
637 {"%# -6d", []byte{1, 11, 111}, "[ 1 11 111 ]"},
638 {"%#+-6d", [3]byte{1, 11, 111}, "[+1 +11 +111 ]"},
639
640 // floates with %v
641 {"%v", 1.2345678, "1.2345678"},
642 {"%v", float32(1.2345678), "1.2345678"},
643
644 // complexes with %v
645 {"%v", 1 + 2i, "(1+2i)"},
646 {"%v", complex64(1 + 2i), "(1+2i)"},
647
648 // structs
649 {"%v", A{1, 2, "a", []int{1, 2}}, `{1 2 a [1 2]}`},
650 {"%+v", A{1, 2, "a", []int{1, 2}}, `{i:1 j:2 s:a x:[1 2]}`},
651
652 // +v on structs with Stringable items
653 {"%+v", B{1, 2}, `{I:<1> j:2}`},
654 {"%+v", C{1, B{2, 3}}, `{i:1 B:{I:<2> j:3}}`},
655
656 // other formats on Stringable items
657 {"%s", I(23), `<23>`},
658 {"%q", I(23), `"<23>"`},
659 {"%x", I(23), `3c32333e`},
660 {"%#x", I(23), `0x3c32333e`},
661 {"%# x", I(23), `0x3c 0x32 0x33 0x3e`},
662 // Stringer applies only to string formats.
663 {"%d", I(23), `23`},
664 // Stringer applies to the extracted value.
665 {"%s", reflect.ValueOf(I(23)), `<23>`},
666
667 // go syntax
668 {"%#v", A{1, 2, "a", []int{1, 2}}, `fmt_test.A{i:1, j:0x2, s:"a", x:[]int{1, 2}}`},
669 {"%#v", new(byte), "(*uint8)(0xPTR)"},
670 {"%#v", TestFmtInterface, "(func(*testing.T))(0xPTR)"},
671 {"%#v", make(chan int), "(chan int)(0xPTR)"},
672 {"%#v", uint64(1<<64 - 1), "0xffffffffffffffff"},
673 {"%#v", 1000000000, "1000000000"},
674 {"%#v", map[string]int{"a": 1}, `map[string]int{"a":1}`},
675 {"%#v", map[string]B{"a": {1, 2}}, `map[string]fmt_test.B{"a":fmt_test.B{I:1, j:2}}`},
676 {"%#v", []string{"a", "b"}, `[]string{"a", "b"}`},
677 {"%#v", SI{}, `fmt_test.SI{I:interface {}(nil)}`},
678 {"%#v", []int(nil), `[]int(nil)`},
679 {"%#v", []int{}, `[]int{}`},
680 {"%#v", array, `[5]int{1, 2, 3, 4, 5}`},
681 {"%#v", &array, `&[5]int{1, 2, 3, 4, 5}`},
682 {"%#v", iarray, `[4]interface {}{1, "hello", 2.5, interface {}(nil)}`},
683 {"%#v", &iarray, `&[4]interface {}{1, "hello", 2.5, interface {}(nil)}`},
684 {"%#v", map[int]byte(nil), `map[int]uint8(nil)`},
685 {"%#v", map[int]byte{}, `map[int]uint8{}`},
686 {"%#v", "foo", `"foo"`},
687 {"%#v", barray, `[5]fmt_test.renamedUint8{0x1, 0x2, 0x3, 0x4, 0x5}`},
688 {"%#v", bslice, `[]fmt_test.renamedUint8{0x1, 0x2, 0x3, 0x4, 0x5}`},
689 {"%#v", []int32(nil), "[]int32(nil)"},
690 {"%#v", 1.2345678, "1.2345678"},
691 {"%#v", float32(1.2345678), "1.2345678"},
692 // Only print []byte and []uint8 as type []byte if they appear at the top level.
693 {"%#v", []byte(nil), "[]byte(nil)"},
694 {"%#v", []uint8(nil), "[]byte(nil)"},
695 {"%#v", []byte{}, "[]byte{}"},
696 {"%#v", []uint8{}, "[]byte{}"},
697 {"%#v", reflect.ValueOf([]byte{}), "[]uint8{}"},
698 {"%#v", reflect.ValueOf([]uint8{}), "[]uint8{}"},
699 {"%#v", &[]byte{}, "&[]uint8{}"},
700 {"%#v", &[]byte{}, "&[]uint8{}"},
701 {"%#v", [3]byte{}, "[3]uint8{0x0, 0x0, 0x0}"},
702 {"%#v", [3]uint8{}, "[3]uint8{0x0, 0x0, 0x0}"},
703
704 // slices with other formats
705 {"%#x", []int{1, 2, 15}, `[0x1 0x2 0xf]`},
706 {"%x", []int{1, 2, 15}, `[1 2 f]`},
707 {"%d", []int{1, 2, 15}, `[1 2 15]`},
708 {"%d", []byte{1, 2, 15}, `[1 2 15]`},
709 {"%q", []string{"a", "b"}, `["a" "b"]`},
710 {"% 02x", []byte{1}, "01"},
711 {"% 02x", []byte{1, 2, 3}, "01 02 03"},
712
713 // Padding with byte slices.
714 {"%2x", []byte{}, " "},
715 {"%#2x", []byte{}, " "},
716 {"% 02x", []byte{}, "00"},
717 {"%# 02x", []byte{}, "00"},
718 {"%-2x", []byte{}, " "},
719 {"%-02x", []byte{}, " "},
720 {"%8x", []byte{0xab}, " ab"},
721 {"% 8x", []byte{0xab}, " ab"},
722 {"%#8x", []byte{0xab}, " 0xab"},
723 {"%# 8x", []byte{0xab}, " 0xab"},
724 {"%08x", []byte{0xab}, "000000ab"},
725 {"% 08x", []byte{0xab}, "000000ab"},
726 {"%#08x", []byte{0xab}, "00000xab"},
727 {"%# 08x", []byte{0xab}, "00000xab"},
728 {"%10x", []byte{0xab, 0xcd}, " abcd"},
729 {"% 10x", []byte{0xab, 0xcd}, " ab cd"},
730 {"%#10x", []byte{0xab, 0xcd}, " 0xabcd"},
731 {"%# 10x", []byte{0xab, 0xcd}, " 0xab 0xcd"},
732 {"%010x", []byte{0xab, 0xcd}, "000000abcd"},
733 {"% 010x", []byte{0xab, 0xcd}, "00000ab cd"},
734 {"%#010x", []byte{0xab, 0xcd}, "00000xabcd"},
735 {"%# 010x", []byte{0xab, 0xcd}, "00xab 0xcd"},
736 {"%-10X", []byte{0xab}, "AB "},
737 {"% -010X", []byte{0xab}, "AB "},
738 {"%#-10X", []byte{0xab, 0xcd}, "0XABCD "},
739 {"%# -010X", []byte{0xab, 0xcd}, "0XAB 0XCD "},
740 // Same for strings
741 {"%2x", "", " "},
742 {"%#2x", "", " "},
743 {"% 02x", "", "00"},
744 {"%# 02x", "", "00"},
745 {"%-2x", "", " "},
746 {"%-02x", "", " "},
747 {"%8x", "\xab", " ab"},
748 {"% 8x", "\xab", " ab"},
749 {"%#8x", "\xab", " 0xab"},
750 {"%# 8x", "\xab", " 0xab"},
751 {"%08x", "\xab", "000000ab"},
752 {"% 08x", "\xab", "000000ab"},
753 {"%#08x", "\xab", "00000xab"},
754 {"%# 08x", "\xab", "00000xab"},
755 {"%10x", "\xab\xcd", " abcd"},
756 {"% 10x", "\xab\xcd", " ab cd"},
757 {"%#10x", "\xab\xcd", " 0xabcd"},
758 {"%# 10x", "\xab\xcd", " 0xab 0xcd"},
759 {"%010x", "\xab\xcd", "000000abcd"},
760 {"% 010x", "\xab\xcd", "00000ab cd"},
761 {"%#010x", "\xab\xcd", "00000xabcd"},
762 {"%# 010x", "\xab\xcd", "00xab 0xcd"},
763 {"%-10X", "\xab", "AB "},
764 {"% -010X", "\xab", "AB "},
765 {"%#-10X", "\xab\xcd", "0XABCD "},
766 {"%# -010X", "\xab\xcd", "0XAB 0XCD "},
767
768 // renamings
769 {"%v", renamedBool(true), "true"},
770 {"%d", renamedBool(true), "%!d(fmt_test.renamedBool=true)"},
771 {"%o", renamedInt(8), "10"},
772 {"%d", renamedInt8(-9), "-9"},
773 {"%v", renamedInt16(10), "10"},
774 {"%v", renamedInt32(-11), "-11"},
775 {"%X", renamedInt64(255), "FF"},
776 {"%v", renamedUint(13), "13"},
777 {"%o", renamedUint8(14), "16"},
778 {"%X", renamedUint16(15), "F"},
779 {"%d", renamedUint32(16), "16"},
780 {"%X", renamedUint64(17), "11"},
781 {"%o", renamedUintptr(18), "22"},
782 {"%x", renamedString("thing"), "7468696e67"},
783 {"%d", renamedBytes([]byte{1, 2, 15}), `[1 2 15]`},
784 {"%q", renamedBytes([]byte("hello")), `"hello"`},
785 {"%x", []renamedUint8{'h', 'e', 'l', 'l', 'o'}, "68656c6c6f"},
786 {"%X", []renamedUint8{'h', 'e', 'l', 'l', 'o'}, "68656C6C6F"},
787 {"%s", []renamedUint8{'h', 'e', 'l', 'l', 'o'}, "hello"},
788 {"%q", []renamedUint8{'h', 'e', 'l', 'l', 'o'}, `"hello"`},
789 {"%v", renamedFloat32(22), "22"},
790 {"%v", renamedFloat64(33), "33"},
791 {"%v", renamedComplex64(3 + 4i), "(3+4i)"},
792 {"%v", renamedComplex128(4 - 3i), "(4-3i)"},
793
794 // Formatter
795 {"%x", F(1), "<x=F(1)>"},
796 {"%x", G(2), "2"},
797 {"%+v", S{F(4), G(5)}, "{F:<v=F(4)> G:5}"},
798
799 // GoStringer
800 {"%#v", G(6), "GoString(6)"},
801 {"%#v", S{F(7), G(8)}, "fmt_test.S{F:<v=F(7)>, G:GoString(8)}"},
802
803 // %T
804 {"%T", byte(0), "uint8"},
805 {"%T", reflect.ValueOf(nil), "reflect.Value"},
806 {"%T", (4 - 3i), "complex128"},
807 {"%T", renamedComplex128(4 - 3i), "fmt_test.renamedComplex128"},
808 {"%T", intVar, "int"},
809 {"%6T", &intVar, " *int"},
810 {"%10T", nil, " <nil>"},
811 {"%-10T", nil, "<nil> "},
812
813 // %p with pointers
814 {"%p", (*int)(nil), "0x0"},
815 {"%#p", (*int)(nil), "0"},
816 {"%p", &intVar, "0xPTR"},
817 {"%#p", &intVar, "PTR"},
818 {"%p", &array, "0xPTR"},
819 {"%p", &slice, "0xPTR"},
820 {"%8.2p", (*int)(nil), " 0x00"},
821 {"%-20.16p", &intVar, "0xPTR "},
822 // %p on non-pointers
823 {"%p", make(chan int), "0xPTR"},
824 {"%p", make(map[int]int), "0xPTR"},
825 {"%p", func() {}, "0xPTR"},
826 {"%p", 27, "%!p(int=27)"}, // not a pointer at all
827 {"%p", nil, "%!p(<nil>)"}, // nil on its own has no type ...
828 {"%#p", nil, "%!p(<nil>)"}, // ... and hence is not a pointer type.
829 // pointers with specified base
830 {"%b", &intVar, "PTR_b"},
831 {"%d", &intVar, "PTR_d"},
832 {"%o", &intVar, "PTR_o"},
833 {"%x", &intVar, "PTR_x"},
834 {"%X", &intVar, "PTR_X"},
835 // %v on pointers
836 {"%v", nil, "<nil>"},
837 {"%#v", nil, "<nil>"},
838 {"%v", (*int)(nil), "<nil>"},
839 {"%#v", (*int)(nil), "(*int)(nil)"},
840 {"%v", &intVar, "0xPTR"},
841 {"%#v", &intVar, "(*int)(0xPTR)"},
842 {"%8.2v", (*int)(nil), " <nil>"},
843 {"%-20.16v", &intVar, "0xPTR "},
844 // string method on pointer
845 {"%s", &pValue, "String(p)"}, // String method...
846 {"%p", &pValue, "0xPTR"}, // ... is not called with %p.
847
848 // %d on Stringer should give integer if possible
849 {"%s", time.Time{}.Month(), "January"},
850 {"%d", time.Time{}.Month(), "1"},
851
852 // erroneous things
853 {"", nil, "%!(EXTRA <nil>)"},
854 {"", 2, "%!(EXTRA int=2)"},
855 {"no args", "hello", "no args%!(EXTRA string=hello)"},
856 {"%s %", "hello", "hello %!(NOVERB)"},
857 {"%s %.2", "hello", "hello %!(NOVERB)"},
858 {"%017091901790959340919092959340919017929593813360", 0, "%!(NOVERB)%!(EXTRA int=0)"},
859 {"%184467440737095516170v", 0, "%!(NOVERB)%!(EXTRA int=0)"},
860 // Extra argument errors should format without flags set.
861 {"%010.2", "12345", "%!(NOVERB)%!(EXTRA string=12345)"},
862
863 // The "<nil>" show up because maps are printed by
864 // first obtaining a list of keys and then looking up
865 // each key. Since NaNs can be map keys but cannot
866 // be fetched directly, the lookup fails and returns a
867 // zero reflect.Value, which formats as <nil>.
868 // This test is just to check that it shows the two NaNs at all.
869 // {"%v", map[float64]int{NaN: 1, NaN: 2}, "map[NaN:<nil> NaN:<nil>]"},
870
871 // Comparison of padding rules with C printf.
872 /*
873 C program:
874 #include <stdio.h>
875
876 char *format[] = {
877 "[%.2f]",
878 "[% .2f]",
879 "[%+.2f]",
880 "[%7.2f]",
881 "[% 7.2f]",
882 "[%+7.2f]",
883 "[% +7.2f]",
884 "[%07.2f]",
885 "[% 07.2f]",
886 "[%+07.2f]",
887 "[% +07.2f]"
888 };
889
890 int main(void) {
891 int i;
892 for(i = 0; i < 11; i++) {
893 printf("%s: ", format[i]);
894 printf(format[i], 1.0);
895 printf(" ");
896 printf(format[i], -1.0);
897 printf("\n");
898 }
899 }
900
901 Output:
902 [%.2f]: [1.00] [-1.00]
903 [% .2f]: [ 1.00] [-1.00]
904 [%+.2f]: [+1.00] [-1.00]
905 [%7.2f]: [ 1.00] [ -1.00]
906 [% 7.2f]: [ 1.00] [ -1.00]
907 [%+7.2f]: [ +1.00] [ -1.00]
908 [% +7.2f]: [ +1.00] [ -1.00]
909 [%07.2f]: [0001.00] [-001.00]
910 [% 07.2f]: [ 001.00] [-001.00]
911 [%+07.2f]: [+001.00] [-001.00]
912 [% +07.2f]: [+001.00] [-001.00]
913
914 */
915 {"%.2f", 1.0, "1.00"},
916 {"%.2f", -1.0, "-1.00"},
917 {"% .2f", 1.0, " 1.00"},
918 {"% .2f", -1.0, "-1.00"},
919 {"%+.2f", 1.0, "+1.00"},
920 {"%+.2f", -1.0, "-1.00"},
921 {"%7.2f", 1.0, " 1.00"},
922 {"%7.2f", -1.0, " -1.00"},
923 {"% 7.2f", 1.0, " 1.00"},
924 {"% 7.2f", -1.0, " -1.00"},
925 {"%+7.2f", 1.0, " +1.00"},
926 {"%+7.2f", -1.0, " -1.00"},
927 {"% +7.2f", 1.0, " +1.00"},
928 {"% +7.2f", -1.0, " -1.00"},
929 {"%07.2f", 1.0, "0001.00"},
930 {"%07.2f", -1.0, "-001.00"},
931 {"% 07.2f", 1.0, " 001.00"},
932 {"% 07.2f", -1.0, "-001.00"},
933 {"%+07.2f", 1.0, "+001.00"},
934 {"%+07.2f", -1.0, "-001.00"},
935 {"% +07.2f", 1.0, "+001.00"},
936 {"% +07.2f", -1.0, "-001.00"},
937
938 // Complex numbers: exhaustively tested in TestComplexFormatting.
939 {"%7.2f", 1 + 2i, "( 1.00 +2.00i)"},
940 {"%+07.2f", -1 - 2i, "(-001.00-002.00i)"},
941
942 // Use spaces instead of zero if padding to the right.
943 {"%0-5s", "abc", "abc "},
944 {"%-05.1f", 1.0, "1.0 "},
945
946 // float and complex formatting should not change the padding width
947 // for other elements. See issue 14642.
948 {"%06v", []interface{}{+10.0, 10}, "[000010 000010]"},
949 {"%06v", []interface{}{-10.0, 10}, "[-00010 000010]"},
950 {"%06v", []interface{}{+10.0 + 10i, 10}, "[(000010+00010i) 000010]"},
951 {"%06v", []interface{}{-10.0 + 10i, 10}, "[(-00010+00010i) 000010]"},
952
953 // integer formatting should not alter padding for other elements.
954 {"%03.6v", []interface{}{1, 2.0, "x"}, "[000001 002 00x]"},
955 {"%03.0v", []interface{}{0, 2.0, "x"}, "[ 002 000]"},
956
957 // Complex fmt used to leave the plus flag set for future entries in the array
958 // causing +2+0i and +3+0i instead of 2+0i and 3+0i.
959 {"%v", []complex64{1, 2, 3}, "[(1+0i) (2+0i) (3+0i)]"},
960 {"%v", []complex128{1, 2, 3}, "[(1+0i) (2+0i) (3+0i)]"},
961
962 // Incomplete format specification caused crash.
963 {"%.", 3, "%!.(int=3)"},
964
965 // Padding for complex numbers. Has been bad, then fixed, then bad again.
966 {"%+10.2f", +104.66 + 440.51i, "( +104.66 +440.51i)"},
967 {"%+10.2f", -104.66 + 440.51i, "( -104.66 +440.51i)"},
968 {"%+10.2f", +104.66 - 440.51i, "( +104.66 -440.51i)"},
969 {"%+10.2f", -104.66 - 440.51i, "( -104.66 -440.51i)"},
970 {"%+010.2f", +104.66 + 440.51i, "(+000104.66+000440.51i)"},
971 {"%+010.2f", -104.66 + 440.51i, "(-000104.66+000440.51i)"},
972 {"%+010.2f", +104.66 - 440.51i, "(+000104.66-000440.51i)"},
973 {"%+010.2f", -104.66 - 440.51i, "(-000104.66-000440.51i)"},
974
975 // []T where type T is a byte with a Stringer method.
976 {"%v", byteStringerSlice, "[X X X X X]"},
977 {"%s", byteStringerSlice, "hello"},
978 {"%q", byteStringerSlice, "\"hello\""},
979 {"%x", byteStringerSlice, "68656c6c6f"},
980 {"%X", byteStringerSlice, "68656C6C6F"},
981 {"%#v", byteStringerSlice, "[]fmt_test.byteStringer{0x68, 0x65, 0x6c, 0x6c, 0x6f}"},
982
983 // And the same for Formatter.
984 {"%v", byteFormatterSlice, "[X X X X X]"},
985 {"%s", byteFormatterSlice, "hello"},
986 {"%q", byteFormatterSlice, "\"hello\""},
987 {"%x", byteFormatterSlice, "68656c6c6f"},
988 {"%X", byteFormatterSlice, "68656C6C6F"},
989 // This next case seems wrong, but the docs say the Formatter wins here.
990 {"%#v", byteFormatterSlice, "[]fmt_test.byteFormatter{X, X, X, X, X}"},
991
992 // pp.WriteString
993 {"%s", writeStringFormatter(""), "******"},
994 {"%s", writeStringFormatter("xyz"), "***xyz***"},
995 {"%s", writeStringFormatter("⌘/⌘"), "***⌘/⌘***"},
996
997 // reflect.Value handled specially in Go 1.5, making it possible to
998 // see inside non-exported fields (which cannot be accessed with Interface()).
999 // Issue 8965.
1000 {"%v", reflect.ValueOf(A{}).Field(0).String(), "<int Value>"}, // Equivalent to the old way.
1001 {"%v", reflect.ValueOf(A{}).Field(0), "0"}, // Sees inside the field.
1002
1003 // verbs apply to the extracted value too.
1004 {"%s", reflect.ValueOf("hello"), "hello"},
1005 {"%q", reflect.ValueOf("hello"), `"hello"`},
1006 {"%#04x", reflect.ValueOf(256), "0x0100"},
1007
1008 // invalid reflect.Value doesn't crash.
1009 {"%v", reflect.Value{}, "<invalid reflect.Value>"},
1010 {"%v", &reflect.Value{}, "<invalid Value>"},
1011 {"%v", SI{reflect.Value{}}, "{<invalid Value>}"},
1012
1013 // Tests to check that not supported verbs generate an error string.
1014 {"%☠", nil, "%!☠(<nil>)"},
1015 {"%☠", interface{}(nil), "%!☠(<nil>)"},
1016 {"%☠", int(0), "%!☠(int=0)"},
1017 {"%☠", uint(0), "%!☠(uint=0)"},
1018 {"%☠", []byte{0, 1}, "[%!☠(uint8=0) %!☠(uint8=1)]"},
1019 {"%☠", []uint8{0, 1}, "[%!☠(uint8=0) %!☠(uint8=1)]"},
1020 {"%☠", [1]byte{0}, "[%!☠(uint8=0)]"},
1021 {"%☠", [1]uint8{0}, "[%!☠(uint8=0)]"},
1022 {"%☠", "hello", "%!☠(string=hello)"},
1023 {"%☠", 1.2345678, "%!☠(float64=1.2345678)"},
1024 {"%☠", float32(1.2345678), "%!☠(float32=1.2345678)"},
1025 {"%☠", 1.2345678 + 1.2345678i, "%!☠(complex128=(1.2345678+1.2345678i))"},
1026 {"%☠", complex64(1.2345678 + 1.2345678i), "%!☠(complex64=(1.2345678+1.2345678i))"},
1027 {"%☠", &intVar, "%!☠(*int=0xPTR)"},
1028 {"%☠", make(chan int), "%!☠(chan int=0xPTR)"},
1029 {"%☠", func() {}, "%!☠(func()=0xPTR)"},
1030 {"%☠", reflect.ValueOf(renamedInt(0)), "%!☠(fmt_test.renamedInt=0)"},
1031 {"%☠", SI{renamedInt(0)}, "{%!☠(fmt_test.renamedInt=0)}"},
1032 {"%☠", &[]interface{}{I(1), G(2)}, "&[%!☠(fmt_test.I=1) %!☠(fmt_test.G=2)]"},
1033 {"%☠", SI{&[]interface{}{I(1), G(2)}}, "{%!☠(*[]interface {}=&[1 2])}"},
1034 {"%☠", reflect.Value{}, "<invalid reflect.Value>"},
1035 // {"%☠", map[float64]int{NaN: 1}, "map[%!☠(float64=NaN):%!☠(<nil>)]"},
1036 }
1037
1038 // zeroFill generates zero-filled strings of the specified width. The length
1039 // of the suffix (but not the prefix) is compensated for in the width calculation.
1040 func zeroFill(prefix string, width int, suffix string) string {
1041 return prefix + strings.Repeat("0", width-len(suffix)) + suffix
1042 }
1043
1044 func TestSprintf(t *testing.T) {
1045 for _, tt := range fmtTests {
1046 s := Sprintf(tt.fmt, tt.val)
1047 i := strings.Index(tt.out, "PTR")
1048 if i >= 0 && i < len(s) {
1049 var pattern, chars string
1050 switch {
1051 case strings.HasPrefix(tt.out[i:], "PTR_b"):
1052 pattern = "PTR_b"
1053 chars = "01"
1054 case strings.HasPrefix(tt.out[i:], "PTR_o"):
1055 pattern = "PTR_o"
1056 chars = "01234567"
1057 case strings.HasPrefix(tt.out[i:], "PTR_d"):
1058 pattern = "PTR_d"
1059 chars = "0123456789"
1060 case strings.HasPrefix(tt.out[i:], "PTR_x"):
1061 pattern = "PTR_x"
1062 chars = "0123456789abcdef"
1063 case strings.HasPrefix(tt.out[i:], "PTR_X"):
1064 pattern = "PTR_X"
1065 chars = "0123456789ABCDEF"
1066 default:
1067 pattern = "PTR"
1068 chars = "0123456789abcdefABCDEF"
1069 }
1070 p := s[:i] + pattern
1071 for j := i; j < len(s); j++ {
1072 if !strings.ContainsRune(chars, rune(s[j])) {
1073 p += s[j:]
1074 break
1075 }
1076 }
1077 s = p
1078 }
1079 if s != tt.out {
1080 if _, ok := tt.val.(string); ok {
1081 // Don't requote the already-quoted strings.
1082 // It's too confusing to read the errors.
1083 t.Errorf("Sprintf(%q, %q) = <%s> want <%s>", tt.fmt, tt.val, s, tt.out)
1084 } else {
1085 t.Errorf("Sprintf(%q, %v) = %q want %q", tt.fmt, tt.val, s, tt.out)
1086 }
1087 }
1088 }
1089 }
1090
1091 // TestComplexFormatting checks that a complex always formats to the same
1092 // thing as if done by hand with two singleton prints.
1093 func TestComplexFormatting(t *testing.T) {
1094 var yesNo = []bool{true, false}
1095 var values = []float64{1, 0, -1, posInf, negInf, NaN}
1096 for _, plus := range yesNo {
1097 for _, zero := range yesNo {
1098 for _, space := range yesNo {
1099 for _, char := range "fFeEgG" {
1100 realFmt := "%"
1101 if zero {
1102 realFmt += "0"
1103 }
1104 if space {
1105 realFmt += " "
1106 }
1107 if plus {
1108 realFmt += "+"
1109 }
1110 realFmt += "10.2"
1111 realFmt += string(char)
1112 // Imaginary part always has a sign, so force + and ignore space.
1113 imagFmt := "%"
1114 if zero {
1115 imagFmt += "0"
1116 }
1117 imagFmt += "+"
1118 imagFmt += "10.2"
1119 imagFmt += string(char)
1120 for _, realValue := range values {
1121 for _, imagValue := range values {
1122 one := Sprintf(realFmt, complex(realValue, imagValue))
1123 two := Sprintf("("+realFmt+imagFmt+"i)", realValue, imagValue)
1124 if one != two {
1125 t.Error(f, one, two)
1126 }
1127 }
1128 }
1129 }
1130 }
1131 }
1132 }
1133 }
1134
1135 type SE []interface{} // slice of empty; notational compactness.
1136
1137 var reorderTests = []struct {
1138 fmt string
1139 val SE
1140 out string
1141 }{
1142 {"%[1]d", SE{1}, "1"},
1143 {"%[2]d", SE{2, 1}, "1"},
1144 {"%[2]d %[1]d", SE{1, 2}, "2 1"},
1145 {"%[2]*[1]d", SE{2, 5}, " 2"},
1146 {"%6.2f", SE{12.0}, " 12.00"}, // Explicit version of next line.
1147 {"%[3]*.[2]*[1]f", SE{12.0, 2, 6}, " 12.00"},
1148 {"%[1]*.[2]*[3]f", SE{6, 2, 12.0}, " 12.00"},
1149 {"%10f", SE{12.0}, " 12.000000"},
1150 {"%[1]*[3]f", SE{10, 99, 12.0}, " 12.000000"},
1151 {"%.6f", SE{12.0}, "12.000000"}, // Explicit version of next line.
1152 {"%.[1]*[3]f", SE{6, 99, 12.0}, "12.000000"},
1153 {"%6.f", SE{12.0}, " 12"}, // // Explicit version of next line; empty precision means zero.
1154 {"%[1]*.[3]f", SE{6, 3, 12.0}, " 12"},
1155 // An actual use! Print the same arguments twice.
1156 {"%d %d %d %#[1]o %#o %#o", SE{11, 12, 13}, "11 12 13 013 014 015"},
1157
1158 // Erroneous cases.
1159 {"%[d", SE{2, 1}, "%!d(BADINDEX)"},
1160 {"%]d", SE{2, 1}, "%!](int=2)d%!(EXTRA int=1)"},
1161 {"%[]d", SE{2, 1}, "%!d(BADINDEX)"},
1162 {"%[-3]d", SE{2, 1}, "%!d(BADINDEX)"},
1163 {"%[99]d", SE{2, 1}, "%!d(BADINDEX)"},
1164 {"%[3]", SE{2, 1}, "%!(NOVERB)"},
1165 {"%[1].2d", SE{5, 6}, "%!d(BADINDEX)"},
1166 {"%[1]2d", SE{2, 1}, "%!d(BADINDEX)"},
1167 {"%3.[2]d", SE{7}, "%!d(BADINDEX)"},
1168 {"%.[2]d", SE{7}, "%!d(BADINDEX)"},
1169 {"%d %d %d %#[1]o %#o %#o %#o", SE{11, 12, 13}, "11 12 13 013 014 015 %!o(MISSING)"},
1170 {"%[5]d %[2]d %d", SE{1, 2, 3}, "%!d(BADINDEX) 2 3"},
1171 {"%d %[3]d %d", SE{1, 2}, "1 %!d(BADINDEX) 2"}, // Erroneous index does not affect sequence.
1172 {"%.[]", SE{}, "%!](BADINDEX)"}, // Issue 10675
1173 {"%.-3d", SE{42}, "%!-(int=42)3d"}, // TODO: Should this set return better error messages?
1174 {"%2147483648d", SE{42}, "%!(NOVERB)%!(EXTRA int=42)"},
1175 {"%-2147483648d", SE{42}, "%!(NOVERB)%!(EXTRA int=42)"},
1176 {"%.2147483648d", SE{42}, "%!(NOVERB)%!(EXTRA int=42)"},
1177 }
1178
1179 func TestReorder(t *testing.T) {
1180 for _, tt := range reorderTests {
1181 s := Sprintf(tt.fmt, tt.val...)
1182 if s != tt.out {
1183 t.Errorf("Sprintf(%q, %v) = <%s> want <%s>", tt.fmt, tt.val, s, tt.out)
1184 } else {
1185 }
1186 }
1187 }
1188
1189 func BenchmarkSprintfPadding(b *testing.B) {
1190 b.RunParallel(func(pb *testing.PB) {
1191 for pb.Next() {
1192 Sprintf("%16f", 1.0)
1193 }
1194 })
1195 }
1196
1197 func BenchmarkSprintfEmpty(b *testing.B) {
1198 b.RunParallel(func(pb *testing.PB) {
1199 for pb.Next() {
1200 Sprintf("")
1201 }
1202 })
1203 }
1204
1205 func BenchmarkSprintfString(b *testing.B) {
1206 b.RunParallel(func(pb *testing.PB) {
1207 for pb.Next() {
1208 Sprintf("%s", "hello")
1209 }
1210 })
1211 }
1212
1213 func BenchmarkSprintfTruncateString(b *testing.B) {
1214 b.RunParallel(func(pb *testing.PB) {
1215 for pb.Next() {
1216 Sprintf("%.3s", "日本語日本語日本語")
1217 }
1218 })
1219 }
1220
1221 func BenchmarkSprintfSlowParsingPath(b *testing.B) {
1222 b.RunParallel(func(pb *testing.PB) {
1223 for pb.Next() {
1224 Sprintf("%.v", nil)
1225 }
1226 })
1227 }
1228
1229 func BenchmarkSprintfQuoteString(b *testing.B) {
1230 b.RunParallel(func(pb *testing.PB) {
1231 for pb.Next() {
1232 Sprintf("%q", "日本語日本語日本語")
1233 }
1234 })
1235 }
1236
1237 func BenchmarkSprintfInt(b *testing.B) {
1238 b.RunParallel(func(pb *testing.PB) {
1239 for pb.Next() {
1240 Sprintf("%d", 5)
1241 }
1242 })
1243 }
1244
1245 func BenchmarkSprintfIntInt(b *testing.B) {
1246 b.RunParallel(func(pb *testing.PB) {
1247 for pb.Next() {
1248 Sprintf("%d %d", 5, 6)
1249 }
1250 })
1251 }
1252
1253 func BenchmarkSprintfPrefixedInt(b *testing.B) {
1254 b.RunParallel(func(pb *testing.PB) {
1255 for pb.Next() {
1256 Sprintf("This is some meaningless prefix text that needs to be scanned %d", 6)
1257 }
1258 })
1259 }
1260
1261 func BenchmarkSprintfFloat(b *testing.B) {
1262 b.RunParallel(func(pb *testing.PB) {
1263 for pb.Next() {
1264 Sprintf("%g", 5.23184)
1265 }
1266 })
1267 }
1268
1269 func BenchmarkSprintfComplex(b *testing.B) {
1270 b.RunParallel(func(pb *testing.PB) {
1271 for pb.Next() {
1272 Sprintf("%f", 5.23184+5.23184i)
1273 }
1274 })
1275 }
1276
1277 func BenchmarkSprintfBoolean(b *testing.B) {
1278 b.RunParallel(func(pb *testing.PB) {
1279 for pb.Next() {
1280 Sprintf("%t", true)
1281 }
1282 })
1283 }
1284
1285 func BenchmarkSprintfHexString(b *testing.B) {
1286 b.RunParallel(func(pb *testing.PB) {
1287 for pb.Next() {
1288 Sprintf("% #x", "0123456789abcdef")
1289 }
1290 })
1291 }
1292
1293 func BenchmarkSprintfHexBytes(b *testing.B) {
1294 data := []byte("0123456789abcdef")
1295 b.RunParallel(func(pb *testing.PB) {
1296 for pb.Next() {
1297 Sprintf("% #x", data)
1298 }
1299 })
1300 }
1301
1302 func BenchmarkSprintfBytes(b *testing.B) {
1303 data := []byte("0123456789abcdef")
1304 b.RunParallel(func(pb *testing.PB) {
1305 for pb.Next() {
1306 Sprintf("%v", data)
1307 }
1308 })
1309 }
1310
1311 func BenchmarkSprintfStringer(b *testing.B) {
1312 stringer := I(12345)
1313 b.RunParallel(func(pb *testing.PB) {
1314 for pb.Next() {
1315 Sprintf("%v", stringer)
1316 }
1317 })
1318 }
1319
1320 func BenchmarkSprintfStructure(b *testing.B) {
1321 s := &[]interface{}{SI{12345}, map[int]string{0: "hello"}}
1322 b.RunParallel(func(pb *testing.PB) {
1323 for pb.Next() {
1324 Sprintf("%#v", s)
1325 }
1326 })
1327 }
1328
1329 func BenchmarkManyArgs(b *testing.B) {
1330 b.RunParallel(func(pb *testing.PB) {
1331 var buf bytes.Buffer
1332 for pb.Next() {
1333 buf.Reset()
1334 Fprintf(&buf, "%2d/%2d/%2d %d:%d:%d %s %s\n", 3, 4, 5, 11, 12, 13, "hello", "world")
1335 }
1336 })
1337 }
1338
1339 func BenchmarkFprintInt(b *testing.B) {
1340 var buf bytes.Buffer
1341 for i := 0; i < b.N; i++ {
1342 buf.Reset()
1343 Fprint(&buf, 123456)
1344 }
1345 }
1346
1347 func BenchmarkFprintfBytes(b *testing.B) {
1348 data := []byte(string("0123456789"))
1349 var buf bytes.Buffer
1350 for i := 0; i < b.N; i++ {
1351 buf.Reset()
1352 Fprintf(&buf, "%s", data)
1353 }
1354 }
1355
1356 func BenchmarkFprintIntNoAlloc(b *testing.B) {
1357 var x interface{} = 123456
1358 var buf bytes.Buffer
1359 for i := 0; i < b.N; i++ {
1360 buf.Reset()
1361 Fprint(&buf, x)
1362 }
1363 }
1364
1365 var mallocBuf bytes.Buffer
1366 var mallocPointer *int // A pointer so we know the interface value won't allocate.
1367
1368 var mallocTest = []struct {
1369 count int
1370 desc string
1371 fn func()
1372 }{
1373 {0, `Sprintf("")`, func() { Sprintf("") }},
1374 {1, `Sprintf("xxx")`, func() { Sprintf("xxx") }},
1375 {2, `Sprintf("%x")`, func() { Sprintf("%x", 7) }},
1376 {2, `Sprintf("%s")`, func() { Sprintf("%s", "hello") }},
1377 {3, `Sprintf("%x %x")`, func() { Sprintf("%x %x", 7, 112) }},
1378 {2, `Sprintf("%g")`, func() { Sprintf("%g", float32(3.14159)) }}, // TODO: Can this be 1?
1379 {1, `Fprintf(buf, "%s")`, func() { mallocBuf.Reset(); Fprintf(&mallocBuf, "%s", "hello") }},
1380 // If the interface value doesn't need to allocate, amortized allocation overhead should be zero.
1381 {0, `Fprintf(buf, "%x %x %x")`, func() {
1382 mallocBuf.Reset()
1383 Fprintf(&mallocBuf, "%x %x %x", mallocPointer, mallocPointer, mallocPointer)
1384 }},
1385 }
1386
1387 var _ bytes.Buffer
1388
1389 func TestCountMallocs(t *testing.T) {
1390 switch {
1391 case testing.Short():
1392 t.Skip("skipping malloc count in short mode")
1393 case runtime.GOMAXPROCS(0) > 1:
1394 t.Skip("skipping; GOMAXPROCS>1")
1395 }
1396 for _, mt := range mallocTest {
1397 mallocs := testing.AllocsPerRun(100, mt.fn)
1398 if got, max := mallocs, float64(mt.count); got > max {
1399 t.Errorf("%s: got %v allocs, want <=%v", mt.desc, got, max)
1400 }
1401 }
1402 }
1403
1404 type flagPrinter struct{}
1405
1406 func (flagPrinter) Format(f State, c rune) {
1407 s := "%"
1408 for i := 0; i < 128; i++ {
1409 if f.Flag(i) {
1410 s += string(rune(i))
1411 }
1412 }
1413 if w, ok := f.Width(); ok {
1414 s += Sprintf("%d", w)
1415 }
1416 if p, ok := f.Precision(); ok {
1417 s += Sprintf(".%d", p)
1418 }
1419 s += string(c)
1420 io.WriteString(f, "["+s+"]")
1421 }
1422
1423 var flagtests = []struct {
1424 in string
1425 out string
1426 }{
1427 {"%a", "[%a]"},
1428 {"%-a", "[%-a]"},
1429 {"%+a", "[%+a]"},
1430 {"%#a", "[%#a]"},
1431 {"% a", "[% a]"},
1432 {"%0a", "[%0a]"},
1433 {"%1.2a", "[%1.2a]"},
1434 {"%-1.2a", "[%-1.2a]"},
1435 {"%+1.2a", "[%+1.2a]"},
1436 {"%-+1.2a", "[%+-1.2a]"},
1437 {"%-+1.2abc", "[%+-1.2a]bc"},
1438 {"%-1.2abc", "[%-1.2a]bc"},
1439 }
1440
1441 func TestFlagParser(t *testing.T) {
1442 var flagprinter flagPrinter
1443 for _, tt := range flagtests {
1444 s := Sprintf(tt.in, &flagprinter)
1445 if s != tt.out {
1446 t.Errorf("Sprintf(%q, &flagprinter) => %q, want %q", tt.in, s, tt.out)
1447 }
1448 }
1449 }
1450
1451 func TestStructPrinter(t *testing.T) {
1452 type T struct {
1453 a string
1454 b string
1455 c int
1456 }
1457 var s T
1458 s.a = "abc"
1459 s.b = "def"
1460 s.c = 123
1461 var tests = []struct {
1462 fmt string
1463 out string
1464 }{
1465 {"%v", "{abc def 123}"},
1466 {"%+v", "{a:abc b:def c:123}"},
1467 {"%#v", `fmt_test.T{a:"abc", b:"def", c:123}`},
1468 }
1469 for _, tt := range tests {
1470 out := Sprintf(tt.fmt, s)
1471 if out != tt.out {
1472 t.Errorf("Sprintf(%q, s) = %#q, want %#q", tt.fmt, out, tt.out)
1473 }
1474 // The same but with a pointer.
1475 out = Sprintf(tt.fmt, &s)
1476 if out != "&"+tt.out {
1477 t.Errorf("Sprintf(%q, &s) = %#q, want %#q", tt.fmt, out, "&"+tt.out)
1478 }
1479 }
1480 }
1481
1482 func TestSlicePrinter(t *testing.T) {
1483 slice := []int{}
1484 s := Sprint(slice)
1485 if s != "[]" {
1486 t.Errorf("empty slice printed as %q not %q", s, "[]")
1487 }
1488 slice = []int{1, 2, 3}
1489 s = Sprint(slice)
1490 if s != "[1 2 3]" {
1491 t.Errorf("slice: got %q expected %q", s, "[1 2 3]")
1492 }
1493 s = Sprint(&slice)
1494 if s != "&[1 2 3]" {
1495 t.Errorf("&slice: got %q expected %q", s, "&[1 2 3]")
1496 }
1497 }
1498
1499 // presentInMap checks map printing using substrings so we don't depend on the
1500 // print order.
1501 func presentInMap(s string, a []string, t *testing.T) {
1502 for i := 0; i < len(a); i++ {
1503 loc := strings.Index(s, a[i])
1504 if loc < 0 {
1505 t.Errorf("map print: expected to find %q in %q", a[i], s)
1506 }
1507 // make sure the match ends here
1508 loc += len(a[i])
1509 if loc >= len(s) || (s[loc] != ' ' && s[loc] != ']') {
1510 t.Errorf("map print: %q not properly terminated in %q", a[i], s)
1511 }
1512 }
1513 }
1514
1515 func TestMapPrinter(t *testing.T) {
1516 m0 := make(map[int]string)
1517 s := Sprint(m0)
1518 if s != "map[]" {
1519 t.Errorf("empty map printed as %q not %q", s, "map[]")
1520 }
1521 m1 := map[int]string{1: "one", 2: "two", 3: "three"}
1522 a := []string{"1:one", "2:two", "3:three"}
1523 presentInMap(Sprintf("%v", m1), a, t)
1524 presentInMap(Sprint(m1), a, t)
1525 // Pointer to map prints the same but with initial &.
1526 if !strings.HasPrefix(Sprint(&m1), "&") {
1527 t.Errorf("no initial & for address of map")
1528 }
1529 presentInMap(Sprintf("%v", &m1), a, t)
1530 presentInMap(Sprint(&m1), a, t)
1531 }
1532
1533 func TestEmptyMap(t *testing.T) {
1534 const emptyMapStr = "map[]"
1535 var m map[string]int
1536 s := Sprint(m)
1537 if s != emptyMapStr {
1538 t.Errorf("nil map printed as %q not %q", s, emptyMapStr)
1539 }
1540 m = make(map[string]int)
1541 s = Sprint(m)
1542 if s != emptyMapStr {
1543 t.Errorf("empty map printed as %q not %q", s, emptyMapStr)
1544 }
1545 }
1546
1547 // TestBlank checks that Sprint (and hence Print, Fprint) puts spaces in the
1548 // right places, that is, between arg pairs in which neither is a string.
1549 func TestBlank(t *testing.T) {
1550 got := Sprint("<", 1, ">:", 1, 2, 3, "!")
1551 expect := "<1>:1 2 3!"
1552 if got != expect {
1553 t.Errorf("got %q expected %q", got, expect)
1554 }
1555 }
1556
1557 // TestBlankln checks that Sprintln (and hence Println, Fprintln) puts spaces in
1558 // the right places, that is, between all arg pairs.
1559 func TestBlankln(t *testing.T) {
1560 got := Sprintln("<", 1, ">:", 1, 2, 3, "!")
1561 expect := "< 1 >: 1 2 3 !\n"
1562 if got != expect {
1563 t.Errorf("got %q expected %q", got, expect)
1564 }
1565 }
1566
1567 // TestFormatterPrintln checks Formatter with Sprint, Sprintln, Sprintf.
1568 func TestFormatterPrintln(t *testing.T) {
1569 f := F(1)
1570 expect := "<v=F(1)>\n"
1571 s := Sprint(f, "\n")
1572 if s != expect {
1573 t.Errorf("Sprint wrong with Formatter: expected %q got %q", expect, s)
1574 }
1575 s = Sprintln(f)
1576 if s != expect {
1577 t.Errorf("Sprintln wrong with Formatter: expected %q got %q", expect, s)
1578 }
1579 s = Sprintf("%v\n", f)
1580 if s != expect {
1581 t.Errorf("Sprintf wrong with Formatter: expected %q got %q", expect, s)
1582 }
1583 }
1584
1585 func args(a ...interface{}) []interface{} { return a }
1586
1587 var startests = []struct {
1588 fmt string
1589 in []interface{}
1590 out string
1591 }{
1592 {"%*d", args(4, 42), " 42"},
1593 {"%-*d", args(4, 42), "42 "},
1594 {"%*d", args(-4, 42), "42 "},
1595 {"%-*d", args(-4, 42), "42 "},
1596 {"%.*d", args(4, 42), "0042"},
1597 {"%*.*d", args(8, 4, 42), " 0042"},
1598 {"%0*d", args(4, 42), "0042"},
1599 // Some non-int types for width. (Issue 10732).
1600 {"%0*d", args(uint(4), 42), "0042"},
1601 {"%0*d", args(uint64(4), 42), "0042"},
1602 {"%0*d", args('\x04', 42), "0042"},
1603 {"%0*d", args(uintptr(4), 42), "0042"},
1604
1605 // erroneous
1606 {"%*d", args(nil, 42), "%!(BADWIDTH)42"},
1607 {"%*d", args(int(1e7), 42), "%!(BADWIDTH)42"},
1608 {"%*d", args(int(-1e7), 42), "%!(BADWIDTH)42"},
1609 {"%.*d", args(nil, 42), "%!(BADPREC)42"},
1610 {"%.*d", args(-1, 42), "%!(BADPREC)42"},
1611 {"%.*d", args(int(1e7), 42), "%!(BADPREC)42"},
1612 {"%.*d", args(uint(1e7), 42), "%!(BADPREC)42"},
1613 {"%.*d", args(uint64(1<<63), 42), "%!(BADPREC)42"}, // Huge negative (-inf).
1614 {"%.*d", args(uint64(1<<64-1), 42), "%!(BADPREC)42"}, // Small negative (-1).
1615 {"%*d", args(5, "foo"), "%!d(string= foo)"},
1616 {"%*% %d", args(20, 5), "% 5"},
1617 {"%*", args(4), "%!(NOVERB)"},
1618 }
1619
1620 func TestWidthAndPrecision(t *testing.T) {
1621 for i, tt := range startests {
1622 s := Sprintf(tt.fmt, tt.in...)
1623 if s != tt.out {
1624 t.Errorf("#%d: %q: got %q expected %q", i, tt.fmt, s, tt.out)
1625 }
1626 }
1627 }
1628
1629 // PanicS is a type that panics in String.
1630 type PanicS struct {
1631 message interface{}
1632 }
1633
1634 // Value receiver.
1635 func (p PanicS) String() string {
1636 panic(p.message)
1637 }
1638
1639 // PanicGo is a type that panics in GoString.
1640 type PanicGo struct {
1641 message interface{}
1642 }
1643
1644 // Value receiver.
1645 func (p PanicGo) GoString() string {
1646 panic(p.message)
1647 }
1648
1649 // PanicF is a type that panics in Format.
1650 type PanicF struct {
1651 message interface{}
1652 }
1653
1654 // Value receiver.
1655 func (p PanicF) Format(f State, c rune) {
1656 panic(p.message)
1657 }
1658
1659 var panictests = []struct {
1660 fmt string
1661 in interface{}
1662 out string
1663 }{
1664 // String
1665 {"%s", (*PanicS)(nil), "<nil>"}, // nil pointer special case
1666 {"%s", PanicS{io.ErrUnexpectedEOF}, "%!s(PANIC=unexpected EOF)"},
1667 {"%s", PanicS{3}, "%!s(PANIC=3)"},
1668 // GoString
1669 {"%#v", (*PanicGo)(nil), "<nil>"}, // nil pointer special case
1670 {"%#v", PanicGo{io.ErrUnexpectedEOF}, "%!v(PANIC=unexpected EOF)"},
1671 {"%#v", PanicGo{3}, "%!v(PANIC=3)"},
1672 // Issue 18282. catchPanic should not clear fmtFlags permanently.
1673 {"%#v", []interface{}{PanicGo{3}, PanicGo{3}}, "[]interface {}{%!v(PANIC=3), %!v(PANIC=3)}"},
1674 // Format
1675 {"%s", (*PanicF)(nil), "<nil>"}, // nil pointer special case
1676 {"%s", PanicF{io.ErrUnexpectedEOF}, "%!s(PANIC=unexpected EOF)"},
1677 {"%s", PanicF{3}, "%!s(PANIC=3)"},
1678 }
1679
1680 var stripMethod = strings.NewReplacer(
1681 "PANIC=String method: ", "PANIC=",
1682 "PANIC=GoString method: ", "PANIC=",
1683 "PANIC=Format method: ", "PANIC=",
1684 )
1685
1686 func TestPanics(t *testing.T) {
1687 for i, tt := range panictests {
1688 s := Sprintf(tt.fmt, tt.in)
1689 s = stripMethod.Replace(s)
1690 if s != tt.out {
1691 t.Errorf("%d: %q: got %q expected %q", i, tt.fmt, s, tt.out)
1692 }
1693 }
1694 }
1695
1696 // recurCount tests that erroneous String routine doesn't cause fatal recursion.
1697 var recurCount = 0
1698
1699 type Recur struct {
1700 i int
1701 failed *bool
1702 }
1703
1704 func (r *Recur) String() string {
1705 if recurCount++; recurCount > 10 {
1706 *r.failed = true
1707 return "FAIL"
1708 }
1709 // This will call badVerb. Before the fix, that would cause us to recur into
1710 // this routine to print %!p(value). Now we don't call the user's method
1711 // during an error.
1712 return Sprintf("recur@%p value: %d", r, r.i)
1713 }
1714
1715 func TestBadVerbRecursion(t *testing.T) {
1716 failed := false
1717 r := &Recur{3, &failed}
1718 Sprintf("recur@%p value: %d\n", &r, r.i)
1719 if failed {
1720 t.Error("fail with pointer")
1721 }
1722 failed = false
1723 r = &Recur{4, &failed}
1724 Sprintf("recur@%p, value: %d\n", r, r.i)
1725 if failed {
1726 t.Error("fail with value")
1727 }
1728 }
1729
1730 /*
1731 func TestIsSpace(t *testing.T) {
1732 // This tests the internal isSpace function.
1733 // IsSpace = isSpace is defined in export_test.go.
1734 for i := rune(0); i <= unicode.MaxRune; i++ {
1735 if IsSpace(i) != unicode.IsSpace(i) {
1736 t.Errorf("isSpace(%U) = %v, want %v", i, IsSpace(i), unicode.IsSpace(i))
1737 }
1738 }
1739 }
1740 */
1741
1742 func hideFromVet(s string) string { return s }
1743
1744 func TestNilDoesNotBecomeTyped(t *testing.T) {
1745 type A struct{}
1746 type B struct{}
1747 var a *A = nil
1748 var b B = B{}
1749 got := Sprintf(hideFromVet("%s %s %s %s %s"), nil, a, nil, b, nil)
1750 const expect = "%!s(<nil>) %!s(*fmt_test.A=<nil>) %!s(<nil>) {} %!s(<nil>)"
1751 if got != expect {
1752 t.Errorf("expected:\n\t%q\ngot:\n\t%q", expect, got)
1753 }
1754 }
1755
1756 var formatterFlagTests = []struct {
1757 in string
1758 val interface{}
1759 out string
1760 }{
1761 // scalar values with the (unused by fmt) 'a' verb.
1762 {"%a", flagPrinter{}, "[%a]"},
1763 {"%-a", flagPrinter{}, "[%-a]"},
1764 {"%+a", flagPrinter{}, "[%+a]"},
1765 {"%#a", flagPrinter{}, "[%#a]"},
1766 {"% a", flagPrinter{}, "[% a]"},
1767 {"%0a", flagPrinter{}, "[%0a]"},
1768 {"%1.2a", flagPrinter{}, "[%1.2a]"},
1769 {"%-1.2a", flagPrinter{}, "[%-1.2a]"},
1770 {"%+1.2a", flagPrinter{}, "[%+1.2a]"},
1771 {"%-+1.2a", flagPrinter{}, "[%+-1.2a]"},
1772 {"%-+1.2abc", flagPrinter{}, "[%+-1.2a]bc"},
1773 {"%-1.2abc", flagPrinter{}, "[%-1.2a]bc"},
1774
1775 // composite values with the 'a' verb
1776 {"%a", [1]flagPrinter{}, "[[%a]]"},
1777 {"%-a", [1]flagPrinter{}, "[[%-a]]"},
1778 {"%+a", [1]flagPrinter{}, "[[%+a]]"},
1779 {"%#a", [1]flagPrinter{}, "[[%#a]]"},
1780 {"% a", [1]flagPrinter{}, "[[% a]]"},
1781 {"%0a", [1]flagPrinter{}, "[[%0a]]"},
1782 {"%1.2a", [1]flagPrinter{}, "[[%1.2a]]"},
1783 {"%-1.2a", [1]flagPrinter{}, "[[%-1.2a]]"},
1784 {"%+1.2a", [1]flagPrinter{}, "[[%+1.2a]]"},
1785 {"%-+1.2a", [1]flagPrinter{}, "[[%+-1.2a]]"},
1786 {"%-+1.2abc", [1]flagPrinter{}, "[[%+-1.2a]]bc"},
1787 {"%-1.2abc", [1]flagPrinter{}, "[[%-1.2a]]bc"},
1788
1789 // simple values with the 'v' verb
1790 {"%v", flagPrinter{}, "[%v]"},
1791 {"%-v", flagPrinter{}, "[%-v]"},
1792 {"%+v", flagPrinter{}, "[%+v]"},
1793 {"%#v", flagPrinter{}, "[%#v]"},
1794 {"% v", flagPrinter{}, "[% v]"},
1795 {"%0v", flagPrinter{}, "[%0v]"},
1796 {"%1.2v", flagPrinter{}, "[%1.2v]"},
1797 {"%-1.2v", flagPrinter{}, "[%-1.2v]"},
1798 {"%+1.2v", flagPrinter{}, "[%+1.2v]"},
1799 {"%-+1.2v", flagPrinter{}, "[%+-1.2v]"},
1800 {"%-+1.2vbc", flagPrinter{}, "[%+-1.2v]bc"},
1801 {"%-1.2vbc", flagPrinter{}, "[%-1.2v]bc"},
1802
1803 // composite values with the 'v' verb.
1804 {"%v", [1]flagPrinter{}, "[[%v]]"},
1805 {"%-v", [1]flagPrinter{}, "[[%-v]]"},
1806 {"%+v", [1]flagPrinter{}, "[[%+v]]"},
1807 {"%#v", [1]flagPrinter{}, "[1]fmt_test.flagPrinter{[%#v]}"},
1808 {"% v", [1]flagPrinter{}, "[[% v]]"},
1809 {"%0v", [1]flagPrinter{}, "[[%0v]]"},
1810 {"%1.2v", [1]flagPrinter{}, "[[%1.2v]]"},
1811 {"%-1.2v", [1]flagPrinter{}, "[[%-1.2v]]"},
1812 {"%+1.2v", [1]flagPrinter{}, "[[%+1.2v]]"},
1813 {"%-+1.2v", [1]flagPrinter{}, "[[%+-1.2v]]"},
1814 {"%-+1.2vbc", [1]flagPrinter{}, "[[%+-1.2v]]bc"},
1815 {"%-1.2vbc", [1]flagPrinter{}, "[[%-1.2v]]bc"},
1816 }
1817
1818 func TestFormatterFlags(t *testing.T) {
1819 for _, tt := range formatterFlagTests {
1820 s := Sprintf(tt.in, tt.val)
1821 if s != tt.out {
1822 t.Errorf("Sprintf(%q, %T) = %q, want %q", tt.in, tt.val, s, tt.out)
1823 }
1824 }
1825 }
1826
1827 /*
1828 func TestParsenum(t *testing.T) {
1829 testCases := []struct {
1830 s string
1831 start, end int
1832 num int
1833 isnum bool
1834 newi int
1835 }{
1836 {"a123", 0, 4, 0, false, 0},
1837 {"1234", 1, 1, 0, false, 1},
1838 {"123a", 0, 4, 123, true, 3},
1839 {"12a3", 0, 4, 12, true, 2},
1840 {"1234", 0, 4, 1234, true, 4},
1841 {"1a234", 1, 3, 0, false, 1},
1842 }
1843 for _, tt := range testCases {
1844 num, isnum, newi := Parsenum(tt.s, tt.start, tt.end)
1845 if num != tt.num || isnum != tt.isnum || newi != tt.newi {
1846 t.Errorf("parsenum(%q, %d, %d) = %d, %v, %d, want %d, %v, %d", tt.s, tt.start, tt.end, num, isnum, newi, tt.num, tt.isnum, tt.newi)
1847 }
1848 }
1849 }
1850 */