-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprinter.go
98 lines (83 loc) · 1.95 KB
/
printer.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
package pretty
import (
"fmt"
"io"
"reflect"
"github.com/pierrre/go-libs/bufpool"
"github.com/pierrre/pretty/internal/must"
"github.com/pierrre/pretty/internal/write"
)
// Write writes the value to the [io.Writer] with [DefaultPrinter].
func Write(w io.Writer, vi any) {
DefaultPrinter.Write(w, vi)
}
// String returns the value as a string with [DefaultPrinter].
func String(vi any) string {
return DefaultPrinter.String(vi)
}
// Formatter returns a [fmt.Formatter] for the value with [DefaultPrinter].
func Formatter(vi any) fmt.Formatter {
return DefaultPrinter.Formatter(vi)
}
// DefaultPrinter is the default [Printer].
var DefaultPrinter = NewPrinter(DefaultConfig, DefaultCommonValueWriter)
// Printer pretty-prints values.
//
// It should be created with [NewPrinter].
type Printer struct {
Config *Config
ValueWriter ValueWriter
}
// NewPrinter creates a new [Printer].
func NewPrinter(c *Config, vw ValueWriter) *Printer {
return &Printer{
Config: c,
ValueWriter: vw,
}
}
// Write writes the value to the [io.Writer].
func (p *Printer) Write(w io.Writer, vi any) {
defer func() {
r := recover()
if r == nil {
return
}
writePanic(w, r)
}()
v := reflect.ValueOf(vi)
if !v.IsValid() {
writeNil(w)
return
}
st := newState(w, p.Config.Indent)
defer st.release()
must.Handle(p.ValueWriter.WriteValue(st, v))
}
func writePanic(w io.Writer, r any) {
_, _ = write.String(w, "<panic>: ")
_, _ = fmt.Fprint(w, r)
}
var bufPool = &bufpool.Pool{
MaxCap: -1,
}
// String returns the value as a string.
func (p *Printer) String(vi any) string {
buf := bufPool.Get()
defer bufPool.Put(buf)
p.Write(buf, vi)
return buf.String()
}
// Formatter returns a [fmt.Formatter] for the value.
func (p *Printer) Formatter(vi any) fmt.Formatter {
return &formatter{
printer: p,
value: vi,
}
}
type formatter struct {
printer *Printer
value any
}
func (ft *formatter) Format(f fmt.State, verb rune) {
ft.printer.Write(f, ft.value)
}