]> asedeno.scripts.mit.edu Git - cl-protobufs.git/blob - wire-format.lisp
wire-format: Start using ENCODE-INT and DECODE-INT
[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 (ldb (byte 64 0) 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 (ldb (byte 32 0) 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 (ldb (byte 32 0) 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          (declare (type (unsigned-byte ,bits) val)
777                   (type (simple-array (unsigned-byte 8)) buffer)
778                   (type fixnum index))
779          ;; Seven bits at a time, least significant bits first
780          (loop do (let ((bits (,ldb (byte 7 0) val)))
781                     (declare (type (unsigned-byte 8) bits))
782                     (setq val (,ash val -7))
783                     (setf (aref buffer index)
784                           (ilogior bits (if ,zerop-val 0 128)))
785                     (iincf index))
786                until ,zerop-val)
787          (values index buffer))                 ;return the buffer to improve 'trace'
788        (defun ,encode-fixed (val buffer index)
789          ,(format nil
790                   "Encodes the unsigned ~A-bit integer 'val' as a fixed int into the buffer at the given index.~
791                    ~&    Modifies the buffer, and returns the new index into the buffer.~
792                    ~&    Watch out, this function turns off all type checking and array bounds checking." bits)
793          (declare #.$optimize-serialization)
794          (declare (type (unsigned-byte ,bits) val)
795                   (type (simple-array (unsigned-byte 8)) buffer)
796                   (type fixnum index))
797          (loop repeat ,bytes doing
798            (let ((byte (,ldb (byte 8 0) val)))
799              (declare (type (unsigned-byte 8) byte))
800              (setq val (,ash val -8))
801              (setf (aref buffer index) byte)
802              (iincf index)))
803          (values index buffer))
804        (defun ,encode-sfixed (val buffer index)
805          ,(format nil
806                   "Encodes the signed ~A-bit integer 'val' as a fixed int into the buffer at the given index.~
807                    ~&    Modifies the buffer, and returns the new index into the buffer.~
808                    ~&    Watch out, this function turns off all type checking and array bounds checking." bits)
809          (declare #.$optimize-serialization)
810          (declare (type (signed-byte ,bits) val)
811                   (type (simple-array (unsigned-byte 8)) buffer)
812                   (type fixnum index))
813          (loop repeat ,bytes doing
814            (let ((byte (,ldb (byte 8 0) val)))
815              (declare (type (unsigned-byte 8) byte))
816              (setq val (,ash val -8))
817              (setf (aref buffer index) byte)
818              (iincf index)))
819          (values index buffer)))))
820
821 (generate-integer-encoders 32)
822 (generate-integer-encoders 64)
823
824 (defun encode-int (val buffer index)
825   "Encodes the signed integer 'val' as a varint into the buffer at the given index.
826    Modifies the buffer, and returns the new index into the buffer.
827    Watch out, this function turns off all type checking and array bounds checking."
828   (declare #.$optimize-serialization)
829   (let ((val (ldb (byte 64 0) val))) ;clamp val to 64-bits maximum
830     (declare (type (unsigned-byte 64) val)
831              (type (simple-array (unsigned-byte 8)) buffer)
832              (type fixnum index))
833     ;; Seven bits at a time, least significant bits first
834     (loop do (let ((bits (ldb (byte 7 0) val)))
835                (declare (type (unsigned-byte 8) bits))
836                (setq val (ash val -7))
837                (setf (aref buffer index)
838                      (ilogior bits (if (zerop val) 0 128)))
839                (iincf index))
840           until (zerop val))
841     (values index buffer)))  ;return the buffer to improve 'trace'
842
843 (defun encode-single (val buffer index)
844   "Encodes the single float 'val' into the buffer at the given index.
845    Modifies the buffer, and returns the new index into the buffer.
846    Watch out, this function turns off all type checking and array bounds checking."
847   (declare #.$optimize-serialization)
848   (declare (type single-float val)
849            (type (simple-array (unsigned-byte 8)) buffer)
850            (type fixnum index))
851   (let ((bits (single-float-bits val)))
852     (loop repeat 4 doing
853       (let ((byte (ldb (byte 8 0) bits)))
854         (declare (type (unsigned-byte 8) byte))
855         (setq bits (ash bits -8))
856         (setf (aref buffer index) byte)
857         (iincf index))))
858   (values index buffer))
859
860 (defun encode-double (val buffer index)
861   "Encodes the double float 'val' into the buffer at the given index.
862    Modifies the buffer, and returns the new index into the buffer.
863    Watch out, this function turns off all type checking and array bounds checking."
864   (declare #.$optimize-serialization)
865   (declare (type double-float val)
866            (type (simple-array (unsigned-byte 8)) buffer)
867            (type fixnum index))
868   (multiple-value-bind (low high)
869       (double-float-bits val)
870     (loop repeat 4 doing
871       (let ((byte (ldb (byte 8 0) low)))
872         (declare (type (unsigned-byte 8) byte))
873         (setq low (ash low -8))
874         (setf (aref buffer index) byte)
875         (iincf index)))
876     (loop repeat 4 doing
877       (let ((byte (ldb (byte 8 0) high)))
878         (declare (type (unsigned-byte 8) byte))
879         (setq high (ash high -8))
880         (setf (aref buffer index) byte)
881         (iincf index))))
882   (values index buffer))
883
884 (defun encode-string (string buffer index)
885   "Encodes the octets into the buffer at the given index.
886    Modifies the buffer, and returns the new index into the buffer.
887    Watch out, this function turns off all type checking and array bounds checking."
888   (declare #.$optimize-serialization)
889   (declare (type (simple-array (unsigned-byte 8)) buffer)
890            (type fixnum index))
891   (let* ((octets (babel:string-to-octets string :encoding :utf-8))
892          (len (length octets))
893          (idx (encode-uint32 len buffer index)))
894     (declare (type (array (unsigned-byte 8)) octets)
895              (type fixnum len)
896              (type (unsigned-byte 32) idx))
897     (replace buffer octets :start1 idx)
898     (values (i+ idx len) buffer)))
899
900 (defun encode-octets (octets buffer index)
901   "Encodes the octets into the buffer at the given index.
902    Modifies the buffer, and returns the new index into the buffer.
903    Watch out, this function turns off all type checking and array bounds checking."
904   (declare #.$optimize-serialization)
905   (declare (type (array (unsigned-byte 8)) octets)
906            (type (simple-array (unsigned-byte 8)) buffer)
907            (type fixnum index))
908   (let* ((len (length octets))
909          (idx (encode-uint32 len buffer index)))
910     (declare (type fixnum len)
911              (type (unsigned-byte 32) idx))
912     (replace buffer octets :start1 idx)
913     (values (i+ idx len) buffer)))
914
915
916 ;;; Wire-level decoders
917 ;;; These are called at the lowest level, so arg types are assumed to be correct
918
919 ;; Decode the value from the buffer at the given index,
920 ;; then return the value and new index into the buffer
921 (defmacro generate-integer-decoders (bits)
922   "Generate 32- or 64-bit versions of integer decoders."
923   (assert (and (plusp bits) (zerop (mod bits 8))))
924   (let* ((decode-uint (fintern "~A~A" 'decode-uint bits))
925          (decode-int  (fintern "~A~A" 'decode-int 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-int (buffer index)
958          ,(format nil
959                   "Decodes the next ~A-bit varint 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          (multiple-value-bind (val index)
966              (,decode-uint buffer index)
967            ,@(when fixnump `((declare (type fixnum val))))
968            (when (i= (,ldb (byte 1 ,(1- bits)) val) 1)
969              (,decf val ,(ash 1 bits)))
970            (values val index)))
971        (defun ,decode-fixed (buffer index)
972          ,(format nil
973                   "Decodes the next ~A-bit unsigned fixed integer in the buffer at the given index.~
974                    ~&    Returns both the decoded value and the new index into the buffer.~
975                    ~&    Watch out, this function turns off all type checking and array bounds checking." bits)
976          (declare #.$optimize-serialization)
977          (declare (type (simple-array (unsigned-byte 8)) buffer)
978                   (type fixnum index))
979          ;; Eight bits at a time, least significant bits first
980          (let ((val 0))
981            ,@(when fixnump `((declare (type fixnum val))))
982            (loop repeat ,bytes
983                  for places fixnum upfrom 0 by 8
984                  for byte fixnum = (prog1 (aref buffer index) (iincf index))
985                  do (setq val (,logior val (,ash byte places))))
986            (values val index)))
987        (defun ,decode-sfixed (buffer index)
988          ,(format nil
989                   "Decodes the next ~A-bit signed fixed integer in the buffer at the given index.~
990                    ~&    Returns both the decoded value and the new index into the buffer.~
991                    ~&    Watch out, this function turns off all type checking and array bounds checking." bits)
992          (declare #.$optimize-serialization)
993          (declare (type (simple-array (unsigned-byte 8)) buffer)
994                   (type fixnum index))
995          ;; Eight bits at a time, least significant bits first
996          (let ((val 0))
997            ,@(when fixnump `((declare (type fixnum val))))
998            (loop repeat ,bytes
999                  for places fixnum upfrom 0 by 8
1000                  for byte fixnum = (prog1 (aref buffer index) (iincf index))
1001                  do (setq val (,logior val (,ash byte places))))
1002            (when (i= (,ldb (byte 1 ,(1- bits)) val) 1)  ;sign bit set, so negative value
1003              (,decf val ,(ash 1 bits)))
1004            (values val index))))))
1005
1006 (generate-integer-decoders 32)
1007 (generate-integer-decoders 64)
1008
1009 (defun decode-int (buffer index)
1010   "Decodes the next varint integer in the buffer at the given index.
1011    Returns both the decoded value and the new index into the buffer.
1012    Watch out, this function turns off all type checking and array bounds checking."
1013   (declare #.$optimize-serialization)
1014   (declare (type (simple-array (unsigned-byte 8)) buffer)
1015            (type fixnum index))
1016   (multiple-value-bind (val index)
1017       (decode-uint64 buffer index)
1018     (when (i= (ldb (byte 1 63) val) 1)
1019       (decf val (ash 1 64)))
1020     (values val index)))
1021
1022 (defun decode-single (buffer index)
1023   "Decodes the next single float in the buffer at the given index.
1024    Returns both the decoded value and the new index into the buffer.
1025    Watch out, this function turns off all type checking and array bounds checking."
1026   (declare #.$optimize-serialization)
1027   (declare (type (simple-array (unsigned-byte 8)) buffer)
1028            (type fixnum index))
1029   ;; Eight bits at a time, least significant bits first
1030   (let ((bits 0))
1031     (loop repeat 4
1032           for places fixnum upfrom 0 by 8
1033           for byte fixnum = (prog1 (aref buffer index) (iincf index))
1034           do (setq bits (logior bits (ash byte places))))
1035     (when (i= (ldb (byte 1 31) bits) 1)             ;sign bit set, so negative value
1036       (decf bits #.(ash 1 32)))
1037     (values (make-single-float bits) index)))
1038
1039 (defun decode-double (buffer index)
1040   "Decodes the next double float in the buffer at the given index.
1041    Returns both the decoded value and the new index into the buffer.
1042    Watch out, this function turns off all type checking and array bounds checking."
1043   (declare #.$optimize-serialization)
1044   (declare (type (simple-array (unsigned-byte 8)) buffer)
1045            (type fixnum index))
1046   ;; Eight bits at a time, least significant bits first
1047   (let ((low  0)
1048         (high 0))
1049     (loop repeat 4
1050           for places fixnum upfrom 0 by 8
1051           for byte fixnum = (prog1 (aref buffer index) (iincf index))
1052           do (setq low (logior low (ash byte places))))
1053     (loop repeat 4
1054           for places fixnum upfrom 0 by 8
1055           for byte fixnum = (prog1 (aref buffer index) (iincf index))
1056           do (setq high (logior high (ash byte places))))
1057     ;; High bits are signed, but low bits are unsigned
1058     (when (i= (ldb (byte 1 31) high) 1)             ;sign bit set, so negative value
1059       (decf high #.(ash 1 32)))
1060     (values (make-double-float low high) index)))
1061
1062 (defun decode-string (buffer index)
1063   "Decodes the next UTF-8 encoded string in the buffer at the given index.
1064    Returns both the decoded string and the new index into the buffer.
1065    Watch out, this function turns off all type checking and array bounds checking."
1066   (declare #.$optimize-serialization)
1067   (declare (type (simple-array (unsigned-byte 8)) buffer)
1068            (type fixnum index))
1069   (multiple-value-bind (len idx)
1070       (decode-uint32 buffer index)
1071     (declare (type (unsigned-byte 32) len)
1072              (type fixnum idx))
1073     (values (babel:octets-to-string buffer :start idx :end (i+ idx len) :encoding :utf-8) (i+ idx len))))
1074
1075 (defun decode-octets (buffer index)
1076   "Decodes the next octets in the buffer at the given index.
1077    Returns both the decoded value and the new index into the buffer.
1078    Watch out, this function turns off all type checking and array bounds checking."
1079   (declare #.$optimize-serialization)
1080   (declare (type (simple-array (unsigned-byte 8)) buffer)
1081            (type fixnum index))
1082   (multiple-value-bind (len idx)
1083       (decode-uint32 buffer index)
1084     (declare (type (unsigned-byte 32) len)
1085              (type fixnum idx))
1086     (values (subseq buffer idx (i+ idx len)) (i+ idx len))))
1087
1088
1089 ;;; Wire-level lengths
1090 ;;; These are called at the lowest level, so arg types are assumed to be correct
1091
1092 (defmacro gen-length (bits)
1093   "Generate 32- or 64-bit versions of integer length functions."
1094   (assert (and (plusp bits) (zerop (mod bits 8))))
1095   (let* (;; Given bits, can we use fixnums safely?
1096          (fixnump (<= bits (integer-length most-negative-fixnum)))
1097          (ash (if fixnump 'iash 'ash))
1098          (zerop-val (if fixnump '(i= val 0) '(zerop val))))
1099     `(defun ,(fintern "~A~A" 'length bits) (val)
1100        ,(format nil "Returns the length that 'val' will take when encoded as a ~A-bit integer." bits)
1101        (declare #.$optimize-serialization)
1102        (declare (type (unsigned-byte ,bits) val))
1103        (let ((size 0))
1104          (declare (type fixnum size))
1105          (loop do (progn
1106                     (setq val (,ash val -7))
1107                     (iincf size))
1108                until ,zerop-val)
1109          size))))
1110
1111 (gen-length 32)
1112 (gen-length 64)
1113
1114 (defun varint-length (val)
1115   "Return the length that 'val' will take when encoded as a varint integer."
1116   (declare #.$optimize-serialization)
1117   (let ((val (ldb (byte 64 0) val))
1118         (size 0))
1119     (declare (type (unsigned-byte 64) val))
1120     (declare (type fixnum size))
1121     (loop do (setq val (ash val -7))
1122              (iincf size)
1123           until (zerop val))
1124     size))
1125
1126
1127 ;;; Skipping elements
1128 ;;; This is called at the lowest level, so arg types are assumed to be correct
1129
1130 (defun skip-element (buffer index tag)
1131   "Skip an element in the buffer at the index of the given wire type.
1132    Returns the new index in the buffer.
1133    Watch out, this function turns off all type checking and all array bounds checking."
1134   (declare #.$optimize-serialization)
1135   (declare (type (simple-array (unsigned-byte 8)) buffer)
1136            (type fixnum index)
1137            (type (unsigned-byte 32) tag))
1138   (case (ilogand tag #x7)
1139     ((#.$wire-type-varint)
1140      (loop for byte fixnum = (prog1 (aref buffer index) (iincf index))
1141            until (i< byte 128))
1142      index)
1143     ((#.$wire-type-string)
1144      (multiple-value-bind (len idx)
1145          (decode-uint32 buffer index)
1146        (declare (type (unsigned-byte 32) len)
1147                 (type fixnum idx))
1148        (i+ idx len)))
1149     ((#.$wire-type-32bit)
1150      (i+ index 4))
1151     ((#.$wire-type-64bit)
1152      (i+ index 8))
1153     ((#.$wire-type-start-group)
1154      (loop (multiple-value-bind (new-tag idx)
1155                (decode-uint32 buffer index)
1156              (cond ((not (i= (ilogand new-tag #x7) $wire-type-end-group))
1157                     ;; If it's not the end of a group, skip the next element
1158                     (setq index (skip-element buffer idx new-tag)))
1159                    ;; If it's the end of the expected group, we're done
1160                    ((i= (i- tag $wire-type-start-group) (i- new-tag $wire-type-end-group))
1161                     (return idx))
1162                    (t
1163                     (unless (i= (i- tag $wire-type-start-group) (i- new-tag $wire-type-end-group))
1164                       (serialization-error "Couldn't find a matching end group tag")))))))
1165     (t index)))