forked from apache/cassandra-gocql-driver
-
Notifications
You must be signed in to change notification settings - Fork 59
/
marshal.go
2028 lines (1793 loc) · 51.2 KB
/
marshal.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 (c) 2012 The gocql Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package gocql
import (
"bytes"
"errors"
"fmt"
"math"
"math/big"
"math/bits"
"reflect"
"strings"
"time"
"unsafe"
"github.com/gocql/gocql/serialization/ascii"
"github.com/gocql/gocql/serialization/bigint"
"github.com/gocql/gocql/serialization/blob"
"github.com/gocql/gocql/serialization/counter"
"github.com/gocql/gocql/serialization/cqlint"
"github.com/gocql/gocql/serialization/cqltime"
"github.com/gocql/gocql/serialization/date"
"github.com/gocql/gocql/serialization/decimal"
"github.com/gocql/gocql/serialization/double"
"github.com/gocql/gocql/serialization/float"
"github.com/gocql/gocql/serialization/inet"
"github.com/gocql/gocql/serialization/smallint"
"github.com/gocql/gocql/serialization/text"
"github.com/gocql/gocql/serialization/timestamp"
"github.com/gocql/gocql/serialization/timeuuid"
"github.com/gocql/gocql/serialization/tinyint"
"github.com/gocql/gocql/serialization/uuid"
"github.com/gocql/gocql/serialization/varchar"
"github.com/gocql/gocql/serialization/varint"
)
var (
bigOne = big.NewInt(1)
emptyValue reflect.Value
)
var (
ErrorUDTUnavailable = errors.New("UDT are not available on protocols less than 3, please update config")
)
// Marshaler is an interface for custom unmarshaler.
// Each value of the 'CQL binary protocol' consist of <value_len> and <value_data>.
// <value_len> can be 'unset'(-2), 'nil'(-1), 'zero'(0) or any value up to 2147483647.
// When <value_len> is 'unset', 'nil' or 'zero', <value_data> is not present.
// 'unset' is applicable only to columns, with some exceptions.
// As you can see from API MarshalCQL only returns <value_data>, but there is a way for it to control <value_len>:
// 1. If MarshalCQL returns (gocql.UnsetValue, nil), gocql writes 'unset' to <value_len>
// 2. If MarshalCQL returns ([]byte(nil), nil), gocql writes 'nil' to <value_len>
// 3. If MarshalCQL returns ([]byte{}, nil), gocql writes 'zero' to <value_len>
//
// Some CQL databases have proprietary value coding features, which you may want to consider.
// CQL binary protocol info:https://github.com/apache/cassandra/tree/trunk/doc
type Marshaler interface {
MarshalCQL(info TypeInfo) ([]byte, error)
}
// Unmarshaler is an interface for custom unmarshaler.
// Each value of the 'CQL binary protocol' consist of <value_len> and <value_data>.
// <value_len> can be 'unset'(-2), 'nil'(-1), 'zero'(0) or any value up to 2147483647.
// When <value_len> is 'unset', 'nil' or 'zero', <value_data> is not present.
// As you can see from an API UnmarshalCQL receives only 'info TypeInfo' and
// 'data []byte', but gocql has the following way to signal about <value_len>:
// 1. When <value_len> is 'nil' gocql feeds nil to 'data []byte'
// 2. When <value_len> is 'zero' gocql feeds []byte{} to 'data []byte'
//
// Some CQL databases have proprietary value coding features, which you may want to consider.
// CQL binary protocol info:https://github.com/apache/cassandra/tree/trunk/doc
type Unmarshaler interface {
UnmarshalCQL(info TypeInfo, data []byte) error
}
// Marshal returns the CQL encoding of the value for the Cassandra
// internal type described by the info parameter.
//
// nil is serialized as CQL null.
// If value implements Marshaler, its MarshalCQL method is called to marshal the data.
// If value is a pointer, the pointed-to value is marshaled.
//
// Supported conversions are as follows, other type combinations may be added in the future:
//
// CQL type | Go type (value) | Note
// varchar, ascii, blob, text | string, []byte |
// boolean | bool |
// tinyint, smallint, int | integer types |
// tinyint, smallint, int | string | formatted as base 10 number
// bigint, counter | integer types |
// bigint, counter | big.Int |
// bigint, counter | string | formatted as base 10 number
// float | float32 |
// double | float64 |
// decimal | inf.Dec |
// time | int64 | nanoseconds since start of day
// time | time.Duration | duration since start of day
// timestamp | int64 | milliseconds since Unix epoch
// timestamp | time.Time |
// list, set | slice, array |
// list, set | map[X]struct{} |
// map | map[X]Y |
// uuid, timeuuid | gocql.UUID |
// uuid, timeuuid | [16]byte | raw UUID bytes
// uuid, timeuuid | []byte | raw UUID bytes, length must be 16 bytes
// uuid, timeuuid | string | hex representation, see ParseUUID
// varint | integer types |
// varint | big.Int |
// varint | string | value of number in decimal notation
// inet | net.IP |
// inet | string | IPv4 or IPv6 address string
// tuple | slice, array |
// tuple | struct | fields are marshaled in order of declaration
// user-defined type | gocql.UDTMarshaler | MarshalUDT is called
// user-defined type | map[string]interface{} |
// user-defined type | struct | struct fields' cql tags are used for column names
// date | int64 | milliseconds since Unix epoch to start of day (in UTC)
// date | time.Time | start of day (in UTC)
// date | string | parsed using "2006-01-02" format
// duration | int64 | duration in nanoseconds
// duration | time.Duration |
// duration | gocql.Duration |
// duration | string | parsed with time.ParseDuration
func Marshal(info TypeInfo, value interface{}) ([]byte, error) {
if info.Version() < protoVersion1 {
panic("protocol version not set")
}
if valueRef := reflect.ValueOf(value); valueRef.Kind() == reflect.Ptr {
if valueRef.IsNil() {
return nil, nil
} else if v, ok := value.(Marshaler); ok {
return v.MarshalCQL(info)
} else {
return Marshal(info, valueRef.Elem().Interface())
}
}
if v, ok := value.(Marshaler); ok {
return v.MarshalCQL(info)
}
switch info.Type() {
case TypeVarchar:
return marshalVarchar(value)
case TypeText:
return marshalText(value)
case TypeBlob:
return marshalBlob(value)
case TypeAscii:
return marshalAscii(value)
case TypeBoolean:
return marshalBool(info, value)
case TypeTinyInt:
return marshalTinyInt(value)
case TypeSmallInt:
return marshalSmallInt(value)
case TypeInt:
return marshalInt(value)
case TypeBigInt:
return marshalBigInt(value)
case TypeCounter:
return marshalCounter(value)
case TypeFloat:
return marshalFloat(value)
case TypeDouble:
return marshalDouble(value)
case TypeDecimal:
return marshalDecimal(value)
case TypeTime:
return marshalTime(value)
case TypeTimestamp:
return marshalTimestamp(value)
case TypeList, TypeSet:
return marshalList(info, value)
case TypeMap:
return marshalMap(info, value)
case TypeUUID:
return marshalUUID(value)
case TypeTimeUUID:
return marshalTimeUUID(value)
case TypeVarint:
return marshalVarint(value)
case TypeInet:
return marshalInet(value)
case TypeTuple:
return marshalTuple(info, value)
case TypeUDT:
return marshalUDT(info, value)
case TypeDate:
return marshalDate(value)
case TypeDuration:
return marshalDuration(info, value)
}
// detect protocol 2 UDT
if strings.HasPrefix(info.Custom(), "org.apache.cassandra.db.marshal.UserType") && info.Version() < 3 {
return nil, ErrorUDTUnavailable
}
// TODO(tux21b): add the remaining types
return nil, fmt.Errorf("can not marshal %T into %s", value, info)
}
// Unmarshal parses the CQL encoded data based on the info parameter that
// describes the Cassandra internal data type and stores the result in the
// value pointed by value.
//
// If value implements Unmarshaler, it's UnmarshalCQL method is called to
// unmarshal the data.
// If value is a pointer to pointer, it is set to nil if the CQL value is
// null. Otherwise, nulls are unmarshalled as zero value.
//
// Supported conversions are as follows, other type combinations may be added in the future:
//
// CQL type | Go type (value) | Note
// varchar, ascii, blob, text | *string |
// varchar, ascii, blob, text | *[]byte | non-nil buffer is reused
// bool | *bool |
// tinyint, smallint, int, bigint, counter | *integer types |
// tinyint, smallint, int, bigint, counter | *big.Int |
// tinyint, smallint, int, bigint, counter | *string | formatted as base 10 number
// float | *float32 |
// double | *float64 |
// decimal | *inf.Dec |
// time | *int64 | nanoseconds since start of day
// time | *time.Duration |
// timestamp | *int64 | milliseconds since Unix epoch
// timestamp | *time.Time |
// list, set | *slice, *array |
// map | *map[X]Y |
// uuid, timeuuid | *string | see UUID.String
// uuid, timeuuid | *[]byte | raw UUID bytes
// uuid, timeuuid | *gocql.UUID |
// timeuuid | *time.Time | timestamp of the UUID
// inet | *net.IP |
// inet | *string | IPv4 or IPv6 address string
// tuple | *slice, *array |
// tuple | *struct | struct fields are set in order of declaration
// user-defined types | gocql.UDTUnmarshaler | UnmarshalUDT is called
// user-defined types | *map[string]interface{} |
// user-defined types | *struct | cql tag is used to determine field name
// date | *time.Time | time of beginning of the day (in UTC)
// date | *string | formatted with 2006-01-02 format
// duration | *gocql.Duration |
func Unmarshal(info TypeInfo, data []byte, value interface{}) error {
if v, ok := value.(Unmarshaler); ok {
return v.UnmarshalCQL(info, data)
}
if isNullableValue(value) {
return unmarshalNullable(info, data, value)
}
switch info.Type() {
case TypeVarchar:
return unmarshalVarchar(data, value)
case TypeText:
return unmarshalText(data, value)
case TypeBlob:
return unmarshalBlob(data, value)
case TypeAscii:
return unmarshalAscii(data, value)
case TypeBoolean:
return unmarshalBool(info, data, value)
case TypeInt:
return unmarshalInt(data, value)
case TypeBigInt:
return unmarshalBigInt(data, value)
case TypeCounter:
return unmarshalCounter(data, value)
case TypeVarint:
return unmarshalVarint(data, value)
case TypeSmallInt:
return unmarshalSmallInt(data, value)
case TypeTinyInt:
return unmarshalTinyInt(data, value)
case TypeFloat:
return unmarshalFloat(data, value)
case TypeDouble:
return unmarshalDouble(data, value)
case TypeDecimal:
return unmarshalDecimal(data, value)
case TypeTime:
return unmarshalTime(data, value)
case TypeTimestamp:
return unmarshalTimestamp(data, value)
case TypeList, TypeSet:
return unmarshalList(info, data, value)
case TypeMap:
return unmarshalMap(info, data, value)
case TypeTimeUUID:
return unmarshalTimeUUID(data, value)
case TypeUUID:
return unmarshalUUID(data, value)
case TypeInet:
return unmarshalInet(data, value)
case TypeTuple:
return unmarshalTuple(info, data, value)
case TypeUDT:
return unmarshalUDT(info, data, value)
case TypeDate:
return unmarshalDate(data, value)
case TypeDuration:
return unmarshalDuration(info, data, value)
}
// detect protocol 2 UDT
if strings.HasPrefix(info.Custom(), "org.apache.cassandra.db.marshal.UserType") && info.Version() < 3 {
return ErrorUDTUnavailable
}
// TODO(tux21b): add the remaining types
return fmt.Errorf("can not unmarshal %s into %T", info, value)
}
func isNullableValue(value interface{}) bool {
v := reflect.ValueOf(value)
return v.Kind() == reflect.Ptr && v.Type().Elem().Kind() == reflect.Ptr
}
func isNullData(info TypeInfo, data []byte) bool {
return data == nil
}
func unmarshalNullable(info TypeInfo, data []byte, value interface{}) error {
valueRef := reflect.ValueOf(value)
if isNullData(info, data) {
nilValue := reflect.Zero(valueRef.Type().Elem())
valueRef.Elem().Set(nilValue)
return nil
}
newValue := reflect.New(valueRef.Type().Elem().Elem())
valueRef.Elem().Set(newValue)
return Unmarshal(info, data, newValue.Interface())
}
func marshalVarchar(value interface{}) ([]byte, error) {
data, err := varchar.Marshal(value)
if err != nil {
return nil, wrapMarshalError(err, "marshal error")
}
return data, nil
}
func marshalText(value interface{}) ([]byte, error) {
data, err := text.Marshal(value)
if err != nil {
return nil, wrapMarshalError(err, "marshal error")
}
return data, nil
}
func marshalBlob(value interface{}) ([]byte, error) {
data, err := blob.Marshal(value)
if err != nil {
return nil, wrapMarshalError(err, "marshal error")
}
return data, nil
}
func marshalAscii(value interface{}) ([]byte, error) {
data, err := ascii.Marshal(value)
if err != nil {
return nil, wrapMarshalError(err, "marshal error")
}
return data, nil
}
func unmarshalVarchar(data []byte, value interface{}) error {
err := varchar.Unmarshal(data, value)
if err != nil {
return wrapUnmarshalError(err, "unmarshal error")
}
return nil
}
func unmarshalText(data []byte, value interface{}) error {
err := text.Unmarshal(data, value)
if err != nil {
return wrapUnmarshalError(err, "unmarshal error")
}
return nil
}
func unmarshalBlob(data []byte, value interface{}) error {
err := blob.Unmarshal(data, value)
if err != nil {
return wrapUnmarshalError(err, "unmarshal error")
}
return nil
}
func unmarshalAscii(data []byte, value interface{}) error {
err := ascii.Unmarshal(data, value)
if err != nil {
return wrapUnmarshalError(err, "unmarshal error")
}
return nil
}
func marshalSmallInt(value interface{}) ([]byte, error) {
data, err := smallint.Marshal(value)
if err != nil {
return nil, wrapMarshalError(err, "marshal error")
}
return data, nil
}
func marshalTinyInt(value interface{}) ([]byte, error) {
data, err := tinyint.Marshal(value)
if err != nil {
return nil, wrapMarshalError(err, "marshal error")
}
return data, nil
}
func marshalInt(value interface{}) ([]byte, error) {
data, err := cqlint.Marshal(value)
if err != nil {
return nil, wrapMarshalError(err, "marshal error")
}
return data, nil
}
func encInt(x int32) []byte {
return []byte{byte(x >> 24), byte(x >> 16), byte(x >> 8), byte(x)}
}
func decInt(x []byte) int32 {
if len(x) != 4 {
return 0
}
return int32(x[0])<<24 | int32(x[1])<<16 | int32(x[2])<<8 | int32(x[3])
}
func marshalBigInt(value interface{}) ([]byte, error) {
data, err := bigint.Marshal(value)
if err != nil {
return nil, wrapMarshalError(err, "marshal error")
}
return data, nil
}
func marshalCounter(value interface{}) ([]byte, error) {
data, err := counter.Marshal(value)
if err != nil {
return nil, wrapMarshalError(err, "marshal error")
}
return data, nil
}
func encBigInt(x int64) []byte {
return []byte{byte(x >> 56), byte(x >> 48), byte(x >> 40), byte(x >> 32),
byte(x >> 24), byte(x >> 16), byte(x >> 8), byte(x)}
}
func unmarshalCounter(data []byte, value interface{}) error {
err := counter.Unmarshal(data, value)
if err != nil {
return wrapUnmarshalError(err, "unmarshal error")
}
return nil
}
func unmarshalInt(data []byte, value interface{}) error {
err := cqlint.Unmarshal(data, value)
if err != nil {
return wrapUnmarshalError(err, "unmarshal error")
}
return nil
}
func unmarshalBigInt(data []byte, value interface{}) error {
err := bigint.Unmarshal(data, value)
if err != nil {
return wrapUnmarshalError(err, "unmarshal error")
}
return nil
}
func unmarshalSmallInt(data []byte, value interface{}) error {
err := smallint.Unmarshal(data, value)
if err != nil {
return wrapUnmarshalError(err, "unmarshal error")
}
return nil
}
func unmarshalTinyInt(data []byte, value interface{}) error {
if err := tinyint.Unmarshal(data, value); err != nil {
return wrapUnmarshalError(err, "unmarshal error")
}
return nil
}
func unmarshalVarint(data []byte, value interface{}) error {
if err := varint.Unmarshal(data, value); err != nil {
return wrapUnmarshalError(err, "unmarshal error")
}
return nil
}
func marshalVarint(value interface{}) ([]byte, error) {
data, err := varint.Marshal(value)
if err != nil {
return nil, wrapMarshalError(err, "marshal error")
}
return data, nil
}
func decBigInt(data []byte) int64 {
if len(data) != 8 {
return 0
}
return int64(data[0])<<56 | int64(data[1])<<48 |
int64(data[2])<<40 | int64(data[3])<<32 |
int64(data[4])<<24 | int64(data[5])<<16 |
int64(data[6])<<8 | int64(data[7])
}
func marshalBool(info TypeInfo, value interface{}) ([]byte, error) {
switch v := value.(type) {
case Marshaler:
return v.MarshalCQL(info)
case unsetColumn:
return nil, nil
case bool:
return encBool(v), nil
}
if value == nil {
return nil, nil
}
rv := reflect.ValueOf(value)
switch rv.Type().Kind() {
case reflect.Bool:
return encBool(rv.Bool()), nil
}
return nil, marshalErrorf("can not marshal %T into %s", value, info)
}
func encBool(v bool) []byte {
if v {
return []byte{1}
}
return []byte{0}
}
func unmarshalBool(info TypeInfo, data []byte, value interface{}) error {
switch v := value.(type) {
case Unmarshaler:
return v.UnmarshalCQL(info, data)
case *bool:
*v = decBool(data)
return nil
}
rv := reflect.ValueOf(value)
if rv.Kind() != reflect.Ptr {
return unmarshalErrorf("can not unmarshal into non-pointer %T", value)
}
rv = rv.Elem()
switch rv.Type().Kind() {
case reflect.Bool:
rv.SetBool(decBool(data))
return nil
}
return unmarshalErrorf("can not unmarshal %s into %T", info, value)
}
func decBool(v []byte) bool {
if len(v) == 0 {
return false
}
return v[0] != 0
}
func marshalFloat(value interface{}) ([]byte, error) {
data, err := float.Marshal(value)
if err != nil {
return nil, wrapMarshalError(err, "marshal error")
}
return data, nil
}
func unmarshalFloat(data []byte, value interface{}) error {
if err := float.Unmarshal(data, value); err != nil {
return wrapUnmarshalError(err, "unmarshal error")
}
return nil
}
func marshalDouble(value interface{}) ([]byte, error) {
data, err := double.Marshal(value)
if err != nil {
return nil, wrapMarshalError(err, "marshal error")
}
return data, nil
}
func unmarshalDouble(data []byte, value interface{}) error {
err := double.Unmarshal(data, value)
if err != nil {
return wrapUnmarshalError(err, "unmarshal error")
}
return nil
}
func marshalDecimal(value interface{}) ([]byte, error) {
data, err := decimal.Marshal(value)
if err != nil {
return nil, wrapMarshalError(err, "marshal error")
}
return data, nil
}
func unmarshalDecimal(data []byte, value interface{}) error {
if err := decimal.Unmarshal(data, value); err != nil {
return wrapUnmarshalError(err, "unmarshal error")
}
return nil
}
// decBigInt2C sets the value of n to the big-endian two's complement
// value stored in the given data. If data[0]&80 != 0, the number
// is negative. If data is empty, the result will be 0.
func decBigInt2C(data []byte, n *big.Int) *big.Int {
if n == nil {
n = new(big.Int)
}
n.SetBytes(data)
if len(data) > 0 && data[0]&0x80 > 0 {
n.Sub(n, new(big.Int).Lsh(bigOne, uint(len(data))*8))
}
return n
}
// encBigInt2C returns the big-endian two's complement
// form of n.
func encBigInt2C(n *big.Int) []byte {
switch n.Sign() {
case 0:
return []byte{0}
case 1:
b := n.Bytes()
if b[0]&0x80 > 0 {
b = append([]byte{0}, b...)
}
return b
case -1:
length := uint(n.BitLen()/8+1) * 8
b := new(big.Int).Add(n, new(big.Int).Lsh(bigOne, length)).Bytes()
// When the most significant bit is on a byte
// boundary, we can get some extra significant
// bits, so strip them off when that happens.
if len(b) >= 2 && b[0] == 0xff && b[1]&0x80 != 0 {
b = b[1:]
}
return b
}
return nil
}
func marshalTime(value interface{}) ([]byte, error) {
data, err := cqltime.Marshal(value)
if err != nil {
return nil, wrapMarshalError(err, "marshal error")
}
return data, nil
}
func unmarshalTime(data []byte, value interface{}) error {
err := cqltime.Unmarshal(data, value)
if err != nil {
return wrapUnmarshalError(err, "unmarshal error")
}
return nil
}
func marshalTimestamp(value interface{}) ([]byte, error) {
data, err := timestamp.Marshal(value)
if err != nil {
return nil, wrapMarshalError(err, "marshal error")
}
return data, nil
}
func unmarshalTimestamp(data []byte, value interface{}) error {
err := timestamp.Unmarshal(data, value)
if err != nil {
return wrapUnmarshalError(err, "unmarshal error")
}
return nil
}
func marshalDate(value interface{}) ([]byte, error) {
data, err := date.Marshal(value)
if err != nil {
return nil, wrapMarshalError(err, "marshal error")
}
return data, nil
}
func unmarshalDate(data []byte, value interface{}) error {
err := date.Unmarshal(data, value)
if err != nil {
return wrapUnmarshalError(err, "unmarshal error")
}
return nil
}
func marshalDuration(info TypeInfo, value interface{}) ([]byte, error) {
switch v := value.(type) {
case Marshaler:
return v.MarshalCQL(info)
case unsetColumn:
return nil, nil
case int64:
return encVints(0, 0, v), nil
case time.Duration:
return encVints(0, 0, v.Nanoseconds()), nil
case string:
d, err := time.ParseDuration(v)
if err != nil {
return nil, err
}
return encVints(0, 0, d.Nanoseconds()), nil
case Duration:
return encVints(v.Months, v.Days, v.Nanoseconds), nil
}
if value == nil {
return nil, nil
}
rv := reflect.ValueOf(value)
switch rv.Type().Kind() {
case reflect.Int64:
return encVints(0, 0, rv.Int()), nil
}
return nil, marshalErrorf("can not marshal %T into %s", value, info)
}
func unmarshalDuration(info TypeInfo, data []byte, value interface{}) error {
switch v := value.(type) {
case Unmarshaler:
return v.UnmarshalCQL(info, data)
case *Duration:
if len(data) == 0 {
*v = Duration{
Months: 0,
Days: 0,
Nanoseconds: 0,
}
return nil
}
months, days, nanos, err := decVints(data)
if err != nil {
return unmarshalErrorf("failed to unmarshal %s into %T: %s", info, value, err.Error())
}
*v = Duration{
Months: months,
Days: days,
Nanoseconds: nanos,
}
return nil
}
return unmarshalErrorf("can not unmarshal %s into %T", info, value)
}
func decVints(data []byte) (int32, int32, int64, error) {
month, i, err := decVint(data, 0)
if err != nil {
return 0, 0, 0, fmt.Errorf("failed to extract month: %s", err.Error())
}
days, i, err := decVint(data, i)
if err != nil {
return 0, 0, 0, fmt.Errorf("failed to extract days: %s", err.Error())
}
nanos, _, err := decVint(data, i)
if err != nil {
return 0, 0, 0, fmt.Errorf("failed to extract nanoseconds: %s", err.Error())
}
return int32(month), int32(days), nanos, err
}
func decVint(data []byte, start int) (int64, int, error) {
if len(data) <= start {
return 0, 0, errors.New("unexpected eof")
}
firstByte := data[start]
if firstByte&0x80 == 0 {
return decIntZigZag(uint64(firstByte)), start + 1, nil
}
numBytes := bits.LeadingZeros32(uint32(^firstByte)) - 24
ret := uint64(firstByte & (0xff >> uint(numBytes)))
if len(data) < start+numBytes+1 {
return 0, 0, fmt.Errorf("data expect to have %d bytes, but it has only %d", start+numBytes+1, len(data))
}
for i := start; i < start+numBytes; i++ {
ret <<= 8
ret |= uint64(data[i+1] & 0xff)
}
return decIntZigZag(ret), start + numBytes + 1, nil
}
func decIntZigZag(n uint64) int64 {
return int64((n >> 1) ^ -(n & 1))
}
func encIntZigZag(n int64) uint64 {
return uint64((n >> 63) ^ (n << 1))
}
func encVints(months int32, days int32, nanos int64) []byte {
buf := append(encVint(int64(months)), encVint(int64(days))...)
return append(buf, encVint(nanos)...)
}
func encVint(v int64) []byte {
vEnc := encIntZigZag(v)
lead0 := bits.LeadingZeros64(vEnc)
numBytes := (639 - lead0*9) >> 6
// It can be 1 or 0 is v ==0
if numBytes <= 1 {
return []byte{byte(vEnc)}
}
extraBytes := numBytes - 1
var buf = make([]byte, numBytes)
for i := extraBytes; i >= 0; i-- {
buf[i] = byte(vEnc)
vEnc >>= 8
}
buf[0] |= byte(^(0xff >> uint(extraBytes)))
return buf
}
func writeCollectionSize(info CollectionType, n int, buf *bytes.Buffer) error {
if info.proto > protoVersion2 {
if n > math.MaxInt32 {
return marshalErrorf("marshal: collection too large")
}
buf.WriteByte(byte(n >> 24))
buf.WriteByte(byte(n >> 16))
buf.WriteByte(byte(n >> 8))
buf.WriteByte(byte(n))
} else {
if n > math.MaxUint16 {
return marshalErrorf("marshal: collection too large")
}
buf.WriteByte(byte(n >> 8))
buf.WriteByte(byte(n))
}
return nil
}
func marshalList(info TypeInfo, value interface{}) ([]byte, error) {
listInfo, ok := info.(CollectionType)
if !ok {
return nil, marshalErrorf("marshal: can not marshal non collection type into list")
}
if value == nil {
return nil, nil
} else if _, ok := value.(unsetColumn); ok {
return nil, nil
}
rv := reflect.ValueOf(value)
t := rv.Type()
k := t.Kind()
if k == reflect.Slice && rv.IsNil() {
return nil, nil
}
switch k {
case reflect.Slice, reflect.Array:
buf := &bytes.Buffer{}
n := rv.Len()
if err := writeCollectionSize(listInfo, n, buf); err != nil {
return nil, err
}
for i := 0; i < n; i++ {
item, err := Marshal(listInfo.Elem, rv.Index(i).Interface())
if err != nil {
return nil, err
}
itemLen := len(item)
// Set the value to null for supported protocols
if item == nil && listInfo.proto > protoVersion2 {
itemLen = -1
}
if err := writeCollectionSize(listInfo, itemLen, buf); err != nil {
return nil, err
}
buf.Write(item)
}
return buf.Bytes(), nil
case reflect.Map:
elem := t.Elem()
if elem.Kind() == reflect.Struct && elem.NumField() == 0 {
rkeys := rv.MapKeys()
keys := make([]interface{}, len(rkeys))
for i := 0; i < len(keys); i++ {
keys[i] = rkeys[i].Interface()
}
return marshalList(listInfo, keys)
}
}
return nil, marshalErrorf("can not marshal %T into %s", value, info)
}
func readCollectionSize(info CollectionType, data []byte) (size, read int, err error) {
if info.proto > protoVersion2 {
if len(data) < 4 {
return 0, 0, unmarshalErrorf("unmarshal list: unexpected eof")
}
size = int(int32(data[0])<<24 | int32(data[1])<<16 | int32(data[2])<<8 | int32(data[3]))
read = 4
} else {
if len(data) < 2 {
return 0, 0, unmarshalErrorf("unmarshal list: unexpected eof")
}
size = int(data[0])<<8 | int(data[1])
read = 2
}
return
}
func unmarshalList(info TypeInfo, data []byte, value interface{}) error {
listInfo, ok := info.(CollectionType)
if !ok {
return unmarshalErrorf("unmarshal: can not unmarshal none collection type into list")
}
rv := reflect.ValueOf(value)
if rv.Kind() != reflect.Ptr {
return unmarshalErrorf("can not unmarshal into non-pointer %T", value)
}
rv = rv.Elem()
t := rv.Type()
k := t.Kind()
switch k {
case reflect.Slice, reflect.Array:
if data == nil {
if k == reflect.Array {
return unmarshalErrorf("unmarshal list: can not store nil in array value")
}
if rv.IsNil() {
return nil
}
rv.Set(reflect.Zero(t))
return nil
}
n, p, err := readCollectionSize(listInfo, data)
if err != nil {
return err
}
data = data[p:]
if k == reflect.Array {
if rv.Len() != n {
return unmarshalErrorf("unmarshal list: array with wrong size")
}
} else {
rv.Set(reflect.MakeSlice(t, n, n))
}
for i := 0; i < n; i++ {
m, p, err := readCollectionSize(listInfo, data)
if err != nil {
return err
}
data = data[p:]
// In case m < 0, the value is null, and unmarshalData should be nil.
var unmarshalData []byte
if m >= 0 {
if len(data) < m {
return unmarshalErrorf("unmarshal list: unexpected eof")
}
unmarshalData = data[:m]
data = data[m:]
}
if err := Unmarshal(listInfo.Elem, unmarshalData, rv.Index(i).Addr().Interface()); err != nil {
return err
}
}
return nil