1 /* pb_common.c: Common support functions for pb_encode.c and pb_decode.c.
3 * 2014 Petteri Aimonen <jpa@kapsi.fi>
8 bool pb_field_iter_begin(pb_field_iter_t *iter, const pb_field_t *fields, void *dest_struct)
12 iter->required_field_index = 0;
13 iter->dest_struct = dest_struct;
14 iter->pData = (char*)dest_struct + iter->pos->data_offset;
15 iter->pSize = (char*)iter->pData + iter->pos->size_offset;
17 return (iter->pos->tag != 0);
20 bool pb_field_iter_next(pb_field_iter_t *iter)
22 const pb_field_t *prev_field = iter->pos;
24 if (prev_field->tag == 0)
26 /* Handle empty message types, where the first field is already the terminator.
27 * In other cases, the iter->pos never points to the terminator. */
33 if (iter->pos->tag == 0)
35 /* Wrapped back to beginning, reinitialize */
36 (void)pb_field_iter_begin(iter, iter->start, iter->dest_struct);
41 /* Increment the pointers based on previous field size */
42 size_t prev_size = prev_field->data_size;
44 if (PB_HTYPE(prev_field->type) == PB_HTYPE_ONEOF &&
45 PB_HTYPE(iter->pos->type) == PB_HTYPE_ONEOF &&
46 iter->pos->data_offset == PB_SIZE_MAX)
48 /* Don't advance pointers inside unions */
51 else if (PB_ATYPE(prev_field->type) == PB_ATYPE_STATIC &&
52 PB_HTYPE(prev_field->type) == PB_HTYPE_REPEATED)
54 /* In static arrays, the data_size tells the size of a single entry and
55 * array_size is the number of entries */
56 prev_size *= prev_field->array_size;
58 else if (PB_ATYPE(prev_field->type) == PB_ATYPE_POINTER)
60 /* Pointer fields always have a constant size in the main structure.
61 * The data_size only applies to the dynamically allocated area. */
62 prev_size = sizeof(void*);
65 if (PB_HTYPE(prev_field->type) == PB_HTYPE_REQUIRED)
67 /* Count the required fields, in order to check their presence in the
69 iter->required_field_index++;
72 iter->pData = (char*)iter->pData + prev_size + iter->pos->data_offset;
73 iter->pSize = (char*)iter->pData + iter->pos->size_offset;
78 bool pb_field_iter_find(pb_field_iter_t *iter, uint32_t tag)
80 const pb_field_t *start = iter->pos;
83 if (iter->pos->tag == tag &&
84 PB_LTYPE(iter->pos->type) != PB_LTYPE_EXTENSION)
86 /* Found the wanted field */
90 (void)pb_field_iter_next(iter);
91 } while (iter->pos != start);
93 /* Searched all the way back to start, and found nothing. */