-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathglint_test.go
More file actions
5204 lines (4569 loc) · 149 KB
/
glint_test.go
File metadata and controls
5204 lines (4569 loc) · 149 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
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 glint
import (
"bytes"
"encoding/binary"
"encoding/json"
"flag"
"fmt"
"math"
"math/rand"
"net/http"
"reflect"
"strings"
"testing"
"time"
)
// Child is used as a nested struct.
type Child struct {
A int `glint:"a"`
B string `glint:"b"`
}
// Comprehensive includes a field for every supported type and combination.
type Comprehensive struct {
// Primitives
Bool bool `glint:"bool"`
Int int `glint:"int"`
Int8 int8 `glint:"int8"`
Int16 int16 `glint:"int16"`
Int32 int32 `glint:"int32"`
Int64 int64 `glint:"int64"`
Uint uint `glint:"uint"`
Uint8 uint8 `glint:"uint8"`
Uint16 uint16 `glint:"uint16"`
Uint32 uint32 `glint:"uint32"`
Uint64 uint64 `glint:"uint64"`
Float32 float32 `glint:"float32"`
Float64 float64 `glint:"float64"`
String string `glint:"string"`
Bytes []byte `glint:"bytes"`
Time time.Time `glint:"time"`
// Nested struct
Child Child `glint:"item1"`
// Pointer fields
PtrInt *int `glint:"ptr_int"`
PtrString *string `glint:"ptr_string"`
PtrTime *time.Time `glint:"ptr_time"`
PtrChild *Child `glint:"ptr_child"`
// // Slices of primitives
BoolSlice []bool `glint:"[]bool"`
IntSlice []int `glint:"[]int"`
Int8Slice []int8 `glint:"[]int8"`
Int16Slice []int16 `glint:"[]int16"`
Int32Slice []int32 `glint:"[]int32"`
Int64Slice []int64 `glint:"[]int64"`
UintSlice []uint `glint:"[]uint"`
Uint8Slice []uint8 `glint:"[]uint8"`
Uint16Slice []uint16 `glint:"[]uint16"`
Uint32Slice []uint32 `glint:"[]uint32"`
Uint64Slice []uint64 `glint:"[]uint64"`
Float32Slice []float32 `glint:"[]float32"`
Float64Slice []float64 `glint:"[]float64"`
StringSlice []string `glint:"[]string"`
BytesSlice [][]byte `glint:"[]bytes"`
TimeSlice []time.Time `glint:"[]time"`
// Slices of nested structs
ChildSlice []Child `glint:"[]child"`
// Maps
MapStringInt map[string]int `glint:"map_str_int"`
MapStringString map[string]string `glint:"map_str_str"`
// Zigzagy fields
ZigzagInt int `glint:"zzint"`
ZigzagIntSlice []int `glint:"[]zzint"`
SimpleEnd bool `glint:"simple_end"`
}
// PartialComprehensive omits some fields so that skip code paths are exercised.
type PartialComprehensive struct {
// Only a subset of the primitives
Bool bool `glint:"bool"`
Int int `glint:"int"`
String string `glint:"string"`
Time time.Time `glint:"time"`
Child Child `glint:"item1"`
PtrInt *int `glint:"ptr_int"`
BoolSlice []bool `glint:"[]bool"`
Int8Slice []int8 `glint:"[]int8"`
SimpleEnd bool `glint:"simple_end"`
}
type TestTime struct {
PtrTime *time.Time `glint:"time"`
}
// TestTypeSupport consolidates all type-related tests into a comprehensive table-driven test
func TestBasicTypesEncodeDecodeRoundtrip(t *testing.T) {
// Helper function to create pointer values
intPtr := func(v int) *int { return &v }
stringPtr := func(v string) *string { return &v }
childPtr := func(v Child) *Child { return &v }
tests := []struct {
name string
testFunc func(t *testing.T)
description string
}{
{
name: "PtrTime",
description: "Test pointer to time.Time encoding/decoding",
testFunc: func(t *testing.T) {
expected := time.Date(2021, time.December, 31, 23, 59, 59, 0, time.UTC)
orig := TestTime{
PtrTime: &expected,
}
enc := newEncoder(TestTime{})
buf := NewBufferFromPool()
enc.Marshal(&orig, buf)
var decoded TestTime
dec := newDecoder(TestTime{})
if err := dec.Unmarshal(buf.Bytes, &decoded); err != nil {
t.Fatalf("Unmarshal error: %v", err)
}
if decoded.PtrTime == nil {
t.Fatalf("Decoded PtrTime is nil")
}
if !decoded.PtrTime.Equal(expected) {
t.Errorf("Time mismatch: expected %v, got %v", expected, decoded.PtrTime)
}
},
},
{
name: "Comprehensive",
description: "Test all supported types comprehensively",
testFunc: func(t *testing.T) {
pTime := time.Date(2021, time.December, 31, 23, 59, 59, 0, time.UTC)
orig := Comprehensive{
// Primitives
Bool: true,
Int: -123,
Int8: -12,
Int16: -1234,
Int32: -123456,
Int64: -1234567890,
Uint: 123,
Uint8: 12,
Uint16: 1234,
Uint32: 123456,
Uint64: 1234567890,
Float32: 3.14,
Float64: 6.28,
String: "test data comprehensive",
Bytes: []byte{1, 2, 3, 4},
Time: time.Date(2020, time.May, 10, 12, 34, 56, 789, time.UTC),
Child: Child{A: 200, B: "nested complete"},
// Pointer fields
PtrInt: intPtr(100),
PtrString: stringPtr("reference text"),
PtrTime: &pTime,
PtrChild: childPtr(Child{A: 10, B: "nested reference"}),
// Slices of primitives
BoolSlice: []bool{true, false, true},
IntSlice: []int{-1, -2, -3},
Int8Slice: []int8{-1, -2, -3},
Int16Slice: []int16{-100, -200},
Int32Slice: []int32{-1000, -2000},
Int64Slice: []int64{-10000, -20000},
UintSlice: []uint{1, 2, 3},
Uint8Slice: []uint8{1, 2, 3},
Uint16Slice: []uint16{100, 200},
Uint32Slice: []uint32{1000, 2000},
Uint64Slice: []uint64{10000, 20000},
Float32Slice: []float32{3.14, 2.71},
Float64Slice: []float64{6.28, 3.1415},
StringSlice: []string{"x", "y", "z"},
BytesSlice: [][]byte{{1}, {2, 2}, {3, 3, 3}},
TimeSlice: []time.Time{
time.Date(2021, time.January, 1, 0, 0, 0, 0, time.UTC),
time.Date(2022, time.January, 1, 0, 0, 0, 0, time.UTC),
},
ChildSlice: []Child{
{A: 300, B: "nested array 1"},
{A: 400, B: "nested array 2"},
},
MapStringInt: map[string]int{"alpha": 1, "beta": 2},
MapStringString: map[string]string{"key1": "value1", "key2": "value2"},
ZigzagInt: -999,
ZigzagIntSlice: []int{-1, -2, 3, 4},
SimpleEnd: true,
}
// Test full roundtrip
enc := newEncoder(Comprehensive{})
buf := NewBufferFromPool()
enc.Marshal(&orig, buf)
var decoded Comprehensive
dec := newDecoder(Comprehensive{})
if err := dec.UnmarshalWithContext(buf.Bytes, &decoded, DecoderContext{
InstructionCache: &DecodeInstructionLookup{},
ID: 0,
}); err != nil {
t.Fatalf("Unmarshal full error: %v", err)
}
PrintStructIfDiff(t, orig, decoded)
// Test partial decoding to exercise skip paths
var partial PartialComprehensive
decPartial := newDecoder(PartialComprehensive{})
if err := decPartial.UnmarshalWithContext(buf.Bytes, &partial, DecoderContext{
InstructionCache: &DecodeInstructionLookup{},
ID: 1,
}); err != nil {
t.Fatalf("Unmarshal partial error: %v", err)
}
expectedPartial := PartialComprehensive{
Bool: orig.Bool,
Int: orig.Int,
String: orig.String,
Time: orig.Time,
Child: orig.Child,
PtrInt: orig.PtrInt,
BoolSlice: orig.BoolSlice,
Int8Slice: orig.Int8Slice,
SimpleEnd: orig.SimpleEnd,
}
PrintStructIfDiff(t, expectedPartial, partial)
},
},
{
name: "EncoderAll",
description: "Test encoding all types with expected byte output",
testFunc: func(t *testing.T) {
type child struct {
Name string `glint:"name"`
Age int `glint:"age"`
}
type All struct {
Vbool bool `glint:"bool"`
Abool []bool `glint:"[]bool"`
Vint int `glint:"int"`
Aint []int `glint:"[]int"`
Vint8 int8 `glint:"int8"`
Aint8 []int8 `glint:"[]int8"`
Vint16 int16 `glint:"int16"`
Aint16 []int16 `glint:"[]int16"`
Vint32 int32 `glint:"int32"`
Aint32 []int32 `glint:"[]int32"`
Vint64 int64 `glint:"int64"`
Aint64 []int64 `glint:"[]int64"`
Vuint uint `glint:"uint"`
Auint []uint `glint:"[]uint"`
Vuint8 uint8 `glint:"uint8"`
Auint8 []uint8 `glint:"[]uint8"`
Vuint16 uint16 `glint:"uint16"`
Auint16 []uint16 `glint:"[]uint16"`
Vuint32 uint32 `glint:"uint32"`
Auint32 []uint32 `glint:"[]uint32"`
Vuint64 uint64 `glint:"uint64"`
Auint64 []uint64 `glint:"[]uint64"`
Vfloat32 float32 `glint:"float32"`
Afloat32 []float32 `glint:"[]float32"`
Vfloat64 float64 `glint:"float64"`
Afloat64 []float64 `glint:"[]float64"`
Vstring string `glint:"string"`
Astring []string `glint:"[]string"`
Vbytes []byte `glint:"bytes"`
Abytes [][]byte `glint:"[]bytes"`
Vstruct child `glint:"Vstruct"`
Astruct []child `glint:"[]Vstruct"`
Vzzint int `glint:"zzint,zigzag"`
Azzint []int `glint:"[]zzint,zigzag"`
VtimeTime time.Time `glint:"timeTime"`
AtimeTime []time.Time `glint:"[]timeTime"`
}
encoder := newEncoder(All{})
buf := NewBufferFromPool()
value := All{
Vbool: true,
Abool: []bool{true, false, true},
Vint: -11,
Aint: []int{-11, -12, -13},
Vint8: -120,
Aint8: []int8{-120, 120, 55},
Vint16: -1000,
Aint16: []int16{-1000, -1001, -1002},
Vint32: -80_000,
Aint32: []int32{-80_000, -80_001, -80_002},
Vint64: MaxInt32 * 2,
Aint64: []int64{MaxInt32 * 2, MaxInt32*2 + 1},
Vuint: MaxUint64,
Auint: []uint{1, MaxUint64, 3},
Vuint8: 38,
Auint8: []uint8{23, 24, 25},
Vuint16: 64000,
Auint16: []uint16{64000, 64001, 64002},
Vuint32: 80_000,
Auint32: []uint32{80_000, 80_001, 80_002},
Vuint64: MaxUint,
Auint64: []uint64{MaxInt + 1, MaxInt + 2, MaxInt + 3},
Vfloat32: MaxFloat32,
Afloat32: []float32{MaxFloat32, 0.1, 0.2},
Vfloat64: MaxFloat64,
Afloat64: []float64{MaxFloat64, 0.1, 0.2},
Vstring: "sample text",
Astring: []string{"sample text", "sample text", "sample text"},
Vbytes: []byte{11, 22, 33},
Abytes: [][]byte{{1, 1}, {2, 2}, {3, 3}},
Vstruct: child{
Name: "nested item",
Age: 29,
},
Astruct: []child{
{Name: "primary nested item", Age: 25},
{Name: "secondary nested item", Age: 31},
{Name: "tertiary nested item", Age: 27},
},
Vzzint: -1,
Azzint: []int{-1, -2, 1, 2},
VtimeTime: time.Date(2023, 6, 15, 10, 30, 45, 123456789, time.UTC),
AtimeTime: []time.Time{
time.Date(2023, 6, 15, 10, 30, 45, 123456789, time.UTC),
time.Date(2022, 3, 8, 16, 20, 30, 987654321, time.UTC),
time.Date(2021, 9, 22, 8, 45, 15, 555666777, time.UTC),
},
}
encoder.Marshal(&value, buf)
expected := []byte{0, 11, 155, 80, 71, 201, 2, 1, 4, 98, 111, 111, 108, 33, 6, 91, 93, 98, 111, 111,
108, 2, 3, 105, 110, 116, 34, 5, 91, 93, 105, 110, 116, 3, 4, 105, 110, 116, 56, 35,
6, 91, 93, 105, 110, 116, 56, 4, 5, 105, 110, 116, 49, 54, 36, 7, 91, 93, 105, 110,
116, 49, 54, 5, 5, 105, 110, 116, 51, 50, 37, 7, 91, 93, 105, 110, 116, 51, 50, 6,
5, 105, 110, 116, 54, 52, 38, 7, 91, 93, 105, 110, 116, 54, 52, 7, 4, 117, 105, 110,
116, 39, 6, 91, 93, 117, 105, 110, 116, 8, 5, 117, 105, 110, 116, 56, 15, 7, 91, 93,
117, 105, 110, 116, 56, 9, 6, 117, 105, 110, 116, 49, 54, 41, 8, 91, 93, 117, 105, 110,
116, 49, 54, 10, 6, 117, 105, 110, 116, 51, 50, 42, 8, 91, 93, 117, 105, 110, 116, 51,
50, 11, 6, 117, 105, 110, 116, 54, 52, 43, 8, 91, 93, 117, 105, 110, 116, 54, 52, 12,
7, 102, 108, 111, 97, 116, 51, 50, 44, 9, 91, 93, 102, 108, 111, 97, 116, 51, 50, 13,
7, 102, 108, 111, 97, 116, 54, 52, 45, 9, 91, 93, 102, 108, 111, 97, 116, 54, 52, 14,
6, 115, 116, 114, 105, 110, 103, 46, 8, 91, 93, 115, 116, 114, 105, 110, 103, 15, 5, 98,
121, 116, 101, 115, 32, 7, 91, 93, 98, 121, 116, 101, 115, 15, 16, 7, 86, 115, 116, 114,
117, 99, 116, 11, 14, 4, 110, 97, 109, 101, 2, 3, 97, 103, 101, 48, 9, 91, 93, 86,
115, 116, 114, 117, 99, 116, 11, 14, 4, 110, 97, 109, 101, 2, 3, 97, 103, 101, 2, 5,
122, 122, 105, 110, 116, 34, 7, 91, 93, 122, 122, 105, 110, 116, 18, 8, 116, 105, 109, 101,
84, 105, 109, 101, 50, 10, 91, 93, 116, 105, 109, 101, 84, 105, 109, 101, 1, 3, 1, 0,
1, 21, 3, 21, 23, 25, 136, 3, 136, 120, 55, 207, 15, 3, 207, 15, 209, 15, 211, 15,
255, 225, 9, 3, 255, 225, 9, 129, 226, 9, 131, 226, 9, 254, 255, 255, 255, 15, 2, 254,
255, 255, 255, 15, 255, 255, 255, 255, 15, 255, 255, 255, 255, 255, 255, 255, 255, 255, 1, 3,
1, 255, 255, 255, 255, 255, 255, 255, 255, 255, 1, 3, 38, 3, 23, 24, 25, 128, 244, 3,
3, 128, 244, 3, 129, 244, 3, 130, 244, 3, 128, 241, 4, 3, 128, 241, 4, 129, 241, 4,
130, 241, 4, 255, 255, 255, 255, 255, 255, 255, 255, 255, 1, 3, 128, 128, 128, 128, 128, 128,
128, 128, 128, 1, 129, 128, 128, 128, 128, 128, 128, 128, 128, 1, 130, 128, 128, 128, 128, 128,
128, 128, 128, 1, 255, 255, 255, 251, 7, 3, 255, 255, 255, 251, 7, 205, 153, 179, 238, 3,
205, 153, 179, 242, 3, 255, 255, 255, 255, 255, 255, 255, 247, 127, 3, 255, 255, 255, 255, 255,
255, 255, 247, 127, 154, 179, 230, 204, 153, 179, 230, 220, 63, 154, 179, 230, 204, 153, 179, 230,
228, 63, 11, 115, 97, 109, 112, 108, 101, 32, 116, 101, 120, 116, 3, 11, 115, 97, 109, 112,
108, 101, 32, 116, 101, 120, 116, 11, 115, 97, 109, 112, 108, 101, 32, 116, 101, 120, 116, 11,
115, 97, 109, 112, 108, 101, 32, 116, 101, 120, 116, 3, 11, 22, 33, 3, 2, 1, 1, 2,
2, 2, 2, 3, 3, 11, 110, 101, 115, 116, 101, 100, 32, 105, 116, 101, 109, 58, 3, 19,
112, 114, 105, 109, 97, 114, 121, 32, 110, 101, 115, 116, 101, 100, 32, 105, 116, 101, 109, 50,
21, 115, 101, 99, 111, 110, 100, 97, 114, 121, 32, 110, 101, 115, 116, 101, 100, 32, 105, 116,
101, 109, 62, 20, 116, 101, 114, 116, 105, 97, 114, 121, 32, 110, 101, 115, 116, 101, 100, 32,
105, 116, 101, 109, 54, 1, 4, 1, 3, 2, 4, 15, 1, 0, 0, 0, 14, 220, 28, 223,
85, 7, 91, 205, 21, 255, 255, 3, 15, 1, 0, 0, 0, 14, 220, 28, 223, 85, 7, 91,
205, 21, 255, 255, 15, 1, 0, 0, 0, 14, 217, 185, 121, 78, 58, 222, 104, 177, 255, 255,
15, 1, 0, 0, 0, 14, 216, 220, 228, 27, 33, 30, 205, 89, 255, 255}
if !bytes.Equal(buf.Bytes, expected) {
t.Errorf("Byte output mismatch.\nGot (%d bytes): %v\nExpected (%d bytes): %v",
len(buf.Bytes), buf.Bytes, len(expected), expected)
}
},
},
{
name: "ArrayOfStructPointers",
description: "Test slice of struct pointers encoding",
testFunc: func(t *testing.T) {
type Point struct {
X uint `glint:"x"`
Y uint `glint:"y"`
}
type Points struct {
Points []*Point `glint:"points"`
}
encoder := newEncoder(Points{})
buf := NewBufferFromPool()
value := Points{
Points: []*Point{
{X: 10, Y: 55},
{X: 11, Y: 56},
},
}
encoder.Marshal(&value, buf)
// Original test only checks encoding, not decoding
// since slice of pointers isn't fully supported for decoding
if len(buf.Bytes) == 0 {
t.Error("Expected non-empty encoding")
}
},
},
{
name: "StringComparison",
description: "Test string comparison utility",
testFunc: func(t *testing.T) {
want := "This is a test string. Line 2 is different."
got := want
if got != want {
t.Errorf("Strings don't match:\n%s", stringDiff(want, got))
}
// Test with actual difference
got = "This is a test string. Line 2 has changed."
if got == want {
t.Error("Strings should be different")
}
},
},
{
name: "Map",
description: "Test various map types including nested maps",
testFunc: func(t *testing.T) {
type subtype struct {
Name string `glint:"name"`
Age int `glint:"age"`
}
type myetype struct {
MapStringInt map[string]int `glint:"ssi"`
MapStringSInt map[int][]subtype `glint:"misls"`
MapStringSrInt map[int]subtype `glint:"sri"`
MapStringSrPInt map[int]subtype `glint:"srpi"`
MapStringMapStringInt map[string]map[string]int `glint:"msmsi"`
}
type mydtype struct {
MapStringInt map[string]int `glint:"ssi"`
MapStringSInt map[int][]subtype `glint:"misls"`
MapStringSrInt map[int]subtype `glint:"sri"`
MapStringMapStringInt map[string]map[string]int `glint:"msmsi"`
}
encoder := newEncoder(myetype{})
buf := Buffer{}
v := myetype{
MapStringInt: map[string]int{"item1": 22, "item2": 22},
MapStringSInt: map[int][]subtype{
11: {
{Name: "ITEM1", Age: 24},
{Name: "ITEM2", Age: 26},
},
22: {
{Name: "ITEM3", Age: 35},
{Name: "ITEM4", Age: 42},
},
},
MapStringSrInt: map[int]subtype{11: {Name: "test data"}, 17: {Name: "test data"}},
MapStringSrPInt: map[int]subtype{11: {Name: "test data", Age: 33}},
MapStringMapStringInt: map[string]map[string]int{
"1": {"1,1": 1999, "1,2": 1999},
"2": {"2,1": 1999, "2,2": 1999},
},
}
encoder.Marshal(&v, &buf)
// Test decoding into partial struct
decoder := newDecoder(mydtype{})
mt := mydtype{}
err := decoder.Unmarshal(buf.Bytes, &mt)
if err != nil {
t.Error(err)
return
}
// Verify decoded values
if mt.MapStringInt["item1"] != 22 {
t.Error("MapStringInt item1 not 22")
}
if len(mt.MapStringSInt) != 2 {
t.Error("MapStringSInt length not 2")
}
if mt.MapStringSrInt[11].Name != "test data" {
t.Error("MapStringSrInt[11].Name not 'test data'")
}
if mt.MapStringMapStringInt["1"]["1,1"] != 1999 {
t.Error("Nested map value incorrect")
}
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
tt.testFunc(t)
})
}
// Test Reader slice methods for coverage
t.Run("ReaderSliceMethods", func(t *testing.T) {
// Test ReadUintSlice
t.Run("ReadUintSlice", func(t *testing.T) {
values := []uint{100, 200}
buf := &Buffer{}
appendVarint(buf, uint64(len(values)))
for _, v := range values {
buf.AppendUint(v)
}
reader := NewReader(buf.Bytes)
result := reader.ReadUintSlice()
if len(result) != len(values) {
t.Errorf("ReadUintSlice length mismatch: got %d, want %d", len(result), len(values))
}
})
// Test other Reader slice methods
t.Run("ReadUint16Slice", func(t *testing.T) {
values := []uint16{1000, 2000}
buf := &Buffer{}
appendVarint(buf, uint64(len(values)))
for _, v := range values {
buf.AppendUint16(v)
}
reader := NewReader(buf.Bytes)
reader.ReadUint16Slice()
})
t.Run("ReadUint32Slice", func(t *testing.T) {
values := []uint32{100000, 200000}
buf := &Buffer{}
appendVarint(buf, uint64(len(values)))
for _, v := range values {
buf.AppendUint32(v)
}
reader := NewReader(buf.Bytes)
reader.ReadUint32Slice()
})
t.Run("ReadInt8Slice", func(t *testing.T) {
values := []int8{-100, 100}
buf := &Buffer{}
appendVarint(buf, uint64(len(values)))
for _, v := range values {
buf.AppendInt8(v)
}
reader := NewReader(buf.Bytes)
reader.ReadInt8Slice()
})
t.Run("ReadInt32Slice", func(t *testing.T) {
values := []int32{-100000, 100000}
buf := &Buffer{}
appendVarint(buf, uint64(len(values)))
for _, v := range values {
buf.AppendInt32(v)
}
reader := NewReader(buf.Bytes)
reader.ReadInt32Slice()
})
t.Run("ReadInt64Slice", func(t *testing.T) {
values := []int64{-1000000000, 1000000000}
buf := &Buffer{}
appendVarint(buf, uint64(len(values)))
for _, v := range values {
buf.AppendInt64(v)
}
reader := NewReader(buf.Bytes)
reader.ReadInt64Slice()
})
t.Run("ReadFloat64Slice", func(t *testing.T) {
values := []float64{-3.14, 2.71}
buf := &Buffer{}
appendVarint(buf, uint64(len(values)))
for _, v := range values {
buf.AppendFloat64(v)
}
reader := NewReader(buf.Bytes)
reader.ReadFloat64Slice()
})
// Test Reader position methods
t.Run("ReaderPositioning", func(t *testing.T) {
data := []byte{1, 2, 3, 4, 5}
reader := NewReader(data)
mark := reader.Mark()
if mark < 0 {
t.Error("Mark should return valid position")
}
// Read some data and reset
reader.ReadUint8()
reader.ResetMark()
})
})
}
// PrintStructIfDiff compares two structs and prints a colorized diff.
// It returns true if differences exist, otherwise returns false.
func PrintStructIfDiff(t *testing.T, a, b any) bool {
jsonA := normalizeJSON(a)
jsonB := normalizeJSON(b)
// If normalized JSON is identical, return false (no differences)
if jsonA == jsonB {
return false
}
compareJSON(t, jsonA, jsonB)
return true
}
// Converts a struct to normalized JSON (ignores `null` vs `[]` for slices)
func normalizeJSON(v any) string {
var buf bytes.Buffer
encoder := json.NewEncoder(&buf)
encoder.SetIndent("", " ") // Pretty-print JSON
encoder.Encode(replaceNilSlices(v))
return buf.String()
}
// Recursively replaces nil slices with empty slices to normalize JSON output
func replaceNilSlices(v any) any {
val := reflect.ValueOf(v)
switch val.Kind() {
case reflect.Ptr:
if val.IsNil() {
return nil
}
return replaceNilSlices(val.Elem().Interface())
case reflect.Struct:
newMap := make(map[string]any)
for i := 0; i < val.NumField(); i++ {
field := val.Type().Field(i)
if field.PkgPath != "" { // Ignore unexported fields
continue
}
newMap[field.Name] = replaceNilSlices(val.Field(i).Interface())
}
return newMap
case reflect.Map:
newMap := make(map[string]any)
for _, key := range val.MapKeys() {
newMap[key.String()] = replaceNilSlices(val.MapIndex(key).Interface())
}
return newMap
case reflect.Slice:
if val.IsNil() {
return []any{} // Convert nil slices to empty slices
}
newSlice := make([]any, val.Len())
for i := 0; i < val.Len(); i++ {
newSlice[i] = replaceNilSlices(val.Index(i).Interface())
}
return newSlice
default:
return v
}
}
// Compares two JSON strings line by line and highlights differences
func compareJSON(t *testing.T, a, b string) {
aLines := strings.Split(a, "\n")
bLines := strings.Split(b, "\n")
maxLen := len(aLines)
if len(bLines) > maxLen {
maxLen = len(bLines)
}
buff := bytes.NewBuffer(nil)
fmt.Fprintln(buff, "Differences (Green = Added, Red = Removed):")
for i := 0; i < maxLen; i++ {
var aLine, bLine string
if i < len(aLines) {
aLine = aLines[i]
}
if i < len(bLines) {
bLine = bLines[i]
}
if aLine == bLine {
fmt.Fprintln(buff, " "+aLine) // No difference, print normally
} else {
if aLine != "" {
fmt.Fprintln(buff, "\033[31m- "+aLine+"\033[0m") // Red for removed
}
if bLine != "" {
fmt.Fprintln(buff, "\033[32m+ "+bLine+"\033[0m") // Green for added
}
}
}
t.Error(buff.String())
fmt.Println(buff.String())
}
func TestSliceUnmarshalWithPreAllocatedSlice(t *testing.T) {
type TestKey struct {
ItemID int `glint:"k1"`
SubItemID int `glint:"k2"`
Label string `glint:"k3"`
}
type TestRequest struct {
Keys []TestKey `json:"keys" glint:"keys"`
}
var testRequestDecoder = newDecoder(TestRequest{})
encoder := newEncoder(TestRequest{})
testItems := []TestKey{
{
ItemID: 1,
SubItemID: 1,
Label: "A",
},
{
ItemID: 2,
SubItemID: 2,
Label: "B",
},
{
ItemID: 3,
SubItemID: 3,
Label: "C",
},
}
pb := NewBufferFromPool()
encoder.Marshal(&TestRequest{
Keys: testItems,
}, pb)
request := TestRequest{
Keys: make([]TestKey, 3),
}
request.Keys = request.Keys[:0]
if err := testRequestDecoder.Unmarshal(pb.Bytes, &request); err != nil {
t.Fatalf("failed to decode body %v\n%s", err, pb.Bytes)
return
}
if len(request.Keys) != 3 {
t.Fatalf("expected 3 keys got %d", len(request.Keys))
}
}
type StringerTest struct {
Name string `glint:"name"`
}
func (s *StringerTest) String() string {
return s.Name
}
// stub for the number.Decimal type which implements binaryEncoder
type number struct {
numericValue float64
}
func (n *number) MarshalBinary() []byte {
buf := make([]byte, 8)
binary.LittleEndian.PutUint64(buf[0:], math.Float64bits(n.numericValue))
return buf
}
type binaryEncoderTest struct {
Decimal number `glint:"decimal,encoder"`
DecimalPtr *number `glint:"decimalptr,encoder"`
}
type numericData struct {
number float64
}
func (w *numericData) UnmarshalBinary(bytes []byte) {
u := binary.LittleEndian.Uint64(bytes)
w.number = math.Float64frombits(u)
}
type binaryDecoderTest struct {
Decimal numericData `glint:"decimal,encoder"`
DecimalPtr *numericData `glint:"decimalptr,encoder"`
}
// tests the encoder tag works with binaryEncoder implementation
func TestCustomBinaryEncoderInterface(t *testing.T) {
encoder := newEncoder(binaryEncoderTest{})
decoder := newDecoder(binaryDecoderTest{})
ebuf := NewBufferFromPool()
defer ebuf.ReturnToPool()
var testStruct = binaryEncoderTest{
number{numericValue: 1.5},
&number{numericValue: 2.5},
}
encoder.Marshal(&testStruct, ebuf)
var result binaryDecoderTest
err := decoder.Unmarshal(ebuf.Bytes, &result)
if err != nil {
t.Fatalf("Error unmarshalling encoded data: %s", err)
}
if result.Decimal.number != 1.5 {
t.Error("decoded Decimal value not 1.5")
}
if result.DecimalPtr.number != 2.5 {
t.Error("decoded DecimalPtr value not 2.5")
}
}
func ExampleDecoder() {
type child struct {
Name string `glint:"name"`
}
type Example struct {
Bool bool `glint:"bool"`
Int int `glint:"int"`
Int8 int8 `glint:"int8"`
Int16 int16 `glint:"int16"`
Int32 int32 `glint:"int32"`
Int64 int64 `glint:"int64"`
Uint uint `glint:"uint"`
Uint8 uint8 `glint:"uint8"`
Uint16 uint16 `glint:"uint16"`
Uint32 uint32 `glint:"uint32"`
Uint64 uint64 `glint:"uint64"`
Float32 float32 `glint:"float32"`
Float64 float64 `glint:"float64"`
String string `glint:"string"`
Bytes []byte `glint:"bytes"`
Struct child `glint:"struct"`
Time time.Time `glint:"time"`
}
test := Example{
Bool: true,
Int: -42,
Int8: -8,
Int16: -2048,
Int32: -1024,
Int64: -9223372036854775808,
Uint: 42,
Uint8: 8,
Uint16: 2048,
Uint32: 1024,
Uint64: 9223372036854775807,
Float32: 3.14,
Float64: 3.142069,
String: "greetings",
Bytes: []byte{42, 7, 255},
Struct: child{
Name: "TestUser",
},
Time: time.Now(),
}
encoder := newEncoder(Example{})
buf := Buffer{}
encoder.Marshal(&test, &buf)
// fmt.Println(buf.Bytes)
// Print(buf.Bytes)
/// Output:
// 1
}
func ExampleEncoder() {
type Point struct {
X int `glint:"x"`
Y int `glint:"y"`
}
encoder := newEncoder(Point{})
buf := NewBufferFromPool()
value := Point{
X: 10,
Y: 55,
}
encoder.Marshal(&value, buf)
fmt.Println(buf.Bytes)
//Output:
// [0 59 198 217 19 6 2 1 120 2 1 121 20 110]
}
func TestTrustedSchemaMode(t *testing.T) {
// buf := glint.NewBufferWithTrust(glint.HTTPTrustee(r), testDataEnc)
type TestStruct2 struct {
String string `glint:"String"`
Float64 float64 `glint:"Float64"`
}
type TestStruct struct {
Bool bool `glint:"Bool"`
Int int `glint:"Int"`
Struct TestStruct2 `glint:"Struct"`
}
encoder := newEncoder(TestStruct{})
decoder := newDecoder(TestStruct{})
testStruct := &TestStruct{Bool: true, Int: 42, Struct: TestStruct2{String: "Struct", Float64: 9.99}}
buf := NewBufferFromPool()
encoder.Marshal(testStruct, buf)
decoder.Unmarshal(buf.Bytes, &TestStruct{})
trustHeader := NewTrustHeader(decoder)
request, err := http.NewRequest("GET", "url", nil)
if err != nil {
t.Error(err)
return
}
request.Header.Set(trustHeader.Key(), trustHeader.Value())
// 35 1 220 181 == 3051094307
/// assert trust header is set to correct value
if request.Header["X-Glint-Trust"][0] != "3051094307" {
t.Errorf("trust header not set to 3051094307: %s", request.Header["X-Glint-Trust"][0])
}
trustee := HTTPTrustee(request)
tb := NewBufferWithTrust(trustee, encoder)
// assert we resulted in a buffer with the correct trust flag set
if tb.TrustedSchema == false {
t.Error("trusted schema false")
}