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