tlog.app/go/errors@v0.9.0/unsafe_fmt_test.go (about) 1 package errors 2 3 import ( 4 "bytes" 5 "fmt" 6 "testing" 7 8 "github.com/stretchr/testify/assert" 9 ) 10 11 type ( 12 testformatter struct { 13 flags [64]bool 14 15 wid int 16 prc int 17 18 widok bool 19 prcok bool 20 21 verb rune 22 23 buf []byte 24 } 25 ) 26 27 func TestSubPrintArg(t *testing.T) { 28 var b bytes.Buffer 29 30 var f testformatter 31 32 fmt.Fprintf(&b, "%+012.6q", &f) 33 34 assert.Equal(t, testformatter{ 35 flags: flags("+0"), 36 wid: 12, 37 widok: true, 38 prc: 6, 39 prcok: true, 40 verb: 'q', 41 }, f) 42 43 // 44 45 var f2 testformatter 46 47 subPrintArg(&f, &f2, 'v') 48 49 assert.Equal(t, testformatter{ 50 flags: flags("+0"), 51 wid: 12, 52 widok: true, 53 prc: 6, 54 prcok: true, 55 verb: 'v', 56 }, f2) 57 58 // 59 60 f = testformatter{} 61 f2 = testformatter{ 62 flags: flags("-# "), 63 prc: 3, 64 prcok: true, 65 } 66 67 subPrintArg(&f2, &f, 'v') 68 69 assert.Equal(t, testformatter{ 70 flags: flags(" -#"), 71 prc: 3, 72 prcok: true, 73 verb: 'v', 74 }, f) 75 } 76 77 func BenchmarkPringArg(b *testing.B) { 78 b.ReportAllocs() 79 80 f := testformatter{} 81 82 for i := 0; i < b.N; i++ { 83 pp := newPrinter() 84 printArg(pp, &f, 'v') 85 ppFree(pp) 86 } 87 } 88 89 func BenchmarkPringArgFallback(b *testing.B) { 90 b.ReportAllocs() 91 92 f := testformatter{} 93 f2 := testformatter{ 94 flags: flags("-# "), 95 prc: 3, 96 prcok: true, 97 } 98 99 for i := 0; i < b.N; i++ { 100 subPrintArg(&f2, &f, 'v') 101 } 102 } 103 104 func (f *testformatter) Format(s fmt.State, verb rune) { 105 f.flags = [64]bool{} 106 107 for _, q := range "-+# 0" { 108 if s.Flag(int(q)) { 109 f.flags[q] = true 110 } 111 } 112 113 f.wid, f.widok = s.Width() 114 f.prc, f.prcok = s.Precision() 115 116 f.verb = verb 117 } 118 119 func (f *testformatter) Flag(c int) bool { 120 return f.flags[c] 121 } 122 123 func (f *testformatter) Width() (int, bool) { 124 return f.wid, f.widok 125 } 126 127 func (f *testformatter) Precision() (int, bool) { 128 return f.prc, f.prcok 129 } 130 131 func (f *testformatter) Write(p []byte) (int, error) { 132 f.buf = append(f.buf, p...) 133 134 return len(p), nil 135 } 136 137 func flags(f string) (r [64]bool) { 138 for _, q := range f { 139 r[q] = true 140 } 141 142 return 143 }