Repository navigation
Expand file tree
/
Copy pathhandler.go
More file actions
450 lines (422 loc) · 11.1 KB
/
Copy pathhandler.go
File metadata and controls
450 lines (422 loc) · 11.1 KB
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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
package enc
import (
"encoding/json"
"fmt"
"math"
"reflect"
"strconv"
"time"
"github.com/ohait/forego/ctx"
"github.com/ohait/forego/ctx/log"
)
// factory holds global type factories registered at init time.
// This map is only written during init() and read-only afterwards, so no locking is needed.
var factory = map[reflect.Type]func(c ctx.C, n Node) (any, error){}
// generic object that do the Unmarshal()/Conflate()
type Handler struct {
Factory map[reflect.Type]func(c ctx.C, n Node) (any, error)
// called if a field is present in the NodeTree but there is no mapping on the object it's unmarshaled into
UnhandledFields func(c ctx.C, path []any, n Node) error
Debugf func(c ctx.C, f string, args ...any)
path path
}
// Register registers a factory function for type T.
// When h is nil, registers globally (must be called during init()).
// When h is non-nil, registers on that specific Handler instance (can be called anytime).
// Note: The factory is registered as *T, not T, so unmarshal lookup checks both T and *T.
func Register[T any](h *Handler, f func(ctx.C, Node) (T, error)) {
var obj *T
t := reflect.TypeOf(obj)
fn := func(c ctx.C, n Node) (any, error) {
return f(c, n)
}
if h == nil {
factory[t] = fn
} else {
if h.Debugf != nil {
h.Debugf(nil, "registered %v (%T)", t, obj)
}
if h.Factory == nil {
h.Factory = map[reflect.Type]func(ctx.C, Node) (any, error){}
}
h.Factory[t] = fn
}
}
func (this Handler) Append(p any) Handler {
this.path = append(this.path, p)
return this
}
var ineff = map[string]bool{}
func MustUnmarshal(c ctx.C, n Node, into any) {
err := Handler{}.Unmarshal(c, n, into)
if err != nil {
panic(err)
}
}
func Unmarshal(c ctx.C, n Node, into any) error {
return Handler{}.Unmarshal(c, n, into)
}
func (this Handler) Unmarshal(c ctx.C, n Node, into any) error {
if n == nil {
n = Nil{}
}
v := reflect.ValueOf(into).Elem()
return this.Append(v.Type()).unmarshal(c, n, v)
}
func (this Handler) unmarshal(c ctx.C, from Node, v reflect.Value) error {
// c = ctx.WithTag(c, "path", this.path.String()) // NOTE(oha): this is a bit slow because the json part
// defer log.Debugf(c, "unmarshal( %T %+v => %v{%+v} )", from, from, v.Type(), v)
if this.Debugf != nil {
this.Debugf(c, "unmarshal( %v -> %v{%v} )", from, v.Type(), v)
}
if !v.CanSet() {
return ctx.NewErrorf(c, "can't assign %v", v)
}
if v.Kind() == reflect.Pointer {
switch from.(type) {
case Nil:
v.SetZero()
return nil
default:
vv := reflect.New(v.Type().Elem())
v.Set(vv)
if this.Debugf != nil {
this.Debugf(c, "pointer deref: %v -> %v", v.Type(), v.Elem().Type())
}
return this.unmarshal(c, from, v.Elem())
}
}
switch into := v.Addr().Interface().(type) {
case Unmarshaler:
if this.Debugf != nil {
this.Debugf(c, "is %T", into)
}
return into.UnmarshalNode(c, from)
case *[]byte:
if this.Debugf != nil {
this.Debugf(c, "is %T", into)
}
switch from := from.(type) {
case Bytes:
out := make([]byte, len(from))
copy(out, from)
*into = out
return nil
default:
j := JSON{}.Encode(c, from)
return json.Unmarshal(j, into)
}
case *json.RawMessage:
if this.Debugf != nil {
this.Debugf(c, "is %T", into)
}
*into = JSON{}.Encode(c, from)
warnIneff(c, "Warn: inefficient json.RawMessage, use enc.Node instead")
return nil
case *time.Time:
var t time.Time
err := json.Unmarshal(JSON{}.Encode(c, from), &t)
if err != nil {
return ctx.NewErrorf(c, "can't unmarshal %#v as time", from)
}
*into = t
return nil
case json.Unmarshaler:
if this.Debugf != nil {
this.Debugf(c, "is %T", into)
}
warnIneff(c, "Warn: inefficient %T.UnmarshalJSON(): implement enc.Unmarshaler instead", into)
j, _ := json.Marshal(from) // we must go back to the json
return into.UnmarshalJSON(j)
case *Node:
if this.Debugf != nil {
this.Debugf(c, "is %T", into)
}
// NOTE(oha) if a struct has a field of type enc.Node, we drop the data there (similarly to json.RawMessage)
*into = from
return nil
}
/*
vv := v.Elem()
switch from.(type) {
case nil, Nil:
vv.SetZero()
return nil
}
*/
var f func(ctx.C, Node) (any, error)
if this.Factory == nil {
f = factory[v.Type()]
if f == nil {
// also check for a pointer to this type
f = factory[reflect.PointerTo(v.Type())]
}
} else {
f = this.Factory[v.Type()]
if f == nil {
// also check for a pointer to this type
f = this.Factory[reflect.PointerTo(v.Type())]
}
}
if f != nil {
if this.Debugf != nil {
this.Debugf(c, "factory for type %v", v.Type())
}
obj, err := f(c, from)
if err != nil {
return ctx.NewErrorf(c, "factory error: %w", err)
}
s := reflect.ValueOf(obj)
if !s.CanConvert(v.Type()) {
return ctx.NewErrorf(c, "Factory %v returned %v which can't be converted to %v",
v.Type(), s.Type(), v.Type())
}
if this.Debugf != nil {
this.Debugf(c, "Factory %v returned %v which can be converted to %v", v.Type(), s.Type(), v.Type())
}
v.Set(s)
return nil
}
// log.Debugf(c, "OHA %T => %v", from, v.Type())
if this.Debugf != nil {
this.Debugf(c, "normal type: %v, use generic %T.unmarshalInto()", v.Type(), from)
}
/*
if v.Kind() == reflect.Pointer {
// if we unmarshal into a pointer, we create the zero value and unmarshal into that instead
// this allow to unmarshal into *bool or *string
e := reflect.New(v.Type().Elem())
log.Debugf(c, "OHA4: %v", e.Type())
err := from.unmarshalInto(c, this, path, e.Elem())
if err != nil {
return err
}
v.Set(e)
return nil
}
*/
return from.unmarshalInto(c, this, v)
}
// skip the factory and unmarshal and directly unmarshal into the object, useful inside a custo Unmarshaler
func UnmarshalInto(c ctx.C, n Node, into any) error {
return Handler{}.UnmarshalInto(c, n, into)
}
func (h Handler) UnmarshalInto(c ctx.C, n Node, into any) error {
return n.unmarshalInto(c, h, reflect.ValueOf(into).Elem())
}
func warnIneff(c ctx.C, f string, args ...any) {
msg := fmt.Sprintf(f, args...)
if !ineff[msg] {
ineff[msg] = true
log.Warnf(c, f, args...)
}
}
func (this Handler) marshalValue(c ctx.C, v reflect.Value) (Node, error) {
if !v.IsValid() {
return Nil{}, nil
}
if v.CanAddr() {
if in, ok := v.Addr().Interface().(Marshaler); ok {
return in.MarshalNode(c)
}
if in, ok := v.Addr().Interface().(json.Marshaler); ok {
j, err := in.MarshalJSON()
if err != nil {
return nil, err
}
return JSON{}.Decode(c, j)
}
}
return this.Marshal(c, v.Interface())
}
// transform a struct into a enc.Node, using the struct tags to determine the field names and options, allow custom pairs
// this can be useful for adding a "type" field to a struct:
//
// func (f Filter) MarshalNode(c ctx.C) (enc.Node, error) {
// return enc.MarshalStruct(c, f, enc.Pair{Name: "type", Value: enc.String("filter")})
// }
func MarshalStruct(c ctx.C, in any, pairs ...Pair) (Pairs, error) {
return Handler{}.MarshalStruct(c, in, pairs...)
}
func (this Handler) MarshalStruct(c ctx.C, in any, pairs ...Pair) (Pairs, error) {
v := reflect.ValueOf(in)
if !v.IsValid() {
return nil, ctx.NewErrorf(c, "can't marshal %T as struct", in)
}
for v.Kind() == reflect.Pointer {
if v.IsNil() {
return nil, ctx.NewErrorf(c, "can't marshal %T as struct", in)
}
v = v.Elem()
}
if v.Kind() != reflect.Struct {
return nil, ctx.NewErrorf(c, "can't marshal %T as struct", in)
}
t := v.Type()
out := Pairs(pairs)
for i := 0; i < v.NumField(); i++ {
ft := t.Field(i)
if !ft.IsExported() {
continue
}
tag, err := parseTag(ft)
if err != nil {
return nil, ctx.WrapError(c, err)
}
if tag.Skip {
continue
}
fv := v.Field(i)
fn, err := this.marshalValue(c, fv)
if err != nil {
return nil, err
}
switch fn := fn.(type) {
case Nil:
if !tag.OmitEmpty {
out = append(out, Pair{tag.Name, fn})
}
case String:
if !tag.OmitEmpty || fn != "" {
out = append(out, Pair{tag.Name, fn})
}
case Integer:
if !tag.OmitEmpty || fn != 0 {
out = append(out, Pair{tag.Name, fn})
}
case Float:
if !tag.OmitEmpty || fn != 0.0 {
out = append(out, Pair{tag.Name, fn})
}
case Digits:
if !tag.OmitEmpty || fn != "" {
out = append(out, Pair{tag.Name, fn})
}
case Bytes:
if !tag.OmitEmpty || len(fn) > 0 {
out = append(out, Pair{tag.Name, fn})
}
case Time:
if !tag.OmitEmpty || !time.Time(fn).IsZero() {
out = append(out, Pair{tag.Name, fn})
}
default:
out = append(out, Pair{tag.Name, fn})
}
}
return out, nil
}
// transform an object into a enc.Node
func Marshal(c ctx.C, in any) (Node, error) {
return Handler{}.Marshal(c, in)
}
func (this Handler) Marshal(c ctx.C, in any) (Node, error) {
// log.Warnf(c, "OHA: %T %v", in, in)
switch in := in.(type) {
case nil:
return Nil{}, nil
case []byte:
if in == nil {
return Nil{}, nil
}
out := make(Bytes, len(in))
copy(out, in)
return out, nil
case time.Time:
return Time(in), nil
// return String(in.Format(time.RFC3339Nano)), nil
case Marshaler:
// log.Warnf(c, "OHA: %T->MarshalNode", in)
return in.MarshalNode(c)
case json.Marshaler:
j, err := in.MarshalJSON()
if err != nil {
return nil, err
}
return JSON{}.Decode(c, j)
case error:
return String(in.Error()), nil
case Node:
return in, nil
}
v := reflect.ValueOf(in)
t := v.Type()
switch t.Kind() {
default:
log.Warnf(c, "possible wrong fallback for type %T", in)
return fromNative(in), nil
case reflect.Func:
return nil, ctx.NewErrorf(c, "can't marshal %T", in)
case reflect.Bool:
return Bool(v.Bool()), nil
case reflect.Float64, reflect.Float32:
return Float(v.Float()), nil
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return Integer(v.Int()), nil
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
u := v.Uint()
if u <= math.MaxInt64 {
return Integer(int64(u)), nil
}
return Digits(strconv.FormatUint(u, 10)), nil
case reflect.String:
return String(v.String()), nil
case reflect.Pointer:
if v.IsNil() {
return Nil{}, nil
}
return this.Marshal(c, v.Elem().Interface())
case reflect.Slice:
if v.IsNil() {
return Nil{}, nil
}
fallthrough // Intentional, since the above check breaks when called on arrays
case reflect.Array:
list := List{}
for i := 0; i < v.Len(); i++ {
ev := v.Index(i)
e, err := this.marshalValue(c, ev)
if err != nil {
return nil, err
}
list = append(list, e)
}
return list, nil
case reflect.Map:
if v.IsNil() {
return Nil{}, nil
}
m := Map{}
for _, kv := range v.MapKeys() {
vv := v.MapIndex(kv)
n, err := this.Marshal(c, vv.Interface())
if err != nil {
return nil, err
}
switch k := kv.Interface().(type) {
case string:
m[k] = n
default:
nk, err := this.Marshal(c, k)
if err != nil {
return nil, err
}
switch nk := nk.(type) {
case String:
m[string(nk)] = n
case Integer:
m[fmt.Sprint(nk)] = n
case Float:
m[fmt.Sprint(nk)] = n
case Digits:
m[fmt.Sprint(nk)] = n
default:
return nil, ctx.NewErrorf(c, "can't marshal %v as map key", kv.Type())
}
}
}
return m, nil
case reflect.Struct:
}
return this.MarshalStruct(c, in)
}