// Copyright 2017 The Go Authors. All rights reserved.// Use of this source code is governed by a BSD-style// license that can be found in the LICENSE file.package messageimport ()const ( ldigits = "0123456789abcdefx" udigits = "0123456789ABCDEFX")const ( signed = true unsigned = false)// A formatInfo is the raw formatter used by Printf etc.// It prints into a buffer that must be set up separately.type formatInfo struct { buf *bytes.Bufferformat.Parser// intbuf is large enough to store %b of an int64 with a sign and // avoids padding at the end of the struct on 32 bit architectures. intbuf [68]byte}func ( *formatInfo) ( *bytes.Buffer) { .ClearFlags() .buf = }// writePadding generates n bytes of padding.func ( *formatInfo) ( int) {if <= 0 { // No padding bytes needed.return } .buf.Grow()// Decide which byte the padding should be filled with. := byte(' ')if .Zero { = byte('0') }// Fill padding with padByte.for := 0; < ; ++ { .buf.WriteByte() // TODO: make more efficient. }}// pad appends b to f.buf, padded on left (!f.minus) or right (f.minus).func ( *formatInfo) ( []byte) {if !.WidthPresent || .Width == 0 { .buf.Write()return } := .Width - utf8.RuneCount()if !.Minus {// left padding .writePadding() .buf.Write() } else {// right padding .buf.Write() .writePadding() }}// padString appends s to f.buf, padded on left (!f.minus) or right (f.minus).func ( *formatInfo) ( string) {if !.WidthPresent || .Width == 0 { .buf.WriteString()return } := .Width - utf8.RuneCountInString()if !.Minus {// left padding .writePadding() .buf.WriteString() } else {// right padding .buf.WriteString() .writePadding() }}// fmt_boolean formats a boolean.func ( *formatInfo) ( bool) {if { .padString("true") } else { .padString("false") }}// fmt_unicode formats a uint64 as "U+0078" or with f.sharp set as "U+0078 'x'".func ( *formatInfo) ( uint64) { := .intbuf[0:]// With default precision set the maximum needed buf length is 18 // for formatting -1 with %#U ("U+FFFFFFFFFFFFFFFF") which fits // into the already allocated intbuf with a capacity of 68 bytes. := 4if .PrecPresent && .Prec > 4 { = .Prec// Compute space needed for "U+" , number, " '", character, "'". := 2 + + 2 + utf8.UTFMax + 1if > len() { = make([]byte, ) } }// Format into buf, ending at buf[i]. Formatting numbers is easier right-to-left. := len()// For %#U we want to add a space and a quoted character at the end of the buffer.if .Sharp && <= utf8.MaxRune && strconv.IsPrint(rune()) { -- [] = '\'' -= utf8.RuneLen(rune())utf8.EncodeRune([:], rune()) -- [] = '\'' -- [] = ' ' }// Format the Unicode code point u as a hexadecimal number.for >= 16 { -- [] = udigits[&0xF] -- >>= 4 } -- [] = udigits[] --// Add zeros in front of the number until requested precision is reached.for > 0 { -- [] = '0' -- }// Add a leading "U+". -- [] = '+' -- [] = 'U' := .Zero .Zero = false .pad([:]) .Zero = }// fmt_integer formats signed and unsigned integers.func ( *formatInfo) ( uint64, int, bool, string) { := && int64() < 0if { = - } := .intbuf[0:]// The already allocated f.intbuf with a capacity of 68 bytes // is large enough for integer formatting when no precision or width is set.if .WidthPresent || .PrecPresent {// Account 3 extra bytes for possible addition of a sign and "0x". := 3 + .Width + .Prec// wid and prec are always positive.if > len() {// We're going to need a bigger boat. = make([]byte, ) } }// Two ways to ask for extra leading zero digits: %.3d or %03d. // If both are specified the f.zero flag is ignored and // padding with spaces is used instead. := 0if .PrecPresent { = .Prec// Precision of 0 and value of 0 means "print nothing" but padding.if == 0 && == 0 { := .Zero .Zero = false .writePadding(.Width) .Zero = return } } elseif .Zero && .WidthPresent { = .Widthif || .Plus || .Space { -- // leave room for sign } }// Because printing is easier right-to-left: format u into buf, ending at buf[i]. // We could make things marginally faster by splitting the 32-bit case out // into a separate block but it's not worth the duplication, so u has 64 bits. := len()// Use constants for the division and modulo for more efficient code. // Switch cases ordered by popularity.switch {case10:for >= 10 { -- := / 10 [] = byte('0' + - *10) = }case16:for >= 16 { -- [] = [&0xF] >>= 4 }case8:for >= 8 { -- [] = byte('0' + &7) >>= 3 }case2:for >= 2 { -- [] = byte('0' + &1) >>= 1 }default:panic("fmt: unknown base; can't happen") } -- [] = []for > 0 && > len()- { -- [] = '0' }// Various prefixes: 0x, -, etc.if .Sharp {switch {case8:if [] != '0' { -- [] = '0' }case16:// Add a leading 0x or 0X. -- [] = [16] -- [] = '0' } }if { -- [] = '-' } elseif .Plus { -- [] = '+' } elseif .Space { -- [] = ' ' }// Left padding with zeros has already been handled like precision earlier // or the f.zero flag is ignored due to an explicitly set precision. := .Zero .Zero = false .pad([:]) .Zero = }// truncate truncates the string to the specified precision, if present.func ( *formatInfo) ( string) string {if .PrecPresent { := .Precfor := range { --if < 0 {return [:] } } }return}// fmt_s formats a string.func ( *formatInfo) ( string) { = .truncate() .padString()}// fmt_sbx formats a string or byte slice as a hexadecimal encoding of its bytes.func ( *formatInfo) ( string, []byte, string) { := len()if == nil {// No byte slice present. Assume string s should be encoded. = len() }// Set length to not process more bytes than the precision demands.if .PrecPresent && .Prec < { = .Prec }// Compute width of the encoding taking into account the f.sharp and f.space flag. := 2 * if > 0 {if .Space {// Each element encoded by two hexadecimals will get a leading 0x or 0X.if .Sharp { *= 2 }// Elements will be separated by a space. += - 1 } elseif .Sharp {// Only a leading 0x or 0X will be added for the whole string. += 2 } } else { // The byte slice or string that should be encoded is empty.if .WidthPresent { .writePadding(.Width) }return }// Handle padding to the left.if .WidthPresent && .Width > && !.Minus { .writePadding(.Width - ) }// Write the encoding directly into the output buffer. := .bufif .Sharp {// Add leading 0x or 0X. .WriteByte('0') .WriteByte([16]) }varbytefor := 0; < ; ++ {if .Space && > 0 {// Separate elements with a space. .WriteByte(' ')if .Sharp {// Add leading 0x or 0X for each element. .WriteByte('0') .WriteByte([16]) } }if != nil { = [] // Take a byte from the input byte slice. } else { = [] // Take a byte from the input string. }// Encode each byte as two hexadecimal digits. .WriteByte([>>4]) .WriteByte([&0xF]) }// Handle padding to the right.if .WidthPresent && .Width > && .Minus { .writePadding(.Width - ) }}// fmt_sx formats a string as a hexadecimal encoding of its bytes.func ( *formatInfo) (, string) { .fmt_sbx(, nil, )}// fmt_bx formats a byte slice as a hexadecimal encoding of its bytes.func ( *formatInfo) ( []byte, string) { .fmt_sbx("", , )}// fmt_q formats a string as a double-quoted, escaped Go string constant.// If f.sharp is set a raw (backquoted) string may be returned instead// if the string does not contain any control characters other than tab.func ( *formatInfo) ( string) { = .truncate()if .Sharp && strconv.CanBackquote() { .padString("`" + + "`")return } := .intbuf[:0]if .Plus { .pad(strconv.AppendQuoteToASCII(, )) } else { .pad(strconv.AppendQuote(, )) }}// fmt_c formats an integer as a Unicode character.// If the character is not valid Unicode, it will print '\ufffd'.func ( *formatInfo) ( uint64) { := rune()if > utf8.MaxRune { = utf8.RuneError } := .intbuf[:0] := utf8.EncodeRune([:utf8.UTFMax], ) .pad([:])}// fmt_qc formats an integer as a single-quoted, escaped Go character constant.// If the character is not valid Unicode, it will print '\ufffd'.func ( *formatInfo) ( uint64) { := rune()if > utf8.MaxRune { = utf8.RuneError } := .intbuf[:0]if .Plus { .pad(strconv.AppendQuoteRuneToASCII(, )) } else { .pad(strconv.AppendQuoteRune(, )) }}// fmt_float formats a float64. It assumes that verb is a valid format specifier// for strconv.AppendFloat and therefore fits into a byte.func ( *formatInfo) ( float64, int, rune, int) {// Explicit precision in format specifier overrules default precision.if .PrecPresent { = .Prec }// Format number, reserving space for leading + sign if needed. := strconv.AppendFloat(.intbuf[:1], , byte(), , )if [1] == '-' || [1] == '+' { = [1:] } else { [0] = '+' }// f.space means to add a leading space instead of a "+" sign unless // the sign is explicitly asked for by f.plus.if .Space && [0] == '+' && !.Plus { [0] = ' ' }// Special handling for infinities and NaN, // which don't look like a number so shouldn't be padded with zeros.if [1] == 'I' || [1] == 'N' { := .Zero .Zero = false// Remove sign before NaN if not asked for.if [1] == 'N' && !.Space && !.Plus { = [1:] } .pad() .Zero = return }// The sharp flag forces printing a decimal point for non-binary formats // and retains trailing zeros, which we may need to restore.if .Sharp && != 'b' { := 0switch {case'v', 'g', 'G': = // If no precision is set explicitly use a precision of 6.if == -1 { = 6 } }// Buffer pre-allocated with enough room for // exponent notations of the form "e+123".var [5]byte := [:0] := false// Starting from i = 1 to skip sign at num[0].for := 1; < len(); ++ {switch [] {case'.': = truecase'e', 'E': = append(, [:]...) = [:]default: -- } }if ! { = append(, '.') }for > 0 { = append(, '0') -- } = append(, ...) }// We want a sign if asked for and if the sign is not positive.if .Plus || [0] != '+' {// If we're zero padding to the left we want the sign before the leading zeros. // Achieve this by writing the sign out and then padding the unsigned number.if .Zero && .WidthPresent && .Width > len() { .buf.WriteByte([0]) .writePadding(.Width - len()) .buf.Write([1:])return } .pad()return }// No sign to show and the number is positive; just print the unsigned number. .pad([1:])}
The pages are generated with Goldsv0.8.2. (GOOS=linux GOARCH=amd64)
Golds is a Go 101 project developed by Tapir Liu.
PR and bug reports are welcome and can be submitted to the issue list.
Please follow @zigo_101 (reachable from the left QR code) to get the latest news of Golds.