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