-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprinter.go
97 lines (81 loc) · 2.07 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
package pretty
import (
"bytes"
"fmt"
"io"
"reflect"
"github.com/pierrre/go-libs/bufpool"
)
// Write writes the value to the [io.Writer] with [DefaultPrinter].
func Write(w io.Writer, vi any, opts ...Option) {
DefaultPrinter.Write(w, vi, opts...)
}
// String returns the value as a string with [DefaultPrinter].
func String(vi any, opts ...Option) string {
return DefaultPrinter.String(vi, opts...)
}
// Formatter returns a [fmt.Formatter] for the value with [DefaultPrinter].
func Formatter(vi any, opts ...Option) fmt.Formatter {
return DefaultPrinter.Formatter(vi, opts...)
}
// DefaultPrinter is the default [Printer].
var DefaultPrinter = NewPrinter(DefaultConfig, DefaultCommonValueWriter.WriteValue)
// 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, opts ...Option) {
v := reflect.ValueOf(vi)
if !v.IsValid() {
writeNil(w)
return
}
st := newState(w, p.Config.Indent)
defer st.release()
for _, opt := range opts {
opt(st)
}
mustHandle(p.ValueWriter(st, v))
}
var bufPool = &bufpool.Pool{
MaxCap: -1,
}
// String returns the value as a string.
func (p *Printer) String(vi any, opts ...Option) string {
buf := p.getBuf(vi, opts...)
defer bufPool.Put(buf)
return buf.String()
}
func (p *Printer) getBuf(vi any, opts ...Option) *bytes.Buffer {
buf := bufPool.Get()
p.Write(buf, vi, opts...)
return buf
}
// Formatter returns a [fmt.Formatter] for the value.
func (p *Printer) Formatter(vi any, opts ...Option) fmt.Formatter {
return &formatter{
printer: p,
value: vi,
}
}
// Option represents an option for the [Printer].
type Option func(*State)
type formatter struct {
printer *Printer
value any
opts []Option
}
func (ft *formatter) Format(f fmt.State, verb rune) {
ft.printer.Write(f, ft.value, ft.opts...)
}