-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstruct2row.go
86 lines (78 loc) · 1.68 KB
/
struct2row.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
package data
import (
"go4ml.xyz/errstr"
"go4ml.xyz/lazy"
"reflect"
)
type StructWrapper struct {
SimpleRowFactory
tp reflect.Type
ndxmap []int
}
func NewWrapper(st interface{}) (w *StructWrapper, err error) {
tp := reflect.TypeOf(st)
if tp.Kind() == reflect.Interface {
tp = tp.Elem()
}
w = &StructWrapper{tp: tp}
flen := tp.NumField()
w.ndxmap = make([]int, flen)
w.SimpleRowFactory.Names = make([]string, flen)
for i := 0; i < flen; i++ {
w.ndxmap[i] = i
w.SimpleRowFactory.Names[i] = tp.Field(i).Name
}
return
}
func (w *StructWrapper) Wrap(st interface{}) (row *Row, err error) {
row = w.New()
if err = w.Fill(row, st); err != nil {
row.Recycle()
row = nil
}
return
}
func (w *StructWrapper) WrapOrFail(st interface{}) interface{} {
row := w.New()
if err := w.Fill(row, st); err != nil {
row.Recycle()
return lazy.Fail(err)
}
return row
}
func (w *StructWrapper) Fill(row *Row, st interface{}) (_ error) {
v := reflect.ValueOf(st)
if v.Kind() == reflect.Interface {
v = v.Elem()
}
if v.Type() != w.tp {
return errstr.Errorf("can't fill row of %v from %v", w.tp, v.Type())
}
for from, to := range w.ndxmap {
row.Data[to].Val = v.Field(from).Interface()
}
return
}
func StructToRow(st interface{}) interface{} {
w, err := NewWrapper(st)
return func(x interface{}) interface{} {
var v interface{}
if err == nil {
v, err = w.Wrap(x)
}
if err != nil {
return lazy.Fail(err)
}
return v
}
}
func ValueToRow(col string) interface{} {
return func(st interface{}) interface{} {
factory := SimpleRowFactory{Names: []string{col}}
return func(x interface{}) interface{} {
row := factory.New()
row.Data[0].Val = x
return row
}
}
}