github.com/nikandfor/errors@v0.8.0/unsafe_fmt.go (about)

     1  package errors
     2  
     3  import (
     4  	"fmt"
     5  	"io"
     6  	"strconv"
     7  	"unsafe"
     8  )
     9  
    10  func subPrintArg(s fmt.State, arg interface{}, verb rune) {
    11  	i := *(*iface)(unsafe.Pointer(&s))
    12  	if i.typ != ppType {
    13  		var buf [64]byte
    14  
    15  		i := 0
    16  
    17  		buf[i] = '%'
    18  		i++
    19  
    20  		for _, f := range "-+# 0" {
    21  			if s.Flag(int(f)) {
    22  				buf[i] = byte(f)
    23  				i++
    24  			}
    25  		}
    26  
    27  		if w, ok := s.Width(); ok {
    28  			q := strconv.AppendInt(buf[:i], int64(w), 10)
    29  			i = len(q)
    30  		}
    31  
    32  		if p, ok := s.Precision(); ok {
    33  			buf[i] = '.'
    34  			i++
    35  
    36  			q := strconv.AppendInt(buf[:i], int64(p), 10)
    37  			i = len(q)
    38  		}
    39  
    40  		buf[i] = byte(verb)
    41  		i++
    42  
    43  		fmt.Fprintf(s, bytesToString(buf[:i]), arg)
    44  
    45  		return
    46  	}
    47  
    48  	printArg(i.word, arg, verb)
    49  }
    50  
    51  type (
    52  	iface struct {
    53  		typ, word unsafe.Pointer
    54  	}
    55  
    56  	formatter struct{}
    57  )
    58  
    59  var ppType unsafe.Pointer
    60  
    61  func init() {
    62  	fmt.Fprintf(io.Discard, "%v", formatter{})
    63  }
    64  
    65  //go:linkname printArg fmt.(*pp).printArg
    66  func printArg(p unsafe.Pointer, arg interface{}, verb rune)
    67  
    68  //go:linkname newPrinter fmt.newPrinter
    69  func newPrinter() unsafe.Pointer
    70  
    71  //go:linkname ppFree fmt.(*pp).free
    72  func ppFree(unsafe.Pointer)
    73  
    74  func (formatter) Format(s fmt.State, c rune) {
    75  	i := *(*iface)(unsafe.Pointer(&s))
    76  
    77  	ppType = i.typ
    78  }
    79  
    80  func bytesToString(b []byte) string {
    81  	return *(*string)(unsafe.Pointer(&b))
    82  }