-
Notifications
You must be signed in to change notification settings - Fork 50
/
Copy pathnode.go
1756 lines (1615 loc) · 51.1 KB
/
node.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
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
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package bindnode
import (
"fmt"
"math"
"reflect"
"runtime"
"strings"
"github.com/ipfs/go-cid"
"github.com/ipld/go-ipld-prime/datamodel"
cidlink "github.com/ipld/go-ipld-prime/linking/cid"
"github.com/ipld/go-ipld-prime/node/basicnode"
"github.com/ipld/go-ipld-prime/node/mixins"
"github.com/ipld/go-ipld-prime/schema"
)
// Assert that we implement all the interfaces as expected.
// Grouped by the interfaces to implement, roughly.
var (
_ datamodel.NodePrototype = (*_prototype)(nil)
_ schema.TypedPrototype = (*_prototype)(nil)
_ datamodel.NodePrototype = (*_prototypeRepr)(nil)
_ datamodel.Node = (*_node)(nil)
_ schema.TypedNode = (*_node)(nil)
_ datamodel.Node = (*_nodeRepr)(nil)
_ datamodel.Node = (*_uintNode)(nil)
_ schema.TypedNode = (*_uintNode)(nil)
_ datamodel.UintNode = (*_uintNode)(nil)
_ datamodel.Node = (*_uintNodeRepr)(nil)
_ datamodel.UintNode = (*_uintNodeRepr)(nil)
_ datamodel.NodeBuilder = (*_builder)(nil)
_ datamodel.NodeBuilder = (*_builderRepr)(nil)
_ datamodel.NodeAssembler = (*_assembler)(nil)
_ datamodel.NodeAssembler = (*_assemblerRepr)(nil)
_ datamodel.MapAssembler = (*_structAssembler)(nil)
_ datamodel.MapAssembler = (*_structAssemblerRepr)(nil)
_ datamodel.MapIterator = (*_structIterator)(nil)
_ datamodel.MapIterator = (*_structIteratorRepr)(nil)
_ datamodel.ListAssembler = (*_listAssembler)(nil)
_ datamodel.ListAssembler = (*_listAssemblerRepr)(nil)
_ datamodel.ListAssembler = (*_listStructAssemblerRepr)(nil)
_ datamodel.ListIterator = (*_listIterator)(nil)
_ datamodel.ListIterator = (*_tupleIteratorRepr)(nil)
_ datamodel.ListIterator = (*_listpairsIteratorRepr)(nil)
_ datamodel.MapAssembler = (*_unionAssembler)(nil)
_ datamodel.MapAssembler = (*_unionAssemblerRepr)(nil)
_ datamodel.MapIterator = (*_unionIterator)(nil)
_ datamodel.MapIterator = (*_unionIteratorRepr)(nil)
)
type _prototype struct {
cfg config
schemaType schema.Type
goType reflect.Type // non-pointer
}
func (w *_prototype) NewBuilder() datamodel.NodeBuilder {
return &_builder{_assembler{
cfg: w.cfg,
schemaType: w.schemaType,
val: reflect.New(w.goType).Elem(),
}}
}
func (w *_prototype) Type() schema.Type {
return w.schemaType
}
func (w *_prototype) Representation() datamodel.NodePrototype {
return (*_prototypeRepr)(w)
}
type _node struct {
cfg config
schemaType schema.Type
val reflect.Value // non-pointer
}
// TODO: only expose TypedNode methods if the schema was explicit.
// type _typedNode struct {
// _node
// }
func newNode(cfg config, schemaType schema.Type, val reflect.Value) schema.TypedNode {
if schemaType.TypeKind() == schema.TypeKind_Int && nonPtrVal(val).Kind() == reflect.Uint64 {
// special case for uint64 values so we can handle the >int64 range
// we give this treatment to all uint64s, regardless of current value
// because we have no guarantees the value won't change underneath us
return &_uintNode{
cfg: cfg,
schemaType: schemaType,
val: val,
}
}
return &_node{cfg, schemaType, val}
}
func (w *_node) Type() schema.Type {
return w.schemaType
}
func (w *_node) Representation() datamodel.Node {
return (*_nodeRepr)(w)
}
func (w *_node) Kind() datamodel.Kind {
return actualKind(w.schemaType)
}
// matching schema level types to data model kinds, since our Node and Builder
// interfaces operate on kinds
func compatibleKind(schemaType schema.Type, kind datamodel.Kind) error {
switch sch := schemaType.(type) {
case *schema.TypeAny:
return nil
default:
actual := actualKind(sch) // ActsLike data model
if actual == kind {
return nil
}
// Error
methodName := ""
if pc, _, _, ok := runtime.Caller(1); ok {
if fn := runtime.FuncForPC(pc); fn != nil {
methodName = fn.Name()
// Go from "pkg/path.Type.Method" to just "Method".
methodName = methodName[strings.LastIndexByte(methodName, '.')+1:]
}
}
return datamodel.ErrWrongKind{
TypeName: schemaType.Name(),
MethodName: methodName,
AppropriateKind: datamodel.KindSet{kind},
ActualKind: actual,
}
}
}
func actualKind(schemaType schema.Type) datamodel.Kind {
return schemaType.TypeKind().ActsLike()
}
func nonPtrVal(val reflect.Value) reflect.Value {
// TODO: support **T as well as *T?
if val.Kind() == reflect.Ptr {
if val.IsNil() {
// TODO: error in this case?
return reflect.Value{}
}
val = val.Elem()
}
return val
}
func ptrVal(val reflect.Value) reflect.Value {
if val.Kind() == reflect.Ptr {
return val
}
return val.Addr()
}
func nonPtrType(val reflect.Value) reflect.Type {
typ := val.Type()
if typ.Kind() == reflect.Ptr {
return typ.Elem()
}
return typ
}
// where we need to cal Set(), ensure the Value we're setting is a pointer or
// not, depending on the field we're setting into.
func matchSettable(val interface{}, to reflect.Value) reflect.Value {
setVal := nonPtrVal(reflect.ValueOf(val))
if !setVal.Type().AssignableTo(to.Type()) && setVal.Type().ConvertibleTo(to.Type()) {
setVal = setVal.Convert(to.Type())
}
return setVal
}
func (w *_node) LookupByString(key string) (datamodel.Node, error) {
switch typ := w.schemaType.(type) {
case *schema.TypeStruct:
field := typ.Field(key)
if field == nil {
return nil, schema.ErrInvalidKey{
TypeName: typ.Name(),
Key: basicnode.NewString(key),
}
}
fval := nonPtrVal(w.val).FieldByName(fieldNameFromSchema(key))
if !fval.IsValid() {
return nil, fmt.Errorf("bindnode TODO: go-schema mismatch")
}
if field.IsOptional() {
if fval.IsNil() {
return datamodel.Absent, nil
}
if fval.Kind() == reflect.Ptr {
fval = fval.Elem()
}
}
if field.IsNullable() {
if fval.IsNil() {
return datamodel.Null, nil
}
if fval.Kind() == reflect.Ptr {
fval = fval.Elem()
}
}
if _, ok := field.Type().(*schema.TypeAny); ok {
if customConverter := w.cfg.converterFor(fval); customConverter != nil {
// field is an Any and we have a custom type converter for the type
return customConverter.customToAny(ptrVal(fval).Interface())
}
// field is an Any, safely assume a Node in fval
return nonPtrVal(fval).Interface().(datamodel.Node), nil
}
return newNode(w.cfg, field.Type(), fval), nil
case *schema.TypeMap:
// maps can only be structs with a Values map
var kval reflect.Value
valuesVal := nonPtrVal(w.val).FieldByName("Values")
switch ktyp := typ.KeyType().(type) {
case *schema.TypeString:
// plain String keys, so safely use the map key as is
kval = reflect.ValueOf(key)
default:
// key is something other than a string that we need to assemble via
// the string representation form, use _assemblerRepr to reverse from
// string to the type that indexes the map
asm := &_assembler{
cfg: w.cfg,
schemaType: ktyp,
val: reflect.New(valuesVal.Type().Key()).Elem(),
}
if err := (*_assemblerRepr)(asm).AssignString(key); err != nil {
return nil, err
}
kval = asm.val
}
fval := valuesVal.MapIndex(kval)
if !fval.IsValid() { // not found
return nil, datamodel.ErrNotExists{Segment: datamodel.PathSegmentOfString(key)}
}
// TODO: Error/panic if fval.IsNil() && !typ.ValueIsNullable()?
// Otherwise we could have two non-equal Go values (nil map,
// non-nil-but-empty map) which represent the exact same IPLD
// node when the field is not nullable.
if typ.ValueIsNullable() {
if fval.IsNil() {
return datamodel.Null, nil
}
fval = fval.Elem()
}
if _, ok := typ.ValueType().(*schema.TypeAny); ok {
if customConverter := w.cfg.converterFor(fval); customConverter != nil {
// value is an Any and we have a custom type converter for the type
return customConverter.customToAny(ptrVal(fval).Interface())
}
// value is an Any, safely assume a Node in fval
return nonPtrVal(fval).Interface().(datamodel.Node), nil
}
return newNode(w.cfg, typ.ValueType(), fval), nil
case *schema.TypeUnion:
// treat a union similar to a struct, but we have the member names more
// easily accessible to match to 'key'
var idx int
var mtyp schema.Type
for i, member := range typ.Members() {
if member.Name() == key {
idx = i
mtyp = member
break
}
}
if mtyp == nil { // not found
return nil, datamodel.ErrNotExists{Segment: datamodel.PathSegmentOfString(key)}
}
// TODO: we could look up the right Go field straight away via idx.
haveIdx, mval := unionMember(nonPtrVal(w.val))
if haveIdx != idx { // mismatching type
return nil, datamodel.ErrNotExists{Segment: datamodel.PathSegmentOfString(key)}
}
return newNode(w.cfg, mtyp, mval), nil
}
return nil, datamodel.ErrWrongKind{
TypeName: w.schemaType.Name(),
MethodName: "LookupByString",
AppropriateKind: datamodel.KindSet_JustMap,
ActualKind: w.Kind(),
}
}
var invalidValue reflect.Value
// unionMember finds which union member is set in the corresponding Go struct.
func unionMember(val reflect.Value) (int, reflect.Value) {
// The first non-nil field is a match.
for i := 0; i < val.NumField(); i++ {
elemVal := val.Field(i)
if elemVal.Kind() != reflect.Ptr {
panic("bindnode bug: found unexpected non-pointer in a union field")
}
if elemVal.IsNil() {
continue
}
return i, elemVal.Elem()
}
return -1, invalidValue
}
func unionSetMember(val reflect.Value, memberIdx int, memberPtr reflect.Value) {
// Reset the entire union struct to zero, to clear any non-nil pointers.
val.Set(reflect.Zero(val.Type()))
// Set the index pointer to the given value.
val.Field(memberIdx).Set(memberPtr)
}
func (w *_node) LookupByIndex(idx int64) (datamodel.Node, error) {
switch typ := w.schemaType.(type) {
case *schema.TypeList:
val := nonPtrVal(w.val)
// we should be able assume that val is something we can Len() and Index()
if idx < 0 || int(idx) >= val.Len() {
return nil, datamodel.ErrNotExists{Segment: datamodel.PathSegmentOfInt(idx)}
}
val = val.Index(int(idx))
_, isAny := typ.ValueType().(*schema.TypeAny)
if isAny {
if customConverter := w.cfg.converterFor(val); customConverter != nil {
// values are Any and we have a converter for this type that will give us
// a datamodel.Node
return customConverter.customToAny(ptrVal(val).Interface())
}
}
if typ.ValueIsNullable() {
if val.IsNil() {
return datamodel.Null, nil
}
// nullable elements are assumed to be pointers
val = val.Elem()
}
if isAny {
// Any always yields a plain datamodel.Node
return nonPtrVal(val).Interface().(datamodel.Node), nil
}
return newNode(w.cfg, typ.ValueType(), val), nil
}
return nil, datamodel.ErrWrongKind{
TypeName: w.schemaType.Name(),
MethodName: "LookupByIndex",
AppropriateKind: datamodel.KindSet_JustList,
ActualKind: w.Kind(),
}
}
func (w *_node) LookupBySegment(seg datamodel.PathSegment) (datamodel.Node, error) {
switch w.Kind() {
case datamodel.Kind_Map:
return w.LookupByString(seg.String())
case datamodel.Kind_List:
idx, err := seg.Index()
if err != nil {
return nil, err
}
return w.LookupByIndex(idx)
}
return nil, datamodel.ErrWrongKind{
TypeName: w.schemaType.Name(),
MethodName: "LookupBySegment",
AppropriateKind: datamodel.KindSet_Recursive,
ActualKind: w.Kind(),
}
}
func (w *_node) LookupByNode(key datamodel.Node) (datamodel.Node, error) {
switch w.Kind() {
case datamodel.Kind_Map:
s, err := key.AsString()
if err != nil {
return nil, err
}
return w.LookupByString(s)
case datamodel.Kind_List:
i, err := key.AsInt()
if err != nil {
return nil, err
}
return w.LookupByIndex(i)
}
return nil, datamodel.ErrWrongKind{
TypeName: w.schemaType.Name(),
MethodName: "LookupByNode",
AppropriateKind: datamodel.KindSet_Recursive,
ActualKind: w.Kind(),
}
}
func (w *_node) MapIterator() datamodel.MapIterator {
val := nonPtrVal(w.val)
// structs, unions and maps can all iterate but they each have different
// access semantics for the underlying type, so we need a different iterator
// for each
switch typ := w.schemaType.(type) {
case *schema.TypeStruct:
return &_structIterator{
cfg: w.cfg,
schemaType: typ,
fields: typ.Fields(),
val: val,
}
case *schema.TypeUnion:
return &_unionIterator{
cfg: w.cfg,
schemaType: typ,
members: typ.Members(),
val: val,
}
case *schema.TypeMap:
// we can assume a: struct{Keys []string, Values map[x]y}
return &_mapIterator{
cfg: w.cfg,
schemaType: typ,
keysVal: val.FieldByName("Keys"),
valuesVal: val.FieldByName("Values"),
}
}
return nil
}
func (w *_node) ListIterator() datamodel.ListIterator {
val := nonPtrVal(w.val)
switch typ := w.schemaType.(type) {
case *schema.TypeList:
return &_listIterator{cfg: w.cfg, schemaType: typ, val: val}
}
return nil
}
func (w *_node) Length() int64 {
val := nonPtrVal(w.val)
switch w.Kind() {
case datamodel.Kind_Map:
switch typ := w.schemaType.(type) {
case *schema.TypeStruct:
return int64(len(typ.Fields()))
case *schema.TypeUnion:
return 1
}
return int64(val.FieldByName("Keys").Len())
case datamodel.Kind_List:
return int64(val.Len())
}
return -1
}
// TODO: better story around pointers and absent/null
func (w *_node) IsAbsent() bool {
return false
}
func (w *_node) IsNull() bool {
return false
}
// The AsX methods are matter of fetching the non-pointer form of the underlying
// value and returning the appropriate Go type. The user may have registered
// custom converters for the kind being converted, in which case the underlying
// type may not be the type we need, but the converter will supply it for us.
func (w *_node) AsBool() (bool, error) {
if err := compatibleKind(w.schemaType, datamodel.Kind_Bool); err != nil {
return false, err
}
if customConverter := w.cfg.converterFor(w.val); customConverter != nil {
// user has registered a converter that takes the underlying type and returns a bool
return customConverter.customToBool(ptrVal(w.val).Interface())
}
return nonPtrVal(w.val).Bool(), nil
}
func (w *_node) AsInt() (int64, error) {
if err := compatibleKind(w.schemaType, datamodel.Kind_Int); err != nil {
return 0, err
}
if customConverter := w.cfg.converterFor(w.val); customConverter != nil {
// user has registered a converter that takes the underlying type and returns an int
return customConverter.customToInt(ptrVal(w.val).Interface())
}
val := nonPtrVal(w.val)
if kindUint[val.Kind()] {
u := val.Uint()
if u > math.MaxInt64 {
return 0, fmt.Errorf("bindnode: integer overflow, %d is too large for an int64", u)
}
return int64(u), nil
}
return val.Int(), nil
}
func (w *_node) AsFloat() (float64, error) {
if err := compatibleKind(w.schemaType, datamodel.Kind_Float); err != nil {
return 0, err
}
if customConverter := w.cfg.converterFor(w.val); customConverter != nil {
// user has registered a converter that takes the underlying type and returns a float
return customConverter.customToFloat(ptrVal(w.val).Interface())
}
return nonPtrVal(w.val).Float(), nil
}
func (w *_node) AsString() (string, error) {
if err := compatibleKind(w.schemaType, datamodel.Kind_String); err != nil {
return "", err
}
if customConverter := w.cfg.converterFor(w.val); customConverter != nil {
// user has registered a converter that takes the underlying type and returns a string
return customConverter.customToString(ptrVal(w.val).Interface())
}
return nonPtrVal(w.val).String(), nil
}
func (w *_node) AsBytes() ([]byte, error) {
if err := compatibleKind(w.schemaType, datamodel.Kind_Bytes); err != nil {
return nil, err
}
if customConverter := w.cfg.converterFor(w.val); customConverter != nil {
// user has registered a converter that takes the underlying type and returns a []byte
return customConverter.customToBytes(ptrVal(w.val).Interface())
}
return nonPtrVal(w.val).Bytes(), nil
}
func (w *_node) AsLink() (datamodel.Link, error) {
if err := compatibleKind(w.schemaType, datamodel.Kind_Link); err != nil {
return nil, err
}
if customConverter := w.cfg.converterFor(w.val); customConverter != nil {
// user has registered a converter that takes the underlying type and returns a cid.Cid
cid, err := customConverter.customToLink(ptrVal(w.val).Interface())
if err != nil {
return nil, err
}
return cidlink.Link{Cid: cid}, nil
}
switch val := nonPtrVal(w.val).Interface().(type) {
case datamodel.Link:
return val, nil
case cid.Cid:
return cidlink.Link{Cid: val}, nil
default:
return nil, fmt.Errorf("bindnode: unexpected link type %T", val)
}
}
func (w *_node) Prototype() datamodel.NodePrototype {
return &_prototype{cfg: w.cfg, schemaType: w.schemaType, goType: w.val.Type()}
}
type _builder struct {
_assembler
}
func (w *_builder) Build() datamodel.Node {
// TODO: should we panic if no Assign call was made, just like codegen?
return newNode(w.cfg, w.schemaType, w.val)
}
func (w *_builder) Reset() {
panic("bindnode TODO: Reset")
}
type _assembler struct {
cfg config
schemaType schema.Type
val reflect.Value // non-pointer
// finish is used as an optional post-assemble step.
// For example, assigning to a kinded union uses a finish func
// to set the right union member in the Go union struct,
// which isn't known before the assemble has finished.
finish func() error
nullable bool // true if field or map value is nullable
}
// createNonPtrVal is used for Set() operations on the underlying value
func (w *_assembler) createNonPtrVal() reflect.Value {
val := w.val
// TODO: if val is not a pointer, we reuse its value.
// If it is a pointer, we allocate a new one and replace it.
// We should probably never reuse the existing value.
// TODO: support **T as well as *T?
if val.Kind() == reflect.Ptr {
// TODO: Sometimes we call createNonPtrVal before an assignment actually
// happens. Does that matter?
// If it matters and we only want to modify the destination value on
// success, then we should make use of the "finish" func.
val.Set(reflect.New(val.Type().Elem()))
val = val.Elem()
}
return val
}
func (w *_assembler) Representation() datamodel.NodeAssembler {
return (*_assemblerRepr)(w)
}
// basicMapAssembler is for assembling basicnode values, it's only use is for
// Any fields that end up needing a BeginMap()
type basicMapAssembler struct {
datamodel.MapAssembler
builder datamodel.NodeBuilder
parent *_assembler
converter *converter
}
func (w *basicMapAssembler) Finish() error {
if err := w.MapAssembler.Finish(); err != nil {
return err
}
basicNode := w.builder.Build()
if w.converter != nil {
// we can assume an Any converter because basicMapAssembler is only for Any
// the user has registered the ability to convert a datamodel.Node to the
// underlying Go type which may not be a datamodel.Node
typ, err := w.converter.customFromAny(basicNode)
if err != nil {
return err
}
w.parent.createNonPtrVal().Set(matchSettable(typ, reflect.ValueOf(basicNode)))
} else {
w.parent.createNonPtrVal().Set(reflect.ValueOf(basicNode))
}
if w.parent.finish != nil {
if err := w.parent.finish(); err != nil {
return err
}
}
return nil
}
func (w *_assembler) BeginMap(sizeHint int64) (datamodel.MapAssembler, error) {
switch typ := w.schemaType.(type) {
case *schema.TypeAny:
basicBuilder := basicnode.Prototype.Any.NewBuilder()
mapAsm, err := basicBuilder.BeginMap(sizeHint)
if err != nil {
return nil, err
}
converter := w.cfg.converterFor(w.val)
return &basicMapAssembler{MapAssembler: mapAsm, builder: basicBuilder, parent: w, converter: converter}, nil
case *schema.TypeStruct:
val := w.createNonPtrVal()
// _structAssembler walks through the fields in order as the entries are
// assembled, verifyCompatibility() should mean it's safe to assume that
// they match the schema, but we need to keep track of the fields that are
// set in case of premature Finish()
doneFields := make([]bool, val.NumField())
return &_structAssembler{
cfg: w.cfg,
schemaType: typ,
val: val,
doneFields: doneFields,
finish: w.finish,
}, nil
case *schema.TypeMap:
// assume a struct{Keys []string, Values map[x]y} that we can fill with
// _mapAssembler
val := w.createNonPtrVal()
keysVal := val.FieldByName("Keys")
valuesVal := val.FieldByName("Values")
if valuesVal.IsNil() {
valuesVal.Set(reflect.MakeMap(valuesVal.Type()))
}
return &_mapAssembler{
cfg: w.cfg,
schemaType: typ,
keysVal: keysVal,
valuesVal: valuesVal,
finish: w.finish,
}, nil
case *schema.TypeUnion:
// we can use _unionAssembler to assemble a union as if it were a map with
// a single entry
val := w.createNonPtrVal()
return &_unionAssembler{
cfg: w.cfg,
schemaType: typ,
val: val,
finish: w.finish,
}, nil
}
return nil, datamodel.ErrWrongKind{
TypeName: w.schemaType.Name(),
MethodName: "BeginMap",
AppropriateKind: datamodel.KindSet_JustMap,
ActualKind: actualKind(w.schemaType),
}
}
// basicListAssembler is for assembling basicnode values, it's only use is for
// Any fields that end up needing a BeginList()
type basicListAssembler struct {
datamodel.ListAssembler
builder datamodel.NodeBuilder
parent *_assembler
converter *converter
}
func (w *basicListAssembler) Finish() error {
if err := w.ListAssembler.Finish(); err != nil {
return err
}
basicNode := w.builder.Build()
if w.converter != nil {
// we can assume an Any converter because basicListAssembler is only for Any
// the user has registered the ability to convert a datamodel.Node to the
// underlying Go type which may not be a datamodel.Node
typ, err := w.converter.customFromAny(basicNode)
if err != nil {
return err
}
w.parent.createNonPtrVal().Set(matchSettable(typ, reflect.ValueOf(basicNode)))
} else {
w.parent.createNonPtrVal().Set(reflect.ValueOf(basicNode))
}
if w.parent.finish != nil {
if err := w.parent.finish(); err != nil {
return err
}
}
return nil
}
func (w *_assembler) BeginList(sizeHint int64) (datamodel.ListAssembler, error) {
switch typ := w.schemaType.(type) {
case *schema.TypeAny:
basicBuilder := basicnode.Prototype.Any.NewBuilder()
listAsm, err := basicBuilder.BeginList(sizeHint)
if err != nil {
return nil, err
}
converter := w.cfg.converterFor(w.val)
return &basicListAssembler{ListAssembler: listAsm, builder: basicBuilder, parent: w, converter: converter}, nil
case *schema.TypeList:
// we should be able to safely assume we're dealing with a Go slice here,
// so _listAssembler can append to that
val := w.createNonPtrVal()
return &_listAssembler{
cfg: w.cfg,
schemaType: typ,
val: val,
finish: w.finish,
}, nil
}
return nil, datamodel.ErrWrongKind{
TypeName: w.schemaType.Name(),
MethodName: "BeginList",
AppropriateKind: datamodel.KindSet_JustList,
ActualKind: actualKind(w.schemaType),
}
}
func (w *_assembler) AssignNull() error {
_, isAny := w.schemaType.(*schema.TypeAny)
if customConverter := w.cfg.converterFor(w.val); customConverter != nil && isAny {
// an Any field that is being assigned a Null, we pass the Null directly to
// the converter, regardless of whether this field is nullable or not
typ, err := customConverter.customFromAny(datamodel.Null)
if err != nil {
return err
}
w.createNonPtrVal().Set(matchSettable(typ, w.val))
} else {
if !w.nullable {
return datamodel.ErrWrongKind{
TypeName: w.schemaType.Name(),
MethodName: "AssignNull",
// TODO
}
}
// set the zero value for the underlying type as a stand-in for Null
w.val.Set(reflect.Zero(w.val.Type()))
}
if w.finish != nil {
if err := w.finish(); err != nil {
return err
}
}
return nil
}
func (w *_assembler) AssignBool(b bool) error {
if err := compatibleKind(w.schemaType, datamodel.Kind_Bool); err != nil {
return err
}
customConverter := w.cfg.converterFor(w.val)
_, isAny := w.schemaType.(*schema.TypeAny)
if customConverter != nil {
var typ interface{}
var err error
if isAny {
// field is an Any, so the converter will be an Any converter that wants
// a datamodel.Node to convert to whatever the underlying Go type is
if typ, err = customConverter.customFromAny(basicnode.NewBool(b)); err != nil {
return err
}
} else {
// field is a Bool, but the user has registered a converter from a bool to
// whatever the underlying Go type is
if typ, err = customConverter.customFromBool(b); err != nil {
return err
}
}
w.createNonPtrVal().Set(matchSettable(typ, w.val))
} else {
if isAny {
// Any means the Go type must receive a datamodel.Node
w.createNonPtrVal().Set(reflect.ValueOf(basicnode.NewBool(b)))
} else {
w.createNonPtrVal().SetBool(b)
}
}
if w.finish != nil {
if err := w.finish(); err != nil {
return err
}
}
return nil
}
func (w *_assembler) assignUInt(uin datamodel.UintNode) error {
if err := compatibleKind(w.schemaType, datamodel.Kind_Int); err != nil {
return err
}
_, isAny := w.schemaType.(*schema.TypeAny)
// TODO: customConverter for uint??
if isAny {
// Any means the Go type must receive a datamodel.Node
w.createNonPtrVal().Set(reflect.ValueOf(uin))
} else {
i, err := uin.AsUint()
if err != nil {
return err
}
if kindUint[w.val.Kind()] {
w.createNonPtrVal().SetUint(i)
} else {
// TODO: check for overflow
w.createNonPtrVal().SetInt(int64(i))
}
}
if w.finish != nil {
if err := w.finish(); err != nil {
return err
}
}
return nil
}
func (w *_assembler) AssignInt(i int64) error {
if err := compatibleKind(w.schemaType, datamodel.Kind_Int); err != nil {
return err
}
// TODO: check for overflow
customConverter := w.cfg.converterFor(w.val)
_, isAny := w.schemaType.(*schema.TypeAny)
if customConverter != nil {
var typ interface{}
var err error
if isAny {
// field is an Any, so the converter will be an Any converter that wants
// a datamodel.Node to convert to whatever the underlying Go type is
if typ, err = customConverter.customFromAny(basicnode.NewInt(i)); err != nil {
return err
}
} else {
// field is an Int, but the user has registered a converter from an int to
// whatever the underlying Go type is
if typ, err = customConverter.customFromInt(i); err != nil {
return err
}
}
w.createNonPtrVal().Set(matchSettable(typ, w.val))
} else {
if isAny {
// Any means the Go type must receive a datamodel.Node
w.createNonPtrVal().Set(reflect.ValueOf(basicnode.NewInt(i)))
} else if kindUint[w.val.Kind()] {
if i < 0 {
// TODO: write a test
return fmt.Errorf("bindnode: cannot assign negative integer to %s", w.val.Type())
}
w.createNonPtrVal().SetUint(uint64(i))
} else {
w.createNonPtrVal().SetInt(i)
}
}
if w.finish != nil {
if err := w.finish(); err != nil {
return err
}
}
return nil
}
func (w *_assembler) AssignFloat(f float64) error {
if err := compatibleKind(w.schemaType, datamodel.Kind_Float); err != nil {
return err
}
customConverter := w.cfg.converterFor(w.val)
_, isAny := w.schemaType.(*schema.TypeAny)
if customConverter != nil {
var typ interface{}
var err error
if isAny {
// field is an Any, so the converter will be an Any converter that wants
// a datamodel.Node to convert to whatever the underlying Go type is
if typ, err = customConverter.customFromAny(basicnode.NewFloat(f)); err != nil {
return err
}
} else {
// field is a Float, but the user has registered a converter from a float
// to whatever the underlying Go type is
if typ, err = customConverter.customFromFloat(f); err != nil {
return err
}
}
w.createNonPtrVal().Set(matchSettable(typ, w.val))
} else {
if isAny {
// Any means the Go type must receive a datamodel.Node
w.createNonPtrVal().Set(reflect.ValueOf(basicnode.NewFloat(f)))
} else {
w.createNonPtrVal().SetFloat(f)
}
}
if w.finish != nil {
if err := w.finish(); err != nil {
return err
}
}
return nil
}
func (w *_assembler) AssignString(s string) error {
if err := compatibleKind(w.schemaType, datamodel.Kind_String); err != nil {
return err
}
customConverter := w.cfg.converterFor(w.val)
_, isAny := w.schemaType.(*schema.TypeAny)
if customConverter != nil {
var typ interface{}
var err error
if isAny {
// field is an Any, so the converter will be an Any converter that wants
// a datamodel.Node to convert to whatever the underlying Go type is
if typ, err = customConverter.customFromAny(basicnode.NewString(s)); err != nil {
return err
}
} else {
// field is a String, but the user has registered a converter from a
// string to whatever the underlying Go type is
if typ, err = customConverter.customFromString(s); err != nil {
return err
}
}
w.createNonPtrVal().Set(matchSettable(typ, w.val))
} else {
if isAny {
// Any means the Go type must receive a datamodel.Node
w.createNonPtrVal().Set(reflect.ValueOf(basicnode.NewString(s)))
} else {
w.createNonPtrVal().SetString(s)
}
}
if w.finish != nil {
if err := w.finish(); err != nil {
return err
}
}
return nil
}
func (w *_assembler) AssignBytes(p []byte) error {