]> asedeno.scripts.mit.edu Git - cl-protobufs.git/blob - serialize.lisp
Make it a bit easier to debug (de)serialization
[cl-protobufs.git] / serialize.lisp
1 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2 ;;;                                                                  ;;;
3 ;;; Confidential and proprietary information of ITA Software, Inc.   ;;;
4 ;;;                                                                  ;;;
5 ;;; Copyright (c) 2012 ITA Software, Inc.  All rights reserved.      ;;;
6 ;;;                                                                  ;;;
7 ;;; Original author: Scott McKay                                     ;;;
8 ;;;                                                                  ;;;
9 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
10
11 (in-package "PROTO-IMPL")
12
13
14 ;;; Protobuf serialization from Lisp objects
15
16 ;;; Serialization
17
18 ;; Serialize the object using the given protobuf type
19 (defun serialize-object-to-stream (object type &key (stream *standard-output*) visited)
20   "Serializes the object 'object' of type 'type' onto the stream 'stream'
21    using the wire format.
22    'type' is the Lisp name of a Protobufs message (usually the name of a 
23    Lisp class) or a 'protobuf-message'.
24    'visited' is a hash table used to cache object sizes. If it is supplied, it will be
25    cleared before it is used; otherwise, a fresh table will be created.
26    The return value is the buffer containing the serialized object. If the stream is
27    nil, the buffer is not actually written to anywhere."
28   (let* ((visited (let ((v (or visited (make-hash-table))))
29                     (clrhash v)
30                     v))
31          (size    (object-size object type visited))
32          (buffer  (make-byte-vector size)))
33     (serialize-object object type buffer 0 visited)
34     (when stream
35       (write-sequence buffer stream))
36     buffer))
37
38 (defun serialize-object-to-file (filename object type &key visited)
39   (with-open-file (stream filename
40                    :direction :output
41                    :element-type '(unsigned-byte 8))
42     (serialize-object-to-stream object type :stream stream :visited visited)))
43
44 ;; Allow clients to add their own methods
45 ;; This is how we address the problem of cycles, e.g. -- if you have an object
46 ;; that may contain cycles, serialize the cyclic object using a "handle"
47 (defgeneric serialize-object (object type buffer &optional start visited)
48   (:documentation
49    "Serializes the object 'object' of type 'type' into the byte array 'buffer'
50     using the wire format.
51     'type' is the Lisp name of a Protobufs message (usually the name of a 
52     Lisp class) or a 'protobuf-message'.
53     The object is serialized into the byte array given by 'buffer' starting
54     at the fixnum index 'index' using the wire format.
55     'visited' is a hash table used to cache object sizes.
56     The return value is the buffer containing the serialized object."))
57
58 (defmethod serialize-object (object type buffer &optional start visited)
59   (let ((message (find-message-for-class type)))
60     (assert message ()
61             "There is no Protobuf message having the type ~S" type)
62     (serialize-object object message buffer start visited)))
63
64 ;; 'visited' is used to cache object sizes
65 ;; If it's passed in explicitly, it is assumed to already have the sizes within it
66 ;; The default method uses metadata from the protobuf "schema" for the message
67 (defmethod serialize-object (object (message protobuf-message) buffer &optional start visited)
68   (declare (type (simple-array (unsigned-byte 8)) buffer))
69   (let ((visited (or visited (make-hash-table)))
70         (index   (or start 0)))
71     (declare (type fixnum index))
72     (macrolet ((read-slot (object slot reader)
73                  ;; Don't do a boundp check, we assume the object is fully populated
74                  ;; Unpopulated slots should be "nullable" and should contain nil
75                  `(if ,reader
76                     (funcall ,reader ,object)
77                     (slot-value ,object ,slot))))
78       (labels ((do-field (object trace field)
79                  ;; We don't do cycle detection here
80                  ;; If the client needs it, he can define his own 'serialize-object'
81                  ;; method to clean things up first
82                  (let* ((type   (if (eq (proto-class field) 'boolean) :bool (proto-class field)))
83                         (slot   (proto-value field))
84                         (reader (proto-reader field))
85                         msg)
86                    (when (or slot reader)
87                      (cond ((eq (proto-required field) :repeated)
88                             (cond ((and (proto-packed field) (packed-type-p type))
89                                    ;; This is where we handle packed primitive types
90                                    ;; Packed enums get handled below
91                                    (let ((tag (make-tag type (proto-index field))))
92                                      (setq index (serialize-packed (read-slot object slot reader)
93                                                                    type tag buffer index))))
94                                   ((keywordp type)
95                                    (let ((tag (make-tag type (proto-index field))))
96                                      (map () #'(lambda (v)
97                                                  (setq index (serialize-prim v type tag buffer index)))
98                                              (read-slot object slot reader))))
99                                   ((typep (setq msg (and type (or (find-message trace type)
100                                                                   (find-enum trace type))))
101                                           'protobuf-message)
102                                    (if (eq (proto-message-type msg) :group)
103                                      (map () #'(lambda (v)
104                                                  ;; To serialize a group, we encode a start tag,
105                                                  ;; serialize the fields, then encode an end tag
106                                                  (let ((tag1 (make-tag $wire-type-start-group (proto-index field)))
107                                                        (tag2 (make-tag $wire-type-end-group   (proto-index field))))
108                                                    (setq index (encode-uint32 tag1 buffer index))
109                                                    (map () (curry #'do-field v msg)
110                                                            (proto-fields msg))
111                                                    (setq index (encode-uint32 tag2 buffer index))))
112                                              (if slot (read-slot object slot reader) (list object)))
113                                      (map () #'(lambda (v)
114                                                  ;; To serialize an embedded message, first say that it's
115                                                  ;; a string, then encode its size, then serialize its fields
116                                                  (let ((tag (make-tag $wire-type-string (proto-index field)))
117                                                        (len (object-size v msg visited)))
118                                                    (setq index (encode-uint32 tag buffer index))
119                                                    (setq index (encode-uint32 len buffer index)))
120                                                  (map () (curry #'do-field v msg)
121                                                          (proto-fields msg)))
122                                              (if slot (read-slot object slot reader) (list object)))))
123                                   ((typep msg 'protobuf-enum)
124                                    (let ((tag (make-tag $wire-type-varint (proto-index field))))
125                                      ;; 'proto-packed-p' of enum types returns nil,
126                                      ;; so packed enum fields won't be handled above
127                                      (if (proto-packed field)
128                                        (setq index (serialize-packed-enum (read-slot object slot reader)
129                                                                           (proto-values msg) tag buffer index))
130                                        (map () #'(lambda (v)
131                                                    (setq index (serialize-enum v (proto-values msg) tag buffer index)))
132                                                (read-slot object slot reader)))))))
133                            (t
134                             (cond ((eq type :bool)
135                                    ;; We have to handle optional boolean fields specially
136                                    ;; because "false" and nil are the same value in Lisp
137                                    (let ((v (cond ((or (eq (proto-required field) :required)
138                                                        (null slot))
139                                                    (read-slot object slot reader))
140                                                   ((slot-boundp object slot)
141                                                    (read-slot object slot reader))
142                                                   (t :unbound))))
143                                      (unless (eq v :unbound)
144                                        (let ((tag (make-tag :bool (proto-index field))))
145                                          (setq index (serialize-prim v type tag buffer index))))))
146                                   ((keywordp type)
147                                    (let ((v (read-slot object slot reader)))
148                                      (when v
149                                        (let ((tag (make-tag type (proto-index field))))
150                                          (setq index (serialize-prim v type tag buffer index))))))
151                                   ((typep (setq msg (and type (or (find-message trace type)
152                                                                   (find-enum trace type))))
153                                           'protobuf-message)
154                                    (let ((v (if slot (read-slot object slot reader) object)))
155                                      (when v
156                                        (if (eq (proto-message-type msg) :group)
157                                          (let ((tag1 (make-tag $wire-type-start-group (proto-index field)))
158                                                (tag2 (make-tag $wire-type-end-group   (proto-index field))))
159                                            (setq index (encode-uint32 tag1 buffer index))
160                                            (map () (curry #'do-field v msg)
161                                                    (proto-fields msg))
162                                            (setq index (encode-uint32 tag2 buffer index)))
163                                          (let ((tag (make-tag $wire-type-string (proto-index field)))
164                                                (len (object-size v msg visited)))
165                                            (setq index (encode-uint32 tag buffer index))
166                                            (setq index (encode-uint32 len buffer index))
167                                            (map () (curry #'do-field v msg)
168                                                    (proto-fields msg)))))))
169                                   ((typep msg 'protobuf-enum)
170                                    (let ((v (read-slot object slot reader)))
171                                      (when v
172                                        (let ((tag (make-tag $wire-type-varint (proto-index field))))
173                                          (setq index (serialize-enum v (proto-values msg) tag buffer index)))))))))))))
174         (declare (dynamic-extent #'do-field))
175         (map () (curry #'do-field object message) (proto-fields message))))
176     (values buffer index)))
177
178
179 ;;; Deserialization
180
181 (defun deserialize-object-from-stream (type &key (stream *standard-input*))
182   "Deserializes an object of the given type 'type' as a Protobuf object.
183    'type' is the Lisp name of a Protobufs message (usually the name of a 
184    Lisp class) or a 'protobuf-message'.
185    The return value is the object."
186   (let* ((size    (file-length stream))
187          (buffer  (make-byte-vector size)))
188     (read-sequence buffer stream)
189     (deserialize-object type buffer 0 size)))
190
191 (defun deserialize-object-from-file (type filename)
192   (with-open-file (stream filename
193                    :direction :input
194                    :element-type '(unsigned-byte 8))
195     (deserialize-object-from-stream type :stream stream)))
196
197 ;; Allow clients to add their own methods
198 ;; This is you might preserve object identity, e.g.
199 (defgeneric deserialize-object (type buffer &optional start end end-tag)
200   (:documentation
201    "Deserializes an object of the given type 'type' as a Protobufs object.
202     'type' is the Lisp name of a Protobufs message (usually the name of a 
203     Lisp class) or a 'protobuf-message'.
204     The encoded bytes are in the byte array given by 'buffer' starting at
205     the fixnum index 'start' up to the end of the buffer, given by 'end'.
206     'start' defaults to 0, 'end' defaults to the length of the buffer.
207     'end-tag' is used internally to handle the (deprecated) \"group\" feature.
208     The return values are the object and the index at which deserialization stopped.."))
209
210 (defmethod deserialize-object (type buffer &optional start end (end-tag 0))
211   (let ((message (find-message-for-class type)))
212     (assert message ()
213             "There is no Protobuf message having the type ~S" type)
214     (deserialize-object message buffer start end end-tag)))
215
216 ;; The default method uses metadata from the protobuf "schema" for the message
217 (defmethod deserialize-object ((message protobuf-message) buffer &optional start end (end-tag 0))
218   (declare (type (simple-array (unsigned-byte 8)) buffer))
219   (let ((index   (or start 0))
220         (length  (or end (length buffer))))
221     (declare (type fixnum index length))
222     (macrolet ((read-slot (object slot reader)
223                  `(if ,reader
224                     (funcall ,reader ,object)
225                     (slot-value ,object ,slot)))
226                (write-slot (object slot writer value)
227                  (with-gensyms (vval)
228                    `(let ((,vval ,value))
229                       (if ,writer
230                         (funcall ,writer ,object ,vval)
231                         (setf (slot-value ,object ,slot) ,vval))))))
232       (labels ((deserialize (type trace end end-tag)
233                  (declare (type fixnum end end-tag))
234                  (let* ((message (find-message trace type))
235                         (object  (and message
236                                       (make-instance (or (proto-alias-for message) (proto-class message)))))
237                         ;; All the slots into which we store a repeated element
238                         ;; These will be reversed at the end of deserialization
239                         (rslots ()))
240                    (loop
241                      (multiple-value-bind (tag idx)
242                          (if (i< index end) (decode-uint32 buffer index) (values 0 index))
243                        ;; We're done if we've gotten to the end index or
244                        ;; we see an end tag that matches a previous group's start tag
245                        ;; Note that the default end tag is 0, which is also an end of
246                        ;; message marker (there can never be "real" zero tags because
247                        ;; field indices start at 1)
248                        (setq index idx)
249                        (when (i= tag end-tag)
250                          ;; Reverse the repeated slots
251                          (dolist (field rslots)
252                            (let ((slot   (proto-value field))
253                                  (reader (proto-reader field))
254                                  (writer (proto-writer field)))
255                              (write-slot object slot writer
256                                          (nreverse (read-slot object slot reader)))))
257                          (return-from deserialize
258                            (values object index)))
259                        (let* ((fidx  (ilogand (iash tag -3) #x1FFFFFFF))
260                               (field (find fidx (proto-fields message) :key #'proto-index))
261                               (type  (and field (if (eq (proto-class field) 'boolean) :bool (proto-class field))))
262                               ;; It's OK for this to be null
263                               ;; That means we're parsing some version of a message
264                               ;; that has the field, but our current message does not
265                               ;; We still have to deserialize everything, though
266                               (slot   (and field (proto-value field)))
267                               (reader (and field (proto-reader field)))
268                               (writer (and field (proto-writer field)))
269                               msg)
270                          (if (null field)
271                            ;; If there's no field descriptor for this index, just skip
272                            ;; the next element in the buffer having the given wire type
273                            (setq index (skip-element buffer index tag))
274                            ;;--- Check for mismatched wire type, running past end of buffer, etc
275                            (cond ((and field (eq (proto-required field) :repeated))
276                                   (let ((vectorp (vector-field-p field)))
277                                     (cond ((and (proto-packed field) (packed-type-p type))
278                                            (multiple-value-bind (values idx)
279                                                (deserialize-packed type buffer index)
280                                              (setq index idx)
281                                              (if vectorp
282                                                (let ((values (make-array (length values)
283                                                                :fill-pointer t :adjustable t
284                                                                :initial-contents values)))
285                                                  (write-slot object slot writer values))
286                                                (write-slot object slot writer values))))
287                                           ((keywordp type)
288                                            (multiple-value-bind (val idx)
289                                                (deserialize-prim type buffer index)
290                                              (setq index idx)
291                                              (cond (vectorp
292                                                     (vector-push-extend val (read-slot object slot reader)))
293                                                    (t
294                                                     (pushnew field rslots)
295                                                     ;; This "push" could type-check the entire list if
296                                                     ;; there's a parameterized list type in effect,
297                                                     ;; so you'll want to avoid using such types
298                                                     ;; We'll reverse the slots at the last minute
299                                                     (write-slot object slot writer
300                                                                 (cons val (read-slot object slot reader)))))))
301                                           ((typep (setq msg (and type (or (find-message trace type)
302                                                                           (find-enum trace type))))
303                                                   'protobuf-message)
304                                            (if (eq (proto-message-type msg) :group)
305                                              (let* ((etag (make-tag $wire-type-end-group fidx))
306                                                     (obj  (deserialize type msg length etag)))
307                                                (cond (vectorp
308                                                       (vector-push-extend obj (read-slot object slot reader)))
309                                                      (t
310                                                       (pushnew field rslots)
311                                                       (write-slot object slot writer
312                                                                   (cons obj (read-slot object slot reader))))))
313                                              (multiple-value-bind (len idx)
314                                                  (decode-uint32 buffer index)
315                                                (setq index idx)
316                                                (let ((obj (deserialize type msg (+ index len) 0)))
317                                                  (cond (vectorp
318                                                         (vector-push-extend obj (read-slot object slot reader)))
319                                                        (t
320                                                         (pushnew field rslots)
321                                                         (write-slot object slot writer
322                                                                     (cons obj (read-slot object slot reader)))))))))
323                                           ((typep msg 'protobuf-enum)
324                                            (if (proto-packed field)
325                                              (multiple-value-bind (values idx)
326                                                  (deserialize-packed-enum (proto-values msg) buffer index)
327                                                (setq index idx)
328                                                (if vectorp
329                                                  (let ((values (make-array (length values)
330                                                                  :fill-pointer t :adjustable t
331                                                                  :initial-contents values)))
332                                                    (write-slot object slot writer values))
333                                                  (write-slot object slot writer values)))
334                                              (multiple-value-bind (val idx)
335                                                  (deserialize-enum (proto-values msg) buffer index)
336                                                (setq index idx)
337                                                (cond (vectorp
338                                                       (vector-push-extend val (read-slot object slot reader)))
339                                                      (t
340                                                       (pushnew field rslots)
341                                                       (write-slot object slot writer
342                                                                   (cons val (read-slot object slot reader)))))))))))
343                                  (t
344                                   (cond ((keywordp type)
345                                          (multiple-value-bind (val idx)
346                                              (deserialize-prim type buffer index)
347                                            (setq index idx)
348                                            (write-slot object slot writer val)))
349                                         ((typep (setq msg (and type (or (find-message trace type)
350                                                                         (find-enum trace type))))
351                                                 'protobuf-message)
352                                          ;;--- If there's already a value in the slot, merge messages
353                                          (if (eq (proto-message-type msg) :group)
354                                            (let* ((etag (make-tag $wire-type-end-group fidx))
355                                                   (obj  (deserialize type msg length etag)))
356                                              (write-slot object slot writer obj))
357                                            (multiple-value-bind (len idx)
358                                                (decode-uint32 buffer index)
359                                              (setq index idx)
360                                              (let ((obj (deserialize type msg (+ index len) 0)))
361                                                (write-slot object slot writer obj)))))
362                                         ((typep msg 'protobuf-enum)
363                                          (multiple-value-bind (val idx)
364                                              (deserialize-enum (proto-values msg) buffer index)
365                                            (setq index idx)
366                                            (write-slot object slot writer val)))))))))))))
367         (declare (dynamic-extent #'deserialize))
368         (deserialize (proto-class message) message length end-tag)))))
369
370 ;;; Object sizes
371
372 ;; Allow clients to add their own methods
373 ;; This is how we address the problem of cycles, e.g. -- if you have an object
374 ;; that may contain cycles, return the size of the "handle" to the object
375 (defgeneric object-size (object type &optional visited)
376   (:documentation
377    "Computes the size in bytes of the object 'object' of type 'type'.
378     'type' is the Lisp name of a Protobufs message (usually the name of a 
379     Lisp class) or a 'protobuf-message'.
380     'visited' is a hash table used to cache object sizes.
381     The return value is the size of the object in bytes."))
382
383 (defmethod object-size (object type &optional visited)
384   (let ((message (find-message-for-class type)))
385     (assert message ()
386             "There is no Protobuf message having the type ~S" type)
387     (object-size object message visited)))
388
389 ;; 'visited' is used to cache object sizes
390 ;; The default method uses metadata from the protobuf "schema" for the message
391 (defmethod object-size (object (message protobuf-message) &optional visited)
392   (let ((size (and visited (gethash object visited))))
393     (when size
394       (return-from object-size size)))
395   (let ((size 0))
396     (declare (type fixnum size))
397     (macrolet ((read-slot (object slot reader)
398                  ;; Don't do a boundp check, we assume the object is fully populated
399                  ;; Unpopulated slots should be "nullable" and should contain nil
400                  `(if ,reader
401                     (funcall ,reader ,object)
402                     (slot-value ,object ,slot))))
403       (labels ((do-field (object trace field)
404                  ;; We don't do cycle detection here
405                  ;; If the client needs it, he can define his own 'object-size'
406                  ;; method to clean things up first
407                  (let* ((type   (if (eq (proto-class field) 'boolean) :bool (proto-class field)))
408                         (slot   (proto-value field))
409                         (reader (proto-reader field))
410                         msg)
411                    (when (or slot reader)
412                      (cond ((eq (proto-required field) :repeated)
413                             (cond ((and (proto-packed field) (packed-type-p type))
414                                    (let ((tag (make-tag type (proto-index field))))
415                                      (iincf size (packed-size (read-slot object slot reader) type tag))))
416                                   ((keywordp type)
417                                    (let ((tag (make-tag type (proto-index field))))
418                                      (map () #'(lambda (v)
419                                                  (iincf size (prim-size v type tag)))
420                                              (read-slot object slot reader))))
421                                   ((typep (setq msg (and type (or (find-message trace type)
422                                                                   (find-enum trace type))))
423                                           'protobuf-message)
424                                    (if (eq (proto-message-type msg) :group)
425                                      (map () #'(lambda (v)
426                                                  (let ((tag1 (make-tag $wire-type-start-group (proto-index field)))
427                                                        (tag2 (make-tag $wire-type-end-group   (proto-index field))))
428                                                    (iincf size (length32 tag1))
429                                                    (map () (curry #'do-field v msg)
430                                                            (proto-fields msg))
431                                                    (iincf size (length32 tag2))))
432                                              (if slot (read-slot object slot reader) (list object)))
433                                      (map () #'(lambda (v)
434                                                  (let ((tag (make-tag $wire-type-string (proto-index field)))
435                                                        (len (object-size v msg visited)))
436                                                    (iincf size (length32 tag))
437                                                    (iincf size (length32 len))
438                                                    (map () (curry #'do-field v msg)
439                                                            (proto-fields msg))))
440                                              (if slot (read-slot object slot reader) (list object)))))
441                                   ((typep msg 'protobuf-enum)
442                                    (let ((tag (make-tag $wire-type-varint (proto-index field))))
443                                      (if (proto-packed field)
444                                        (iincf size (packed-enum-size (read-slot object slot reader) type tag))
445                                        (map () #'(lambda (v)
446                                                    (iincf size (enum-size v (proto-values msg) tag)))
447                                                (read-slot object slot reader)))))))
448                            (t
449                             (cond ((eq type :bool)
450                                    (let ((v (cond ((or (eq (proto-required field) :required)
451                                                        (null slot))
452                                                    (read-slot object slot reader))
453                                                   ((slot-boundp object slot)
454                                                    (read-slot object slot reader))
455                                                   (t :unbound))))
456                                      (unless (eq v :unbound)
457                                        (let ((tag (make-tag :bool (proto-index field))))
458                                          (iincf size (prim-size v type tag))))))
459                                   ((keywordp type)
460                                    (let ((v (read-slot object slot reader)))
461                                      (when v
462                                        (let ((tag (make-tag type (proto-index field))))
463                                          (iincf size (prim-size v type tag))))))
464                                   ((typep (setq msg (and type (or (find-message trace type)
465                                                                   (find-enum trace type))))
466                                           'protobuf-message)
467                                    (let ((v (if slot (read-slot object slot reader) object)))
468                                      (when v
469                                        (if (eq (proto-message-type msg) :group)
470                                          (let ((tag1 (make-tag $wire-type-start-group (proto-index field)))
471                                              (tag2 (make-tag $wire-type-end-group   (proto-index field))))
472                                            (iincf size (length32 tag1))
473                                            (map () (curry #'do-field v msg)
474                                                    (proto-fields msg))
475                                            (iincf size (length32 tag2)))
476                                          (let ((tag (make-tag $wire-type-string (proto-index field)))
477                                                (len (object-size v msg visited)))
478                                            (iincf size (length32 tag))
479                                            (iincf size (length32 len))
480                                            (map () (curry #'do-field v msg)
481                                                 (proto-fields msg)))))))
482                                   ((typep msg 'protobuf-enum)
483                                    (let ((v (read-slot object slot reader)))
484                                      (when v
485                                        (let ((tag (make-tag $wire-type-varint (proto-index field))))
486                                          (iincf size (enum-size (read-slot object slot reader) (proto-values msg) tag)))))))))))))
487         (declare (dynamic-extent #'do-field))
488         (map () (curry #'do-field object message) (proto-fields message))
489         (when visited
490           (setf (gethash object visited) size))   ;cache the size
491         size))))
492
493 \f
494 ;;; Compile-time generation of serializers
495 ;;; Type-checking is done at the top-level methods specialized on 'symbol',
496 ;;; so we turn off all type checking at the level of these functions
497
498 ;; Note well: keep this in sync with the main 'serialize-object' method above
499 (defun generate-serializer (message)
500   "Generate a 'serialize-object' method for the given message."
501   (with-gensyms (vobj vbuf vidx vval vclass)
502     (when (null (proto-fields message))
503       (return-from generate-serializer
504         `(defmethod serialize-object
505            (,vobj (,vclass (eql ,message)) ,vbuf &optional (,vidx 0) visited)
506          (declare #.$optimize-serialization)
507          (declare (ignorable ,vobj ,vclass visited)
508                   (type (simple-array (unsigned-byte 8)) ,vbuf)
509                   (type fixnum ,vidx))
510          (values ,vbuf ,vidx))))
511     (with-collectors ((serializers collect-serializer))
512       (dolist (field (proto-fields message))
513         (let* ((class  (if (eq (proto-class field) 'boolean) :bool (proto-class field)))
514                (msg    (and class (not (keywordp class))
515                             (or (find-message message class)
516                                 (find-enum message class))))
517                (reader (cond ((proto-reader field)
518                               `(,(proto-reader field) ,vobj))
519                              ((proto-value field)
520                               `(slot-value ,vobj ',(proto-value field)))))
521                (index  (proto-index field)))
522           (when reader
523             (cond ((eq (proto-required field) :repeated)
524                    (let ((iterator (if (vector-field-p field) 'dovector 'dolist)))
525                      (cond ((and (proto-packed field) (packed-type-p class))
526                             (collect-serializer
527                              (let ((tag (make-tag class index)))
528                                `(setq ,vidx (serialize-packed ,reader ,class ,tag ,vbuf ,vidx)))))
529                            ((keywordp class)
530                             (collect-serializer
531                              (let ((tag (make-tag class index)))
532                                `(,iterator (,vval ,reader)
533                                   (setq ,vidx (serialize-prim ,vval ,class ,tag ,vbuf ,vidx))))))
534                            ((typep msg 'protobuf-message)
535                             (collect-serializer
536                              (if (eq (proto-message-type msg) :group)
537                                (let ((tag1 (make-tag $wire-type-start-group index))
538                                      (tag2 (make-tag $wire-type-end-group   index)))
539                                  `(,iterator (,vval ,reader)
540                                     (let ((len (or (and visited (gethash ,vval visited))
541                                                    (object-size ,vval ,msg visited))))
542                                       (setq ,vidx (encode-uint32 ,tag1 ,vbuf ,vidx))
543                                       (serialize-object ,vval ,msg ,vbuf ,vidx visited)
544                                       (iincf ,vidx len)
545                                       (setq ,vidx (encode-uint32 ,tag2 ,vbuf ,vidx)))))
546                                (let ((tag (make-tag $wire-type-string index)))
547                                  `(,iterator (,vval ,reader)
548                                     (let ((len (or (and visited (gethash ,vval visited))
549                                                    (object-size ,vval ,msg visited))))
550                                       (setq ,vidx (encode-uint32 ,tag ,vbuf ,vidx))
551                                       (setq ,vidx (encode-uint32 len ,vbuf ,vidx))
552                                       (serialize-object ,vval ,msg ,vbuf ,vidx visited)
553                                       (iincf ,vidx len)))))))
554                            ((typep msg 'protobuf-enum)
555                             (collect-serializer
556                              (let ((tag (make-tag $wire-type-varint index)))
557                                (if (proto-packed field)
558                                  `(setq ,vidx (serialize-packed-enum ,reader '(,@(proto-values msg)) ,tag ,vbuf ,vidx))
559
560                                  `(,iterator (,vval ,reader)
561                                     (setq ,vidx (serialize-enum ,vval '(,@(proto-values msg)) ,tag ,vbuf ,vidx))))))))))
562                   (t
563                    (cond ((keywordp class)
564                           (collect-serializer
565                            (let ((tag (make-tag class index)))
566                              (if (eq class :bool)
567                                (if (or (eq (proto-required field) :required)
568                                        reader)
569                                  `(let ((,vval ,reader))
570                                     (setq ,vidx (serialize-prim ,vval ,class ,tag ,vbuf ,vidx)))
571                                  `(let ((,vval (cond ((slot-boundp ,vobj ',(proto-value field))
572                                                       ,reader)
573                                                      (t :unbound))))
574                                     (unless (eq ,vval :unbound)
575                                       (setq ,vidx (serialize-prim ,vval ,class ,tag ,vbuf ,vidx)))))
576                                `(let ((,vval ,reader))
577                                   (when ,vval
578                                     (setq ,vidx (serialize-prim ,vval ,class ,tag ,vbuf ,vidx))))))))
579                          ((typep msg 'protobuf-message)
580                           (collect-serializer
581                            (if (eq (proto-message-type msg) :group)
582                              (let ((tag1 (make-tag $wire-type-start-group index))
583                                    (tag2 (make-tag $wire-type-end-group   index)))
584                                `(let ((,vval ,reader))
585                                   (when ,vval
586                                     (let ((len (or (and visited (gethash ,vval visited))
587                                                    (object-size ,vval ,msg visited))))
588                                       (setq ,vidx (encode-uint32 ,tag1 ,vbuf ,vidx))
589                                       (serialize-object ,vval ,msg ,vbuf ,vidx visited)
590                                       (iincf ,vidx len)
591                                       (setq ,vidx (encode-uint32 ,tag2 ,vbuf ,vidx))))))
592                              (let ((tag (make-tag $wire-type-string index)))
593                                `(let ((,vval ,reader))
594                                   (when ,vval
595                                     (let ((len (or (and visited (gethash ,vval visited))
596                                                    (object-size ,vval ,msg visited))))
597                                       (setq ,vidx (encode-uint32 ,tag ,vbuf ,vidx))
598                                       (setq ,vidx (encode-uint32 len ,vbuf ,vidx))
599                                       (serialize-object ,vval ,msg ,vbuf ,vidx visited)
600                                       (iincf ,vidx len))))))))
601                          ((typep msg 'protobuf-enum)
602                           (collect-serializer
603                            (let ((tag (make-tag $wire-type-varint index)))
604                              `(let ((,vval ,reader))
605                                 (when ,vval
606                                   (setq ,vidx (serialize-enum ,vval '(,@(proto-values msg)) ,tag ,vbuf ,vidx)))))))))))))
607       `(defmethod serialize-object
608            (,vobj (,vclass (eql ,message)) ,vbuf &optional (,vidx 0) visited)
609          (declare #.$optimize-serialization)
610          (declare (ignorable visited)
611                   (type (simple-array (unsigned-byte 8)) ,vbuf)
612                   (type fixnum ,vidx))
613          ,@serializers
614          (values ,vbuf ,vidx)))))
615
616 ;; Note well: keep this in sync with the main 'deserialize-object' method above
617 (defun generate-deserializer (message)
618   "Generate a 'deserialize-object' method for the given message."
619   (with-gensyms (vclass vbuf vidx vlen vendtag vobj vval)
620     (when (null (proto-fields message))
621       (return-from generate-deserializer
622         `(defmethod deserialize-object
623              ((,vclass (eql ,message)) ,vbuf &optional ,vidx ,vlen (,vendtag 0))
624            (declare #.$optimize-serialization)
625            (declare (ignorable ,vclass ,vbuf ,vlen ,vendtag)
626                     (type (simple-array (unsigned-byte 8)) ,vbuf))
627            (let ((,vidx (or ,vidx 0)))
628              (declare (type fixnum ,vidx))
629              (let ((,vobj (make-instance ',(or (proto-alias-for message) (proto-class message)))))
630                (values ,vobj ,vidx))))))
631     (with-collectors ((deserializers collect-deserializer)
632                       ;; For tracking repeated slots that will need to be reversed
633                       (rslots collect-rslot))
634       (flet ((read-slot (object field)
635                (cond ((proto-reader field)
636                       `(,(proto-reader field) ,object))
637                      ((proto-value field)
638                       `(slot-value ,object ',(proto-value field)))))
639              (write-slot (object field value)
640                (cond ((proto-writer field)
641                       `(,(proto-writer field) ,object ,value))
642                      ((proto-value field)
643                       `(setf (slot-value ,object ',(proto-value field)) ,value)))))
644         (dolist (field (proto-fields message))
645           (let* ((class  (if (eq (proto-class field) 'boolean) :bool (proto-class field)))
646                  (msg    (and class (not (keywordp class))
647                               (or (find-message message class)
648                                   (find-enum message class))))
649                  (index  (proto-index field)))
650             (cond ((eq (proto-required field) :repeated)
651                    (cond ((and (proto-packed field) (packed-type-p class))
652                           (collect-deserializer
653                            `((,(make-tag class index))
654                              (multiple-value-bind (,vval idx)
655                                  (deserialize-packed ,class ,vbuf ,vidx)
656                                (setq ,vidx idx)
657                                ,@(when (vector-field-p field)
658                                    `((setq ,vval (make-array (length ,vval)
659                                                    :fill-pointer t :adjustable t
660                                                    :initial-contents ,vval))))
661                                ,(write-slot vobj field vval)))))
662                          ((keywordp class)
663                           (let ((temp (gensym (string (proto-value field)))))
664                             (collect-rslot (list field temp))
665                             (collect-deserializer
666                              `((,(make-tag class index))
667                                (multiple-value-bind (,vval idx)
668                                    (deserialize-prim ,class ,vbuf ,vidx)
669                                  (setq ,vidx idx)
670                                  (push ,vval ,temp))))))
671                          ((typep msg 'protobuf-message)
672                           (let ((temp (gensym (string (proto-value field)))))
673                             (collect-rslot (list field temp))
674                             (collect-deserializer
675                              (if (eq (proto-message-type msg) :group)
676                                `((,(make-tag $wire-type-start-group index))
677                                  (multiple-value-bind (,vval idx)
678                                      (deserialize-object ,msg ,vbuf ,vidx ,vlen
679                                                          ,(make-tag $wire-type-end-group index))
680                                    (setq ,vidx idx)
681                                    (push ,vval ,temp)))
682                                `((,(make-tag $wire-type-string index))
683                                  (multiple-value-bind (len idx)
684                                      (decode-uint32 ,vbuf ,vidx)
685                                    (setq ,vidx idx)
686                                    (multiple-value-bind (,vval idx)
687                                        (deserialize-object ,msg ,vbuf ,vidx (i+ ,vidx len) 0)
688                                      (setq ,vidx idx)
689                                      (push ,vval ,temp))))))))
690                          ((typep msg 'protobuf-enum)
691                           (if (proto-packed field)
692                             (collect-deserializer
693                              `((,(make-tag $wire-type-varint index))
694                                (multiple-value-bind (,vval idx)
695                                    (deserialize-packed-enum '(,@(proto-values msg)) ,vbuf ,vidx)
696                                  (setq ,vidx idx)
697                                  ,(write-slot vobj field vval))))
698                             (let ((temp (gensym (string (proto-value field)))))
699                               (collect-rslot (list field temp))
700                               (collect-deserializer
701                                `((,(make-tag $wire-type-varint index))
702                                  (multiple-value-bind (,vval idx)
703                                      (deserialize-enum '(,@(proto-values msg)) ,vbuf ,vidx)
704                                    (setq ,vidx idx)
705                                    (push ,vval ,temp)))))))))
706                   (t
707                    (cond ((keywordp class)
708                           (collect-deserializer
709                            `((,(make-tag class index))
710                              (multiple-value-bind (,vval idx)
711                                  (deserialize-prim ,class ,vbuf ,vidx)
712                                (setq ,vidx idx)
713                                ,(write-slot vobj field vval)))))
714                          ((typep msg 'protobuf-message)
715                           (collect-deserializer
716                            (if (eq (proto-message-type msg) :group)
717                              `((,(make-tag $wire-type-start-group index))
718                                (multiple-value-bind (,vval idx)
719                                    (deserialize-object ,msg ,vbuf ,vidx  ,vlen
720                                                        ,(make-tag $wire-type-end-group index))
721                                  (setq ,vidx idx)
722                                  ,(write-slot vobj field vval)))
723                              `((,(make-tag $wire-type-string index))
724                                (multiple-value-bind (len idx)
725                                    (decode-uint32 ,vbuf ,vidx)
726                                  (setq ,vidx idx)
727                                  (multiple-value-bind (,vval idx)
728                                      (deserialize-object ,msg ,vbuf ,vidx (i+ ,vidx len) 0)
729                                    (setq ,vidx idx)
730                                    ,(write-slot vobj field vval)))))))
731                          ((typep msg 'protobuf-enum)
732                           (collect-deserializer
733                            `((,(make-tag $wire-type-varint index))
734                              (multiple-value-bind (,vval idx)
735                                  (deserialize-enum '(,@(proto-values msg)) ,vbuf ,vidx)
736                                (setq ,vidx idx)
737                                ,(write-slot vobj field vval)))))))))))
738       (let* ((rslots  (delete-duplicates rslots :key #'first))
739              (rfields (mapcar #'first  rslots))
740              (rtemps  (mapcar #'second rslots)))
741         `(defmethod deserialize-object
742              ((,vclass (eql ,message)) ,vbuf &optional ,vidx ,vlen (,vendtag 0))
743            (declare #.$optimize-serialization)
744            (declare (type (simple-array (unsigned-byte 8)) ,vbuf))
745            (let ((,vidx (or ,vidx 0))
746                  (,vlen (or ,vlen (length ,vbuf))))
747              (declare (type fixnum ,vidx ,vlen))
748              (let ((,vobj (make-instance ',(or (proto-alias-for message) (proto-class message))))
749                    ;; Bind the temporary variables that hold repeated slots
750                    ,@rtemps)
751                (loop
752                  (multiple-value-bind (tag idx)
753                      (if (i< ,vidx ,vlen) (decode-uint32 ,vbuf ,vidx) (values 0 ,vidx))
754                    (setq ,vidx idx)
755                    (when (i= tag ,vendtag)
756                      ;; Set the (un)reversed values of the repeated slots
757                      ,@(loop for field in rfields
758                              for temp in rtemps
759                              as slot = (proto-value field)
760                              as writer = (proto-writer field)
761                              collect (cond ((vector-field-p field)
762                                             (if writer
763                                               `(funcall ,writer ,vobj (make-array (length ,temp)
764                                                                         :fill-pointer t :adjustable t
765                                                                         :initial-contents (nreverse ,temp)))
766                                               `(setf (slot-value ,vobj ',slot) (make-array (length ,temp)
767                                                                                  :fill-pointer t :adjustable t
768                                                                                  :initial-contents (nreverse ,temp)))))
769                                            (t
770                                             (if writer
771                                               `(funcall ,writer ,vobj (nreverse ,temp))
772                                               `(setf (slot-value ,vobj ',slot) (nreverse ,temp))))))
773                      (return-from deserialize-object
774                        (values ,vobj ,vidx)))
775                    (case tag
776                      ,@deserializers
777                      (otherwise
778                       (setq ,vidx (skip-element ,vbuf ,vidx tag)))))))))))))
779
780 ;; Note well: keep this in sync with the main 'object-size' method above
781 (defun generate-object-size (message)
782   "Generate an 'object-size' method for the given message."
783   (with-gensyms (vobj vsize vval vclass)
784     (when (null (proto-fields message))
785       (return-from generate-object-size
786         `(defmethod object-size
787              (,vobj (,vclass (eql ,message)) &optional visited)
788          (declare #.$optimize-serialization)
789          (declare (ignorable ,vobj visited))
790          0)))
791     (with-collectors ((sizers collect-sizer))
792       (dolist (field (proto-fields message))
793         (let* ((class  (if (eq (proto-class field) 'boolean) :bool (proto-class field)))
794                (msg    (and class (not (keywordp class))
795                             (or (find-message message class)
796                                 (find-enum message class))))
797                (reader (cond ((proto-reader field)
798                               `(,(proto-reader field) ,vobj))
799                              ((proto-value field)
800                               `(slot-value ,vobj ',(proto-value field)))))
801                (index  (proto-index field)))
802           (when reader
803             (cond ((eq (proto-required field) :repeated)
804                    (let ((iterator (if (vector-field-p field) 'dovector 'dolist)))
805                      (cond ((and (proto-packed field) (packed-type-p class))
806                             (collect-sizer
807                              (let ((tag (make-tag class index)))
808                                `(iincf ,vsize (packed-size ,reader ,class ,tag)))))
809                            ((keywordp class)
810                             (collect-sizer
811                              (let ((tag (make-tag class index)))
812                                `(,iterator (,vval ,reader)
813                                   (iincf ,vsize (prim-size ,vval ,class ,tag))))))
814                            ((typep msg 'protobuf-message)
815                             (collect-sizer
816                              (if (eq (proto-message-type msg) :group)
817                                (let ((tag1 (make-tag $wire-type-start-group index))
818                                      (tag2 (make-tag $wire-type-end-group   index)))
819                                  `(,iterator (,vval ,reader)
820                                     (let ((len (or (and visited (gethash ,vval visited))
821                                                    (object-size ,vval ,msg visited))))
822                                       (iincf ,vsize (length32 ,tag1))
823                                       (iincf ,vsize len)
824                                       (iincf ,vsize ,tag2))))
825                                (let ((tag (make-tag $wire-type-string index)))
826                                  `(,iterator (,vval ,reader)
827                                     (let ((len (or (and visited (gethash ,vval visited))
828                                                    (object-size ,vval ,msg visited))))
829                                       (iincf ,vsize (length32 ,tag))
830                                       (iincf ,vsize (length32 len))
831                                       (iincf ,vsize len)))))))
832                            ((typep msg 'protobuf-enum)
833                             (let ((tag (make-tag $wire-type-varint index)))
834                               (collect-sizer
835                                (if (proto-packed field)
836                                  `(iincf ,vsize (packed-enum-size ,reader '(,@(proto-values msg)) ,tag))
837                                  `(,iterator (,vval ,reader)
838                                     (iincf ,vsize (enum-size ,vval '(,@(proto-values msg)) ,tag))))))))))
839                   (t
840                    (cond ((keywordp class)
841                           (let ((tag (make-tag class index)))
842                             (collect-sizer
843                              (if (eq class :bool)
844                                (if (or (eq (proto-required field) :required)
845                                        reader)
846                                  `(let ((,vval ,reader))
847                                     (declare (ignorable ,vval))
848                                     (iincf ,vsize (prim-size ,vval ,class ,tag)))
849                                  `(let ((,vval (cond ((slot-boundp ,vobj ',(proto-value field))
850                                                       ,reader)
851                                                      (t :unbound))))
852                                     (unless (eq ,vval :unbound)
853                                       (iincf ,vsize (prim-size ,vval ,class ,tag)))))
854                                `(let ((,vval ,reader))
855                                   (when ,vval
856                                     (iincf ,vsize (prim-size ,vval ,class ,tag))))))))
857                          ((typep msg 'protobuf-message)
858                           (collect-sizer
859                            (if (eq (proto-message-type msg) :group)
860                              (let ((tag1 (make-tag $wire-type-start-group index))
861                                    (tag2 (make-tag $wire-type-end-group   index)))
862                                `(let ((,vval ,reader))
863                                   (when ,vval
864                                     (let ((len (or (and visited (gethash ,vval visited))
865                                                    (object-size ,vval ,msg visited))))
866                                       (iincf ,vsize (length32 ,tag1))
867                                       (iincf ,vsize len)
868                                       (iincf ,vsize (length32 ,tag2))))))
869                              (let ((tag (make-tag $wire-type-string index)))
870                                `(let ((,vval ,reader))
871                                   (when ,vval
872                                     (let ((len (or (and visited (gethash ,vval visited))
873                                                    (object-size ,vval ,msg visited))))
874                                       (iincf ,vsize (length32 ,tag))
875                                       (iincf ,vsize (length32 len))
876                                       (iincf ,vsize len))))))))
877                          ((typep msg 'protobuf-enum)
878                           (let ((tag (make-tag $wire-type-varint index)))
879                             (collect-sizer
880                              `(let ((,vval ,reader))
881                                 (when ,vval
882                                   (iincf ,vsize (enum-size ,vval '(,@(proto-values msg)) ,tag)))))))))))))
883       `(defmethod object-size
884            (,vobj (,vclass (eql ,message)) &optional visited)
885          (declare #.$optimize-serialization)
886          (declare (ignorable visited))
887          (let ((,vsize (and visited (gethash ,vobj visited))))
888            (when ,vsize
889              (return-from object-size ,vsize)))
890          (let ((,vsize 0))
891            (declare (type fixnum ,vsize))
892            ,@sizers
893            (when visited
894              (setf (gethash ,vobj visited) ,vsize))
895            ,vsize)))))