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