Debian Codegraph @

errors/fmt/format.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
6
7 import (
8 "strconv"
9 "unicode/utf8"
10 )
11
12 const (
13 ldigits = "0123456789abcdefx"
14 udigits = "0123456789ABCDEFX"
15 )
16
17 const (
18 signed = true
19 unsigned = false
20 )
21
22 // flags placed in a separate struct for easy clearing.
23 type fmtFlags struct {
24 widPresent bool
25 precPresent bool
26 minus bool
27 plus bool
28 sharp bool
29 space bool
30 zero bool
31
32 // For the formats %+v %#v, we set the plusV/sharpV flags
33 // and clear the plus/sharp flags since %+v and %#v are in effect
34 // different, flagless formats set at the top level.
35 plusV bool
36 sharpV bool
37
38 // error-related flags.
39 inDetail bool
40 needNewline bool
41 }
42
43 // A fmt is the raw formatter used by Printf etc.
44 // It prints into a buffer that must be set up separately.
45 type fmt struct {
46 buf *buffer
47
48 fmtFlags
49
50 wid int // width
51 prec int // precision
52
53 // intbuf is large enough to store %b of an int64 with a sign and
54 // avoids padding at the end of the struct on 32 bit architectures.
55 intbuf [68]byte
56 }
57
58 func (f *fmt) clearflags() {
59 f.fmtFlags = fmtFlags{}
60 }
61
62 func (f *fmt) init(buf *buffer) {
63 f.buf = buf
64 f.clearflags()
65 }
66
67 // writePadding generates n bytes of padding.
68 func (f *fmt) writePadding(n int) {
69 if n <= 0 { // No padding bytes needed.
70 return
71 }
72 buf := *f.buf
73 oldLen := len(buf)
74 newLen := oldLen + n
75 // Make enough room for padding.
76 if newLen > cap(buf) {
77 buf = make(buffer, cap(buf)*2+n)
78 copy(buf, *f.buf)
79 }
80 // Decide which byte the padding should be filled with.
81 padByte := byte(' ')
82 if f.zero {
83 padByte = byte('0')
84 }
85 // Fill padding with padByte.
86 padding := buf[oldLen:newLen]
87 for i := range padding {
88 padding[i] = padByte
89 }
90 *f.buf = buf[:newLen]
91 }
92
93 // pad appends b to f.buf, padded on left (!f.minus) or right (f.minus).
94 func (f *fmt) pad(b []byte) {
95 if !f.widPresent || f.wid == 0 {
96 f.buf.Write(b)
97 return
98 }
99 width := f.wid - utf8.RuneCount(b)
100 if !f.minus {
101 // left padding
102 f.writePadding(width)
103 f.buf.Write(b)
104 } else {
105 // right padding
106 f.buf.Write(b)
107 f.writePadding(width)
108 }
109 }
110
111 // padString appends s to f.buf, padded on left (!f.minus) or right (f.minus).
112 func (f *fmt) padString(s string) {
113 if !f.widPresent || f.wid == 0 {
114 f.buf.WriteString(s)
115 return
116 }
117 width := f.wid - utf8.RuneCountInString(s)
118 if !f.minus {
119 // left padding
120 f.writePadding(width)
121 f.buf.WriteString(s)
122 } else {
123 // right padding
124 f.buf.WriteString(s)
125 f.writePadding(width)
126 }
127 }
128
129 // fmtBoolean formats a boolean.
130 func (f *fmt) fmtBoolean(v bool) {
131 if v {
132 f.padString("true")
133 } else {
134 f.padString("false")
135 }
136 }
137
138 // fmtUnicode formats a uint64 as "U+0078" or with f.sharp set as "U+0078 'x'".
139 func (f *fmt) fmtUnicode(u uint64) {
140 buf := f.intbuf[0:]
141
142 // With default precision set the maximum needed buf length is 18
143 // for formatting -1 with %#U ("U+FFFFFFFFFFFFFFFF") which fits
144 // into the already allocated intbuf with a capacity of 68 bytes.
145 prec := 4
146 if f.precPresent && f.prec > 4 {
147 prec = f.prec
148 // Compute space needed for "U+" , number, " '", character, "'".
149 width := 2 + prec + 2 + utf8.UTFMax + 1
150 if width > len(buf) {
151 buf = make([]byte, width)
152 }
153 }
154
155 // Format into buf, ending at buf[i]. Formatting numbers is easier right-to-left.
156 i := len(buf)
157
158 // For %#U we want to add a space and a quoted character at the end of the buffer.
159 if f.sharp && u <= utf8.MaxRune && strconv.IsPrint(rune(u)) {
160 i--
161 buf[i] = '\''
162 i -= utf8.RuneLen(rune(u))
163 utf8.EncodeRune(buf[i:], rune(u))
164 i--
165 buf[i] = '\''
166 i--
167 buf[i] = ' '
168 }
169 // Format the Unicode code point u as a hexadecimal number.
170 for u >= 16 {
171 i--
172 buf[i] = udigits[u&0xF]
173 prec--
174 u >>= 4
175 }
176 i--
177 buf[i] = udigits[u]
178 prec--
179 // Add zeros in front of the number until requested precision is reached.
180 for prec > 0 {
181 i--
182 buf[i] = '0'
183 prec--
184 }
185 // Add a leading "U+".
186 i--
187 buf[i] = '+'
188 i--
189 buf[i] = 'U'
190
191 oldZero := f.zero
192 f.zero = false
193 f.pad(buf[i:])
194 f.zero = oldZero
195 }
196
197 // fmtInteger formats signed and unsigned integers.
198 func (f *fmt) fmtInteger(u uint64, base int, isSigned bool, digits string) {
199 negative := isSigned && int64(u) < 0
200 if negative {
201 u = -u
202 }
203
204 buf := f.intbuf[0:]
205 // The already allocated f.intbuf with a capacity of 68 bytes
206 // is large enough for integer formatting when no precision or width is set.
207 if f.widPresent || f.precPresent {
208 // Account 3 extra bytes for possible addition of a sign and "0x".
209 width := 3 + f.wid + f.prec // wid and prec are always positive.
210 if width > len(buf) {
211 // We're going to need a bigger boat.
212 buf = make([]byte, width)
213 }
214 }
215
216 // Two ways to ask for extra leading zero digits: %.3d or %03d.
217 // If both are specified the f.zero flag is ignored and
218 // padding with spaces is used instead.
219 prec := 0
220 if f.precPresent {
221 prec = f.prec
222 // Precision of 0 and value of 0 means "print nothing" but padding.
223 if prec == 0 && u == 0 {
224 oldZero := f.zero
225 f.zero = false
226 f.writePadding(f.wid)
227 f.zero = oldZero
228 return
229 }
230 } else if f.zero && f.widPresent {
231 prec = f.wid
232 if negative || f.plus || f.space {
233 prec-- // leave room for sign
234 }
235 }
236
237 // Because printing is easier right-to-left: format u into buf, ending at buf[i].
238 // We could make things marginally faster by splitting the 32-bit case out
239 // into a separate block but it's not worth the duplication, so u has 64 bits.
240 i := len(buf)
241 // Use constants for the division and modulo for more efficient code.
242 // Switch cases ordered by popularity.
243 switch base {
244 case 10:
245 for u >= 10 {
246 i--
247 next := u / 10
248 buf[i] = byte('0' + u - next*10)
249 u = next
250 }
251 case 16:
252 for u >= 16 {
253 i--
254 buf[i] = digits[u&0xF]
255 u >>= 4
256 }
257 case 8:
258 for u >= 8 {
259 i--
260 buf[i] = byte('0' + u&7)
261 u >>= 3
262 }
263 case 2:
264 for u >= 2 {
265 i--
266 buf[i] = byte('0' + u&1)
267 u >>= 1
268 }
269 default:
270 panic("fmt: unknown base; can't happen")
271 }
272 i--
273 buf[i] = digits[u]
274 for i > 0 && prec > len(buf)-i {
275 i--
276 buf[i] = '0'
277 }
278
279 // Various prefixes: 0x, -, etc.
280 if f.sharp {
281 switch base {
282 case 8:
283 if buf[i] != '0' {
284 i--
285 buf[i] = '0'
286 }
287 case 16:
288 // Add a leading 0x or 0X.
289 i--
290 buf[i] = digits[16]
291 i--
292 buf[i] = '0'
293 }
294 }
295
296 if negative {
297 i--
298 buf[i] = '-'
299 } else if f.plus {
300 i--
301 buf[i] = '+'
302 } else if f.space {
303 i--
304 buf[i] = ' '
305 }
306
307 // Left padding with zeros has already been handled like precision earlier
308 // or the f.zero flag is ignored due to an explicitly set precision.
309 oldZero := f.zero
310 f.zero = false
311 f.pad(buf[i:])
312 f.zero = oldZero
313 }
314
315 // truncate truncates the string to the specified precision, if present.
316 func (f *fmt) truncate(s string) string {
317 if f.precPresent {
318 n := f.prec
319 for i := range s {
320 n--
321 if n < 0 {
322 return s[:i]
323 }
324 }
325 }
326 return s
327 }
328
329 // fmtS formats a string.
330 func (f *fmt) fmtS(s string) {
331 s = f.truncate(s)
332 f.padString(s)
333 }
334
335 // fmtSbx formats a string or byte slice as a hexadecimal encoding of its bytes.
336 func (f *fmt) fmtSbx(s string, b []byte, digits string) {
337 length := len(b)
338 if b == nil {
339 // No byte slice present. Assume string s should be encoded.
340 length = len(s)
341 }
342 // Set length to not process more bytes than the precision demands.
343 if f.precPresent && f.prec < length {
344 length = f.prec
345 }
346 // Compute width of the encoding taking into account the f.sharp and f.space flag.
347 width := 2 * length
348 if width > 0 {
349 if f.space {
350 // Each element encoded by two hexadecimals will get a leading 0x or 0X.
351 if f.sharp {
352 width *= 2
353 }
354 // Elements will be separated by a space.
355 width += length - 1
356 } else if f.sharp {
357 // Only a leading 0x or 0X will be added for the whole string.
358 width += 2
359 }
360 } else { // The byte slice or string that should be encoded is empty.
361 if f.widPresent {
362 f.writePadding(f.wid)
363 }
364 return
365 }
366 // Handle padding to the left.
367 if f.widPresent && f.wid > width && !f.minus {
368 f.writePadding(f.wid - width)
369 }
370 // Write the encoding directly into the output buffer.
371 buf := *f.buf
372 if f.sharp {
373 // Add leading 0x or 0X.
374 buf = append(buf, '0', digits[16])
375 }
376 var c byte
377 for i := 0; i < length; i++ {
378 if f.space && i > 0 {
379 // Separate elements with a space.
380 buf = append(buf, ' ')
381 if f.sharp {
382 // Add leading 0x or 0X for each element.
383 buf = append(buf, '0', digits[16])
384 }
385 }
386 if b != nil {
387 c = b[i] // Take a byte from the input byte slice.
388 } else {
389 c = s[i] // Take a byte from the input string.
390 }
391 // Encode each byte as two hexadecimal digits.
392 buf = append(buf, digits[c>>4], digits[c&0xF])
393 }
394 *f.buf = buf
395 // Handle padding to the right.
396 if f.widPresent && f.wid > width && f.minus {
397 f.writePadding(f.wid - width)
398 }
399 }
400
401 // fmtSx formats a string as a hexadecimal encoding of its bytes.
402 func (f *fmt) fmtSx(s, digits string) {
403 f.fmtSbx(s, nil, digits)
404 }
405
406 // fmtBx formats a byte slice as a hexadecimal encoding of its bytes.
407 func (f *fmt) fmtBx(b []byte, digits string) {
408 f.fmtSbx("", b, digits)
409 }
410
411 // fmtQ formats a string as a double-quoted, escaped Go string constant.
412 // If f.sharp is set a raw (backquoted) string may be returned instead
413 // if the string does not contain any control characters other than tab.
414 func (f *fmt) fmtQ(s string) {
415 s = f.truncate(s)
416 if f.sharp && strconv.CanBackquote(s) {
417 f.padString("`" + s + "`")
418 return
419 }
420 buf := f.intbuf[:0]
421 if f.plus {
422 f.pad(strconv.AppendQuoteToASCII(buf, s))
423 } else {
424 f.pad(strconv.AppendQuote(buf, s))
425 }
426 }
427
428 // fmtC formats an integer as a Unicode character.
429 // If the character is not valid Unicode, it will print '\ufffd'.
430 func (f *fmt) fmtC(c uint64) {
431 r := rune(c)
432 if c > utf8.MaxRune {
433 r = utf8.RuneError
434 }
435 buf := f.intbuf[:0]
436 w := utf8.EncodeRune(buf[:utf8.UTFMax], r)
437 f.pad(buf[:w])
438 }
439
440 // fmtQc formats an integer as a single-quoted, escaped Go character constant.
441 // If the character is not valid Unicode, it will print '\ufffd'.
442 func (f *fmt) fmtQc(c uint64) {
443 r := rune(c)
444 if c > utf8.MaxRune {
445 r = utf8.RuneError
446 }
447 buf := f.intbuf[:0]
448 if f.plus {
449 f.pad(strconv.AppendQuoteRuneToASCII(buf, r))
450 } else {
451 f.pad(strconv.AppendQuoteRune(buf, r))
452 }
453 }
454
455 // fmtFloat formats a float64. It assumes that verb is a valid format specifier
456 // for strconv.AppendFloat and therefore fits into a byte.
457 func (f *fmt) fmtFloat(v float64, size int, verb rune, prec int) {
458 // Explicit precision in format specifier overrules default precision.
459 if f.precPresent {
460 prec = f.prec
461 }
462 // Format number, reserving space for leading + sign if needed.
463 num := strconv.AppendFloat(f.intbuf[:1], v, byte(verb), prec, size)
464 if num[1] == '-' || num[1] == '+' {
465 num = num[1:]
466 } else {
467 num[0] = '+'
468 }
469 // f.space means to add a leading space instead of a "+" sign unless
470 // the sign is explicitly asked for by f.plus.
471 if f.space && num[0] == '+' && !f.plus {
472 num[0] = ' '
473 }
474 // Special handling for infinities and NaN,
475 // which don't look like a number so shouldn't be padded with zeros.
476 if num[1] == 'I' || num[1] == 'N' {
477 oldZero := f.zero
478 f.zero = false
479 // Remove sign before NaN if not asked for.
480 if num[1] == 'N' && !f.space && !f.plus {
481 num = num[1:]
482 }
483 f.pad(num)
484 f.zero = oldZero
485 return
486 }
487 // The sharp flag forces printing a decimal point for non-binary formats
488 // and retains trailing zeros, which we may need to restore.
489 if f.sharp && verb != 'b' {
490 digits := 0
491 switch verb {
492 case 'v', 'g', 'G':
493 digits = prec
494 // If no precision is set explicitly use a precision of 6.
495 if digits == -1 {
496 digits = 6
497 }
498 }
499
500 // Buffer pre-allocated with enough room for
501 // exponent notations of the form "e+123".
502 var tailBuf [5]byte
503 tail := tailBuf[:0]
504
505 hasDecimalPoint := false
506 // Starting from i = 1 to skip sign at num[0].
507 for i := 1; i < len(num); i++ {
508 switch num[i] {
509 case '.':
510 hasDecimalPoint = true
511 case 'e', 'E':
512 tail = append(tail, num[i:]...)
513 num = num[:i]
514 default:
515 digits--
516 }
517 }
518 if !hasDecimalPoint {
519 num = append(num, '.')
520 }
521 for digits > 0 {
522 num = append(num, '0')
523 digits--
524 }
525 num = append(num, tail...)
526 }
527 // We want a sign if asked for and if the sign is not positive.
528 if f.plus || num[0] != '+' {
529 // If we're zero padding to the left we want the sign before the leading zeros.
530 // Achieve this by writing the sign out and then padding the unsigned number.
531 if f.zero && f.widPresent && f.wid > len(num) {
532 f.buf.WriteByte(num[0])
533 f.writePadding(f.wid - len(num))
534 f.buf.Write(num[1:])
535 return
536 }
537 f.pad(num)
538 return
539 }
540 // No sign to show and the number is positive; just print the unsigned number.
541 f.pad(num[1:])
542 }