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