Some more docs updates
[apps/agl-service-can-low-level.git] / pb_encode.c
1 /* pb_encode.c -- encode a protobuf using minimal resources
2  *
3  * 2011 Petteri Aimonen <jpa@kapsi.fi>
4  */
5
6 #include "pb.h"
7 #include "pb_encode.h"
8 #include "pb_common.h"
9
10 /* Use the GCC warn_unused_result attribute to check that all return values
11  * are propagated correctly. On other compilers and gcc before 3.4.0 just
12  * ignore the annotation.
13  */
14 #if !defined(__GNUC__) || ( __GNUC__ < 3) || (__GNUC__ == 3 && __GNUC_MINOR__ < 4)
15     #define checkreturn
16 #else
17     #define checkreturn __attribute__((warn_unused_result))
18 #endif
19
20 /**************************************
21  * Declarations internal to this file *
22  **************************************/
23 typedef bool (*pb_encoder_t)(pb_ostream_t *stream, const pb_field_t *field, const void *src) checkreturn;
24
25 static bool checkreturn buf_write(pb_ostream_t *stream, const pb_byte_t *buf, size_t count);
26 static bool checkreturn encode_array(pb_ostream_t *stream, const pb_field_t *field, const void *pData, size_t count, pb_encoder_t func);
27 static bool checkreturn encode_field(pb_ostream_t *stream, const pb_field_t *field, const void *pData);
28 static bool checkreturn default_extension_encoder(pb_ostream_t *stream, const pb_extension_t *extension);
29 static bool checkreturn encode_extension_field(pb_ostream_t *stream, const pb_field_t *field, const void *pData);
30 static bool checkreturn pb_enc_varint(pb_ostream_t *stream, const pb_field_t *field, const void *src);
31 static bool checkreturn pb_enc_uvarint(pb_ostream_t *stream, const pb_field_t *field, const void *src);
32 static bool checkreturn pb_enc_svarint(pb_ostream_t *stream, const pb_field_t *field, const void *src);
33 static bool checkreturn pb_enc_fixed32(pb_ostream_t *stream, const pb_field_t *field, const void *src);
34 static bool checkreturn pb_enc_fixed64(pb_ostream_t *stream, const pb_field_t *field, const void *src);
35 static bool checkreturn pb_enc_bytes(pb_ostream_t *stream, const pb_field_t *field, const void *src);
36 static bool checkreturn pb_enc_string(pb_ostream_t *stream, const pb_field_t *field, const void *src);
37 static bool checkreturn pb_enc_submessage(pb_ostream_t *stream, const pb_field_t *field, const void *src);
38
39 /* --- Function pointers to field encoders ---
40  * Order in the array must match pb_action_t LTYPE numbering.
41  */
42 static const pb_encoder_t PB_ENCODERS[PB_LTYPES_COUNT] = {
43     &pb_enc_varint,
44     &pb_enc_uvarint,
45     &pb_enc_svarint,
46     &pb_enc_fixed32,
47     &pb_enc_fixed64,
48     
49     &pb_enc_bytes,
50     &pb_enc_string,
51     &pb_enc_submessage,
52     NULL /* extensions */
53 };
54
55 /*******************************
56  * pb_ostream_t implementation *
57  *******************************/
58
59 static bool checkreturn buf_write(pb_ostream_t *stream, const pb_byte_t *buf, size_t count)
60 {
61     pb_byte_t *dest = (pb_byte_t*)stream->state;
62     stream->state = dest + count;
63     
64     while (count--)
65         *dest++ = *buf++;
66     
67     return true;
68 }
69
70 pb_ostream_t pb_ostream_from_buffer(pb_byte_t *buf, size_t bufsize)
71 {
72     pb_ostream_t stream;
73 #ifdef PB_BUFFER_ONLY
74     stream.callback = (void*)1; /* Just a marker value */
75 #else
76     stream.callback = &buf_write;
77 #endif
78     stream.state = buf;
79     stream.max_size = bufsize;
80     stream.bytes_written = 0;
81 #ifndef PB_NO_ERRMSG
82     stream.errmsg = NULL;
83 #endif
84     return stream;
85 }
86
87 bool checkreturn pb_write(pb_ostream_t *stream, const pb_byte_t *buf, size_t count)
88 {
89     if (stream->callback != NULL)
90     {
91         if (stream->bytes_written + count > stream->max_size)
92             PB_RETURN_ERROR(stream, "stream full");
93
94 #ifdef PB_BUFFER_ONLY
95         if (!buf_write(stream, buf, count))
96             PB_RETURN_ERROR(stream, "io error");
97 #else        
98         if (!stream->callback(stream, buf, count))
99             PB_RETURN_ERROR(stream, "io error");
100 #endif
101     }
102     
103     stream->bytes_written += count;
104     return true;
105 }
106
107 /*************************
108  * Encode a single field *
109  *************************/
110
111 /* Encode a static array. Handles the size calculations and possible packing. */
112 static bool checkreturn encode_array(pb_ostream_t *stream, const pb_field_t *field,
113                          const void *pData, size_t count, pb_encoder_t func)
114 {
115     size_t i;
116     const void *p;
117     size_t size;
118     
119     if (count == 0)
120         return true;
121
122     if (PB_ATYPE(field->type) != PB_ATYPE_POINTER && count > field->array_size)
123         PB_RETURN_ERROR(stream, "array max size exceeded");
124     
125     /* We always pack arrays if the datatype allows it. */
126     if (PB_LTYPE(field->type) <= PB_LTYPE_LAST_PACKABLE)
127     {
128         if (!pb_encode_tag(stream, PB_WT_STRING, field->tag))
129             return false;
130         
131         /* Determine the total size of packed array. */
132         if (PB_LTYPE(field->type) == PB_LTYPE_FIXED32)
133         {
134             size = 4 * count;
135         }
136         else if (PB_LTYPE(field->type) == PB_LTYPE_FIXED64)
137         {
138             size = 8 * count;
139         }
140         else
141         { 
142             pb_ostream_t sizestream = PB_OSTREAM_SIZING;
143             p = pData;
144             for (i = 0; i < count; i++)
145             {
146                 if (!func(&sizestream, field, p))
147                     return false;
148                 p = (const char*)p + field->data_size;
149             }
150             size = sizestream.bytes_written;
151         }
152         
153         if (!pb_encode_varint(stream, (uint64_t)size))
154             return false;
155         
156         if (stream->callback == NULL)
157             return pb_write(stream, NULL, size); /* Just sizing.. */
158         
159         /* Write the data */
160         p = pData;
161         for (i = 0; i < count; i++)
162         {
163             if (!func(stream, field, p))
164                 return false;
165             p = (const char*)p + field->data_size;
166         }
167     }
168     else
169     {
170         p = pData;
171         for (i = 0; i < count; i++)
172         {
173             if (!pb_encode_tag_for_field(stream, field))
174                 return false;
175
176             /* Normally the data is stored directly in the array entries, but
177              * for pointer-type string and bytes fields, the array entries are
178              * actually pointers themselves also. So we have to dereference once
179              * more to get to the actual data. */
180             if (PB_ATYPE(field->type) == PB_ATYPE_POINTER &&
181                 (PB_LTYPE(field->type) == PB_LTYPE_STRING ||
182                  PB_LTYPE(field->type) == PB_LTYPE_BYTES))
183             {
184                 if (!func(stream, field, *(const void* const*)p))
185                     return false;      
186             }
187             else
188             {
189                 if (!func(stream, field, p))
190                     return false;
191             }
192             p = (const char*)p + field->data_size;
193         }
194     }
195     
196     return true;
197 }
198
199 /* Encode a field with static or pointer allocation, i.e. one whose data
200  * is available to the encoder directly. */
201 static bool checkreturn encode_basic_field(pb_ostream_t *stream,
202     const pb_field_t *field, const void *pData)
203 {
204     pb_encoder_t func;
205     const void *pSize;
206     bool implicit_has = true;
207     
208     func = PB_ENCODERS[PB_LTYPE(field->type)];
209     
210     if (field->size_offset)
211         pSize = (const char*)pData + field->size_offset;
212     else
213         pSize = &implicit_has;
214
215     if (PB_ATYPE(field->type) == PB_ATYPE_POINTER)
216     {
217         /* pData is a pointer to the field, which contains pointer to
218          * the data. If the 2nd pointer is NULL, it is interpreted as if
219          * the has_field was false.
220          */
221         
222         pData = *(const void* const*)pData;
223         implicit_has = (pData != NULL);
224     }
225
226     switch (PB_HTYPE(field->type))
227     {
228         case PB_HTYPE_REQUIRED:
229             if (!pData)
230                 PB_RETURN_ERROR(stream, "missing required field");
231             if (!pb_encode_tag_for_field(stream, field))
232                 return false;
233             if (!func(stream, field, pData))
234                 return false;
235             break;
236         
237         case PB_HTYPE_OPTIONAL:
238             if (*(const bool*)pSize)
239             {
240                 if (!pb_encode_tag_for_field(stream, field))
241                     return false;
242             
243                 if (!func(stream, field, pData))
244                     return false;
245             }
246             break;
247         
248         case PB_HTYPE_REPEATED:
249             if (!encode_array(stream, field, pData, *(const pb_size_t*)pSize, func))
250                 return false;
251             break;
252         
253         case PB_HTYPE_ONEOF:
254             if (*(const pb_size_t*)pSize == field->tag)
255             {
256                 if (!pb_encode_tag_for_field(stream, field))
257                     return false;
258
259                 if (!func(stream, field, pData))
260                     return false;
261             }
262             break;
263             
264         default:
265             PB_RETURN_ERROR(stream, "invalid field type");
266     }
267     
268     return true;
269 }
270
271 /* Encode a field with callback semantics. This means that a user function is
272  * called to provide and encode the actual data. */
273 static bool checkreturn encode_callback_field(pb_ostream_t *stream,
274     const pb_field_t *field, const void *pData)
275 {
276     const pb_callback_t *callback = (const pb_callback_t*)pData;
277     
278 #ifdef PB_OLD_CALLBACK_STYLE
279     const void *arg = callback->arg;
280 #else
281     void * const *arg = &(callback->arg);
282 #endif    
283     
284     if (callback->funcs.encode != NULL)
285     {
286         if (!callback->funcs.encode(stream, field, arg))
287             PB_RETURN_ERROR(stream, "callback error");
288     }
289     return true;
290 }
291
292 /* Encode a single field of any callback or static type. */
293 static bool checkreturn encode_field(pb_ostream_t *stream,
294     const pb_field_t *field, const void *pData)
295 {
296     switch (PB_ATYPE(field->type))
297     {
298         case PB_ATYPE_STATIC:
299         case PB_ATYPE_POINTER:
300             return encode_basic_field(stream, field, pData);
301         
302         case PB_ATYPE_CALLBACK:
303             return encode_callback_field(stream, field, pData);
304         
305         default:
306             PB_RETURN_ERROR(stream, "invalid field type");
307     }
308 }
309
310 /* Default handler for extension fields. Expects to have a pb_field_t
311  * pointer in the extension->type->arg field. */
312 static bool checkreturn default_extension_encoder(pb_ostream_t *stream,
313     const pb_extension_t *extension)
314 {
315     const pb_field_t *field = (const pb_field_t*)extension->type->arg;
316     
317     if (PB_ATYPE(field->type) == PB_ATYPE_POINTER)
318     {
319         /* For pointer extensions, the pointer is stored directly
320          * in the extension structure. This avoids having an extra
321          * indirection. */
322         return encode_field(stream, field, &extension->dest);
323     }
324     else
325     {
326         return encode_field(stream, field, extension->dest);
327     }
328 }
329
330 /* Walk through all the registered extensions and give them a chance
331  * to encode themselves. */
332 static bool checkreturn encode_extension_field(pb_ostream_t *stream,
333     const pb_field_t *field, const void *pData)
334 {
335     const pb_extension_t *extension = *(const pb_extension_t* const *)pData;
336     PB_UNUSED(field);
337     
338     while (extension)
339     {
340         bool status;
341         if (extension->type->encode)
342             status = extension->type->encode(stream, extension);
343         else
344             status = default_extension_encoder(stream, extension);
345
346         if (!status)
347             return false;
348         
349         extension = extension->next;
350     }
351     
352     return true;
353 }
354
355 /*********************
356  * Encode all fields *
357  *********************/
358
359 static void *remove_const(const void *p)
360 {
361     /* Note: this casts away const, in order to use the common field iterator
362      * logic for both encoding and decoding. */
363     union {
364         void *p1;
365         const void *p2;
366     } t;
367     t.p2 = p;
368     return t.p1;
369 }
370
371 bool checkreturn pb_encode(pb_ostream_t *stream, const pb_field_t fields[], const void *src_struct)
372 {
373     pb_field_iter_t iter;
374     if (!pb_field_iter_begin(&iter, fields, remove_const(src_struct)))
375         return true; /* Empty message type */
376     
377     do {
378         if (PB_LTYPE(iter.pos->type) == PB_LTYPE_EXTENSION)
379         {
380             /* Special case for the extension field placeholder */
381             if (!encode_extension_field(stream, iter.pos, iter.pData))
382                 return false;
383         }
384         else
385         {
386             /* Regular field */
387             if (!encode_field(stream, iter.pos, iter.pData))
388                 return false;
389         }
390     } while (pb_field_iter_next(&iter));
391     
392     return true;
393 }
394
395 bool pb_encode_delimited(pb_ostream_t *stream, const pb_field_t fields[], const void *src_struct)
396 {
397     return pb_encode_submessage(stream, fields, src_struct);
398 }
399
400 bool pb_get_encoded_size(size_t *size, const pb_field_t fields[], const void *src_struct)
401 {
402     pb_ostream_t stream = PB_OSTREAM_SIZING;
403     
404     if (!pb_encode(&stream, fields, src_struct))
405         return false;
406     
407     *size = stream.bytes_written;
408     return true;
409 }
410
411 /********************
412  * Helper functions *
413  ********************/
414 bool checkreturn pb_encode_varint(pb_ostream_t *stream, uint64_t value)
415 {
416     pb_byte_t buffer[10];
417     size_t i = 0;
418     
419     if (value <= 0x7F)
420     {
421         pb_byte_t v = (pb_byte_t)value;
422         return pb_write(stream, &v, 1);
423     }
424     
425     while (value)
426     {
427         buffer[i] = (pb_byte_t)((value & 0x7F) | 0x80);
428         value >>= 7;
429         i++;
430     }
431     buffer[i-1] &= 0x7F; /* Unset top bit on last byte */
432     
433     return pb_write(stream, buffer, i);
434 }
435
436 bool checkreturn pb_encode_svarint(pb_ostream_t *stream, int64_t value)
437 {
438     uint64_t zigzagged;
439     if (value < 0)
440         zigzagged = ~((uint64_t)value << 1);
441     else
442         zigzagged = (uint64_t)value << 1;
443     
444     return pb_encode_varint(stream, zigzagged);
445 }
446
447 bool checkreturn pb_encode_fixed32(pb_ostream_t *stream, const void *value)
448 {
449     uint32_t val = *(const uint32_t*)value;
450     pb_byte_t bytes[4];
451     bytes[0] = (pb_byte_t)(val & 0xFF);
452     bytes[1] = (pb_byte_t)((val >> 8) & 0xFF);
453     bytes[2] = (pb_byte_t)((val >> 16) & 0xFF);
454     bytes[3] = (pb_byte_t)((val >> 24) & 0xFF);
455     return pb_write(stream, bytes, 4);
456 }
457
458 bool checkreturn pb_encode_fixed64(pb_ostream_t *stream, const void *value)
459 {
460     uint64_t val = *(const uint64_t*)value;
461     pb_byte_t bytes[8];
462     bytes[0] = (pb_byte_t)(val & 0xFF);
463     bytes[1] = (pb_byte_t)((val >> 8) & 0xFF);
464     bytes[2] = (pb_byte_t)((val >> 16) & 0xFF);
465     bytes[3] = (pb_byte_t)((val >> 24) & 0xFF);
466     bytes[4] = (pb_byte_t)((val >> 32) & 0xFF);
467     bytes[5] = (pb_byte_t)((val >> 40) & 0xFF);
468     bytes[6] = (pb_byte_t)((val >> 48) & 0xFF);
469     bytes[7] = (pb_byte_t)((val >> 56) & 0xFF);
470     return pb_write(stream, bytes, 8);
471 }
472
473 bool checkreturn pb_encode_tag(pb_ostream_t *stream, pb_wire_type_t wiretype, uint32_t field_number)
474 {
475     uint64_t tag = ((uint64_t)field_number << 3) | wiretype;
476     return pb_encode_varint(stream, tag);
477 }
478
479 bool checkreturn pb_encode_tag_for_field(pb_ostream_t *stream, const pb_field_t *field)
480 {
481     pb_wire_type_t wiretype;
482     switch (PB_LTYPE(field->type))
483     {
484         case PB_LTYPE_VARINT:
485         case PB_LTYPE_UVARINT:
486         case PB_LTYPE_SVARINT:
487             wiretype = PB_WT_VARINT;
488             break;
489         
490         case PB_LTYPE_FIXED32:
491             wiretype = PB_WT_32BIT;
492             break;
493         
494         case PB_LTYPE_FIXED64:
495             wiretype = PB_WT_64BIT;
496             break;
497         
498         case PB_LTYPE_BYTES:
499         case PB_LTYPE_STRING:
500         case PB_LTYPE_SUBMESSAGE:
501             wiretype = PB_WT_STRING;
502             break;
503         
504         default:
505             PB_RETURN_ERROR(stream, "invalid field type");
506     }
507     
508     return pb_encode_tag(stream, wiretype, field->tag);
509 }
510
511 bool checkreturn pb_encode_string(pb_ostream_t *stream, const pb_byte_t *buffer, size_t size)
512 {
513     if (!pb_encode_varint(stream, (uint64_t)size))
514         return false;
515     
516     return pb_write(stream, buffer, size);
517 }
518
519 bool checkreturn pb_encode_submessage(pb_ostream_t *stream, const pb_field_t fields[], const void *src_struct)
520 {
521     /* First calculate the message size using a non-writing substream. */
522     pb_ostream_t substream = PB_OSTREAM_SIZING;
523     size_t size;
524     bool status;
525     
526     if (!pb_encode(&substream, fields, src_struct))
527     {
528 #ifndef PB_NO_ERRMSG
529         stream->errmsg = substream.errmsg;
530 #endif
531         return false;
532     }
533     
534     size = substream.bytes_written;
535     
536     if (!pb_encode_varint(stream, (uint64_t)size))
537         return false;
538     
539     if (stream->callback == NULL)
540         return pb_write(stream, NULL, size); /* Just sizing */
541     
542     if (stream->bytes_written + size > stream->max_size)
543         PB_RETURN_ERROR(stream, "stream full");
544         
545     /* Use a substream to verify that a callback doesn't write more than
546      * what it did the first time. */
547     substream.callback = stream->callback;
548     substream.state = stream->state;
549     substream.max_size = size;
550     substream.bytes_written = 0;
551 #ifndef PB_NO_ERRMSG
552     substream.errmsg = NULL;
553 #endif
554     
555     status = pb_encode(&substream, fields, src_struct);
556     
557     stream->bytes_written += substream.bytes_written;
558     stream->state = substream.state;
559 #ifndef PB_NO_ERRMSG
560     stream->errmsg = substream.errmsg;
561 #endif
562     
563     if (substream.bytes_written != size)
564         PB_RETURN_ERROR(stream, "submsg size changed");
565     
566     return status;
567 }
568
569 /* Field encoders */
570
571 static bool checkreturn pb_enc_varint(pb_ostream_t *stream, const pb_field_t *field, const void *src)
572 {
573     int64_t value = 0;
574     
575     if (field->data_size == sizeof(int_least8_t))
576         value = *(const int_least8_t*)src;
577     else if (field->data_size == sizeof(int_least16_t))
578         value = *(const int_least16_t*)src;
579     else if (field->data_size == sizeof(int32_t))
580         value = *(const int32_t*)src;
581     else if (field->data_size == sizeof(int64_t))
582         value = *(const int64_t*)src;
583     else
584         PB_RETURN_ERROR(stream, "invalid data_size");
585     
586     return pb_encode_varint(stream, (uint64_t)value);
587 }
588
589 static bool checkreturn pb_enc_uvarint(pb_ostream_t *stream, const pb_field_t *field, const void *src)
590 {
591     uint64_t value = 0;
592     
593     if (field->data_size == sizeof(uint_least8_t))
594         value = *(const uint_least8_t*)src;
595     else if (field->data_size == sizeof(uint_least16_t))
596         value = *(const uint_least16_t*)src;
597     else if (field->data_size == sizeof(uint32_t))
598         value = *(const uint32_t*)src;
599     else if (field->data_size == sizeof(uint64_t))
600         value = *(const uint64_t*)src;
601     else
602         PB_RETURN_ERROR(stream, "invalid data_size");
603     
604     return pb_encode_varint(stream, value);
605 }
606
607 static bool checkreturn pb_enc_svarint(pb_ostream_t *stream, const pb_field_t *field, const void *src)
608 {
609     int64_t value = 0;
610     
611     if (field->data_size == sizeof(int_least8_t))
612         value = *(const int_least8_t*)src;
613     else if (field->data_size == sizeof(int_least16_t))
614         value = *(const int_least16_t*)src;
615     else if (field->data_size == sizeof(int32_t))
616         value = *(const int32_t*)src;
617     else if (field->data_size == sizeof(int64_t))
618         value = *(const int64_t*)src;
619     else
620         PB_RETURN_ERROR(stream, "invalid data_size");
621     
622     return pb_encode_svarint(stream, value);
623 }
624
625 static bool checkreturn pb_enc_fixed64(pb_ostream_t *stream, const pb_field_t *field, const void *src)
626 {
627     PB_UNUSED(field);
628     return pb_encode_fixed64(stream, src);
629 }
630
631 static bool checkreturn pb_enc_fixed32(pb_ostream_t *stream, const pb_field_t *field, const void *src)
632 {
633     PB_UNUSED(field);
634     return pb_encode_fixed32(stream, src);
635 }
636
637 static bool checkreturn pb_enc_bytes(pb_ostream_t *stream, const pb_field_t *field, const void *src)
638 {
639     const pb_bytes_array_t *bytes = (const pb_bytes_array_t*)src;
640     
641     if (src == NULL)
642     {
643         /* Threat null pointer as an empty bytes field */
644         return pb_encode_string(stream, NULL, 0);
645     }
646     
647     if (PB_ATYPE(field->type) == PB_ATYPE_STATIC &&
648         PB_BYTES_ARRAY_T_ALLOCSIZE(bytes->size) > field->data_size)
649     {
650         PB_RETURN_ERROR(stream, "bytes size exceeded");
651     }
652     
653     return pb_encode_string(stream, bytes->bytes, bytes->size);
654 }
655
656 static bool checkreturn pb_enc_string(pb_ostream_t *stream, const pb_field_t *field, const void *src)
657 {
658     size_t size = 0;
659     size_t max_size = field->data_size;
660     const char *p = (const char*)src;
661     
662     if (PB_ATYPE(field->type) == PB_ATYPE_POINTER)
663         max_size = (size_t)-1;
664
665     if (src == NULL)
666     {
667         size = 0; /* Threat null pointer as an empty string */
668     }
669     else
670     {
671         /* strnlen() is not always available, so just use a loop */
672         while (size < max_size && *p != '\0')
673         {
674             size++;
675             p++;
676         }
677     }
678
679     return pb_encode_string(stream, (const pb_byte_t*)src, size);
680 }
681
682 static bool checkreturn pb_enc_submessage(pb_ostream_t *stream, const pb_field_t *field, const void *src)
683 {
684     if (field->ptr == NULL)
685         PB_RETURN_ERROR(stream, "invalid field descriptor");
686     
687     return pb_encode_submessage(stream, (const pb_field_t*)field->ptr, src);
688 }
689