-
Notifications
You must be signed in to change notification settings - Fork 113
/
resp.go
2415 lines (2122 loc) · 67.1 KB
/
resp.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 resp3 implements the upgraded redis RESP3 protocol, a plaintext
// protocol which is also binary safe and backwards compatible with the original
// RESP2 protocol.
//
// Redis uses the RESP protocol to communicate with its clients, but there's
// nothing about the protocol which ties it to redis, it could be used for
// almost anything.
//
// See https://github.com/antirez/RESP3 for more details on the protocol.
//
// In general attribute messages are transarently discarded in this package. The
// user can read them manually prior to the message they are attached to if they
// are expected and desired.
package resp3
import (
"bufio"
"bytes"
"encoding"
"errors"
"fmt"
"io"
"math"
"math/big"
"reflect"
"sort"
"strconv"
"sync"
"github.com/mediocregopher/radix/v4/internal/bytesutil"
"github.com/mediocregopher/radix/v4/resp"
)
var delim = []byte{'\r', '\n'}
// Prefix enumerates the possible RESP3 types by enumerating the different
// prefix bytes a RESP3 message might start with.
type Prefix byte
// Enumeration of each of RESP3 prefices.
var (
// Simple type prefices.
BlobStringPrefix Prefix = '$'
SimpleStringPrefix Prefix = '+'
SimpleErrorPrefix Prefix = '-'
NumberPrefix Prefix = ':'
NullPrefix Prefix = '_'
DoublePrefix Prefix = ','
BooleanPrefix Prefix = '#'
BlobErrorPrefix Prefix = '!'
VerbatimStringPrefix Prefix = '='
BigNumberPrefix Prefix = '('
// Aggregated type prefices.
ArrayHeaderPrefix Prefix = '*'
MapHeaderPrefix Prefix = '%'
SetHeaderPrefix Prefix = '~'
AttributeHeaderPrefix Prefix = '|'
PushHeaderPrefix Prefix = '>'
// Streamed type prefices.
StreamedAggregatedTypeEndPrefix Prefix = '.'
StreamedStringChunkPrefix Prefix = ';'
)
func (p Prefix) String() string {
pStr := string(p)
switch pStr {
case string(BlobStringPrefix):
return "blob-string"
case string(SimpleStringPrefix):
return "simple-string"
case string(SimpleErrorPrefix):
return "simple-error"
case string(NumberPrefix):
return "number"
case string(NullPrefix):
return "null"
case string(DoublePrefix):
return "double"
case string(BooleanPrefix):
return "boolean"
case string(BlobErrorPrefix):
return "blob-error"
case string(VerbatimStringPrefix):
return "verbatim-string"
case string(BigNumberPrefix):
return "big-number"
case string(ArrayHeaderPrefix):
return "array"
case string(MapHeaderPrefix):
return "map"
case string(SetHeaderPrefix):
return "set"
case string(AttributeHeaderPrefix):
return "attribute"
case string(PushHeaderPrefix):
return "push"
case string(StreamedAggregatedTypeEndPrefix):
return "streamed-aggregated-type-end"
case string(StreamedStringChunkPrefix):
return "streamed-string-chunk"
default:
return pStr
}
}
func (p Prefix) doesPrefix(b []byte) bool {
if len(b) == 0 {
panic("empty byte slice should not be passed here, please submit a bug report")
}
return Prefix(b[0]) == p
}
var (
nullRESP2Suffix = []byte("-1\r")
null = []byte("_\r\n")
booleanTrue = []byte("#t\r\n")
booleanFalse = []byte("#f\r\n")
streamHeaderSize = []byte("?")
streamedHeaderTail = []byte("?\r\n")
streamAggEnd = []byte(".\r\n")
emptyAggTail = []byte("0\r\n")
)
var (
emptyStructT = reflect.TypeOf(struct{}{})
)
////////////////////////////////////////////////////////////////////////////////
// l may be negative to indicate that elements should be discarded until a
// streamed aggregated end type message is encountered.
func discardMulti(br resp.BufferedReader, l int, o *resp.Opts) error {
for i := 0; i < l || l < 0; i++ {
if more, err := maybeUnmarshalRESP(br, l < 0, nil, o); err != nil {
return err
} else if !more {
return nil
}
}
return nil
}
// DiscardAttribute discards the next RESP3 message if it is an attribute message.
// If the next message is not an attribute message then DiscardAttribute does nothing..
func DiscardAttribute(br resp.BufferedReader, o *resp.Opts) error {
var attrHead AttributeHeader
b, err := br.Peek(1)
if err != nil {
return err
} else if !AttributeHeaderPrefix.doesPrefix(b) {
return nil
} else if err := attrHead.UnmarshalRESP(br, o); err != nil {
return nil
}
return discardMulti(br, attrHead.NumPairs*2, o)
}
// NextMessageIs returns true if the next value in the given reader has the given
// prefix.
//
// If there is an error reading from br, NextMessageIs will return false and the error.
func NextMessageIs(br resp.BufferedReader, p Prefix) (bool, error) {
b, err := br.Peek(1)
return err == nil && p.doesPrefix(b), err
}
type errUnexpectedPrefix struct {
Prefix Prefix
ExpectedPrefix Prefix
}
func (e errUnexpectedPrefix) Error() string {
return fmt.Sprintf("expected prefix %q, got %q", e.ExpectedPrefix, e.Prefix)
}
// peekAndAssertPrefix will peek at the next incoming redis message and assert
// that it is of the type identified by the given prefix.
//
// If the message is a RESP error (and that wasn't the intended prefix) then it
// will be unmarshaled into the appropriate RESP error type and returned.
//
// If the message is a not a RESP error(except the intended prefix) it will be
// discarded and errUnexpectedPrefix will be returned.
//
// peekAndAssertPrefix will discard any preceding attribute message when called
// with discardAttr set.
func peekAndAssertPrefix(br resp.BufferedReader, expectedPrefix Prefix, discardAttr bool, o *resp.Opts) error {
if discardAttr {
if err := DiscardAttribute(br, o); err != nil {
return err
}
}
b, err := br.Peek(1)
if err != nil {
return err
} else if expectedPrefix.doesPrefix(b) {
return nil
} else if SimpleErrorPrefix.doesPrefix(b) {
var respErr SimpleError
if err := respErr.UnmarshalRESP(br, o); err != nil {
return err
}
return resp.ErrConnUsable{Err: respErr}
} else if BlobErrorPrefix.doesPrefix(b) {
var respErr BlobError
if err := respErr.UnmarshalRESP(br, o); err != nil {
return err
}
return resp.ErrConnUsable{Err: respErr}
} else if err := Unmarshal(br, nil, o); err != nil {
return err
}
return resp.ErrConnUsable{Err: errUnexpectedPrefix{
Prefix: Prefix(b[0]),
ExpectedPrefix: expectedPrefix,
}}
}
// like peekAndAssertPrefix, but will consume the prefix if it is the correct
// one as well.
func readAndAssertPrefix(br resp.BufferedReader, prefix Prefix, discardAttr bool, o *resp.Opts) error {
if err := peekAndAssertPrefix(br, prefix, discardAttr, o); err != nil {
return err
}
_, err := br.Discard(1)
return err
}
////////////////////////////////////////////////////////////////////////////////
// BlobStringBytes represents the blob string type in the RESP protocol using a
// go byte slice. A B value of nil is an empty string.
//
// BlobStringBytes can also be used as the header message of a streamed string.
// When used in that way it will be followed by one or more BlobStringChunk
// messages, ending in a BlobStringChunk with a zero length.
//
// BlobStringBytes will unmarshal a nil RESP2 bulk string as an empty B value.
type BlobStringBytes struct {
B []byte
// StreamedStringHeader indicates that this message is the header message of
// a streamed string. It is mutually exclusive with B.
StreamedStringHeader bool
}
// MarshalRESP implements the method for resp.Marshaler.
func (b BlobStringBytes) MarshalRESP(w io.Writer, o *resp.Opts) error {
scratch := o.GetBytes()
defer o.PutBytes(scratch)
*scratch = append(*scratch, byte(BlobStringPrefix))
if b.StreamedStringHeader {
*scratch = append(*scratch, streamHeaderSize...)
} else {
*scratch = strconv.AppendInt(*scratch, int64(len(b.B)), 10)
*scratch = append(*scratch, delim...)
*scratch = append(*scratch, b.B...)
}
*scratch = append(*scratch, delim...)
_, err := w.Write(*scratch)
return err
}
// UnmarshalRESP implements the method for resp.Unmarshaler.
func (b *BlobStringBytes) UnmarshalRESP(br resp.BufferedReader, o *resp.Opts) error {
if err := readAndAssertPrefix(br, BlobStringPrefix, true, o); err != nil {
return err
}
byt, err := bytesutil.ReadBytesDelim(br)
if err != nil {
return err
} else if bytes.Equal(byt, streamHeaderSize) {
b.B = nil
b.StreamedStringHeader = true
return nil
}
n, err := bytesutil.ParseInt(byt)
if err != nil {
return err
} else if n == -1 {
b.B = []byte{}
return nil
} else if n < 0 {
return fmt.Errorf("invalid blob string length: %d", n)
} else if n == 0 {
b.B = []byte{}
} else {
b.B = bytesutil.Expand(b.B, int(n))
if _, err := io.ReadFull(br, b.B); err != nil {
return err
}
}
if _, err := bytesutil.ReadBytesDelim(br); err != nil {
return err
}
return nil
}
////////////////////////////////////////////////////////////////////////////////
// BlobString represents the blob string type in the RESP protocol using a go
// string.
//
// BlobString can also be used as the header message of a streamed string. When
// used in that way it will be followed by one or more BlobStringChunk messages,
// ending in a BlobStringChunk with a zero length.
//
// BlobStringBytes will unmarshal a nil RESP2 bulk string as an empty S value.
type BlobString struct {
S string
// StreamedStringHeader indicates that this message is the header message of
// a streamed string. It is mutually exclusive with S.
StreamedStringHeader bool
}
// MarshalRESP implements the method for resp.Marshaler.
func (b BlobString) MarshalRESP(w io.Writer, o *resp.Opts) error {
scratch := o.GetBytes()
defer o.PutBytes(scratch)
*scratch = append(*scratch, byte(BlobStringPrefix))
if b.StreamedStringHeader {
*scratch = append(*scratch, streamHeaderSize...)
} else {
*scratch = strconv.AppendInt(*scratch, int64(len(b.S)), 10)
*scratch = append(*scratch, delim...)
*scratch = append(*scratch, b.S...)
}
*scratch = append(*scratch, delim...)
_, err := w.Write(*scratch)
return err
}
// UnmarshalRESP implements the method for resp.Unmarshaler.
func (b *BlobString) UnmarshalRESP(br resp.BufferedReader, o *resp.Opts) error {
if err := readAndAssertPrefix(br, BlobStringPrefix, true, o); err != nil {
return err
}
byt, err := bytesutil.ReadBytesDelim(br)
if err != nil {
return err
} else if bytes.Equal(byt, streamHeaderSize) {
b.S = ""
b.StreamedStringHeader = true
return nil
}
n, err := bytesutil.ParseInt(byt)
if err != nil {
return err
} else if n == -1 {
b.S = ""
return nil
} else if n < 0 {
return fmt.Errorf("invalid blob string length: %d", n)
} else if n == 0 {
b.S = ""
} else {
scratch := o.GetBytes()
defer o.PutBytes(scratch)
*scratch = bytesutil.Expand(*scratch, int(n))
if _, err := io.ReadFull(br, *scratch); err != nil {
return err
}
b.S = string(*scratch)
}
if _, err := bytesutil.ReadBytesDelim(br); err != nil {
return err
}
return nil
}
////////////////////////////////////////////////////////////////////////////////
// BlobStringWriter represents a blob string in the RESP protocol.
//
// BlobStringWriter only supports marshalling and will use the given LenReader
// to do so.
type BlobStringWriter struct {
LR resp.LenReader
}
// MarshalRESP implements the method for resp.Marshaler.
func (b BlobStringWriter) MarshalRESP(w io.Writer, o *resp.Opts) error {
scratch := o.GetBytes()
defer o.PutBytes(scratch)
l := int64(b.LR.Len())
*scratch = append(*scratch, byte(BlobStringPrefix))
*scratch = strconv.AppendInt(*scratch, l, 10)
*scratch = append(*scratch, delim...)
_, err := w.Write(*scratch)
if err != nil {
return err
}
if _, err := io.CopyN(w, b.LR, l); err != nil {
return err
} else if _, err := w.Write(delim); err != nil {
return err
}
return nil
}
////////////////////////////////////////////////////////////////////////////////
// SimpleString represents the simple string type in the RESP protocol.
type SimpleString struct {
S string
}
// MarshalRESP implements the method for resp.Marshaler.
func (ss SimpleString) MarshalRESP(w io.Writer, o *resp.Opts) error {
scratch := o.GetBytes()
defer o.PutBytes(scratch)
*scratch = append(*scratch, byte(SimpleStringPrefix))
*scratch = append(*scratch, ss.S...)
*scratch = append(*scratch, delim...)
_, err := w.Write(*scratch)
return err
}
// UnmarshalRESP implements the method for resp.Unmarshaler.
func (ss *SimpleString) UnmarshalRESP(br resp.BufferedReader, o *resp.Opts) error {
if err := readAndAssertPrefix(br, SimpleStringPrefix, true, o); err != nil {
return err
}
b, err := bytesutil.ReadBytesDelim(br)
if err != nil {
return err
}
ss.S = string(b)
return nil
}
////////////////////////////////////////////////////////////////////////////////
// SimpleError represents the simple error type in the RESP protocol.
//
// SimpleError represents an actual error message being read/written on the
// wire, it is separate from network or parsing errors.
type SimpleError struct {
S string
}
func (e SimpleError) Error() string {
return e.S
}
// MarshalRESP implements the method for resp.Marshaler.
func (e SimpleError) MarshalRESP(w io.Writer, o *resp.Opts) error {
scratch := o.GetBytes()
defer o.PutBytes(scratch)
*scratch = append(*scratch, byte(SimpleErrorPrefix))
*scratch = append(*scratch, e.S...)
*scratch = append(*scratch, delim...)
_, err := w.Write(*scratch)
return err
}
// UnmarshalRESP implements the method for resp.Unmarshaler.
func (e *SimpleError) UnmarshalRESP(br resp.BufferedReader, o *resp.Opts) error {
if err := readAndAssertPrefix(br, SimpleErrorPrefix, true, o); err != nil {
return err
}
b, err := bytesutil.ReadBytesDelim(br)
e.S = string(b)
return err
}
////////////////////////////////////////////////////////////////////////////////
// Number represents the number type in the RESP protocol.
type Number struct {
N int64
}
// MarshalRESP implements the method for resp.Marshaler.
func (n Number) MarshalRESP(w io.Writer, o *resp.Opts) error {
scratch := o.GetBytes()
defer o.PutBytes(scratch)
*scratch = append(*scratch, byte(NumberPrefix))
*scratch = strconv.AppendInt(*scratch, n.N, 10)
*scratch = append(*scratch, delim...)
_, err := w.Write(*scratch)
return err
}
// UnmarshalRESP implements the method for resp.Unmarshaler.
func (n *Number) UnmarshalRESP(br resp.BufferedReader, o *resp.Opts) error {
if err := readAndAssertPrefix(br, NumberPrefix, true, o); err != nil {
return err
}
i, err := bytesutil.ReadIntDelim(br)
n.N = i
return err
}
////////////////////////////////////////////////////////////////////////////////
// Null represents the null type in the RESP protocol.
//
// Null will always marshal to the RESP3 null type, but for convenience is also
// capable of unmarshaling the RESP2 null bulk string and null array values.
type Null struct{}
// MarshalRESP implements the method for resp.Marshaler.
func (Null) MarshalRESP(w io.Writer, o *resp.Opts) error {
_, err := w.Write(null)
return err
}
// UnmarshalRESP implements the method for resp.Unmarshaler.
func (*Null) UnmarshalRESP(br resp.BufferedReader, o *resp.Opts) error {
if err := DiscardAttribute(br, o); err != nil {
return err
}
b, err := br.Peek(1)
if err != nil {
return err
}
prefix := Prefix(b[0])
switch prefix {
case NullPrefix:
b, err := bytesutil.ReadBytesDelim(br)
if err != nil {
return err
} else if len(b) != 1 {
return errors.New("malformed null resp")
}
return nil
case ArrayHeaderPrefix, BlobStringPrefix:
// no matter what size an array or blob string is it _must_ have at
// least 4 characters on the wire (prefix+size+delim). So only check
// that.
b, err := br.Peek(4)
if err != nil {
return err
} else if !bytes.Equal(b[1:], nullRESP2Suffix) {
if err := Unmarshal(br, nil, o); err != nil {
return err
}
return resp.ErrConnUsable{Err: errors.New("malformed null resp")}
}
// actually consume the message, after all this peeking.
_, err = bytesutil.ReadBytesDelim(br)
return err
default:
if err := Unmarshal(br, nil, o); err != nil {
return err
}
return resp.ErrConnUsable{Err: errUnexpectedPrefix{
Prefix: prefix,
ExpectedPrefix: NullPrefix,
}}
}
}
////////////////////////////////////////////////////////////////////////////////
// Double represents the double type in the RESP protocol.
type Double struct {
F float64
}
// MarshalRESP implements the method for resp.Marshaler.
func (d Double) MarshalRESP(w io.Writer, o *resp.Opts) error {
scratch := o.GetBytes()
*scratch = append(*scratch, byte(DoublePrefix))
if math.IsInf(d.F, 1) {
*scratch = append(*scratch, "inf"...)
} else if math.IsInf(d.F, -1) {
*scratch = append(*scratch, "-inf"...)
} else {
*scratch = strconv.AppendFloat(*scratch, d.F, 'f', -1, 64)
}
*scratch = append(*scratch, delim...)
_, err := w.Write(*scratch)
o.PutBytes(scratch)
return err
}
// UnmarshalRESP implements the method for resp.Unmarshaler.
func (d *Double) UnmarshalRESP(br resp.BufferedReader, o *resp.Opts) error {
if err := readAndAssertPrefix(br, DoublePrefix, true, o); err != nil {
return err
}
b, err := bytesutil.ReadBytesDelim(br)
if err != nil {
return err
} else if d.F, err = strconv.ParseFloat(string(b), 64); err != nil {
return resp.ErrConnUsable{
Err: fmt.Errorf("failed to parse double resp %q as float: %w", b, err),
}
}
return nil
}
////////////////////////////////////////////////////////////////////////////////
// Boolean represents the boolean type in the RESP protocol.
type Boolean struct {
B bool
}
// MarshalRESP implements the method for resp.Marshaler.
func (b Boolean) MarshalRESP(w io.Writer, o *resp.Opts) error {
var err error
if b.B {
_, err = w.Write(booleanTrue)
} else {
_, err = w.Write(booleanFalse)
}
return err
}
// UnmarshalRESP implements the method for resp.Unmarshaler.
func (b *Boolean) UnmarshalRESP(br resp.BufferedReader, o *resp.Opts) error {
if err := readAndAssertPrefix(br, BooleanPrefix, true, o); err != nil {
return err
}
byt, err := bytesutil.ReadBytesDelim(br)
if err != nil {
return err
} else if len(byt) != 1 {
return errors.New("malformed boolean resp")
} else if byt[0] == 't' {
b.B = true
} else if byt[0] == 'f' {
b.B = false
} else {
return errors.New("malformed boolean resp")
}
return nil
}
////////////////////////////////////////////////////////////////////////////////
// BlobError represents the blob error type in the RESP protocol.
//
// BlobError only represents an actual error message being read/written on the
// wire, it is separate from network or parsing errors.
type BlobError struct {
B []byte
}
func (e BlobError) Error() string {
return string(e.B)
}
// MarshalRESP implements the method for resp.Marshaler.
func (e BlobError) MarshalRESP(w io.Writer, o *resp.Opts) error {
scratch := o.GetBytes()
defer o.PutBytes(scratch)
*scratch = append(*scratch, byte(BlobErrorPrefix))
*scratch = strconv.AppendInt(*scratch, int64(len(e.B)), 10)
*scratch = append(*scratch, delim...)
*scratch = append(*scratch, e.B...)
*scratch = append(*scratch, delim...)
_, err := w.Write(*scratch)
return err
}
// UnmarshalRESP implements the method for resp.Unmarshaler.
func (e *BlobError) UnmarshalRESP(br resp.BufferedReader, o *resp.Opts) error {
if err := readAndAssertPrefix(br, BlobErrorPrefix, true, o); err != nil {
return err
}
n, err := bytesutil.ReadIntDelim(br)
if err != nil {
return err
} else if n < 0 {
return fmt.Errorf("invalid blob error length: %d", n)
}
e.B = bytesutil.Expand(e.B, int(n))
if _, err := io.ReadFull(br, e.B); err != nil {
return err
} else if _, err := bytesutil.ReadBytesDelim(br); err != nil {
return err
}
return nil
}
////////////////////////////////////////////////////////////////////////////////
// VerbatimStringBytes represents the verbatim string type in the RESP protocol
// using a go byte slice. A B value of nil is an empty string.
type VerbatimStringBytes struct {
B []byte
// Format is a 3 character string describing the format that the verbatim
// string is encoded in, e.g. "txt" or "mkd". If Format is not exactly 3
// characters then MarshalRESP will error without writing anything.
Format []byte
}
// MarshalRESP implements the method for resp.Marshaler.
func (b VerbatimStringBytes) MarshalRESP(w io.Writer, o *resp.Opts) error {
if len(b.Format) != 3 {
return resp.ErrConnUsable{
Err: errors.New("format must be exactly 3 characters"),
}
}
scratch := o.GetBytes()
defer o.PutBytes(scratch)
*scratch = append(*scratch, byte(VerbatimStringPrefix))
*scratch = strconv.AppendInt(*scratch, int64(len(b.B))+4, 10)
*scratch = append(*scratch, delim...)
*scratch = append(*scratch, b.Format...)
*scratch = append(*scratch, ':')
*scratch = append(*scratch, b.B...)
*scratch = append(*scratch, delim...)
_, err := w.Write(*scratch)
return err
}
// UnmarshalRESP implements the method for resp.Unmarshaler.
func (b *VerbatimStringBytes) UnmarshalRESP(br resp.BufferedReader, o *resp.Opts) error {
if err := readAndAssertPrefix(br, VerbatimStringPrefix, true, o); err != nil {
return err
}
n, err := bytesutil.ReadIntDelim(br)
if err != nil {
return err
} else if n < 4 {
return fmt.Errorf("invalid verbatim string length: %d", n)
}
b.B = bytesutil.Expand(b.B, int(n))
if _, err := io.ReadFull(br, b.B); err != nil {
return err
} else if _, err := bytesutil.ReadBytesDelim(br); err != nil {
return err
}
b.Format, b.B = b.B[:3], b.B[4:]
return nil
}
////////////////////////////////////////////////////////////////////////////////
// VerbatimString represents the verbatim string type in the RESP protocol
// using a go string.
type VerbatimString struct {
S string
// Format is a 3 character string describing the format that the verbatim
// string is encoded in, e.g. "txt" or "mkd". If Format is not exactly 3
// characters then MarshalRESP will error without writing anything.
Format string
}
// MarshalRESP implements the method for resp.Marshaler.
func (b VerbatimString) MarshalRESP(w io.Writer, o *resp.Opts) error {
if len(b.Format) != 3 {
return resp.ErrConnUsable{
Err: errors.New("format must be exactly 3 characters"),
}
}
scratch := o.GetBytes()
defer o.PutBytes(scratch)
*scratch = append(*scratch, byte(VerbatimStringPrefix))
*scratch = strconv.AppendInt(*scratch, int64(len(b.S))+4, 10)
*scratch = append(*scratch, delim...)
*scratch = append(*scratch, b.Format...)
*scratch = append(*scratch, ':')
*scratch = append(*scratch, b.S...)
*scratch = append(*scratch, delim...)
_, err := w.Write(*scratch)
return err
}
// UnmarshalRESP implements the method for resp.Unmarshaler.
func (b *VerbatimString) UnmarshalRESP(br resp.BufferedReader, o *resp.Opts) error {
if err := readAndAssertPrefix(br, VerbatimStringPrefix, true, o); err != nil {
return err
}
n, err := bytesutil.ReadIntDelim(br)
if err != nil {
return err
} else if n < 4 {
return fmt.Errorf("invalid verbatim string length: %d", n)
}
scratch := o.GetBytes()
defer o.PutBytes(scratch)
*scratch = bytesutil.Expand(*scratch, int(n))
if _, err := io.ReadFull(br, *scratch); err != nil {
return err
} else if _, err := bytesutil.ReadBytesDelim(br); err != nil {
return err
}
b.Format = string((*scratch)[:3])
b.S = string((*scratch)[4:])
return nil
}
////////////////////////////////////////////////////////////////////////////////
// BigNumber represents the big number type in the RESP protocol. Marshaling a
// nil I value will cause a panic.
type BigNumber struct {
I *big.Int
}
// MarshalRESP implements the method for resp.Marshaler.
func (b BigNumber) MarshalRESP(w io.Writer, o *resp.Opts) error {
scratch := o.GetBytes()
defer o.PutBytes(scratch)
*scratch = append(*scratch, byte(BigNumberPrefix))
*scratch = b.I.Append(*scratch, 10)
*scratch = append(*scratch, delim...)
_, err := w.Write(*scratch)
return err
}
// UnmarshalRESP implements the method for resp.Unmarshaler.
func (b *BigNumber) UnmarshalRESP(br resp.BufferedReader, o *resp.Opts) error {
if err := readAndAssertPrefix(br, BigNumberPrefix, true, o); err != nil {
return err
}
byt, err := bytesutil.ReadBytesDelim(br)
if err != nil {
return err
} else if b.I == nil {
b.I = new(big.Int)
}
var ok bool
if b.I, ok = b.I.SetString(string(byt), 10); !ok {
return fmt.Errorf("malformed big number: %q", byt)
}
return nil
}
////////////////////////////////////////////////////////////////////////////////
func marshalAggHeader(w io.Writer, prefix Prefix, n int, streamHeader bool, o *resp.Opts) error {
scratch := o.GetBytes()
defer o.PutBytes(scratch)
*scratch = append(*scratch, byte(prefix))
if streamHeader {
*scratch = append(*scratch, streamHeaderSize...)
} else {
*scratch = strconv.AppendInt(*scratch, int64(n), 10)
}
*scratch = append(*scratch, delim...)
_, err := w.Write(*scratch)
return err
}
type unmarshalAggHeaderParams struct {
br resp.BufferedReader
prefix Prefix
n *int
streamHeader *bool
opts *resp.Opts
discardAttr bool
allowNegativeOne bool
}
func unmarshalAggHeader(params unmarshalAggHeaderParams) error {
if err := readAndAssertPrefix(params.br, params.prefix, params.discardAttr, params.opts); err != nil {
return err
}
b, err := bytesutil.ReadBytesDelim(params.br)
if err != nil {
return err
} else if params.streamHeader != nil {
if *params.streamHeader = bytes.Equal(b, streamHeaderSize); *params.streamHeader {
*params.n = 0
return nil
}
*params.streamHeader = false
}
n64, err := bytesutil.ParseInt(b)
if err != nil {
return err
} else if n64 == -1 && params.allowNegativeOne {
n64 = 0
} else if n64 < 0 {
return fmt.Errorf("invalid number of elements: %d", n64)
}
*params.n = int(n64)
return nil
}
////////////////////////////////////////////////////////////////////////////////
// ArrayHeader represents the header sent preceding array elements in the RESP
// protocol. ArrayHeader only declares how many elements are in the array
// message.
//
// ArrayHeader can also be used as the header of a streamed array, whose size is
// not known in advance, by setting StreamedArrayHeader instead of NumElems.
//
// ArrayHeader will unmarshal a RESP2 nil array as an array of length zero.
type ArrayHeader struct {
NumElems int
// StreamedArrayHeader indicates that this message is the header message of
// a streamed array. It is mutually exclusive with NumElems.
StreamedArrayHeader bool
}
// MarshalRESP implements the method for resp.Marshaler.
func (h ArrayHeader) MarshalRESP(w io.Writer, o *resp.Opts) error {
return marshalAggHeader(w, ArrayHeaderPrefix, h.NumElems, h.StreamedArrayHeader, o)
}
// UnmarshalRESP implements the method for resp.Unmarshaler.
func (h *ArrayHeader) UnmarshalRESP(br resp.BufferedReader, o *resp.Opts) error {
return unmarshalAggHeader(unmarshalAggHeaderParams{
br: br,
prefix: ArrayHeaderPrefix,
n: &h.NumElems,
streamHeader: &h.StreamedArrayHeader,
discardAttr: true,
allowNegativeOne: true,
opts: o,
})
}
////////////////////////////////////////////////////////////////////////////////
// MapHeader represents the header sent preceding map elements in the RESP
// protocol. MapHeader only declares how many elements are in the map message.
//
// MapHeader can also be used as the header of a streamed array, whose size is
// not known in advance, by setting StreamedMapHeader instead of NumElems.
type MapHeader struct {
NumPairs int
// StreamedMapHeader indicates that this message is the header message of
// a streamed map. It is mutually exclusive with NumPairs.
StreamedMapHeader bool
}
// MarshalRESP implements the method for resp.Marshaler.
func (h MapHeader) MarshalRESP(w io.Writer, o *resp.Opts) error {
return marshalAggHeader(w, MapHeaderPrefix, h.NumPairs, h.StreamedMapHeader, o)
}
// UnmarshalRESP implements the method for resp.Unmarshaler.
func (h *MapHeader) UnmarshalRESP(br resp.BufferedReader, o *resp.Opts) error {
return unmarshalAggHeader(unmarshalAggHeaderParams{
br: br,
prefix: MapHeaderPrefix,
n: &h.NumPairs,
streamHeader: &h.StreamedMapHeader,
discardAttr: true,
opts: o,
})
}
////////////////////////////////////////////////////////////////////////////////
// SetHeader represents the header sent preceding set elements in the RESP