-
-
Notifications
You must be signed in to change notification settings - Fork 6
/
dumpfunc.go
35 lines (30 loc) · 912 Bytes
/
dumpfunc.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
//go:build !go1.18
// +build !go1.18
package dd
import "reflect"
// DumpFunc is a function to dump you specified custom format.
type DumpFunc func(interface{}, Writer)
var typeWriter = reflect.TypeOf((*Writer)(nil)).Elem()
// WithDumpFunc is an option to add function for customize specified type dump string.
// want function f like "func(string, Writer)"
func WithDumpFunc(f interface{}) OptionFunc {
frv := reflect.ValueOf(f)
typ := frv.Type()
if typ.Kind() != reflect.Func {
panic("f must be function")
}
numIn := typ.NumIn()
if numIn != 2 {
panic("f must be the number of parameter is 2")
}
p0 := typ.In(0)
p1 := typ.In(1)
if !p1.Implements(typeWriter) {
panic("the second parameter must be implemented interface Writer")
}
return func(o *options) {
o.convertibleTypes[p0] = dumpFunc(func(rv reflect.Value, w Writer) {
frv.Call([]reflect.Value{rv, reflect.ValueOf(w)})
})
}
}