]> asedeno.scripts.mit.edu Git - cl-protobufs.git/blob - wire-format.lisp
wire-format: Drop unnecessary clamping for callers of ENCODE-UINT functions
[cl-protobufs.git] / wire-format.lisp
1 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2 ;;;                                                                  ;;;
3 ;;; Free Software published under an MIT-like license. See LICENSE   ;;;
4 ;;;                                                                  ;;;
5 ;;; Copyright (c) 2012 Google, Inc.  All rights reserved.            ;;;
6 ;;;                                                                  ;;;
7 ;;; Original author: Scott McKay                                     ;;;
8 ;;;                                                                  ;;;
9 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
10
11 (in-package "PROTO-IMPL")
12
13
14 ;;; Protocol buffers wire format
15
16 ;;; Utilities
17
18 (eval-when (:compile-toplevel :load-toplevel :execute)
19
20 ;; If you need to debug the (de)serializer, (pushnew :debug-serialization *features*)
21 ;; Otherwise, we try to make (de)serialization as fast as possible,
22 ;; risking life and limb to do so
23 (defparameter $optimize-serialization
24   #+debug-serialization $optimize-default
25   #-debug-serialization $optimize-fast-unsafe)
26
27 (defconstant $wire-type-varint 0)
28 (defconstant $wire-type-64bit  1)
29 (defconstant $wire-type-string 2)
30 (defconstant $wire-type-start-group 3)          ;supposedly deprecated, but no such luck
31 (defconstant $wire-type-end-group   4)          ;supposedly deprecated
32 (defconstant $wire-type-32bit  5)
33
34 )       ;eval-when
35
36
37 (defun make-tag (type index)
38   "Given a wire type or the name of a Protobufs type and a field index,
39    return the tag that encodes both of them."
40   (locally (declare #.$optimize-serialization)
41     (if (typep type 'fixnum)
42       (ilogior type (iash index 3))
43       (let ((type (ecase type
44                     ((:int32 :uint32) $wire-type-varint)
45                     ((:int64 :uint64) $wire-type-varint)
46                     ((:sint32 :sint64) $wire-type-varint)
47                     ((:fixed32 :sfixed32) $wire-type-32bit)
48                     ((:fixed64 :sfixed64) $wire-type-64bit)
49                     ((:string :bytes) $wire-type-string)
50                     ((:bool) $wire-type-varint)
51                     ((:float) $wire-type-32bit)
52                     ((:double) $wire-type-64bit)
53                     ;; A few of our homegrown types
54                     ((:symbol) $wire-type-string)
55                     ((:date :time :datetime :timestamp) $wire-type-64bit))))
56         (ilogior type (iash index 3))))))
57
58 (define-compiler-macro make-tag (&whole form type index)
59   (setq type (fold-symbol type))
60   (cond ((typep type 'fixnum)
61          `(ilogior ,type (iash ,index 3)))
62         ((keywordp type)
63          (let ((type (ecase type
64                        ((:int32 :uint32) $wire-type-varint)
65                        ((:int64 :uint64) $wire-type-varint)
66                        ((:sint32 :sint64) $wire-type-varint)
67                        ((:fixed32 :sfixed32) $wire-type-32bit)
68                        ((:fixed64 :sfixed64) $wire-type-64bit)
69                        ((:string :bytes) $wire-type-string)
70                        ((:bool) $wire-type-varint)
71                        ((:float) $wire-type-32bit)
72                        ((:double) $wire-type-64bit)
73                        ;; A few of our homegrown types
74                        ((:symbol) $wire-type-string)
75                        ((:date :time :datetime :timestamp) $wire-type-64bit))))
76            `(ilogior ,type (iash ,index 3))))
77         (t form)))
78
79 (defun fold-symbol (x)
80   "Given an expression 'x', constant-fold it until it can be folded no more."
81   (let ((last '#:last))
82     (loop
83       (cond ((eq x last) (return x))
84             ((and (listp x)
85                   (eq (first x) 'quote)
86                   (constantp (second x)))
87              (shiftf last x (second x)))
88             ((and (symbolp x)
89                   (boundp x))
90              (shiftf last x (symbol-value x)))
91             (t (return x))))))
92
93
94 (defmacro gen-zig-zag (bits)
95   "Generate 32- or 64-bit versions of zig-zag encoder/decoder."
96   (assert (and (plusp bits) (zerop (mod bits 8))))
97   (let* ((zig-zag-encode (fintern "~A~A" 'zig-zag-encode bits))
98          (zig-zag-decode (fintern "~A~A" 'zig-zag-decode bits))
99          (zig-zag-shift (1+ (- bits))))
100     `(progn
101        (defun ,zig-zag-encode (val)
102          (declare #.$optimize-serialization)
103          (declare (type (signed-byte ,bits) val))
104          (logxor (ash val 1) (ash val ,zig-zag-shift)))
105        (define-compiler-macro ,zig-zag-encode (&whole form val)
106          (if (atom val)
107            `(locally (declare #.$optimize-serialization
108                               (type (signed-byte ,',bits) ,val))
109               (logxor (ash ,val 1) (ash ,val ,',zig-zag-shift)))
110            form))
111        (defun ,zig-zag-decode (val)
112          (declare #.$optimize-serialization)
113          (declare (type (unsigned-byte ,bits) val))
114          (logxor (ash val -1) (- (logand val 1))))
115        (define-compiler-macro ,zig-zag-decode (&whole form val)
116          (if (atom val)
117            `(locally (declare #.$optimize-serialization
118                               (type (unsigned-byte ,',bits) ,val))
119               (logxor (ash ,val -1) (- (logand ,val 1))))
120            form)))))
121
122 (gen-zig-zag 32)
123 (gen-zig-zag 64)
124
125
126 ;;; Serializers
127
128 ;; Serialize 'val' of primitive type 'type' into the buffer
129 (defun serialize-prim (val type tag buffer index)
130   "Serializes a Protobufs primitive (scalar) value into the buffer at the given index.
131    The value is given by 'val', the primitive type by 'type'.
132    Modifies the buffer in place, and returns the new index into the buffer.
133    Watch out, this function turns off most type checking and all array bounds checking."
134   (declare (type (unsigned-byte 32) tag)
135            (type fixnum index))
136   (locally (declare #.$optimize-serialization)
137     (let ((idx (encode-uint32 tag buffer index)))
138       (declare (type fixnum idx))
139       (ecase type
140         ((:int32 :int64)
141          (encode-int val buffer idx))
142         ((:uint32)
143          (encode-uint32 val buffer idx))
144         ((:uint64)
145          (encode-uint64 val buffer idx))
146         ((:sint32)
147          (encode-uint32 (zig-zag-encode32 val) buffer idx))
148         ((:sint64)
149          (encode-uint64 (zig-zag-encode64 val) buffer idx))
150         ((:fixed32)
151          (encode-fixed32 val buffer idx))
152         ((:sfixed32)
153          (encode-sfixed32 val buffer idx))
154         ((:fixed64)
155          (encode-fixed64 val buffer idx))
156         ((:sfixed64)
157          (encode-sfixed64 val buffer idx))
158         ((:string)
159          (encode-string val buffer idx))
160         ((:bytes)
161          (encode-octets val buffer idx))
162         ((:bool)
163          (encode-uint32 (if val 1 0) buffer idx))
164         ((:float)
165          (encode-single val buffer idx))
166         ((:double)
167          (encode-double val buffer idx))
168         ;; A few of our homegrown types
169         ((:symbol)
170          (let ((val (if (keywordp val)
171                       (string val)
172                       ;; Non-keyword symbols are consy, avoid them if possible
173                       (format nil "~A:~A" (package-name (symbol-package val)) (symbol-name val)))))
174            (encode-string val buffer idx)))
175         ((:date :time :datetime :timestamp)
176          (encode-uint64 val buffer idx))))))
177
178 (define-compiler-macro serialize-prim (&whole form val type tag buffer index)
179   (setq type (fold-symbol type)
180         tag  (fold-symbol tag))
181   (if (member type '(:int32 :uint32 :int64 :uint64 :sint32 :sint64
182                      :fixed32 :sfixed32 :fixed64 :sfixed64
183                      :string :bytes :bool :float :double))
184     `(locally (declare #.$optimize-serialization
185                        (type (simple-array (unsigned-byte 8)) ,buffer)
186                        ;; 'tag' is a constant, no need to declare its type
187                        (type fixnum ,index))
188        (let ((idx (encode-uint32 ,tag ,buffer ,index)))
189          (declare (type fixnum idx))
190          ,(ecase type
191             ((:int32 :int64)
192              `(encode-int ,val ,buffer idx))
193             ((:uint32)
194              `(encode-uint32 ,val ,buffer idx))
195             ((:uint64)
196              `(encode-uint64 ,val ,buffer idx))
197             ((:sint32)
198              `(encode-uint32 (zig-zag-encode32 ,val) ,buffer idx))
199             ((:sint64)
200              `(encode-uint64 (zig-zag-encode64 ,val) ,buffer idx))
201             ((:fixed32)
202              `(encode-fixed32 ,val ,buffer idx))
203             ((:sfixed32)
204              `(encode-sfixed32 ,val ,buffer idx))
205             ((:fixed64)
206              `(encode-fixed64 ,val ,buffer idx))
207             ((:sfixed64)
208              `(encode-sfixed64 ,val ,buffer idx))
209             ((:string)
210              `(encode-string ,val ,buffer idx))
211             ((:bytes)
212              `(encode-octets ,val ,buffer idx))
213             ((:bool)
214              `(encode-uint32 (if ,val 1 0) ,buffer idx))
215             ((:float)
216              `(encode-single ,val ,buffer idx))
217             ((:double)
218              `(encode-double ,val ,buffer idx)))))
219     form))
220
221 (defun serialize-packed (values type tag buffer index &optional vectorp)
222   "Serializes a set of packed values into the buffer at the given index.
223    The values are given by 'values', the primitive type by 'type'.
224    Modifies the buffer in place, and returns the new index into the buffer.
225    Watch out, this function turns off most type checking and all array bounds checking."
226   (declare (ignore vectorp)
227            (type (simple-array (unsigned-byte 8)) buffer)
228            (type (unsigned-byte 32) tag)
229            (type fixnum index))
230   (locally (declare #.$optimize-serialization)
231     (let ((idx (encode-uint32 tag buffer index)))
232       (declare (type fixnum idx))
233       (multiple-value-bind (full-len len)
234           (packed-size values type tag)
235         (declare (type fixnum len) (ignore full-len))
236         (setq idx (encode-uint32 len buffer idx)))
237       (ecase type
238         ((:int32 :int64)
239          (map () #'(lambda (val) (setq idx (encode-int val buffer idx))) values))
240         ((:uint32)
241          (map () #'(lambda (val) (setq idx (encode-uint32 val buffer idx))) values))
242         ((:uint64)
243          (map () #'(lambda (val) (setq idx (encode-uint64 val buffer idx))) values))
244         ((:sint32)
245          (map () #'(lambda (val) (setq idx (encode-uint32 (zig-zag-encode32 val) buffer idx))) values))
246         ((:sint64)
247          (map () #'(lambda (val) (setq idx (encode-uint64 (zig-zag-encode64 val) buffer idx))) values))
248         ((:fixed32)
249          (map () #'(lambda (val) (setq idx (encode-fixed32 val buffer idx))) values))
250         ((:sfixed32)
251          (map () #'(lambda (val) (setq idx (encode-sfixed32 val buffer idx))) values))
252         ((:fixed64)
253          (map () #'(lambda (val) (setq idx (encode-fixed64 val buffer idx))) values))
254         ((:sfixed64)
255          (map () #'(lambda (val) (setq idx (encode-sfixed64 val buffer idx))) values))
256         ((:bool)
257          (map () #'(lambda (val) (setq idx (encode-uint32 (if val 1 0) buffer idx))) values))
258         ((:float)
259          (map () #'(lambda (val) (setq idx (encode-single val buffer idx))) values))
260         ((:double)
261          (map () #'(lambda (val) (setq idx (encode-double val buffer idx))) values)))
262       idx)))
263
264 ;; The optimized serializers supply 'vectorp' so we can generate better code
265 (define-compiler-macro serialize-packed (&whole form values type tag buffer index
266                                          &optional (vectorp nil vectorp-p))
267   (setq type (fold-symbol type)
268         tag  (fold-symbol tag))
269   (if (and vectorp-p
270            `(member type '(:int32 :uint32 :int64 :uint64 :sint32 :sint64
271                            :fixed32 :sfixed32 :fixed64 :sfixed64
272                            :bool :float :double)))
273     `(locally (declare #.$optimize-serialization
274                        (type (simple-array (unsigned-byte 8)) ,buffer)
275                        ;; 'tag' is a constant, no need to declare its type
276                        (type fixnum ,index))
277        (let ((idx (encode-uint32 ,tag ,buffer ,index)))
278          (declare (type fixnum idx))
279          (multiple-value-bind (full-len len)
280              (packed-size ,values ,type ,tag)
281            (declare (type fixnum len) (ignore full-len))
282            (setq idx (encode-uint32 len ,buffer idx)))
283          (,(if vectorp 'dovector 'dolist) (val ,values)
284             ,(ecase type
285                ((:int32 :int64)
286                 `(setq idx (encode-int val ,buffer idx)))
287                ((:uint32)
288                 `(setq idx (encode-uint32 val ,buffer idx)))
289                ((:uint64)
290                 `(setq idx (encode-uint64 val ,buffer idx)))
291                ((:sint32)
292                 `(setq idx (encode-uint32 (zig-zag-encode32 val) ,buffer idx)))
293                ((:sint64)
294                 `(setq idx (encode-uint64 (zig-zag-encode64 val) ,buffer idx)))
295                ((:fixed32)
296                 `(setq idx (encode-fixed32 val ,buffer idx)))
297                ((:sfixed32)
298                 `(setq idx (encode-sfixed32 val ,buffer idx)))
299                ((:fixed64)
300                 `(setq idx (encode-fixed64 val ,buffer idx)))
301                ((:sfixed64)
302                 `(setq idx (encode-sfixed64 val ,buffer idx)))
303                ((:bool)
304                 `(setq idx (encode-uint32 (if val 1 0) ,buffer idx)))
305                ((:float)
306                 `(setq idx (encode-single val ,buffer idx)))
307                ((:double)
308                 `(setq idx (encode-double val ,buffer idx)))))
309          idx))
310     form))
311
312 (defun serialize-enum (val enum-values tag buffer index)
313   "Serializes a Protobufs enum value into the buffer at the given index.
314    The value is given by 'val', the enum values are in 'enum-values'.
315    Modifies the buffer in place, and returns the new index into the buffer.
316    Watch out, this function turns off most type checking and all array bounds checking."
317   (declare (type list enum-values)
318            (type (simple-array (unsigned-byte 8)) buffer)
319            (type (unsigned-byte 32) tag)
320            (type fixnum index))
321   (locally (declare #.$optimize-serialization)
322     (let* ((val (let ((e (find val enum-values :key #'proto-value)))
323                   (and e (proto-index e))))
324            (idx (encode-uint32 tag buffer index)))
325       (declare (type (unsigned-byte 32) val)
326                (type fixnum idx))
327       (encode-uint32 val buffer idx))))
328
329 (defun serialize-packed-enum (values enum-values tag buffer index)
330   "Serializes Protobufs enum values into the buffer at the given index.
331    The values are given by 'values', the enum values are in 'enum-values'.
332    Modifies the buffer in place, and returns the new index into the buffer.
333    Watch out, this function turns off most type checking and all array bounds checking."
334   (declare (type list enum-values)
335            (type (simple-array (unsigned-byte 8)) buffer)
336            (type (unsigned-byte 32) tag)
337            (type fixnum index))
338   (locally (declare #.$optimize-serialization)
339     (let ((idx (encode-uint32 tag buffer index)))
340       (declare (type fixnum idx))
341       (multiple-value-bind (full-len len)
342           (packed-enum-size values enum-values tag)
343         (declare (type fixnum len) (ignore full-len))
344         (setq idx (encode-uint32 len buffer idx)))
345       (map () #'(lambda (val)
346                   (let ((val (let ((e (find val enum-values :key #'proto-value)))
347                                (and e (proto-index e)))))
348                     (declare (type (unsigned-byte 32) val))
349                     (setq idx (encode-uint32 val buffer idx)))) values)
350       idx)))
351
352
353 ;;; Deserializers
354
355 ;; Deserialize the next object of type 'type'
356 (defun deserialize-prim (type buffer index)
357   "Deserializes the next object of primitive type 'type'.
358    Deserializes from the byte vector 'buffer' starting at 'index'.
359    Returns the value and and the new index into the buffer.
360    Watch out, this function turns off most type checking and all array bounds checking."
361   (declare (type (simple-array (unsigned-byte 8)) buffer)
362            (type fixnum index))
363   (locally (declare #.$optimize-serialization)
364     (ecase type
365       ((:int32 :int64)
366        (decode-int buffer index))
367       ((:uint32)
368        (decode-uint32 buffer index))
369       ((:uint64)
370        (decode-uint64 buffer index))
371       ((:sint32)
372        (multiple-value-bind (val idx)
373            (decode-uint32 buffer index)
374          (values (zig-zag-decode32 val) idx)))
375       ((:sint64)
376        (multiple-value-bind (val idx)
377            (decode-uint64 buffer index)
378          (values (zig-zag-decode64 val) idx)))
379       ((:fixed32)
380        (decode-fixed32 buffer index))
381       ((:sfixed32)
382        (decode-sfixed32 buffer index))
383       ((:fixed64)
384        (decode-fixed64 buffer index))
385       ((:sfixed64)
386        (decode-sfixed64 buffer index))
387       ((:string)
388        (decode-string buffer index))
389       ((:bytes)
390        (decode-octets buffer index))
391       ((:bool)
392        (multiple-value-bind (val idx)
393            (decode-uint32 buffer index)
394          (values (if (i= val 0) nil t) idx)))
395       ((:float)
396        (decode-single buffer index))
397       ((:double)
398        (decode-double buffer index))
399       ;; A few of our homegrown types
400       ((:symbol)
401        ;; Note that this is consy, avoid it if possible
402        (multiple-value-bind (val idx)
403            (decode-string buffer index)
404          (values (make-lisp-symbol val) idx)))
405       ((:date :time :datetime :timestamp)
406        (decode-uint64 buffer index)))))
407
408 (define-compiler-macro deserialize-prim (&whole form type buffer index)
409   (setq type (fold-symbol type))
410   (if (member type '(:int32 :uint32 :int64 :uint64 :sint32 :sint64
411                      :fixed32 :sfixed32 :fixed64 :sfixed64
412                      :string :bytes :bool :float :double))
413     `(locally (declare #.$optimize-serialization
414                        (type (simple-array (unsigned-byte 8)) ,buffer)
415                        (type fixnum ,index))
416        ,(ecase type
417           ((:int32 :int64)
418            `(decode-int ,buffer ,index))
419           ((:uint32)
420            `(decode-uint32 ,buffer ,index))
421           ((:uint64)
422            `(decode-uint64 ,buffer ,index))
423           ((:sint32)
424            `(multiple-value-bind (val idx)
425                 (decode-uint32 ,buffer ,index)
426               (values (zig-zag-decode32 val) idx)))
427           ((:sint64)
428            `(multiple-value-bind (val idx)
429                (decode-uint64 ,buffer ,index)
430              (values (zig-zag-decode64 val) idx)))
431           ((:fixed32)
432            `(decode-fixed32 ,buffer ,index))
433           ((:sfixed32)
434            `(decode-sfixed32 ,buffer ,index))
435           ((:fixed64)
436            `(decode-fixed64 ,buffer ,index))
437           ((:sfixed64)
438            `(decode-sfixed64 ,buffer ,index))
439           ((:string)
440            `(decode-string ,buffer ,index))
441           ((:bytes)
442            `(decode-octets ,buffer ,index))
443           ((:bool)
444            `(multiple-value-bind (val idx)
445                 (decode-uint32 ,buffer ,index)
446               (values (if (i= val 0) nil t) idx)))
447           ((:float)
448            `(decode-single ,buffer ,index))
449           ((:double)
450            `(decode-double ,buffer ,index))))
451     form))
452
453 (defun deserialize-packed (type buffer index)
454   "Deserializes the next packed values of type 'type'.
455    Deserializes from the byte vector 'buffer' starting at 'index'.
456    Returns the value and and the new index into the buffer.
457    Watch out, this function turns off most type checking and all array bounds checking."
458   (declare (type (simple-array (unsigned-byte 8)) buffer)
459            (type fixnum index))
460   (locally (declare #.$optimize-serialization)
461     (multiple-value-bind (len idx)
462         (decode-uint32 buffer index)
463       (declare (type (unsigned-byte 32) len)
464                (type fixnum idx))
465       (let ((end (i+ idx len)))
466         (declare (type (unsigned-byte 32) end))
467         (with-collectors ((values collect-value))
468           (loop
469             (when (>= idx end)
470               (return-from deserialize-packed (values values idx)))
471             (multiple-value-bind (val nidx)
472                 (ecase type
473                   ((:int32 :int64)
474                    (decode-int buffer idx))
475                   ((:uint32)
476                    (decode-uint32 buffer idx))
477                   ((:uint64)
478                    (decode-uint64 buffer idx))
479                   ((:sint32)
480                    (multiple-value-bind (val nidx)
481                        (decode-uint32 buffer idx)
482                      (values (zig-zag-decode32 val) nidx)))
483                   ((:sint64)
484                    (multiple-value-bind (val nidx)
485                        (decode-uint64 buffer idx)
486                      (values (zig-zag-decode64 val) nidx)))
487                   ((:fixed32)
488                    (decode-fixed32 buffer idx))
489                   ((:sfixed32)
490                    (decode-sfixed32 buffer idx))
491                   ((:fixed64)
492                    (decode-fixed64 buffer idx))
493                   ((:sfixed64)
494                    (decode-sfixed64 buffer idx))
495                   ((:bool)
496                    (multiple-value-bind (val nidx)
497                        (decode-uint32 buffer idx)
498                      (values (if (i= val 0) nil t) nidx)))
499                   ((:float)
500                    (decode-single buffer idx))
501                   ((:double)
502                    (decode-double buffer idx)))
503               (collect-value val)
504               (setq idx nidx))))))))
505
506 (define-compiler-macro deserialize-packed (&whole form type buffer index)
507   (setq type (fold-symbol type))
508   (if (member type '(:int32 :uint32 :int64 :uint64 :sint32 :sint64
509                      :fixed32 :sfixed32 :fixed64 :sfixed64
510                      :bool :float :double))
511     `(locally (declare #.$optimize-serialization
512                        (type (simple-array (unsigned-byte 8)) ,buffer)
513                        (type fixnum ,index))
514        (block deserialize-packed
515          (multiple-value-bind (len idx)
516              (decode-uint32 ,buffer ,index)
517            (declare (type (unsigned-byte 32) len)
518                     (type fixnum idx))
519            (let ((end (i+ idx len)))
520              (declare (type (unsigned-byte 32) end))
521              (with-collectors ((values collect-value))
522                (loop
523                  (when (>= idx end)
524                    (return-from deserialize-packed (values values idx)))
525                  (multiple-value-bind (val nidx)
526                      ,(ecase type
527                         ((:int32 :int64)
528                          `(decode-int ,buffer idx))
529                         ((:uint32)
530                          `(decode-uint32 ,buffer idx))
531                         ((:uint64)
532                          `(decode-uint64 ,buffer idx))
533                         ((:sint32)
534                          `(multiple-value-bind (val nidx)
535                               (decode-uint32 ,buffer idx)
536                             (values (zig-zag-decode32 val) nidx)))
537                         ((:sint64)
538                          `(multiple-value-bind (val nidx)
539                               (decode-uint64 ,buffer idx)
540                             (values (zig-zag-decode64 val) nidx)))
541                         ((:fixed32)
542                          `(decode-fixed32 ,buffer idx))
543                         ((:sfixed32)
544                          `(decode-sfixed32 ,buffer idx))
545                         ((:fixed64)
546                          `(decode-fixed64 ,buffer idx))
547                         ((:sfixed64)
548                          `(decode-sfixed64 ,buffer idx))
549                         ((:bool)
550                          `(multiple-value-bind (val nidx)
551                               (decode-uint32 ,buffer idx)
552                             (values (if (i= val 0) nil t) nidx)))
553                         ((:float)
554                          `(decode-single ,buffer idx))
555                         ((:double)
556                          `(decode-double ,buffer idx)))
557                    (collect-value val)
558                    (setq idx nidx))))))))
559     form))
560
561 (defun deserialize-enum (enum-values buffer index)
562   "Deserializes the next enum value take from 'enum-values'.
563    Deserializes from the byte vector 'buffer' starting at 'index'.
564    Returns the value and and the new index into the buffer.
565    Watch out, this function turns off most type checking and all array bounds checking."
566   (declare (type list enum-values)
567            (type (simple-array (unsigned-byte 8)) buffer)
568            (type fixnum index))
569   (locally (declare #.$optimize-serialization)
570     (multiple-value-bind (val idx)
571         (decode-int buffer index)
572       (let ((val (let ((e (find val enum-values :key #'proto-index)))
573                    (and e (proto-value e)))))
574         (values val idx)))))
575
576 (defun deserialize-packed-enum (enum-values buffer index)
577   "Deserializes the next packed enum values given in 'enum-values'.
578    Deserializes from the byte vector 'buffer' starting at 'index'.
579    Returns the value and and the new index into the buffer.
580    Watch out, this function turns off most type checking and all array bounds checking."
581   (declare (type list enum-values)
582            (type (simple-array (unsigned-byte 8)) buffer)
583            (type fixnum index))
584   (locally (declare #.$optimize-serialization)
585     (multiple-value-bind (len idx)
586         (decode-uint32 buffer index)
587       (declare (type (unsigned-byte 32) len)
588                (type fixnum idx))
589       (let ((end (i+ idx len)))
590         (declare (type (unsigned-byte 32) end))
591         (with-collectors ((values collect-value))
592           (loop
593             (when (>= idx end)
594               (return-from deserialize-packed-enum (values values idx)))
595             (multiple-value-bind (val nidx)
596                 (decode-int buffer idx)
597               (let ((val (let ((e (find val enum-values :key #'proto-index)))
598                            (and e (proto-value e)))))
599                 (collect-value val)
600                 (setq idx nidx)))))))))
601
602
603 ;;; Object sizing
604
605 (defun prim-size (val type tag)
606   "Returns the size in bytes that the primitive object will take when serialized.
607    Watch out, this function turns off most type checking."
608   (declare (type (unsigned-byte 32) tag))
609   (locally (declare #.$optimize-serialization)
610     (ecase type
611       ((:int32 :uint32 :int64 :uint64)
612        (i+ (varint-length tag) (varint-length val)))
613       ((:sint32)
614        (i+ (varint-length tag) (varint-length (zig-zag-encode32 val))))
615       ((:sint64)
616        (i+ (varint-length tag) (varint-length (zig-zag-encode64 val))))
617       ((:fixed32 :sfixed32)
618        (i+ (varint-length tag) 4))
619       ((:fixed64 :sfixed64)
620        (i+ (varint-length tag) 8))
621       ((:string)
622        (let ((len (babel:string-size-in-octets val :encoding :utf-8)))
623          (i+ (varint-length tag) (varint-length len) len)))
624       ((:bytes)
625        (let ((len (length val)))
626          (i+ (varint-length tag) (varint-length len) len)))
627       ((:bool)
628        (i+ (varint-length tag) 1))
629       ((:float)
630        (i+ (varint-length tag) 4))
631       ((:double)
632        (i+ (varint-length tag) 8))
633       ;; A few of our homegrown types
634       ((:symbol)
635        (let ((len (if (keywordp val)
636                     (length (symbol-name val))
637                     (i+ (length (package-name (symbol-package val))) 1 (length (symbol-name val))))))
638          (i+ (varint-length tag) (varint-length len) len)))
639       ((:date :time :datetime :timestamp)
640        (i+ (varint-length tag) 8)))))
641
642 (define-compiler-macro prim-size (&whole form val type tag)
643   (setq type (fold-symbol type)
644         tag  (fold-symbol tag))
645   (if (member type '(:int32 :uint32 :int64 :uint64 :sint32 :sint64
646                      :fixed32 :sfixed32 :fixed64 :sfixed64
647                      :string :bytes :bool :float :double))
648     `(locally (declare #.$optimize-serialization)
649        ,(ecase type
650           ((:int32 :int64 :uint32 :uint64)
651            `(i+ (varint-length ,tag) (varint-length ,val)))
652           ((:sint32)
653            `(i+ (varint-length ,tag) (varint-length (zig-zag-encode32 ,val))))
654           ((:sint64)
655            `(i+ (varint-length ,tag) (varint-length (zig-zag-encode64 ,val))))
656           ((:fixed32 :sfixed32)
657            `(i+ (varint-length ,tag) 4))
658           ((:fixed64 :sfixed64)
659            `(i+ (varint-length ,tag) 8))
660           ((:string)
661            `(let ((len (babel:string-size-in-octets ,val :encoding :utf-8)))
662               (i+ (varint-length ,tag) (varint-length len) len)))
663           ((:bytes)
664            `(let ((len (length ,val)))
665               (i+ (varint-length ,tag) (varint-length len) len)))
666           ((:bool)
667            `(i+ (varint-length ,tag) 1))
668           ((:float)
669            `(i+ (varint-length ,tag) 4))
670           ((:double)
671            `(i+ (varint-length ,tag) 8))))
672     form))
673
674 (defun packed-size (values type tag &optional vectorp)
675   "Returns the size in bytes that the packed object will take when serialized.
676    Watch out, this function turns off most type checking."
677   (declare (ignore vectorp)
678            (type (unsigned-byte 32) tag))
679   (locally (declare #.$optimize-serialization)
680     (let ((len (let ((len 0))
681                  (declare (type fixnum len))
682                  (map () #'(lambda (val)
683                              (iincf len (ecase type
684                                           ((:int32 :uint32 :int64 :uint64) (varint-length val))
685                                           ((:sint32) (varint-length (zig-zag-encode32 val)))
686                                           ((:sint64) (varint-length (zig-zag-encode64 val)))
687                                           ((:fixed32 :sfixed32) 4)
688                                           ((:fixed64 :sfixed64) 8)
689                                           ((:bool)   1)
690                                           ((:float)  4)
691                                           ((:double) 8)))) values)
692                  len)))
693       (declare (type (unsigned-byte 32) len))
694       ;; Two value: the full size of the packed object, and the size
695       ;; of just the payload
696       (values (i+ (varint-length tag) (varint-length len) len) len))))
697
698 ;; The optimized serializers supply 'vectorp' so we can generate better code
699 (define-compiler-macro packed-size (&whole form values type tag
700                                     &optional (vectorp nil vectorp-p))
701   (setq type (fold-symbol type)
702         tag  (fold-symbol tag))
703   (if (and vectorp-p
704            (member type '(:int32 :uint32 :int64 :uint64 :sint32 :sint64
705                           :fixed32 :sfixed32 :fixed64 :sfixed64
706                           :bool :float :double)))
707     `(locally (declare #.$optimize-serialization)
708        (let ((len (let ((len 0))
709                     (declare (type fixnum len))
710                     (,(if vectorp 'dovector 'dolist) (val ,values)
711                        (iincf len ,(ecase type
712                                      ((:int32 :uint32 :int64 :uint64) `(varint-length val))
713                                      ((:sint32) `(varint-length (zig-zag-encode32 val)))
714                                      ((:sint64) `(varint-length (zig-zag-encode64 val)))
715                                      ((:fixed32 :sfixed32) `4)
716                                      ((:fixed64 :sfixed64) `8)
717                                      ((:bool)   `1)
718                                      ((:float)  `4)
719                                      ((:double) `8))))
720                     len)))
721          (declare (type (unsigned-byte 32) len))
722          (values (i+ (varint-length (the (unsigned-byte 32) ,tag)) (varint-length len) len) len)))
723     form))
724
725 (defun enum-size (val enum-values tag)
726   "Returns the size in bytes that the enum object will take when serialized."
727   (declare (type list enum-values)
728            (type (unsigned-byte 32) tag))
729   (let ((idx (let ((e (find val enum-values :key #'proto-value)))
730                (and e (proto-index e)))))
731     (unless idx
732       (serialization-error "There is no enum value for ~S" val))
733     (i+ (varint-length tag) (varint-length (ldb (byte 32 0) idx)))))
734
735 (defun packed-enum-size (values enum-values tag)
736   "Returns the size in bytes that the enum values will take when serialized."
737   (declare (type list enum-values)
738            (type (unsigned-byte 32) tag))
739   (let ((len (let ((len 0))
740                (declare (type fixnum len))
741                (map () #'(lambda (val)
742                            (let ((idx (let ((e (find val enum-values :key #'proto-value)))
743                                         (and e (proto-index e)))))
744                              (unless idx
745                                (serialization-error "There is no enum value for ~S" val))
746                              (iincf len (varint-length (ldb (byte 32 0) idx))))) values)
747                len)))
748     (declare (type (unsigned-byte 32) len))
749     ;; Two value: the full size of the packed object, and the size
750     ;; of just the payload
751     (values (i+ (varint-length tag) (varint-length len) len) len)))
752
753 \f
754 ;;; Wire-level encoders
755 ;;; These are called at the lowest level, so arg types are assumed to be correct
756
757 (defmacro generate-integer-encoders (bits)
758   "Generate 32- or 64-bit versions of integer encoders."
759   (assert (and (plusp bits) (zerop (mod bits 8))))
760   (let* ((encode-uint   (fintern "~A~A" 'encode-uint bits))
761          (encode-fixed  (fintern "~A~A" 'encode-fixed bits))
762          (encode-sfixed (fintern "~A~A" 'encode-sfixed bits))
763          (bytes (/ bits 8))
764          ;; Given bits, can we use fixnums safely?
765          (fixnump (<= bits (integer-length most-negative-fixnum)))
766          (ldb (if fixnump 'ildb 'ldb))
767          (ash (if fixnump 'iash 'ash))
768          (zerop-val (if fixnump '(i= val 0) '(zerop val))))
769     `(progn
770        (defun ,encode-uint (val buffer index)
771          ,(format nil
772                   "Encodes the unsigned ~A-bit integer 'val' as a varint into the buffer at the given index.~
773                    ~&    Modifies the buffer, and returns the new index into the buffer.~
774                    ~&    Watch out, this function turns off all type checking and array bounds checking." bits)
775          (declare #.$optimize-serialization)
776          (let ((val (ldb (byte ,bits 0) val)))
777            (declare (type (unsigned-byte ,bits) val)
778                     (type (simple-array (unsigned-byte 8)) buffer)
779                     (type fixnum index))
780            ;; Seven bits at a time, least significant bits first
781            (loop do (let ((bits (,ldb (byte 7 0) val)))
782                       (declare (type (unsigned-byte 8) bits))
783                       (setq val (,ash val -7))
784                       (setf (aref buffer index)
785                             (ilogior bits (if ,zerop-val 0 128)))
786                       (iincf index))
787                  until ,zerop-val))
788          (values index buffer))                 ;return the buffer to improve 'trace'
789        (defun ,encode-fixed (val buffer index)
790          ,(format nil
791                   "Encodes the unsigned ~A-bit integer 'val' as a fixed int into the buffer at the given index.~
792                    ~&    Modifies the buffer, and returns the new index into the buffer.~
793                    ~&    Watch out, this function turns off all type checking and array bounds checking." bits)
794          (declare #.$optimize-serialization)
795          (declare (type (unsigned-byte ,bits) val)
796                   (type (simple-array (unsigned-byte 8)) buffer)
797                   (type fixnum index))
798          (loop repeat ,bytes doing
799            (let ((byte (,ldb (byte 8 0) val)))
800              (declare (type (unsigned-byte 8) byte))
801              (setq val (,ash val -8))
802              (setf (aref buffer index) byte)
803              (iincf index)))
804          (values index buffer))
805        (defun ,encode-sfixed (val buffer index)
806          ,(format nil
807                   "Encodes the signed ~A-bit integer 'val' as a fixed int into the buffer at the given index.~
808                    ~&    Modifies the buffer, and returns the new index into the buffer.~
809                    ~&    Watch out, this function turns off all type checking and array bounds checking." bits)
810          (declare #.$optimize-serialization)
811          (declare (type (signed-byte ,bits) val)
812                   (type (simple-array (unsigned-byte 8)) buffer)
813                   (type fixnum index))
814          (loop repeat ,bytes doing
815            (let ((byte (,ldb (byte 8 0) val)))
816              (declare (type (unsigned-byte 8) byte))
817              (setq val (,ash val -8))
818              (setf (aref buffer index) byte)
819              (iincf index)))
820          (values index buffer)))))
821
822 (generate-integer-encoders 32)
823 (generate-integer-encoders 64)
824
825 (defun encode-int (val buffer index)
826   "Encodes the signed integer 'val' as a varint into the buffer at the given index.
827    Modifies the buffer, and returns the new index into the buffer.
828    Watch out, this function turns off all type checking and array bounds checking."
829   (declare #.$optimize-serialization)
830   (let ((val (ldb (byte 64 0) val))) ;clamp val to 64-bits maximum
831     (declare (type (unsigned-byte 64) val)
832              (type (simple-array (unsigned-byte 8)) buffer)
833              (type fixnum index))
834     ;; Seven bits at a time, least significant bits first
835     (loop do (let ((bits (ldb (byte 7 0) val)))
836                (declare (type (unsigned-byte 8) bits))
837                (setq val (ash val -7))
838                (setf (aref buffer index)
839                      (ilogior bits (if (zerop val) 0 128)))
840                (iincf index))
841           until (zerop val))
842     (values index buffer)))  ;return the buffer to improve 'trace'
843
844 (defun encode-single (val buffer index)
845   "Encodes the single float 'val' into the buffer at the given index.
846    Modifies the buffer, and returns the new index into the buffer.
847    Watch out, this function turns off all type checking and array bounds checking."
848   (declare #.$optimize-serialization)
849   (declare (type single-float val)
850            (type (simple-array (unsigned-byte 8)) buffer)
851            (type fixnum index))
852   (let ((bits (single-float-bits val)))
853     (loop repeat 4 doing
854       (let ((byte (ldb (byte 8 0) bits)))
855         (declare (type (unsigned-byte 8) byte))
856         (setq bits (ash bits -8))
857         (setf (aref buffer index) byte)
858         (iincf index))))
859   (values index buffer))
860
861 (defun encode-double (val buffer index)
862   "Encodes the double float 'val' into the buffer at the given index.
863    Modifies the buffer, and returns the new index into the buffer.
864    Watch out, this function turns off all type checking and array bounds checking."
865   (declare #.$optimize-serialization)
866   (declare (type double-float val)
867            (type (simple-array (unsigned-byte 8)) buffer)
868            (type fixnum index))
869   (multiple-value-bind (low high)
870       (double-float-bits val)
871     (loop repeat 4 doing
872       (let ((byte (ldb (byte 8 0) low)))
873         (declare (type (unsigned-byte 8) byte))
874         (setq low (ash low -8))
875         (setf (aref buffer index) byte)
876         (iincf index)))
877     (loop repeat 4 doing
878       (let ((byte (ldb (byte 8 0) high)))
879         (declare (type (unsigned-byte 8) byte))
880         (setq high (ash high -8))
881         (setf (aref buffer index) byte)
882         (iincf index))))
883   (values index buffer))
884
885 (defun encode-string (string buffer index)
886   "Encodes the octets into the buffer at the given index.
887    Modifies the buffer, and returns the new index into the buffer.
888    Watch out, this function turns off all type checking and array bounds checking."
889   (declare #.$optimize-serialization)
890   (declare (type (simple-array (unsigned-byte 8)) buffer)
891            (type fixnum index))
892   (let* ((octets (babel:string-to-octets string :encoding :utf-8))
893          (len (length octets))
894          (idx (encode-uint32 len buffer index)))
895     (declare (type (array (unsigned-byte 8)) octets)
896              (type fixnum len)
897              (type (unsigned-byte 32) idx))
898     (replace buffer octets :start1 idx)
899     (values (i+ idx len) buffer)))
900
901 (defun encode-octets (octets buffer index)
902   "Encodes the octets into the buffer at the given index.
903    Modifies the buffer, and returns the new index into the buffer.
904    Watch out, this function turns off all type checking and array bounds checking."
905   (declare #.$optimize-serialization)
906   (declare (type (array (unsigned-byte 8)) octets)
907            (type (simple-array (unsigned-byte 8)) buffer)
908            (type fixnum index))
909   (let* ((len (length octets))
910          (idx (encode-uint32 len buffer index)))
911     (declare (type fixnum len)
912              (type (unsigned-byte 32) idx))
913     (replace buffer octets :start1 idx)
914     (values (i+ idx len) buffer)))
915
916
917 ;;; Wire-level decoders
918 ;;; These are called at the lowest level, so arg types are assumed to be correct
919
920 ;; Decode the value from the buffer at the given index,
921 ;; then return the value and new index into the buffer
922 (defmacro generate-integer-decoders (bits)
923   "Generate 32- or 64-bit versions of integer decoders."
924   (assert (and (plusp bits) (zerop (mod bits 8))))
925   (let* ((decode-uint (fintern "~A~A" 'decode-uint bits))
926          (decode-fixed  (fintern "~A~A" 'decode-fixed bits))
927          (decode-sfixed (fintern "~A~A" 'decode-sfixed bits))
928          (bytes (/ bits 8))
929          ;; Given bits, can we use fixnums safely?
930          (fixnump (<= bits (integer-length most-negative-fixnum)))
931          (ldb (if fixnump 'ildb 'ldb))
932          (ash (if fixnump 'iash 'ash))
933          (decf (if fixnump 'idecf 'decf))
934          (logior (if fixnump 'ilogior 'logior)))
935     `(progn
936        (defun ,decode-uint (buffer index)
937          ,(format nil
938                   "Decodes the next ~A-bit varint integer in the buffer at the given index.~
939                    ~&    Returns both the decoded value and the new index into the buffer.~
940                    ~&    Watch out, this function turns off all type checking and array bounds checking." bits)
941          (declare #.$optimize-serialization)
942          (declare (type (simple-array (unsigned-byte 8)) buffer)
943                   (type fixnum index))
944          ;; Seven bits at a time, least significant bits first
945          (let ((val 0))
946            (declare (type (unsigned-byte ,bits) val))
947            (loop for places fixnum upfrom 0 by 7
948                  for byte fixnum = (prog1 (aref buffer index) (iincf index))
949                  do (let ((bits (ildb (byte 7 0) byte)))
950                       (declare (type (unsigned-byte 8) bits))
951                       (setq val (,logior val (,ash bits places))))
952                  until (i< byte 128)
953                  finally (progn
954                            (unless (< val ,(ash 1 bits))
955                              (serialization-error "The value ~D is longer than ~A bits" val ,bits))
956                            (return (values val index))))))
957        (defun ,decode-fixed (buffer index)
958          ,(format nil
959                   "Decodes the next ~A-bit unsigned fixed integer in the buffer at the given index.~
960                    ~&    Returns both the decoded value and the new index into the buffer.~
961                    ~&    Watch out, this function turns off all type checking and array bounds checking." bits)
962          (declare #.$optimize-serialization)
963          (declare (type (simple-array (unsigned-byte 8)) buffer)
964                   (type fixnum index))
965          ;; Eight bits at a time, least significant bits first
966          (let ((val 0))
967            ,@(when fixnump `((declare (type fixnum val))))
968            (loop repeat ,bytes
969                  for places fixnum upfrom 0 by 8
970                  for byte fixnum = (prog1 (aref buffer index) (iincf index))
971                  do (setq val (,logior val (,ash byte places))))
972            (values val index)))
973        (defun ,decode-sfixed (buffer index)
974          ,(format nil
975                   "Decodes the next ~A-bit signed fixed integer in the buffer at the given index.~
976                    ~&    Returns both the decoded value and the new index into the buffer.~
977                    ~&    Watch out, this function turns off all type checking and array bounds checking." bits)
978          (declare #.$optimize-serialization)
979          (declare (type (simple-array (unsigned-byte 8)) buffer)
980                   (type fixnum index))
981          ;; Eight bits at a time, least significant bits first
982          (let ((val 0))
983            ,@(when fixnump `((declare (type fixnum val))))
984            (loop repeat ,bytes
985                  for places fixnum upfrom 0 by 8
986                  for byte fixnum = (prog1 (aref buffer index) (iincf index))
987                  do (setq val (,logior val (,ash byte places))))
988            (when (i= (,ldb (byte 1 ,(1- bits)) val) 1)  ;sign bit set, so negative value
989              (,decf val ,(ash 1 bits)))
990            (values val index))))))
991
992 (generate-integer-decoders 32)
993 (generate-integer-decoders 64)
994
995 (defun decode-int (buffer index)
996   "Decodes the next varint integer in the buffer at the given index.
997    Returns both the decoded value and the new index into the buffer.
998    Watch out, this function turns off all type checking and array bounds checking."
999   (declare #.$optimize-serialization)
1000   (declare (type (simple-array (unsigned-byte 8)) buffer)
1001            (type fixnum index))
1002   (multiple-value-bind (val index)
1003       (decode-uint64 buffer index)
1004     (when (i= (ldb (byte 1 63) val) 1)
1005       (decf val (ash 1 64)))
1006     (values val index)))
1007
1008 (defun decode-single (buffer index)
1009   "Decodes the next single float in the buffer at the given index.
1010    Returns both the decoded value and the new index into the buffer.
1011    Watch out, this function turns off all type checking and array bounds checking."
1012   (declare #.$optimize-serialization)
1013   (declare (type (simple-array (unsigned-byte 8)) buffer)
1014            (type fixnum index))
1015   ;; Eight bits at a time, least significant bits first
1016   (let ((bits 0))
1017     (loop repeat 4
1018           for places fixnum upfrom 0 by 8
1019           for byte fixnum = (prog1 (aref buffer index) (iincf index))
1020           do (setq bits (logior bits (ash byte places))))
1021     (when (i= (ldb (byte 1 31) bits) 1)             ;sign bit set, so negative value
1022       (decf bits #.(ash 1 32)))
1023     (values (make-single-float bits) index)))
1024
1025 (defun decode-double (buffer index)
1026   "Decodes the next double float in the buffer at the given index.
1027    Returns both the decoded value and the new index into the buffer.
1028    Watch out, this function turns off all type checking and array bounds checking."
1029   (declare #.$optimize-serialization)
1030   (declare (type (simple-array (unsigned-byte 8)) buffer)
1031            (type fixnum index))
1032   ;; Eight bits at a time, least significant bits first
1033   (let ((low  0)
1034         (high 0))
1035     (loop repeat 4
1036           for places fixnum upfrom 0 by 8
1037           for byte fixnum = (prog1 (aref buffer index) (iincf index))
1038           do (setq low (logior low (ash byte places))))
1039     (loop repeat 4
1040           for places fixnum upfrom 0 by 8
1041           for byte fixnum = (prog1 (aref buffer index) (iincf index))
1042           do (setq high (logior high (ash byte places))))
1043     ;; High bits are signed, but low bits are unsigned
1044     (when (i= (ldb (byte 1 31) high) 1)             ;sign bit set, so negative value
1045       (decf high #.(ash 1 32)))
1046     (values (make-double-float low high) index)))
1047
1048 (defun decode-string (buffer index)
1049   "Decodes the next UTF-8 encoded string in the buffer at the given index.
1050    Returns both the decoded string and the new index into the buffer.
1051    Watch out, this function turns off all type checking and array bounds checking."
1052   (declare #.$optimize-serialization)
1053   (declare (type (simple-array (unsigned-byte 8)) buffer)
1054            (type fixnum index))
1055   (multiple-value-bind (len idx)
1056       (decode-uint32 buffer index)
1057     (declare (type (unsigned-byte 32) len)
1058              (type fixnum idx))
1059     (values (babel:octets-to-string buffer :start idx :end (i+ idx len) :encoding :utf-8) (i+ idx len))))
1060
1061 (defun decode-octets (buffer index)
1062   "Decodes the next octets in the buffer at the given index.
1063    Returns both the decoded value and the new index into the buffer.
1064    Watch out, this function turns off all type checking and array bounds checking."
1065   (declare #.$optimize-serialization)
1066   (declare (type (simple-array (unsigned-byte 8)) buffer)
1067            (type fixnum index))
1068   (multiple-value-bind (len idx)
1069       (decode-uint32 buffer index)
1070     (declare (type (unsigned-byte 32) len)
1071              (type fixnum idx))
1072     (values (subseq buffer idx (i+ idx len)) (i+ idx len))))
1073
1074
1075 ;;; Wire-level lengths
1076 ;;; These are called at the lowest level, so arg types are assumed to be correct
1077
1078 (defun varint-length (val)
1079   "Return the length that 'val' will take when encoded as a varint integer."
1080   (declare #.$optimize-serialization)
1081   (let ((val (ldb (byte 64 0) val))
1082         (size 0))
1083     (declare (type (unsigned-byte 64) val))
1084     (declare (type fixnum size))
1085     (loop do (setq val (ash val -7))
1086              (iincf size)
1087           until (zerop val))
1088     size))
1089
1090
1091 ;;; Skipping elements
1092 ;;; This is called at the lowest level, so arg types are assumed to be correct
1093
1094 (defun skip-element (buffer index tag)
1095   "Skip an element in the buffer at the index of the given wire type.
1096    Returns the new index in the buffer.
1097    Watch out, this function turns off all type checking and all array bounds checking."
1098   (declare #.$optimize-serialization)
1099   (declare (type (simple-array (unsigned-byte 8)) buffer)
1100            (type fixnum index)
1101            (type (unsigned-byte 32) tag))
1102   (case (ilogand tag #x7)
1103     ((#.$wire-type-varint)
1104      (loop for byte fixnum = (prog1 (aref buffer index) (iincf index))
1105            until (i< byte 128))
1106      index)
1107     ((#.$wire-type-string)
1108      (multiple-value-bind (len idx)
1109          (decode-uint32 buffer index)
1110        (declare (type (unsigned-byte 32) len)
1111                 (type fixnum idx))
1112        (i+ idx len)))
1113     ((#.$wire-type-32bit)
1114      (i+ index 4))
1115     ((#.$wire-type-64bit)
1116      (i+ index 8))
1117     ((#.$wire-type-start-group)
1118      (loop (multiple-value-bind (new-tag idx)
1119                (decode-uint32 buffer index)
1120              (cond ((not (i= (ilogand new-tag #x7) $wire-type-end-group))
1121                     ;; If it's not the end of a group, skip the next element
1122                     (setq index (skip-element buffer idx new-tag)))
1123                    ;; If it's the end of the expected group, we're done
1124                    ((i= (i- tag $wire-type-start-group) (i- new-tag $wire-type-end-group))
1125                     (return idx))
1126                    (t
1127                     (unless (i= (i- tag $wire-type-start-group) (i- new-tag $wire-type-end-group))
1128                       (serialization-error "Couldn't find a matching end group tag")))))))
1129     (t index)))