-
Notifications
You must be signed in to change notification settings - Fork 320
/
node.go
1824 lines (1659 loc) · 51 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
/*
* Copyright 2021 ByteDance Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ast
import (
`encoding/json`
`fmt`
`strconv`
`unsafe`
`github.com/bytedance/sonic/internal/native/types`
`github.com/bytedance/sonic/internal/rt`
)
const (
_V_NONE types.ValueType = 0
_V_NODE_BASE types.ValueType = 1 << 5
_V_LAZY types.ValueType = 1 << 7
_V_RAW types.ValueType = 1 << 8
_V_NUMBER = _V_NODE_BASE + 1
_V_ANY = _V_NODE_BASE + 2
_V_ARRAY_LAZY = _V_LAZY | types.V_ARRAY
_V_OBJECT_LAZY = _V_LAZY | types.V_OBJECT
_MASK_LAZY = _V_LAZY - 1
_MASK_RAW = _V_RAW - 1
)
const (
V_NONE = 0
V_ERROR = 1
V_NULL = int(types.V_NULL)
V_TRUE = int(types.V_TRUE)
V_FALSE = int(types.V_FALSE)
V_ARRAY = int(types.V_ARRAY)
V_OBJECT = int(types.V_OBJECT)
V_STRING = int(types.V_STRING)
V_NUMBER = int(_V_NUMBER)
V_ANY = int(_V_ANY)
)
type Node struct {
t types.ValueType
l uint
p unsafe.Pointer
}
// UnmarshalJSON is just an adapter to json.Unmarshaler.
// If you want better performance, use Searcher.GetByPath() directly
func (self *Node) UnmarshalJSON(data []byte) (err error) {
*self = NewRaw(string(data))
return self.Check()
}
/** Node Type Accessor **/
// Type returns json type represented by the node
// It will be one of belows:
// V_NONE = 0 (empty node, key not exists)
// V_ERROR = 1 (error node)
// V_NULL = 2 (json value `null`, key exists)
// V_TRUE = 3 (json value `true`)
// V_FALSE = 4 (json value `false`)
// V_ARRAY = 5 (json value array)
// V_OBJECT = 6 (json value object)
// V_STRING = 7 (json value string)
// V_NUMBER = 33 (json value number )
// V_ANY = 34 (golang interface{})
func (self Node) Type() int {
return int(self.t & _MASK_LAZY & _MASK_RAW)
}
func (self Node) itype() types.ValueType {
return self.t & _MASK_LAZY & _MASK_RAW
}
// Exists returns false only if the self is nil or empty node V_NONE
func (self *Node) Exists() bool {
return self.Valid() && self.t != _V_NONE
}
// Valid reports if self is NOT V_ERROR or nil
func (self *Node) Valid() bool {
if self == nil {
return false
}
return self.t != V_ERROR
}
// Check checks if the node itself is valid, and return:
// - ErrNotExist If the node is nil
// - Its underlying error If the node is V_ERROR
func (self *Node) Check() error {
if self == nil {
return ErrNotExist
} else if self.t != V_ERROR {
return nil
} else {
return self
}
}
// IsRaw returns true if node's underlying value is raw json
func (self Node) IsRaw() bool {
return self.t&_V_RAW != 0
}
func (self *Node) isLazy() bool {
return self != nil && self.t&_V_LAZY != 0
}
func (self *Node) isAny() bool {
return self != nil && self.t == _V_ANY
}
/** Simple Value Methods **/
// Raw returns json representation of the node,
func (self *Node) Raw() (string, error) {
if self == nil {
return "", ErrNotExist
}
if !self.IsRaw() {
buf, err := self.MarshalJSON()
return rt.Mem2Str(buf), err
}
return self.toString(), nil
}
func (self *Node) checkRaw() error {
if err := self.Check(); err != nil {
return err
}
if self.IsRaw() {
self.parseRaw(false)
}
return self.Check()
}
// Bool returns bool value represented by this node,
// including types.V_TRUE|V_FALSE|V_NUMBER|V_STRING|V_ANY|V_NULL,
// V_NONE will return error
func (self *Node) Bool() (bool, error) {
if err := self.checkRaw(); err != nil {
return false, err
}
switch self.t {
case types.V_TRUE : return true , nil
case types.V_FALSE : return false, nil
case types.V_NULL : return false, nil
case _V_NUMBER :
if i, err := self.toInt64(); err == nil {
return i != 0, nil
} else if f, err := self.toFloat64(); err == nil {
return f != 0, nil
} else {
return false, err
}
case types.V_STRING: return strconv.ParseBool(self.toString())
case _V_ANY :
any := self.packAny()
switch v := any.(type) {
case bool : return v, nil
case int : return v != 0, nil
case int8 : return v != 0, nil
case int16 : return v != 0, nil
case int32 : return v != 0, nil
case int64 : return v != 0, nil
case uint : return v != 0, nil
case uint8 : return v != 0, nil
case uint16 : return v != 0, nil
case uint32 : return v != 0, nil
case uint64 : return v != 0, nil
case float32: return v != 0, nil
case float64: return v != 0, nil
case string : return strconv.ParseBool(v)
case json.Number:
if i, err := v.Int64(); err == nil {
return i != 0, nil
} else if f, err := v.Float64(); err == nil {
return f != 0, nil
} else {
return false, err
}
default: return false, ErrUnsupportType
}
default : return false, ErrUnsupportType
}
}
// Int64 casts the node to int64 value,
// including V_NUMBER|V_TRUE|V_FALSE|V_ANY|V_STRING
// V_NONE it will return error
func (self *Node) Int64() (int64, error) {
if err := self.checkRaw(); err != nil {
return 0, err
}
switch self.t {
case _V_NUMBER, types.V_STRING :
if i, err := self.toInt64(); err == nil {
return i, nil
} else if f, err := self.toFloat64(); err == nil {
return int64(f), nil
} else {
return 0, err
}
case types.V_TRUE : return 1, nil
case types.V_FALSE : return 0, nil
case types.V_NULL : return 0, nil
case _V_ANY :
any := self.packAny()
switch v := any.(type) {
case bool : if v { return 1, nil } else { return 0, nil }
case int : return int64(v), nil
case int8 : return int64(v), nil
case int16 : return int64(v), nil
case int32 : return int64(v), nil
case int64 : return int64(v), nil
case uint : return int64(v), nil
case uint8 : return int64(v), nil
case uint16 : return int64(v), nil
case uint32 : return int64(v), nil
case uint64 : return int64(v), nil
case float32: return int64(v), nil
case float64: return int64(v), nil
case string :
if i, err := strconv.ParseInt(v, 10, 64); err == nil {
return i, nil
} else if f, err := strconv.ParseFloat(v, 64); err == nil {
return int64(f), nil
} else {
return 0, err
}
case json.Number:
if i, err := v.Int64(); err == nil {
return i, nil
} else if f, err := v.Float64(); err == nil {
return int64(f), nil
} else {
return 0, err
}
default: return 0, ErrUnsupportType
}
default : return 0, ErrUnsupportType
}
}
// StrictInt64 exports underlying int64 value, including V_NUMBER, V_ANY
func (self *Node) StrictInt64() (int64, error) {
if err := self.checkRaw(); err != nil {
return 0, err
}
switch self.t {
case _V_NUMBER : return self.toInt64()
case _V_ANY :
any := self.packAny()
switch v := any.(type) {
case int : return int64(v), nil
case int8 : return int64(v), nil
case int16 : return int64(v), nil
case int32 : return int64(v), nil
case int64 : return int64(v), nil
case uint : return int64(v), nil
case uint8 : return int64(v), nil
case uint16: return int64(v), nil
case uint32: return int64(v), nil
case uint64: return int64(v), nil
case json.Number:
if i, err := v.Int64(); err == nil {
return i, nil
} else {
return 0, err
}
default: return 0, ErrUnsupportType
}
default : return 0, ErrUnsupportType
}
}
func castNumber(v bool) json.Number {
if v {
return json.Number("1")
} else {
return json.Number("0")
}
}
// Number casts node to float64,
// including V_NUMBER|V_TRUE|V_FALSE|V_ANY|V_STRING|V_NULL,
// V_NONE it will return error
func (self *Node) Number() (json.Number, error) {
if err := self.checkRaw(); err != nil {
return json.Number(""), err
}
switch self.t {
case _V_NUMBER : return self.toNumber(), nil
case types.V_STRING :
if _, err := self.toInt64(); err == nil {
return self.toNumber(), nil
} else if _, err := self.toFloat64(); err == nil {
return self.toNumber(), nil
} else {
return json.Number(""), err
}
case types.V_TRUE : return json.Number("1"), nil
case types.V_FALSE : return json.Number("0"), nil
case types.V_NULL : return json.Number("0"), nil
case _V_ANY :
any := self.packAny()
switch v := any.(type) {
case bool : return castNumber(v), nil
case int : return castNumber(v != 0), nil
case int8 : return castNumber(v != 0), nil
case int16 : return castNumber(v != 0), nil
case int32 : return castNumber(v != 0), nil
case int64 : return castNumber(v != 0), nil
case uint : return castNumber(v != 0), nil
case uint8 : return castNumber(v != 0), nil
case uint16 : return castNumber(v != 0), nil
case uint32 : return castNumber(v != 0), nil
case uint64 : return castNumber(v != 0), nil
case float32: return castNumber(v != 0), nil
case float64: return castNumber(v != 0), nil
case string :
if _, err := strconv.ParseFloat(v, 64); err == nil {
return json.Number(v), nil
} else {
return json.Number(""), err
}
case json.Number: return v, nil
default: return json.Number(""), ErrUnsupportType
}
default : return json.Number(""), ErrUnsupportType
}
}
// Number exports underlying float64 value, including V_NUMBER, V_ANY of json.Number
func (self *Node) StrictNumber() (json.Number, error) {
if err := self.checkRaw(); err != nil {
return json.Number(""), err
}
switch self.t {
case _V_NUMBER : return self.toNumber() , nil
case _V_ANY :
if v, ok := self.packAny().(json.Number); ok {
return v, nil
} else {
return json.Number(""), ErrUnsupportType
}
default : return json.Number(""), ErrUnsupportType
}
}
// String cast node to string,
// including V_NUMBER|V_TRUE|V_FALSE|V_ANY|V_STRING|V_NULL,
// V_NONE it will return error
func (self *Node) String() (string, error) {
if err := self.checkRaw(); err != nil {
return "", err
}
switch self.t {
case types.V_NULL : return "" , nil
case types.V_TRUE : return "true" , nil
case types.V_FALSE : return "false", nil
case types.V_STRING, _V_NUMBER : return self.toString(), nil
case _V_ANY :
any := self.packAny()
switch v := any.(type) {
case bool : return strconv.FormatBool(v), nil
case int : return strconv.Itoa(v), nil
case int8 : return strconv.Itoa(int(v)), nil
case int16 : return strconv.Itoa(int(v)), nil
case int32 : return strconv.Itoa(int(v)), nil
case int64 : return strconv.Itoa(int(v)), nil
case uint : return strconv.Itoa(int(v)), nil
case uint8 : return strconv.Itoa(int(v)), nil
case uint16 : return strconv.Itoa(int(v)), nil
case uint32 : return strconv.Itoa(int(v)), nil
case uint64 : return strconv.Itoa(int(v)), nil
case float32: return strconv.FormatFloat(float64(v), 'g', -1, 64), nil
case float64: return strconv.FormatFloat(float64(v), 'g', -1, 64), nil
case string : return v, nil
case json.Number: return v.String(), nil
default: return "", ErrUnsupportType
}
default : return "" , ErrUnsupportType
}
}
// StrictString returns string value (unescaped), includeing V_STRING, V_ANY of string.
// In other cases, it will return empty string.
func (self *Node) StrictString() (string, error) {
if err := self.checkRaw(); err != nil {
return "", err
}
switch self.t {
case types.V_STRING : return self.toString(), nil
case _V_ANY :
if v, ok := self.packAny().(string); ok {
return v, nil
} else {
return "", ErrUnsupportType
}
default : return "", ErrUnsupportType
}
}
// Float64 cast node to float64,
// including V_NUMBER|V_TRUE|V_FALSE|V_ANY|V_STRING|V_NULL,
// V_NONE it will return error
func (self *Node) Float64() (float64, error) {
if err := self.checkRaw(); err != nil {
return 0.0, err
}
switch self.t {
case _V_NUMBER, types.V_STRING : return self.toFloat64()
case types.V_TRUE : return 1.0, nil
case types.V_FALSE : return 0.0, nil
case types.V_NULL : return 0.0, nil
case _V_ANY :
any := self.packAny()
switch v := any.(type) {
case bool :
if v {
return 1.0, nil
} else {
return 0.0, nil
}
case int : return float64(v), nil
case int8 : return float64(v), nil
case int16 : return float64(v), nil
case int32 : return float64(v), nil
case int64 : return float64(v), nil
case uint : return float64(v), nil
case uint8 : return float64(v), nil
case uint16 : return float64(v), nil
case uint32 : return float64(v), nil
case uint64 : return float64(v), nil
case float32: return float64(v), nil
case float64: return float64(v), nil
case string :
if f, err := strconv.ParseFloat(v, 64); err == nil {
return float64(f), nil
} else {
return 0, err
}
case json.Number:
if f, err := v.Float64(); err == nil {
return float64(f), nil
} else {
return 0, err
}
default : return 0, ErrUnsupportType
}
default : return 0.0, ErrUnsupportType
}
}
// Float64 exports underlying float64 value, includeing V_NUMBER, V_ANY
func (self *Node) StrictFloat64() (float64, error) {
if err := self.checkRaw(); err != nil {
return 0.0, err
}
switch self.t {
case _V_NUMBER : return self.toFloat64()
case _V_ANY :
any := self.packAny()
switch v := any.(type) {
case float32 : return float64(v), nil
case float64 : return float64(v), nil
default : return 0, ErrUnsupportType
}
default : return 0.0, ErrUnsupportType
}
}
/** Sequencial Value Methods **/
// Len returns children count of a array|object|string node
// WARN: For partially loaded node, it also works but only counts the parsed children
func (self *Node) Len() (int, error) {
if err := self.checkRaw(); err != nil {
return 0, err
}
if self.t == types.V_ARRAY || self.t == types.V_OBJECT || self.t == _V_ARRAY_LAZY || self.t == _V_OBJECT_LAZY || self.t == types.V_STRING {
return int(self.l), nil
} else if self.t == _V_NONE || self.t == types.V_NULL {
return 0, nil
} else {
return 0, ErrUnsupportType
}
}
func (self Node) len() int {
return int(self.l)
}
// Cap returns malloc capacity of a array|object node for children
func (self *Node) Cap() (int, error) {
if err := self.checkRaw(); err != nil {
return 0, err
}
switch self.t {
case types.V_ARRAY: return (*linkedNodes)(self.p).Cap(), nil
case types.V_OBJECT: return (*linkedPairs)(self.p).Cap(), nil
case _V_ARRAY_LAZY: return (*parseArrayStack)(self.p).v.Cap(), nil
case _V_OBJECT_LAZY: return (*parseObjectStack)(self.p).v.Cap(), nil
case _V_NONE, types.V_NULL: return 0, nil
default: return 0, ErrUnsupportType
}
}
// Set sets the node of given key under self, and reports if the key has existed.
//
// If self is V_NONE or V_NULL, it becomes V_OBJECT and sets the node at the key.
func (self *Node) Set(key string, node Node) (bool, error) {
if err := self.Check(); err != nil {
return false, err
}
if err := node.Check(); err != nil {
return false, err
}
if self.t == _V_NONE || self.t == types.V_NULL {
*self = NewObject([]Pair{{key, node}})
return false, nil
} else if self.itype() != types.V_OBJECT {
return false, ErrUnsupportType
}
p := self.Get(key)
if !p.Exists() {
// self must be fully-loaded here
if self.len() == 0 {
*self = newObject(new(linkedPairs))
}
s := (*linkedPairs)(self.p)
s.Push(Pair{key, node})
self.l++
return false, nil
} else if err := p.Check(); err != nil {
return false, err
}
*p = node
return true, nil
}
// SetAny wraps val with V_ANY node, and Set() the node.
func (self *Node) SetAny(key string, val interface{}) (bool, error) {
return self.Set(key, NewAny(val))
}
// Unset REMOVE (soft) the node of given key under object parent, and reports if the key has existed.
func (self *Node) Unset(key string) (bool, error) {
if err := self.should(types.V_OBJECT, "an object"); err != nil {
return false, err
}
// NOTICE: must get acurate length before deduct
if err := self.skipAllKey(); err != nil {
return false, err
}
p, i := self.skipKey(key)
if !p.Exists() {
return false, nil
} else if err := p.Check(); err != nil {
return false, err
}
self.removePairAt(i)
return true, nil
}
// SetByIndex sets the node of given index, and reports if the key has existed.
//
// The index must be within self's children.
func (self *Node) SetByIndex(index int, node Node) (bool, error) {
if err := self.Check(); err != nil {
return false, err
}
if err := node.Check(); err != nil {
return false, err
}
if index == 0 && (self.t == _V_NONE || self.t == types.V_NULL) {
*self = NewArray([]Node{node})
return false, nil
}
p := self.Index(index)
if !p.Exists() {
return false, ErrNotExist
} else if err := p.Check(); err != nil {
return false, err
}
*p = node
return true, nil
}
// SetAny wraps val with V_ANY node, and SetByIndex() the node.
func (self *Node) SetAnyByIndex(index int, val interface{}) (bool, error) {
return self.SetByIndex(index, NewAny(val))
}
// UnsetByIndex REOMVE (softly) the node of given index.
//
// WARN: this will change address of elements, which is a dangerous action.
// Use Unset() for object or Pop() for array instead.
func (self *Node) UnsetByIndex(index int) (bool, error) {
if err := self.checkRaw(); err != nil {
return false, err
}
var p *Node
it := self.itype()
if it == types.V_ARRAY {
if err := self.skipAllIndex(); err != nil {
return false, err
}
p = self.nodeAt(index)
} else if it == types.V_OBJECT {
if err := self.skipAllKey(); err != nil {
return false, err
}
pr := self.pairAt(index)
if pr == nil {
return false, ErrNotExist
}
p = &pr.Value
} else {
return false, ErrUnsupportType
}
if !p.Exists() {
return false, ErrNotExist
}
// last elem
if index == self.len() - 1 {
return true, self.Pop()
}
// not last elem, self.len() change but linked-chunk not change
if it == types.V_ARRAY {
self.removeNode(index)
}else if it == types.V_OBJECT {
self.removePair(index)
}
return true, nil
}
// Add appends the given node under self.
//
// If self is V_NONE or V_NULL, it becomes V_ARRAY and sets the node at index 0.
func (self *Node) Add(node Node) error {
if err := self.Check(); err != nil {
return err
}
if self != nil && (self.t == _V_NONE || self.t == types.V_NULL) {
*self = NewArray([]Node{node})
return nil
}
if err := self.should(types.V_ARRAY, "an array"); err != nil {
return err
}
s, err := self.unsafeArray()
if err != nil {
return err
}
// Notice: array won't have unset node in tail
s.Push(node)
self.l++
return nil
}
// Pop remove the last child of the V_Array or V_Object node.
func (self *Node) Pop() error {
if err := self.checkRaw(); err != nil {
return err
}
if it := self.itype(); it == types.V_ARRAY {
s, err := self.unsafeArray()
if err != nil {
return err
}
// remove tail unset nodes
for i := s.Len()-1; i >= 0; i-- {
if s.At(i).Exists() {
s.Pop()
self.l--
break
}
s.Pop()
}
} else if it == types.V_OBJECT {
s, err := self.unsafeMap()
if err != nil {
return err
}
// remove tail unset nodes
for i := s.Len()-1; i >= 0; i-- {
if p := s.At(i); p != nil && p.Value.Exists() {
s.Pop()
self.l--
break
}
s.Pop()
}
} else {
return ErrUnsupportType
}
return nil
}
// Move moves the child at src index to dst index,
// meanwhile slides sliblings from src+1 to dst.
//
// WARN: this will change address of elements, which is a dangerous action.
func (self *Node) Move(dst, src int) error {
if err := self.should(types.V_ARRAY, "an array"); err != nil {
return err
}
s, err := self.unsafeArray()
if err != nil {
return err
}
// check if any unset node exists
if l := s.Len(); self.len() != l {
di, si := dst, src
// find real pos of src and dst
for i := 0; i < l; i++ {
if s.At(i).Exists() {
di--
si--
}
if di == -1 {
dst = i
di--
}
if si == -1 {
src = i
si--
}
if di == -2 && si == -2 {
break
}
}
}
s.MoveOne(src, dst)
return nil
}
// SetAny wraps val with V_ANY node, and Add() the node.
func (self *Node) AddAny(val interface{}) error {
return self.Add(NewAny(val))
}
// GetByPath load given path on demands,
// which only ensure nodes before this path got parsed.
//
// Note, the api expects the json is well-formed at least,
// otherwise it may return unexpected result.
func (self *Node) GetByPath(path ...interface{}) *Node {
if !self.Valid() {
return self
}
var s = self
for _, p := range path {
switch p := p.(type) {
case int:
s = s.Index(p)
if !s.Valid() {
return s
}
case string:
s = s.Get(p)
if !s.Valid() {
return s
}
default:
panic("path must be either int or string")
}
}
return s
}
// Get loads given key of an object node on demands
func (self *Node) Get(key string) *Node {
if err := self.should(types.V_OBJECT, "an object"); err != nil {
return unwrapError(err)
}
n, _ := self.skipKey(key)
return n
}
// Index indexies node at given idx,
// node type CAN be either V_OBJECT or V_ARRAY
func (self *Node) Index(idx int) *Node {
if err := self.checkRaw(); err != nil {
return unwrapError(err)
}
it := self.itype()
if it == types.V_ARRAY {
return self.skipIndex(idx)
}else if it == types.V_OBJECT {
pr := self.skipIndexPair(idx)
if pr == nil {
return newError(_ERR_NOT_FOUND, "value not exists")
}
return &pr.Value
} else {
return newError(_ERR_UNSUPPORT_TYPE, fmt.Sprintf("unsupported type: %v", self.itype()))
}
}
// IndexPair indexies pair at given idx,
// node type MUST be either V_OBJECT
func (self *Node) IndexPair(idx int) *Pair {
if err := self.should(types.V_OBJECT, "an object"); err != nil {
return nil
}
return self.skipIndexPair(idx)
}
func (self *Node) indexOrGet(idx int, key string) (*Node, int) {
if err := self.should(types.V_OBJECT, "an object"); err != nil {
return unwrapError(err), idx
}
pr := self.skipIndexPair(idx)
if pr != nil && pr.Key == key {
return &pr.Value, idx
}
return self.skipKey(key)
}
// IndexOrGet firstly use idx to index a value and check if its key matches
// If not, then use the key to search value
func (self *Node) IndexOrGet(idx int, key string) *Node {
node, _ := self.indexOrGet(idx, key)
return node
}
// IndexOrGetWithIdx attempts to retrieve a node by index and key, returning the node and its correct index.
// If the key does not match at the given index, it searches by key and returns the node with its updated index.
func (self *Node) IndexOrGetWithIdx(idx int, key string) (*Node, int) {
return self.indexOrGet(idx, key)
}
/** Generic Value Converters **/
// Map loads all keys of an object node
func (self *Node) Map() (map[string]interface{}, error) {
if self.isAny() {
any := self.packAny()
if v, ok := any.(map[string]interface{}); ok {
return v, nil
} else {
return nil, ErrUnsupportType
}
}
if err := self.should(types.V_OBJECT, "an object"); err != nil {
return nil, err
}
if err := self.loadAllKey(); err != nil {
return nil, err
}
return self.toGenericObject()
}
// MapUseNumber loads all keys of an object node, with numeric nodes casted to json.Number
func (self *Node) MapUseNumber() (map[string]interface{}, error) {
if self.isAny() {
any := self.packAny()
if v, ok := any.(map[string]interface{}); ok {
return v, nil
} else {
return nil, ErrUnsupportType
}
}
if err := self.should(types.V_OBJECT, "an object"); err != nil {
return nil, err
}
if err := self.loadAllKey(); err != nil {
return nil, err
}
return self.toGenericObjectUseNumber()
}
// MapUseNode scans both parsed and non-parsed chidren nodes,
// and map them by their keys
func (self *Node) MapUseNode() (map[string]Node, error) {
if self.isAny() {
any := self.packAny()
if v, ok := any.(map[string]Node); ok {
return v, nil
} else {
return nil, ErrUnsupportType
}
}
if err := self.should(types.V_OBJECT, "an object"); err != nil {
return nil, err
}
if err := self.skipAllKey(); err != nil {
return nil, err
}
return self.toGenericObjectUseNode()
}
// MapUnsafe exports the underlying pointer to its children map
// WARN: don't use it unless you know what you are doing
//
// Deprecated: this API now returns copied nodes instead of directly reference,
// func (self *Node) UnsafeMap() ([]Pair, error) {
// if err := self.should(types.V_OBJECT, "an object"); err != nil {
// return nil, err
// }
// if err := self.skipAllKey(); err != nil {
// return nil, err
// }
// return self.toGenericObjectUsePair()
// }
//go:nocheckptr
func (self *Node) unsafeMap() (*linkedPairs, error) {
if err := self.skipAllKey(); err != nil {
return nil, err
}
if self.p == nil {
*self = newObject(new(linkedPairs))
}
return (*linkedPairs)(self.p), nil
}
// SortKeys sorts children of a V_OBJECT node in ascending key-order.
// If recurse is true, it recursively sorts children's children as long as a V_OBJECT node is found.
func (self *Node) SortKeys(recurse bool) error {
// check raw node first
if err := self.checkRaw(); err != nil {
return err
}
if self.itype() == types.V_OBJECT {
return self.sortKeys(recurse)
} else if self.itype() == types.V_ARRAY {
var err error
err2 := self.ForEach(func(path Sequence, node *Node) bool {
it := node.itype()
if it == types.V_ARRAY || it == types.V_OBJECT {
err = node.SortKeys(recurse)
if err != nil {
return false
}
}
return true
})
if err != nil {
return err
}
return err2
} else {
return nil
}
}
func (self *Node) sortKeys(recurse bool) (err error) {
// check raw node first
if err := self.checkRaw(); err != nil {
return err
}
ps, err := self.unsafeMap()