forked from qitab/cl-protobufs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwire-format.lisp
1195 lines (1123 loc) · 54.2 KB
/
wire-format.lisp
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 2012-2020 Google LLC
;;;
;;; Use of this source code is governed by an MIT-style
;;; license that can be found in the LICENSE file or at
;;; https://opensource.org/licenses/MIT.
(in-package #:cl-protobufs.implementation)
(eval-when (:compile-toplevel :load-toplevel :execute)
;; Warning: see comment at the top of utilities.lisp about these settings.
(defparameter $optimize-serialization *optimize-fast-unsafe*) ; NOLINT
(defconstant $wire-type-varint 0)
(defconstant $wire-type-64bit 1)
(defconstant $wire-type-string 2)
(defconstant $wire-type-start-group 3) ;supposedly deprecated, but no such luck
(defconstant $wire-type-end-group 4) ;supposedly deprecated
(defconstant $wire-type-32bit 5)
) ; eval-when
(defun-inline make-wire-tag (wire-type field-number)
"Create a protobuf field tag, the combination of a WIRE-TYPE (3 bits) and a
FIELD-NUMBER (29 bits, minimum value 1) that precedes the field data itself."
(declare (type (unsigned-byte 3) wire-type)
(type field-number field-number))
(the (unsigned-byte 32)
(ilogior wire-type (iash field-number 3))))
(defun make-tag (type index)
"Given the name of a protobuf type (a keyword symbol) and a field index,
return the field tag that encodes both of them."
(declare (type field-number index))
(locally (declare #.$optimize-serialization)
(let ((tag-bits (ecase type
((int32 uint32) $wire-type-varint)
((int64 uint64) $wire-type-varint)
((sint32 sint64) $wire-type-varint)
((fixed32 sfixed32) $wire-type-32bit)
((fixed64 sfixed64) $wire-type-64bit)
((string byte-vector) $wire-type-string)
((boolean) $wire-type-varint)
((float) $wire-type-32bit)
((double-float) $wire-type-64bit)
;; A few of our homegrown types
((symbol) $wire-type-string)
((date time datetime timestamp) $wire-type-64bit))))
(declare (type (unsigned-byte 3) tag-bits))
(make-wire-tag tag-bits index))))
(define-compiler-macro make-tag (&whole form type index)
(cond ((typep type 'fixnum)
`(ilogior ,type (iash ,index 3)))
((keywordp type)
(let ((type (ecase type
((int32 uint32) $wire-type-varint)
((int64 uint64) $wire-type-varint)
((sint32 sint64) $wire-type-varint)
((fixed32 sfixed32) $wire-type-32bit)
((fixed64 sfixed64) $wire-type-64bit)
((string byte-vector) $wire-type-string)
((boolean) $wire-type-varint)
((float) $wire-type-32bit)
((double-float) $wire-type-64bit)
;; A few of our homegrown types
((symbol) $wire-type-string)
((date time datetime timestamp) $wire-type-64bit))))
`(ilogior ,type (iash ,index 3))))
(t form)))
(defun packed-tag (index)
"Takes a field number, INDEX, and returns a tag for a packed field with that same index."
(declare (type field-number index))
(make-wire-tag $wire-type-string index))
(defun length-encoded-tag-p (tag)
"Returns non-nil if TAG represents a length-encoded field.
Otherwise nil."
(declare (type (unsigned-byte 32) tag))
(= $wire-type-string (ldb (byte 3 0) tag)))
(defmacro gen-zig-zag (bits)
"Generate 32- or 64-bit versions of zig-zag encoder/decoder."
(assert (and (plusp bits) (zerop (mod bits 8))))
(let* ((zig-zag-encode (fintern "~A~A" 'zig-zag-encode bits))
(zig-zag-decode (fintern "~A~A" 'zig-zag-decode bits))
(zig-zag-shift (1+ (- bits))))
`(progn
(defun ,zig-zag-encode (val)
(declare #.$optimize-serialization)
(declare (type (signed-byte ,bits) val))
(logxor (ash val 1) (ash val ,zig-zag-shift)))
(define-compiler-macro ,zig-zag-encode (&whole form val)
(if (atom val)
`(locally (declare #.$optimize-serialization
(type (signed-byte ,',bits) ,val))
(logxor (ash ,val 1) (ash ,val ,',zig-zag-shift)))
form))
(defun ,zig-zag-decode (val)
(declare #.$optimize-serialization)
(declare (type (unsigned-byte ,bits) val))
(logxor (ash val -1) (- (logand val 1))))
(define-compiler-macro ,zig-zag-decode (&whole form val)
(if (atom val)
`(locally (declare #.$optimize-serialization
(type (unsigned-byte ,',bits) ,val))
(logxor (ash ,val -1) (- (logand ,val 1))))
form)))))
(gen-zig-zag 32)
(gen-zig-zag 64)
;;; Serializers
;; Serialize 'val' of scalar type 'type' into the buffer
(declaim (ftype (function (t t (unsigned-byte 32) t) (values fixnum &optional))
serialize-scalar))
(defun serialize-scalar (val type tag buffer)
"Serializes a Protobufs scalar value into the buffer at the given index.
Modifies the buffer in place, and returns the new index into the buffer.
Watch out, this function turns off most type checking and all array bounds checking.
Parameters:
VAL: The value to serialize.
TYPE: The type of VAL.
TAG: The protobuf tag to serialize.
BUFFER: The buffer to serialize to."
(declare (type (unsigned-byte 32) tag))
(locally (declare #.$optimize-serialization)
(i+
(encode-uint32 tag buffer)
(ecase type
((int32 uint32) (encode-uint32 (ldb (byte 32 0) val) buffer))
(uint64 (encode-uint64 val buffer))
(int64 (encode-int64 val buffer))
(sint32 (encode-uint32 (zig-zag-encode32 val) buffer))
(sint64 (encode-uint64 (zig-zag-encode64 val) buffer))
(fixed32 (encode-fixed32 val buffer))
(sfixed32 (encode-sfixed32 val buffer))
(fixed64 (encode-fixed64 val buffer))
(sfixed64 (encode-sfixed64 val buffer))
(string (encode-string val buffer))
(byte-vector (encode-octets val buffer))
(boolean (encode-uint32 (if val 1 0) buffer))
(float (encode-single val buffer))
(double-float (encode-double val buffer))
;; A few of our homegrown types
(symbol
;; XXX: This implementation is bad. Should write one uint32 for the sum of
;; lengths of package-name and symbol-name plus 1, then the tokens.
(encode-string (lisp-symbol-string val) buffer))
((date time datetime timestamp)
(encode-int64 val buffer))))))
(defun get-scalar-encoder-form (type val buffer)
"Returns a form that encodes a value VAL with type TYPE to buffer BUFFER."
(and (consp type)
(eq (car type) 'quote)
(case (second type)
(uint32 `(encode-uint32 ,val ,buffer))
(uint64 `(encode-uint64 ,val ,buffer))
(int32 `(encode-uint32 (ldb (byte 32 0) ,val) ,buffer))
(int64 `(encode-int64 ,val ,buffer))
(sint32 `(encode-uint32 (zig-zag-encode32 ,val) ,buffer))
(sint64 `(encode-uint64 (zig-zag-encode64 ,val) ,buffer))
(fixed32 `(encode-fixed32 ,val ,buffer))
(sfixed32 `(encode-sfixed32 ,val ,buffer))
(fixed64 `(encode-fixed64 ,val ,buffer))
(sfixed64 `(encode-sfixed64 ,val ,buffer))
(string `(encode-string ,val ,buffer))
(boolean `(encode-uint32 (if ,val 1 0) ,buffer))
(float `(encode-single ,val ,buffer))
(byte-vector `(encode-octets ,val ,buffer))
(double-float `(encode-double ,val ,buffer)))))
(defun get-scalar-encoder-function (type)
"Given a type TYPE, return a function that takes a value of type TYPE
and a buffer which encodes the value to the buffer."
(ecase type
(uint32 #'encode-uint32)
(uint64 #'encode-uint64)
(int32 (lambda (val b) (encode-uint32 (ldb (byte 32 0) val) b)))
(int64 #'encode-int64)
;; FIXME: should bury the zigzag algorithm into a specialized encoder.
;; Now we're consing bignums to pass to encode-uint64.
(sint32 (lambda (val b) (encode-uint32 (zig-zag-encode32 val) b)))
(sint64 (lambda (val b) (encode-uint64 (zig-zag-encode64 val) b)))
(fixed32 #'encode-fixed32)
(sfixed32 #'encode-sfixed32)
(fixed64 #'encode-fixed64)
(sfixed64 #'encode-sfixed64)
(boolean (lambda (val b) (encode-uint32 (if val 1 0) b)))
(float #'encode-single)
(double-float #'encode-double)))
(define-compiler-macro serialize-scalar (&whole form val type tag buffer)
(let ((encoder (get-scalar-encoder-form type val buffer)))
(if encoder
`(locally (declare #.$optimize-serialization)
(+ (encode-uint32 ,tag ,buffer) ,encoder))
form)))
(declaim (ftype (function (t t &optional t) (values fixnum &optional))
packed-size))
(defun serialize-packed (values type index buffer &optional vectorp)
"Serializes a set of packed VALUES of scalar type TYPE into BUFFER starting
at the given INDEX. Modifies the buffer in place, and returns the new index
into the buffer."
(declare (type (unsigned-byte 32) index))
(locally (declare #.$optimize-serialization)
#+sbcl (declare (notinline packed-size))
(when (zerop (length values))
(return-from serialize-packed 0))
;; It's not helpful to "inline" N different calls to MAP if the sequence
;; type is unknown - MAP can't be inlined in that case, so has to
;; act as a higher-order function. We can do slightly better by
;; actually specializing for two subtypes of sequence though.
;; Of course, we *could* dispatch on both the sequence type and the
;; scalar wire type, to create 22 (= 11 x 2) cases,
;; but I'm too lazy to hand-roll that, or even think of a macroish way.
(let* ((encoder (get-scalar-encoder-function type))
(tag-len (encode-uint32 (packed-tag index) buffer))
(payload-len (packed-size values type))
(prefix-len (encode-uint32 payload-len buffer))
(sum 0)) ; for double-check
(declare (fixnum sum))
(cond (vectorp
(assert (vectorp values))
(loop for x across values
;; This is a work-around for a bug in a client library that
;; starts with 'Q' and should eventually be removed. The
;; caller should be supplying a sequence of numeric scalars.
while x
do (iincf sum (funcall encoder x buffer))))
(t
(assert (listp values))
(dolist (x values)
(iincf sum (funcall encoder x buffer)))))
(assert (= sum payload-len))
(i+ tag-len prefix-len payload-len))))
;; The optimized serializers supply 'vectorp' so we can generate better code
;; In SBCL this would be better as a transform sensitive to the type of VALUES.
;; I mean, really, an argument that decides if another argument is a vector? WTF?!
;; ... you must be new here :)
;; TODO(cgay): The semantics of the arguments here are totally different than for
;; the function by the same name. Can we make this a regular macro with a different
;; name?
(define-compiler-macro serialize-packed (&whole form values type index buffer
&optional (vectorp nil vectorp-supplied-p))
(if vectorp-supplied-p
(let ((encode (or (get-scalar-encoder-form type 'val buffer)
(error 'unknown-type
:format-control "No scalar encoder for ~S"
:format-arguments (list type)))))
;; FIXME: probably should have ONCE-ONLY for BUFFER
;; [Same goes for a lot of the compiler macros]
`(locally (declare #.$optimize-serialization)
(if (zerop (length ,values)) 0
;; else
(let* ((tag-len (encode-uint32 (packed-tag ,index) ,buffer))
(payload-len (packed-size ,values ,type ,vectorp))
(prefix-len (encode-uint32 payload-len ,buffer))
(sum 0)) ; for double-check
(declare (fixnum sum))
(,(if vectorp 'dovector 'dolist) (val ,values) (iincf sum ,encode))
(assert (= sum payload-len))
(i+ tag-len prefix-len payload-len)))))
form))
(defun-inline find-enum-value (name value-descriptors)
"Find the enum value corresponding to NAME by searching for it in
VALUE-DESCRIPTORS."
(declare (type keyword name))
(let* ((desc (find name value-descriptors :key #'enum-value-descriptor-name)))
(the sfixed32
(if desc
(enum-value-descriptor-value desc)
(parse-integer (cadr (split-string (symbol-name name))))))))
(defun-inline find-enum-name (value value-descriptors)
"Find the enum name corresponding to VALUE by searching for it in
VALUE-DESCRIPTORS."
(declare (type sfixed32 value))
(let* ((desc (find value value-descriptors :key #'enum-value-descriptor-value)))
(the keyword
(if desc
(enum-value-descriptor-name desc)
(kintern "~a-~a" "%UNDEFINED" value)))))
(defun serialize-enum (name value-descriptors tag buffer)
"Serializes the protobuf enum value corresponding to NAME (a keyword symbol)
into BUFFER. The enum values are in VALUE-DESCRIPTORS. Modifies BUFFER in
place, and returns the new index into the buffer. TAG is the protobuf field
number with wire-type tag bits added. Watch out, this function turns off
most type checking and all array bounds checking."
(declare (type list value-descriptors)
(type (unsigned-byte 32) tag))
(locally (declare #.$optimize-serialization)
(let ((val (find-enum-value name value-descriptors)))
(declare (type (unsigned-byte 32) val))
(i+ (encode-uint32 tag buffer) (encode-uint32 val buffer)))))
(defun serialize-packed-enum (names value-descriptors index buffer)
"Serializes protobuf enum values corresponding to NAMES (keyword symbols)
into BUFFER at the given INDEX. The enum value descriptors are in
VALUE-DESCRIPTORS. Modifies BUFFER in place, and returns the new index into
the buffer. Watch out, this function turns off most type checking and all
array bounds checking."
(declare (type list value-descriptors)
(type (unsigned-byte 32) index))
(when (zerop (length names))
(return-from serialize-packed-enum 0))
(locally (declare #.$optimize-serialization)
(let* ((tag-len (encode-uint32 (packed-tag index) buffer))
(payload-len (packed-enum-size names value-descriptors))
(prefix-len (encode-uint32 payload-len buffer))
(sum 0)) ; for double-check
(declare (type fixnum sum))
(map nil
(lambda (name)
(let ((val (find-enum-value name value-descriptors)))
(declare (type (unsigned-byte 32) val))
(iincf sum (encode-uint32 (ldb (byte 32 0) val) buffer))))
names)
(assert (= sum payload-len))
(i+ tag-len prefix-len payload-len))))
;;; Deserializers
;;; Wire-level decoders
;;; These are called at the lowest level, so arg types are assumed to be correct
(declaim (ftype (function ((simple-array (unsigned-byte 8) (*)) array-index
(unsigned-byte 14) (member 32 64))
(values integer array-index))
%decode-rest-of-uint))
(defun %decode-rest-of-uint (buffer index start-value max-bits)
"Decodes the rest of the 64-bit varint integer in the BUFFER at the given INDEX.
Assumes that the first two bytes of the integer have already been read from the buffer,
resulting in START-VALUE.
Returns both the decoded value and the new index into the buffer, and checks that the value fits
in MAX-BITS.
Watch out, this function turns off all type checking and array bounds checking."
(declare #.$optimize-serialization)
(let ((idx index))
(flet ((get-byte ()
(prog1 (aref buffer (the array-index idx))
(iincf idx)))
(return-as-correct-size (value)
;; Negative numbers are always encoded as ten bytes. We need to
;; return just the MAX-BITS low bits.
(return-from %decode-rest-of-uint (values (ldb (byte max-bits 0) value) idx))))
(let ((fixnum-bits (* (floor (integer-length most-negative-fixnum) 7) 7))
(bits-read 14)
(low-word start-value))
(declare (type fixnum low-word fixnum-bits))
;; Read as much as we can fit in a fixnum, and return as soon as we're done
(loop for place from bits-read by 7 below fixnum-bits
for byte fixnum = (get-byte)
for bits = (ildb (byte 7 0) byte)
do (setq low-word (ilogior (the fixnum low-word) (the fixnum (iash bits place))))
(when (i< byte 128)
(return-as-correct-size low-word)))
;; Value doesn't fit into a fixnum. Read any additional values into another fixnum, and then
;; shift left and add to the low fixnum.
(let ((high-word 0))
(declare (type fixnum high-word))
(loop for place from 0 by 7 below fixnum-bits
for byte fixnum = (get-byte)
for bits = (ildb (byte 7 0) byte)
do (setq high-word (ilogior (the fixnum high-word) (the fixnum (iash bits place))))
(when (i< byte 128)
(return-as-correct-size (+ (ash high-word fixnum-bits) low-word)))))
;; We shouldn't get here unless we're reading a value that doesn't fit in two fixnums.
(assert nil nil "The value doesn't fit into ~A bits" (* 2 fixnum-bits))))))
;; TODO(jgodbout): Find all of the different instances of word-size
;; for each language, make a defconstant for word-size, then use it.
(declaim (ftype (function ((simple-array (unsigned-byte 8) (*)) array-index)
(values (unsigned-byte 64) array-index))
decode-varint)
(inline decode-varint))
(defun decode-varint (a index)
"Decode the varint in buffer A at INDEX."
(let ((word 0))
(declare (type (simple-array (unsigned-byte 8) (*)) a)
#+sbcl (type sb-ext:word word)
#+sbcl (type sb-int:index index)
(optimize (safety 0)))
(let ((shift 0)
(idx index))
(dotimes (i 10)
(let ((byte (aref a idx)))
(incf idx)
(setf word
(logior (logand (ash (logand byte 127) (the (mod 64) shift))
#+sbcl sb-ext:most-positive-word)
word))
(unless (logbitp 7 byte) (return)))
(incf shift 7))
(values word idx))))
;; Decode the value from the buffer at the given index,
;; then return the value and new index into the buffer
;; These produce a storm of efficiency notes in SBCL.
(defmacro generate-integer-decoders (bits)
"Generate 32- or 64-bit versions of integer decoders, specified by BITS."
(assert (and (plusp bits) (zerop (mod bits 8))))
(let* ((decode-uint (fintern "~A~A" 'decode-uint bits))
(decode-int (fintern "~A~A" 'decode-int bits))
(decode-fixed (fintern "~A~A" 'decode-fixed bits))
(decode-sfixed (fintern "~A~A" 'decode-sfixed bits))
(bytes (/ bits 8))
;; Given bits, can we use fixnums safely?
(fixnump (<= bits (integer-length most-negative-fixnum)))
(ldb (if fixnump 'ildb 'ldb))
(ash (if fixnump 'iash 'ash))
(decf (if fixnump 'idecf 'decf))
(logior (if fixnump 'ilogior 'logior)))
`(progn
(declaim (ftype (function ((simple-array (unsigned-byte 8) (*)) array-index)
(values (unsigned-byte ,bits) array-index))
,decode-uint)
(inline ,decode-uint))
(defun ,decode-uint (buffer index)
,(format
nil
"Decodes the next ~A-bit varint integer in the buffer at the given index.~
~& Returns both the decoded value and the new index into the buffer.~
~& Watch out, this function turns off all type checking and array bounds checking."
bits)
(declare #.$optimize-serialization)
(multiple-value-bind (val new-index)
(decode-varint buffer index)
,(when (= bits 32)
`(setf val (ildb (byte ,bits 0) val)))
(values val new-index)))
(declaim (ftype (function ((simple-array (unsigned-byte 8) (*)) array-index)
(values (signed-byte ,bits) array-index))
,decode-int)
(inline ,decode-int))
(defun ,decode-int (buffer index)
,(format
nil
"Decodes the next ~A-bit varint integer in the buffer at the given index.~
~& Returns both the decoded value and the new index into the buffer.~
~& Watch out, this function turns off all type checking and array bounds checking."
bits)
(declare #.$optimize-serialization)
(declare (type (simple-array (unsigned-byte 8) (*)) buffer)
(array-index index))
(multiple-value-bind (val new-index)
(decode-varint buffer index)
(declare (type array-index new-index))
(if (i= (ldb (byte 1 ,(1- bits)) val) 1)
(values (the (signed-byte ,bits) (logior val ,(ash -1 bits))) new-index)
(values val new-index))))
(defun ,decode-fixed (buffer index)
,(format
nil
"Decodes the next ~A-bit unsigned fixed integer in the buffer at the given index.~
~& Returns both the decoded value and the new index into the buffer.~
~& Watch out, this function turns off all type checking and array bounds checking."
bits)
(declare #.$optimize-serialization)
(declare (type (simple-array (unsigned-byte 8) (*)) buffer)
(array-index index))
;; Eight bits at a time, least significant bits first
(let ((val 0))
,@(when fixnump `((declare (type fixnum val))))
(loop repeat ,bytes
for places fixnum upfrom 0 by 8
for byte fixnum = (prog1 (aref buffer index) (iincf index))
do (setq val (,logior val (,ash byte places))))
(values val index)))
(defun ,decode-sfixed (buffer index)
,(format
nil
"Decodes the next ~A-bit signed fixed integer in the buffer at the given index.~
~& Returns both the decoded value and the new index into the buffer.~
~& Watch out, this function turns off all type checking and array bounds checking."
bits)
(declare #.$optimize-serialization)
(declare (type (simple-array (unsigned-byte 8) (*)) buffer)
(array-index index))
;; Eight bits at a time, least significant bits first
(let ((val 0))
,@(when fixnump `((declare (type fixnum val))))
(loop repeat ,bytes
for places fixnum upfrom 0 by 8
for byte fixnum = (prog1 (aref buffer index) (iincf index))
do (setq val (,logior val (,ash byte places))))
(when (i= (,ldb (byte 1 ,(1- bits)) val) 1) ; sign bit set, so negative value
(,decf val ,(ash 1 bits)))
(values val index))))))
(generate-integer-decoders 32)
(generate-integer-decoders 64)
;; Deserialize the next object of type 'type'
;; FIXME: most of these are bad. QPX does not do much decoding,
;; so I'll not touch them for the time being.
(defun deserialize-scalar (type buffer index)
"Deserializes the next object of scalar type TYPE.
Deserializes from the byte vector BUFFER starting at INDEX.
Returns the value and the new index into the buffer.
Watch out, this function turns off most type checking and all array bounds checking."
(declare (type (simple-array (unsigned-byte 8) (*)) buffer)
(array-index index))
(locally (declare #.$optimize-serialization)
(ecase type
(int32 (decode-int32 buffer index))
(int64 (decode-int64 buffer index))
(uint32 (decode-uint32 buffer index))
(uint64 (decode-uint64 buffer index))
(sint32 (multiple-value-bind (val idx)
(decode-uint32 buffer index)
(values (zig-zag-decode32 val) idx)))
(sint64 (multiple-value-bind (val idx)
(decode-uint64 buffer index)
(values (zig-zag-decode64 val) idx)))
(fixed32 (decode-fixed32 buffer index))
(sfixed32 (decode-sfixed32 buffer index))
(fixed64 (decode-fixed64 buffer index))
(sfixed64 (decode-sfixed64 buffer index))
(string (decode-string buffer index))
(byte-vector (decode-octets buffer index))
(boolean (multiple-value-bind (val idx)
(decode-uint32 buffer index)
(values (if (i= val 0) nil t) idx)))
(float (decode-single buffer index))
(double-float (decode-double buffer index))
;; A few of our homegrown types
((symbol)
;; Note that this is consy, avoid it if possible
;; XXX: This needn't cons. Just make strings displaced
;; to the data buffer.
(multiple-value-bind (val idx)
(decode-string buffer index)
(values (make-lisp-symbol val) idx)))
((date time datetime timestamp)
(decode-uint64 buffer index)))))
(define-compiler-macro deserialize-scalar (&whole form type buffer index)
(let ((decoder
(case type
(int32 `(decode-int32 ,buffer ,index))
(int64 `(decode-int64 ,buffer ,index))
(uint32 `(decode-uint32 ,buffer ,index))
(uint64 `(decode-uint64 ,buffer ,index))
(sint32 `(multiple-value-bind (val idx)
(decode-uint32 ,buffer ,index)
(values (zig-zag-decode32 val) idx)))
(sint64 `(multiple-value-bind (val idx)
(decode-uint64 ,buffer ,index)
(values (zig-zag-decode64 val) idx)))
(fixed32 `(decode-fixed32 ,buffer ,index))
(sfixed32 `(decode-sfixed32 ,buffer ,index))
(fixed64 `(decode-fixed64 ,buffer ,index))
(sfixed64 `(decode-sfixed64 ,buffer ,index))
(string `(decode-string ,buffer ,index))
(byte-vector `(decode-octets ,buffer ,index))
(boolean `(multiple-value-bind (val idx)
(decode-uint32 ,buffer ,index)
(values (if (i= val 0) nil t) idx)))
(float `(decode-single ,buffer ,index))
(double-float `(decode-double ,buffer ,index)))))
(if decoder
;; The type declaration of BUFFER is essentially useless since these are
;; all out-of-line calls to unsafe functions, and we're not imparting any
;; more safety because this also elides type-checks.
`(locally (declare #.$optimize-serialization
(type (simple-array (unsigned-byte 8) (*)) ,buffer)
(type fixnum ,index))
,decoder)
form)))
(defun deserialize-packed (type buffer index)
"Deserializes the next packed values of type 'type'.
Deserializes from the byte vector 'buffer' starting at 'index'.
Returns the value and the new index into the buffer.
Watch out, this function turns off most type checking and all array bounds checking."
(declare (type (simple-array (unsigned-byte 8) (*)) buffer)
(array-index index))
(locally (declare #.$optimize-serialization)
(multiple-value-bind (len idx)
(decode-uint32 buffer index)
(declare (type (unsigned-byte 32) len)
(type fixnum idx))
(let ((end (i+ idx len)))
(declare (type (unsigned-byte 32) end))
(with-collectors ((values collect-value))
(loop
(when (>= idx end)
(return-from deserialize-packed (values values idx)))
(multiple-value-bind (val nidx)
(ecase type
((int32)
(decode-int32 buffer idx))
((int64)
(decode-int64 buffer idx))
((uint32)
(decode-uint32 buffer idx))
((uint64)
(decode-uint64 buffer idx))
((sint32)
(multiple-value-bind (val nidx)
(decode-uint32 buffer idx)
(values (zig-zag-decode32 val) nidx)))
((sint64)
(multiple-value-bind (val nidx)
(decode-uint64 buffer idx)
(values (zig-zag-decode64 val) nidx)))
((fixed32)
(decode-fixed32 buffer idx))
((sfixed32)
(decode-sfixed32 buffer idx))
((fixed64)
(decode-fixed64 buffer idx))
((sfixed64)
(decode-sfixed64 buffer idx))
((boolean)
(multiple-value-bind (val nidx)
(decode-uint32 buffer idx)
(values (if (i= val 0) nil t) nidx)))
((float)
(decode-single buffer idx))
((double-float)
(decode-double buffer idx)))
(collect-value val)
(setq idx nidx))))))))
(define-compiler-macro deserialize-packed (&whole form type buffer index)
(if (member type '(int32 uint32 int64 uint64 sint32 sint64
fixed32 sfixed32 fixed64 sfixed64
boolean float double-float))
`(locally (declare #.$optimize-serialization
(type (simple-array (unsigned-byte 8) (*)) ,buffer)
(type fixnum ,index))
(block deserialize-packed
(multiple-value-bind (len idx)
(decode-uint32 ,buffer ,index)
(declare (type (unsigned-byte 32) len)
(type fixnum idx))
(let ((end (i+ idx len)))
(declare (type (unsigned-byte 32) end))
(with-collectors ((values collect-value))
(loop
(when (>= idx end)
(return-from deserialize-packed (values values idx)))
(multiple-value-bind (val nidx)
,(ecase type
((int32)
`(decode-int32 ,buffer idx))
((int64)
`(decode-int64 ,buffer idx))
((uint32)
`(decode-uint32 ,buffer idx))
((uint64)
`(decode-uint64 ,buffer idx))
((sint32)
`(multiple-value-bind (val nidx)
(decode-uint32 ,buffer idx)
(values (zig-zag-decode32 val) nidx)))
((sint64)
`(multiple-value-bind (val nidx)
(decode-uint64 ,buffer idx)
(values (zig-zag-decode64 val) nidx)))
((fixed32)
`(decode-fixed32 ,buffer idx))
((sfixed32)
`(decode-sfixed32 ,buffer idx))
((fixed64)
`(decode-fixed64 ,buffer idx))
((sfixed64)
`(decode-sfixed64 ,buffer idx))
((boolean)
`(multiple-value-bind (val nidx)
(decode-uint32 ,buffer idx)
(values (if (i= val 0) nil t) nidx)))
((float)
`(decode-single ,buffer idx))
((double-float)
`(decode-double ,buffer idx)))
(collect-value val)
(setq idx nidx))))))))
form))
(defun deserialize-enum (value-descriptors buffer index)
"Deserializes the next enum value taken from VALUE-DESCRIPTORS.
Deserializes from the byte vector BUFFER starting at INDEX.
Returns the enum value name (a keyword symbol) and the new index into the buffer.
Watch out, this function turns off most type checking and all array bounds checking."
(declare (type list value-descriptors)
(type (simple-array (unsigned-byte 8) (*)) buffer)
(array-index index))
(locally (declare #.$optimize-serialization)
(multiple-value-bind (val idx)
(decode-int32 buffer index)
(let ((name (find-enum-name val value-descriptors)))
(values (the keyword name) idx)))))
(defun deserialize-packed-enum (value-descriptors buffer index)
"Deserializes the next packed enum value given in VALUE-DESCRIPTORS.
Deserializes from the byte vector BUFFER starting at INDEX. Returns the
enum value name (a keyword symbol) and the new index into the buffer. Watch
out, this function turns off most type checking and all array bounds
checking."
(declare (type list value-descriptors)
(type (simple-array (unsigned-byte 8) (*)) buffer)
(array-index index))
(locally (declare #.$optimize-serialization)
(multiple-value-bind (len idx)
(decode-uint32 buffer index)
(declare (type (unsigned-byte 32) len)
(type fixnum idx))
(let ((end (i+ idx len)))
(declare (type (unsigned-byte 32) end))
(with-collectors ((names collect-name))
(loop
(when (>= idx end)
(return-from deserialize-packed-enum (values names idx)))
(multiple-value-bind (val nidx)
(decode-int32 buffer idx)
(collect-name (find-enum-name val value-descriptors))
(setq idx nidx))))))))
(defun packed-size (values type &optional vectorp)
"Returns the size in bytes that the packed object will take when serialized.
Watch out, this function turns off most type checking."
(declare (ignore vectorp))
(locally (declare #.$optimize-serialization)
(let ((sum 0))
(declare (type fixnum sum))
(map nil
(lambda (val)
(iincf sum (ecase type
((int32 uint32) (length32 val))
((int64 uint64) (length64 val))
((sint32) (length32 (zig-zag-encode32 val)))
((sint64) (length64 (zig-zag-encode64 val)))
((fixed32 sfixed32) 4)
((fixed64 sfixed64) 8)
((boolean) 1)
((float) 4)
((double-float) 8))))
values)
sum)))
;; The optimized serializers supply 'vectorp' so we can generate better code
(define-compiler-macro packed-size (&whole form values type
&optional (vectorp nil vectorp-p))
(let ((size-form
(case type
(int32 `(length32 val))
(int64 `(length64 val))
(uint32 `(length32 val))
(uint64 `(length64 val))
(sint32 `(length32 (zig-zag-encode32 val)))
(sint64 `(length64 (zig-zag-encode64 val)))
((fixed32 sfixed32) 4)
((fixed64 sfixed64) 8)
(boolean 1)
(float 4)
(double-float 8))))
(if (and vectorp-p size-form)
`(locally (declare #.$optimize-serialization)
(let ((sum 0))
(declare (type fixnum sum))
(,(if vectorp 'dovector 'dolist) (val ,values) (iincf sum ,size-form))
sum))
form)))
(defun packed-enum-size (names value-descriptors)
"Returns the size in bytes that the enum values corresponding to
NAMES (keyword symbols) will take when serialized. VALUE-DESCRIPTORS are the
enum-value-descriptor objects for the enum."
(declare (type list value-descriptors))
(let ((sum 0))
(declare (type fixnum sum))
(map nil
(lambda (name)
(let ((val (find-enum-value name value-descriptors)))
(iincf sum (length32 (ldb (byte 32 0) val)))))
names)
sum))
;;; Wire-level encoders
;;; These are called at the lowest level, so arg types are assumed to be correct
;; Todo: macroize the encoding loop for uint{32,64}
;; because it's repeated in a bunch of places.
(defun fast-octet-out-loop (buffer scratchpad count)
(declare (type (simple-array octet-type 1) scratchpad))
(dotimes (i count count)
(fast-octet-out buffer (aref scratchpad i))))
#+(and sbcl x86-64)
(macrolet ((define-fixed-width-encoder (n-bytes name lisp-type accessor)
`(progn
(declaim (ftype (function (,lisp-type buffer)
(values (eql ,n-bytes) &optional))
,name))
(defun ,name (val buffer)
(declare ,$optimize-serialization)
(declare (type ,lisp-type val))
;; Don't worry about unaligned writes - they're still faster than
;; looping. Todo: featurize for non-x86 and other than SBCL.
(if (buffer-ensure-space buffer ,n-bytes)
(let ((index (buffer-index buffer)))
(setf (,accessor (buffer-sap buffer) index) val
(buffer-index buffer) (+ index ,n-bytes))
,n-bytes)
(let ((scratchpad (octet-buffer-scratchpad buffer)))
(setf (,accessor (sb-sys:vector-sap scratchpad) 0) val)
(fast-octet-out-loop buffer scratchpad ,n-bytes)))))))
(define-fixed-width-encoder 4 encode-fixed32 (unsigned-byte 32) sb-sys:sap-ref-32)
(define-fixed-width-encoder 8 encode-fixed64 (unsigned-byte 64) sb-sys:sap-ref-64)
(define-fixed-width-encoder 4 encode-sfixed32 (signed-byte 32) sb-sys:signed-sap-ref-32)
(define-fixed-width-encoder 8 encode-sfixed64 (signed-byte 64) sb-sys:signed-sap-ref-64)
(define-fixed-width-encoder 4 encode-single single-float sb-sys:sap-ref-single)
(define-fixed-width-encoder 8 encode-double double-float sb-sys:sap-ref-double))
;;; TODO(jgodbout):
;;; The amount of repeated code below and in some other places
;;; boggles my mind. This should be reduced...
;;; At least macroize writing 4-byte integer so that you can use
;;; it for fixed32, single float, and (twice) for double-float
#-(and sbcl 64-bit)
(progn
(defmacro generate-integer-encoders (bits)
"Generate 32- or 64-bit versions of integer encoders given BITS."
(assert (and (plusp bits) (zerop (mod bits 8))))
(let* ((encode-uint (fintern "~A~A" 'encode-uint bits))
(encode-fixed (fintern "~A~A" 'encode-fixed bits))
(encode-sfixed (fintern "~A~A" 'encode-sfixed bits))
(bytes (/ bits 8))
;; Given bits, can we use fixnums safely?
(fixnump (<= bits (integer-length most-negative-fixnum)))
(ldb (if fixnump 'ildb 'ldb))
(ash (if fixnump 'iash 'ash))
(zerop-val (if fixnump '(i= val 0) '(zerop val))))
;; TODO(jgodbout): At this point with a little effort we can collapse these
;; into one.
`(progn
(defun ,encode-uint (val buffer)
,(format nil
"Encodes the unsigned ~A-bit integer 'val' as a varint
into the buffer at the given index.~
Modifies the buffer, and returns the new index into the buffer.~
Watch out, this function turns off all type
checking and array bounds checking." bits)
(declare #.$optimize-serialization)
(let ((val (ldb (byte ,bits 0) val))
(nbytes-written ,(if (= bits 32)
'(length32 val)
'(length64 val))))
(declare (type (unsigned-byte ,bits) val))
(buffer-ensure-space buffer nbytes-written)
;; Seven bits at a time, least significant bits first
(loop do (let ((bits (,ldb (byte 7 0) val)))
(declare (type (unsigned-byte 8) bits))
(setq val (,ash val -7))
(fast-octet-out buffer (ilogior bits (if ,zerop-val 0 128))))
until ,zerop-val)
nbytes-written))
(defun ,encode-fixed (val buffer)
,(format nil
"Encodes the unsigned ~A-bit integer 'val' as a
fixed int into the buffer at the given index.~
~& Modifies the buffer, and returns the new
index into the buffer.~
~& Watch out, this function turns off all
type checking and array bounds checking." bits)
(declare #.$optimize-serialization)
(declare (type (unsigned-byte ,bits) val))
(buffer-ensure-space buffer ,bytes)
(loop repeat ,bytes doing
(let ((byte (,ldb (byte 8 0) val)))
(declare (type (unsigned-byte 8) byte))
(setq val (,ash val -8))
(fast-octet-out buffer byte)))
,bytes)
(defun ,encode-sfixed (val buffer)
,(format nil
"Encodes the signed ~A-bit integer 'val' as a
fixed int into the buffer at the given index.~
~& Modifies the buffer, and returns the new
index into the buffer.~
~& Watch out, this function turns off all type
checking and array bounds checking." bits)
(declare #.$optimize-serialization)
(declare (type (signed-byte ,bits) val))
(buffer-ensure-space buffer ,bytes)
(loop repeat ,bytes doing
(let ((byte (,ldb (byte 8 0) val)))
(declare (type (unsigned-byte 8) byte))
(setq val (,ash val -8))
(fast-octet-out buffer byte)))
,bytes))))
(generate-integer-encoders 32)
(generate-integer-encoders 64)
(defun encode-single (val buffer)
"Encodes the single float VAL into the buffer.
Modifies the BUFFER, and returns the new index into the buffer.
Watch out, this function turns off all type checking and array bounds checking."
(declare #.$optimize-serialization)
(declare (type single-float val))
(let ((bits (float-features:single-float-bits val)))
(declare (type (signed-byte 32) bits))
(buffer-ensure-space buffer 4)
(loop repeat 4 doing
(let ((byte (ldb (byte 8 0) bits)))
(declare (type (unsigned-byte 8) byte))
(setq bits (ash bits -8))
(fast-octet-out buffer byte)))
4))
;; This seems ghastly. Would it make sense for double-float-bits to
;; returns all 8 bytes? Any implementation on which you have to
;; call integer-decode-float is going perform so badly anyway that
;; returning a bignum is the least of the problems.
(defun encode-double (val buffer)
"Encodes the double float VAL into the BUFFER.
Modifies the buffer, and returns the new index into the buffer.
Watch out, this function turns off all type checking and array bounds checking."
(declare #.$optimize-serialization)
(declare (type double-float val))
(buffer-ensure-space buffer 8)
(let ((bits (float-features:double-float-bits val)))
(loop repeat 8 doing
(let ((byte (ldb (byte 8 0) bits)))
(declare (type (unsigned-byte 8) byte))
(setf byte (ash bits -8))
(fast-octet-out buffer byte)))
8)))
(defun-inline fast-utf8-encode (string)
#+sbcl
(sb-kernel:with-array-data ((string string) (start 0) (end nil)
:check-fill-pointer t)
;; This avoids calling GET-EXTERNAL-FORMAT at runtime.
(funcall (load-time-value
(sb-impl::ef-string-to-octets-fun
(sb-impl::get-external-format-or-lose :utf-8)))
string start end 0))
#-sbcl
(babel:string-to-octets string))
;; The number of bytes to reserve to write a 'uint32' for the length of
;; a sub-message. In theory a uint32 should reserve 5 bytes,
;; but in submessage lengths can't, practically speaking, need that.
(defconstant +SUBMSG-LEN-SPACE-RESERVATION+ 4)
;; Convert a STRING to UTF-8 and write into BUFFER.
;; If the string is purely ASCII, no UTF-8 conversion occurs, and only one
;; pass over the string is required.
(declaim (ftype (function (string buffer) (values (unsigned-byte 32) &optional))
encode-string))
(defun encode-string (string buffer)
(declare #.$optimize-serialization)
;; The string doesn't technically have to be SIMPLE to allow the single-pass
;; optimization but I didn't feel like adding more hair.
(when (simple-string-p string)
(let ((strlen (length string)))
;; First ensure space, *then* mark where we are.
(buffer-ensure-space buffer (+ strlen +SUBMSG-LEN-SPACE-RESERVATION+))
(with-bookmark (buffer)
;; FAST-ENCODE merely skips a redundant call to ENSURE-SPACE
(let ((prefix-len (fast-encode-uint32 strlen buffer)))
(macrolet ((scan ()
`(dotimes (i strlen
(return-from encode-string
(+ prefix-len strlen)))
(let ((code (char-code (char string i))))
(if (< code 128)
(fast-octet-out buffer code)
(return))))))
;; "procedure cloning" elides the runtime per-character dispatch
;; based on whether the source string is UCS-4-encoded.
;; (The commonest case is UCS-4 but with no char-code over 127)
;; XXX: is there is a type that expresses UCS-4-encoded?
;; T works ok, since STRING is already known to be STRINGP.
(typecase string
(base-string (scan))
(t (scan))))))))