Coverage Report

Created: 2026-05-30 06:30

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/nanopb/pb_encode.c
Line
Count
Source
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, gcc before 3.4.0 and iar
12
 * before 9.40.1 just ignore the annotation.
13
 */
14
#if (defined(__GNUC__) && ((__GNUC__ > 3) || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4))) || \
15
    (defined(__IAR_SYSTEMS_ICC__) && (__VER__ >= 9040001))
16
    #define checkreturn __attribute__((warn_unused_result))
17
#else
18
    #define checkreturn
19
#endif
20
21
/**************************************
22
 * Declarations internal to this file *
23
 **************************************/
24
static bool checkreturn buf_write(pb_ostream_t *stream, const pb_byte_t *buf, size_t count);
25
static bool checkreturn encode_array(pb_ostream_t *stream, pb_field_iter_t *field);
26
static bool checkreturn pb_check_proto3_default_value(const pb_field_iter_t *field);
27
static bool checkreturn encode_basic_field(pb_ostream_t *stream, const pb_field_iter_t *field);
28
static bool checkreturn encode_callback_field(pb_ostream_t *stream, const pb_field_iter_t *field);
29
static bool checkreturn encode_field(pb_ostream_t *stream, pb_field_iter_t *field);
30
static pb_noinline bool checkreturn encode_extension_field(pb_ostream_t *stream, const pb_field_iter_t *field);
31
static bool checkreturn default_extension_encoder(pb_ostream_t *stream, const pb_extension_t *extension);
32
static bool checkreturn pb_encode_varint_32(pb_ostream_t *stream, uint32_t low, uint32_t high);
33
static bool checkreturn pb_enc_bool(pb_ostream_t *stream, const pb_field_iter_t *field);
34
static bool checkreturn pb_enc_varint(pb_ostream_t *stream, const pb_field_iter_t *field);
35
static bool checkreturn pb_enc_fixed(pb_ostream_t *stream, const pb_field_iter_t *field);
36
static bool checkreturn pb_enc_bytes(pb_ostream_t *stream, const pb_field_iter_t *field);
37
static bool checkreturn pb_enc_string(pb_ostream_t *stream, const pb_field_iter_t *field);
38
static bool checkreturn pb_enc_submessage(pb_ostream_t *stream, const pb_field_iter_t *field);
39
static bool checkreturn pb_enc_fixed_length_bytes(pb_ostream_t *stream, const pb_field_iter_t *field);
40
41
#ifdef PB_WITHOUT_64BIT
42
#define pb_int64_t int32_t
43
#define pb_uint64_t uint32_t
44
#else
45
15.0M
#define pb_int64_t int64_t
46
11.2M
#define pb_uint64_t uint64_t
47
#endif
48
49
/*******************************
50
 * pb_ostream_t implementation *
51
 *******************************/
52
53
static bool checkreturn buf_write(pb_ostream_t *stream, const pb_byte_t *buf, size_t count)
54
30.1M
{
55
30.1M
    pb_byte_t *dest = (pb_byte_t*)stream->state;
56
30.1M
    stream->state = dest + count;
57
58
    /* Skip the copy if buf is NULL. Callers should not invoke this with NULL,
59
     * but pb_write may pass NULL for sizing passes. Some compilers
60
     * (e.g. picolibc/arm-zephyr-eabi GCC 12.2) emit a -Wnonnull warning
61
     * against memcpy's nonnull argument even though count would be 0 in
62
     * that case. See #1141.
63
     */
64
30.1M
    if (buf != NULL)
65
30.1M
    {
66
30.1M
        memcpy(dest, buf, count * sizeof(pb_byte_t));
67
30.1M
    }
68
69
30.1M
    return true;
70
30.1M
}
71
72
pb_ostream_t pb_ostream_from_buffer(pb_byte_t *buf, size_t bufsize)
73
3.99k
{
74
3.99k
    pb_ostream_t stream;
75
#ifdef PB_BUFFER_ONLY
76
    /* In PB_BUFFER_ONLY configuration the callback pointer is just int*.
77
     * NULL pointer marks a sizing field, so put a non-NULL value to mark a buffer stream.
78
     */
79
    static const int marker = 0;
80
    stream.callback = &marker;
81
#else
82
3.99k
    stream.callback = &buf_write;
83
3.99k
#endif
84
3.99k
    stream.state = buf;
85
3.99k
    stream.max_size = bufsize;
86
3.99k
    stream.bytes_written = 0;
87
3.99k
#ifndef PB_NO_ERRMSG
88
3.99k
    stream.errmsg = NULL;
89
3.99k
#endif
90
3.99k
    return stream;
91
3.99k
}
92
93
bool checkreturn pb_write(pb_ostream_t *stream, const pb_byte_t *buf, size_t count)
94
38.5M
{
95
38.5M
    if (count > 0 && stream->callback != NULL)
96
30.1M
    {
97
30.1M
        if (stream->bytes_written + count < stream->bytes_written ||
98
30.1M
            stream->bytes_written + count > stream->max_size)
99
160
        {
100
160
            PB_RETURN_ERROR(stream, "stream full");
101
160
        }
102
103
#ifdef PB_BUFFER_ONLY
104
        if (!buf_write(stream, buf, count))
105
            PB_RETURN_ERROR(stream, "io error");
106
#else        
107
30.1M
        if (!stream->callback(stream, buf, count))
108
0
            PB_RETURN_ERROR(stream, "io error");
109
30.1M
#endif
110
30.1M
    }
111
    
112
38.5M
    stream->bytes_written += count;
113
38.5M
    return true;
114
38.5M
}
115
116
/*************************
117
 * Encode a single field *
118
 *************************/
119
120
/* Read a bool value without causing undefined behavior even if the value
121
 * is invalid. See issue #434 and
122
 * https://stackoverflow.com/questions/27661768/weird-results-for-conditional
123
 */
124
static bool safe_read_bool(const void *pSize)
125
288
{
126
288
    const char *p = (const char *)pSize;
127
288
    size_t i;
128
334
    for (i = 0; i < sizeof(bool); i++)
129
288
    {
130
288
        if (p[i] != 0)
131
242
            return true;
132
288
    }
133
46
    return false;
134
288
}
135
136
/* Encode a static array. Handles the size calculations and possible packing. */
137
static bool checkreturn encode_array(pb_ostream_t *stream, pb_field_iter_t *field)
138
5.37k
{
139
5.37k
    pb_size_t i;
140
5.37k
    pb_size_t count;
141
5.37k
#ifndef PB_ENCODE_ARRAYS_UNPACKED
142
5.37k
    size_t size;
143
5.37k
#endif
144
145
5.37k
    count = *(pb_size_t*)field->pSize;
146
147
5.37k
    if (count == 0)
148
0
        return true;
149
150
5.37k
    if (PB_ATYPE(field->type) != PB_ATYPE_POINTER && count > field->array_size)
151
0
        PB_RETURN_ERROR(stream, "array max size exceeded");
152
    
153
5.37k
#ifndef PB_ENCODE_ARRAYS_UNPACKED
154
    /* We always pack arrays if the datatype allows it. */
155
5.37k
    if (PB_LTYPE(field->type) <= PB_LTYPE_LAST_PACKABLE)
156
2.57k
    {
157
2.57k
        if (!pb_encode_tag(stream, PB_WT_STRING, field->tag))
158
1
            return false;
159
        
160
        /* Determine the total size of packed array. */
161
2.57k
        if (PB_LTYPE(field->type) == PB_LTYPE_FIXED32)
162
372
        {
163
372
            size = 4 * (size_t)count;
164
372
        }
165
2.20k
        else if (PB_LTYPE(field->type) == PB_LTYPE_FIXED64)
166
413
        {
167
413
            size = 8 * (size_t)count;
168
413
        }
169
1.78k
        else
170
1.78k
        { 
171
1.78k
            pb_ostream_t sizestream = PB_OSTREAM_SIZING;
172
1.78k
            void *pData_orig = field->pData;
173
8.15M
            for (i = 0; i < count; i++)
174
8.15M
            {
175
8.15M
                if (!pb_enc_varint(&sizestream, field))
176
0
                    PB_RETURN_ERROR(stream, PB_GET_ERROR(&sizestream));
177
8.15M
                field->pData = (char*)field->pData + field->data_size;
178
8.15M
            }
179
1.78k
            field->pData = pData_orig;
180
1.78k
            size = sizestream.bytes_written;
181
1.78k
        }
182
        
183
2.57k
        if (!pb_encode_varint(stream, (pb_uint64_t)size))
184
4
            return false;
185
        
186
2.56k
        if (stream->callback == NULL)
187
0
            return pb_write(stream, NULL, size); /* Just sizing.. */
188
        
189
        /* Write the data */
190
8.18M
        for (i = 0; i < count; i++)
191
8.18M
        {
192
8.18M
            if (PB_LTYPE(field->type) == PB_LTYPE_FIXED32 || PB_LTYPE(field->type) == PB_LTYPE_FIXED64)
193
29.0k
            {
194
29.0k
                if (!pb_enc_fixed(stream, field))
195
4
                    return false;
196
29.0k
            }
197
8.15M
            else
198
8.15M
            {
199
8.15M
                if (!pb_enc_varint(stream, field))
200
5
                    return false;
201
8.15M
            }
202
203
8.18M
            field->pData = (char*)field->pData + field->data_size;
204
8.18M
        }
205
2.56k
    }
206
2.79k
    else /* Unpacked fields */
207
2.79k
#endif
208
2.79k
    {
209
7.62M
        for (i = 0; i < count; i++)
210
7.62M
        {
211
            /* Normally the data is stored directly in the array entries, but
212
             * for pointer-type string and bytes fields, the array entries are
213
             * actually pointers themselves also. So we have to dereference once
214
             * more to get to the actual data. */
215
7.62M
            if (PB_ATYPE(field->type) == PB_ATYPE_POINTER &&
216
7.62M
                (PB_LTYPE(field->type) == PB_LTYPE_STRING ||
217
7.60M
                 PB_LTYPE(field->type) == PB_LTYPE_BYTES))
218
173k
            {
219
173k
                bool status;
220
173k
                void *pData_orig = field->pData;
221
173k
                field->pData = *(void* const*)field->pData;
222
223
173k
                if (!field->pData)
224
0
                {
225
                    /* Null pointer in array is treated as empty string / bytes */
226
0
                    status = pb_encode_tag_for_field(stream, field) &&
227
0
                             pb_encode_varint(stream, 0);
228
0
                }
229
173k
                else
230
173k
                {
231
173k
                    status = encode_basic_field(stream, field);
232
173k
                }
233
234
173k
                field->pData = pData_orig;
235
236
173k
                if (!status)
237
25
                    return false;
238
173k
            }
239
7.45M
            else
240
7.45M
            {
241
7.45M
                if (!encode_basic_field(stream, field))
242
97
                    return false;
243
7.45M
            }
244
7.62M
            field->pData = (char*)field->pData + field->data_size;
245
7.62M
        }
246
2.79k
    }
247
    
248
5.23k
    return true;
249
5.37k
}
250
251
/* In proto3, all fields are optional and are only encoded if their value is "non-zero".
252
 * This function implements the check for the zero value. */
253
static bool checkreturn pb_check_proto3_default_value(const pb_field_iter_t *field)
254
0
{
255
0
    pb_type_t type = field->type;
256
257
0
    if (PB_ATYPE(type) == PB_ATYPE_STATIC)
258
0
    {
259
0
        if (PB_HTYPE(type) == PB_HTYPE_REQUIRED)
260
0
        {
261
            /* Required proto2 fields inside proto3 submessage, pretty rare case */
262
0
            return false;
263
0
        }
264
0
        else if (PB_HTYPE(type) == PB_HTYPE_REPEATED)
265
0
        {
266
            /* Repeated fields inside proto3 submessage: present if count != 0 */
267
0
            return *(const pb_size_t*)field->pSize == 0;
268
0
        }
269
0
        else if (PB_HTYPE(type) == PB_HTYPE_ONEOF)
270
0
        {
271
            /* Oneof fields */
272
0
            return *(const pb_size_t*)field->pSize == 0;
273
0
        }
274
0
        else if (PB_HTYPE(type) == PB_HTYPE_OPTIONAL && field->pSize != NULL)
275
0
        {
276
            /* Proto2 optional fields inside proto3 message, or proto3
277
             * submessage fields. */
278
0
            return safe_read_bool(field->pSize) == false;
279
0
        }
280
0
        else if (field->descriptor->default_value)
281
0
        {
282
            /* Proto3 messages do not have default values, but proto2 messages
283
             * can contain optional fields without has_fields (generator option 'proto3').
284
             * In this case they must always be encoded, to make sure that the
285
             * non-zero default value is overwritten.
286
             */
287
0
            return false;
288
0
        }
289
290
        /* Rest is proto3 singular fields */
291
0
        if (PB_LTYPE(type) <= PB_LTYPE_LAST_PACKABLE)
292
0
        {
293
            /* Simple integer / float fields */
294
0
            pb_size_t i;
295
0
            const char *p = (const char*)field->pData;
296
0
            for (i = 0; i < field->data_size; i++)
297
0
            {
298
0
                if (p[i] != 0)
299
0
                {
300
0
                    return false;
301
0
                }
302
0
            }
303
304
0
            return true;
305
0
        }
306
0
        else if (PB_LTYPE(type) == PB_LTYPE_BYTES)
307
0
        {
308
0
            const pb_bytes_array_t *bytes = (const pb_bytes_array_t*)field->pData;
309
0
            return bytes->size == 0;
310
0
        }
311
0
        else if (PB_LTYPE(type) == PB_LTYPE_STRING)
312
0
        {
313
0
            return *(const char*)field->pData == '\0';
314
0
        }
315
0
        else if (PB_LTYPE(type) == PB_LTYPE_FIXED_LENGTH_BYTES)
316
0
        {
317
            /* Fixed length bytes is only empty if its length is fixed
318
             * as 0. Which would be pretty strange, but we can check
319
             * it anyway. */
320
0
            return field->data_size == 0;
321
0
        }
322
0
        else if (PB_LTYPE_IS_SUBMSG(type))
323
0
        {
324
            /* Check all fields in the submessage to find if any of them
325
             * are non-zero. The comparison cannot be done byte-per-byte
326
             * because the C struct may contain padding bytes that must
327
             * be skipped. Note that usually proto3 submessages have
328
             * a separate has_field that is checked earlier in this if.
329
             */
330
0
            pb_field_iter_t iter;
331
0
            if (pb_field_iter_begin(&iter, field->submsg_desc, field->pData))
332
0
            {
333
0
                do
334
0
                {
335
0
                    if (!pb_check_proto3_default_value(&iter))
336
0
                    {
337
0
                        return false;
338
0
                    }
339
0
                } while (pb_field_iter_next(&iter));
340
0
            }
341
0
            return true;
342
0
        }
343
0
    }
344
0
    else if (PB_ATYPE(type) == PB_ATYPE_POINTER)
345
0
    {
346
0
        return field->pData == NULL;
347
0
    }
348
0
    else if (PB_ATYPE(type) == PB_ATYPE_CALLBACK)
349
0
    {
350
0
        if (PB_LTYPE(type) == PB_LTYPE_EXTENSION)
351
0
        {
352
0
            const pb_extension_t *extension = *(const pb_extension_t* const *)field->pData;
353
0
            return extension == NULL;
354
0
        }
355
0
        else if (field->descriptor->field_callback == pb_default_field_callback)
356
0
        {
357
0
            pb_callback_t *pCallback = (pb_callback_t*)field->pData;
358
0
            return pCallback->funcs.encode == NULL;
359
0
        }
360
0
        else
361
0
        {
362
0
            return field->descriptor->field_callback == NULL;
363
0
        }
364
0
    }
365
366
0
    return false; /* Not typically reached, safe default for weird special cases. */
367
0
}
368
369
/* Encode a field with static or pointer allocation, i.e. one whose data
370
 * is available to the encoder directly. */
371
static bool checkreturn encode_basic_field(pb_ostream_t *stream, const pb_field_iter_t *field)
372
7.65M
{
373
7.65M
    if (!field->pData)
374
0
    {
375
        /* Missing pointer field */
376
0
        return true;
377
0
    }
378
379
7.65M
    if (!pb_encode_tag_for_field(stream, field))
380
30
        return false;
381
382
7.65M
    switch (PB_LTYPE(field->type))
383
7.65M
    {
384
288
        case PB_LTYPE_BOOL:
385
288
            return pb_enc_bool(stream, field);
386
387
8.10k
        case PB_LTYPE_VARINT:
388
9.28k
        case PB_LTYPE_UVARINT:
389
10.5k
        case PB_LTYPE_SVARINT:
390
10.5k
            return pb_enc_varint(stream, field);
391
392
1.27k
        case PB_LTYPE_FIXED32:
393
1.61k
        case PB_LTYPE_FIXED64:
394
1.61k
            return pb_enc_fixed(stream, field);
395
396
151k
        case PB_LTYPE_BYTES:
397
151k
            return pb_enc_bytes(stream, field);
398
399
34.6k
        case PB_LTYPE_STRING:
400
34.6k
            return pb_enc_string(stream, field);
401
402
749k
        case PB_LTYPE_SUBMESSAGE:
403
749k
        case PB_LTYPE_SUBMSG_W_CB:
404
749k
            return pb_enc_submessage(stream, field);
405
406
6.70M
        case PB_LTYPE_FIXED_LENGTH_BYTES:
407
6.70M
            return pb_enc_fixed_length_bytes(stream, field);
408
409
0
        default:
410
0
            PB_RETURN_ERROR(stream, "invalid field type");
411
7.65M
    }
412
7.65M
}
413
414
/* Encode a field with callback semantics. This means that a user function is
415
 * called to provide and encode the actual data. */
416
static bool checkreturn encode_callback_field(pb_ostream_t *stream, const pb_field_iter_t *field)
417
0
{
418
0
    if (field->descriptor->field_callback != NULL)
419
0
    {
420
0
        if (!field->descriptor->field_callback(NULL, stream, field))
421
0
            PB_RETURN_ERROR(stream, "callback error");
422
0
    }
423
0
    return true;
424
0
}
425
426
/* Encode a single field of any callback, pointer or static type. */
427
static bool checkreturn encode_field(pb_ostream_t *stream, pb_field_iter_t *field)
428
4.61M
{
429
    /* Check field presence */
430
4.61M
    if (PB_HTYPE(field->type) == PB_HTYPE_ONEOF)
431
11.5k
    {
432
11.5k
        if (*(const pb_size_t*)field->pSize != field->tag)
433
11.0k
        {
434
            /* Different type oneof field */
435
11.0k
            return true;
436
11.0k
        }
437
11.5k
    }
438
4.60M
    else if (PB_HTYPE(field->type) == PB_HTYPE_OPTIONAL)
439
4.52M
    {
440
4.52M
        if (field->pSize)
441
0
        {
442
0
            if (safe_read_bool(field->pSize) == false)
443
0
            {
444
                /* Missing optional field */
445
0
                return true;
446
0
            }
447
0
        }
448
4.52M
        else if (PB_ATYPE(field->type) == PB_ATYPE_STATIC)
449
0
        {
450
            /* Proto3 singular field */
451
0
            if (pb_check_proto3_default_value(field))
452
0
                return true;
453
0
        }
454
4.52M
    }
455
456
4.60M
    if (!field->pData)
457
4.57M
    {
458
4.57M
        if (PB_HTYPE(field->type) == PB_HTYPE_REQUIRED)
459
0
            PB_RETURN_ERROR(stream, "missing required field");
460
461
        /* Pointer field set to NULL */
462
4.57M
        return true;
463
4.57M
    }
464
465
    /* Then encode field contents */
466
31.8k
    if (PB_ATYPE(field->type) == PB_ATYPE_CALLBACK)
467
0
    {
468
0
        return encode_callback_field(stream, field);
469
0
    }
470
31.8k
    else if (PB_HTYPE(field->type) == PB_HTYPE_REPEATED)
471
5.37k
    {
472
5.37k
        return encode_array(stream, field);
473
5.37k
    }
474
26.4k
    else
475
26.4k
    {
476
26.4k
        return encode_basic_field(stream, field);
477
26.4k
    }
478
31.8k
}
479
480
/* Default handler for extension fields. Expects to have a pb_msgdesc_t
481
 * pointer in the extension->type->arg field, pointing to a message with
482
 * only one field in it.  */
483
static bool checkreturn default_extension_encoder(pb_ostream_t *stream, const pb_extension_t *extension)
484
0
{
485
0
    pb_field_iter_t iter;
486
487
0
    if (!pb_field_iter_begin_extension_const(&iter, extension))
488
0
        PB_RETURN_ERROR(stream, "invalid extension");
489
490
0
    return encode_field(stream, &iter);
491
0
}
492
493
494
/* Walk through all the registered extensions and give them a chance
495
 * to encode themselves. */
496
static pb_noinline bool checkreturn encode_extension_field(pb_ostream_t *stream, const pb_field_iter_t *field)
497
0
{
498
0
    const pb_extension_t *extension = *(const pb_extension_t* const *)field->pData;
499
500
0
    while (extension)
501
0
    {
502
0
        bool status;
503
0
        if (extension->type->encode)
504
0
            status = extension->type->encode(stream, extension);
505
0
        else
506
0
            status = default_extension_encoder(stream, extension);
507
508
0
        if (!status)
509
0
            return false;
510
        
511
0
        extension = extension->next;
512
0
    }
513
    
514
0
    return true;
515
0
}
516
517
/*********************
518
 * Encode all fields *
519
 *********************/
520
521
bool checkreturn pb_encode(pb_ostream_t *stream, const pb_msgdesc_t *fields, const void *src_struct)
522
1.50M
{
523
1.50M
    pb_field_iter_t iter;
524
1.50M
    if (!pb_field_iter_begin_const(&iter, fields, src_struct))
525
19.3k
        return true; /* Empty message type */
526
    
527
4.61M
    do {
528
4.61M
        if (PB_LTYPE(iter.type) == PB_LTYPE_EXTENSION)
529
0
        {
530
            /* Special case for the extension field placeholder */
531
0
            if (!encode_extension_field(stream, &iter))
532
0
                return false;
533
0
        }
534
4.61M
        else
535
4.61M
        {
536
            /* Regular field */
537
4.61M
            if (!encode_field(stream, &iter))
538
169
                return false;
539
4.61M
        }
540
4.61M
    } while (pb_field_iter_next(&iter));
541
    
542
1.48M
    return true;
543
1.48M
}
544
545
bool checkreturn pb_encode_ex(pb_ostream_t *stream, const pb_msgdesc_t *fields, const void *src_struct, unsigned int flags)
546
0
{
547
0
  if ((flags & PB_ENCODE_DELIMITED) != 0)
548
0
  {
549
0
    return pb_encode_submessage(stream, fields, src_struct);
550
0
  }
551
0
  else if ((flags & PB_ENCODE_NULLTERMINATED) != 0)
552
0
  {
553
0
    const pb_byte_t zero = 0;
554
555
0
    if (!pb_encode(stream, fields, src_struct))
556
0
        return false;
557
558
0
    return pb_write(stream, &zero, 1);
559
0
  }
560
0
  else
561
0
  {
562
0
    return pb_encode(stream, fields, src_struct);
563
0
  }
564
0
}
565
566
bool pb_get_encoded_size(size_t *size, const pb_msgdesc_t *fields, const void *src_struct)
567
0
{
568
0
    pb_ostream_t stream = PB_OSTREAM_SIZING;
569
    
570
0
    if (!pb_encode(&stream, fields, src_struct))
571
0
        return false;
572
    
573
0
    *size = stream.bytes_written;
574
0
    return true;
575
0
}
576
577
/********************
578
 * Helper functions *
579
 ********************/
580
581
/* This function avoids 64-bit shifts as they are quite slow on many platforms. */
582
static bool checkreturn pb_encode_varint_32(pb_ostream_t *stream, uint32_t low, uint32_t high)
583
13.3M
{
584
13.3M
    size_t i = 0;
585
13.3M
    pb_byte_t buffer[10];
586
13.3M
    pb_byte_t byte = (pb_byte_t)(low & 0x7F);
587
13.3M
    low >>= 7;
588
589
38.8M
    while (i < 4 && (low != 0 || high != 0))
590
25.4M
    {
591
25.4M
        byte |= 0x80;
592
25.4M
        buffer[i++] = byte;
593
25.4M
        byte = (pb_byte_t)(low & 0x7F);
594
25.4M
        low >>= 7;
595
25.4M
    }
596
597
13.3M
    if (high)
598
3.82M
    {
599
3.82M
        byte = (pb_byte_t)(byte | ((high & 0x07) << 4));
600
3.82M
        high >>= 3;
601
602
22.7M
        while (high)
603
18.9M
        {
604
18.9M
            byte |= 0x80;
605
18.9M
            buffer[i++] = byte;
606
18.9M
            byte = (pb_byte_t)(high & 0x7F);
607
18.9M
            high >>= 7;
608
18.9M
        }
609
3.82M
    }
610
611
13.3M
    buffer[i++] = byte;
612
613
13.3M
    return pb_write(stream, buffer, i);
614
13.3M
}
615
616
bool checkreturn pb_encode_varint(pb_ostream_t *stream, pb_uint64_t value)
617
31.6M
{
618
31.6M
    if (value <= 0x7F)
619
18.2M
    {
620
        /* Fast path: single byte */
621
18.2M
        pb_byte_t byte = (pb_byte_t)value;
622
18.2M
        return pb_write(stream, &byte, 1);
623
18.2M
    }
624
13.3M
    else
625
13.3M
    {
626
#ifdef PB_WITHOUT_64BIT
627
        return pb_encode_varint_32(stream, value, 0);
628
#else
629
13.3M
        return pb_encode_varint_32(stream, (uint32_t)value, (uint32_t)(value >> 32));
630
13.3M
#endif
631
13.3M
    }
632
31.6M
}
633
634
bool checkreturn pb_encode_svarint(pb_ostream_t *stream, pb_int64_t value)
635
1.16M
{
636
1.16M
    pb_uint64_t zigzagged;
637
1.16M
    pb_uint64_t mask = ((pb_uint64_t)-1) >> 1; /* Satisfy clang -fsanitize=integer */
638
1.16M
    if (value < 0)
639
97.4k
        zigzagged = ~(((pb_uint64_t)value & mask) << 1);
640
1.06M
    else
641
1.06M
        zigzagged = (pb_uint64_t)value << 1;
642
    
643
1.16M
    return pb_encode_varint(stream, zigzagged);
644
1.16M
}
645
646
bool checkreturn pb_encode_fixed32(pb_ostream_t *stream, const void *value)
647
14.5k
{
648
14.5k
#if defined(PB_LITTLE_ENDIAN_8BIT) && PB_LITTLE_ENDIAN_8BIT == 1
649
    /* Fast path if we know that we're on little endian */
650
14.5k
    return pb_write(stream, (const pb_byte_t*)value, 4);
651
#else
652
    uint32_t val = *(const uint32_t*)value;
653
    pb_byte_t bytes[4];
654
    bytes[0] = (pb_byte_t)(val & 0xFF);
655
    bytes[1] = (pb_byte_t)((val >> 8) & 0xFF);
656
    bytes[2] = (pb_byte_t)((val >> 16) & 0xFF);
657
    bytes[3] = (pb_byte_t)((val >> 24) & 0xFF);
658
    return pb_write(stream, bytes, 4);
659
#endif
660
14.5k
}
661
662
#ifndef PB_WITHOUT_64BIT
663
bool checkreturn pb_encode_fixed64(pb_ostream_t *stream, const void *value)
664
16.0k
{
665
16.0k
#if defined(PB_LITTLE_ENDIAN_8BIT) && PB_LITTLE_ENDIAN_8BIT == 1
666
    /* Fast path if we know that we're on little endian */
667
16.0k
    return pb_write(stream, (const pb_byte_t*)value, 8);
668
#else
669
    uint64_t val = *(const uint64_t*)value;
670
    pb_byte_t bytes[8];
671
    bytes[0] = (pb_byte_t)(val & 0xFF);
672
    bytes[1] = (pb_byte_t)((val >> 8) & 0xFF);
673
    bytes[2] = (pb_byte_t)((val >> 16) & 0xFF);
674
    bytes[3] = (pb_byte_t)((val >> 24) & 0xFF);
675
    bytes[4] = (pb_byte_t)((val >> 32) & 0xFF);
676
    bytes[5] = (pb_byte_t)((val >> 40) & 0xFF);
677
    bytes[6] = (pb_byte_t)((val >> 48) & 0xFF);
678
    bytes[7] = (pb_byte_t)((val >> 56) & 0xFF);
679
    return pb_write(stream, bytes, 8);
680
#endif
681
16.0k
}
682
#endif
683
684
bool checkreturn pb_encode_tag(pb_ostream_t *stream, pb_wire_type_t wiretype, uint32_t field_number)
685
7.65M
{
686
7.65M
    pb_uint64_t tag = ((pb_uint64_t)field_number << 3) | wiretype;
687
7.65M
    return pb_encode_varint(stream, tag);
688
7.65M
}
689
690
bool pb_encode_tag_for_field ( pb_ostream_t* stream, const pb_field_iter_t* field )
691
7.65M
{
692
7.65M
    pb_wire_type_t wiretype;
693
7.65M
    switch (PB_LTYPE(field->type))
694
7.65M
    {
695
288
        case PB_LTYPE_BOOL:
696
8.39k
        case PB_LTYPE_VARINT:
697
9.57k
        case PB_LTYPE_UVARINT:
698
10.8k
        case PB_LTYPE_SVARINT:
699
10.8k
            wiretype = PB_WT_VARINT;
700
10.8k
            break;
701
        
702
1.27k
        case PB_LTYPE_FIXED32:
703
1.27k
            wiretype = PB_WT_32BIT;
704
1.27k
            break;
705
        
706
334
        case PB_LTYPE_FIXED64:
707
334
            wiretype = PB_WT_64BIT;
708
334
            break;
709
        
710
151k
        case PB_LTYPE_BYTES:
711
186k
        case PB_LTYPE_STRING:
712
936k
        case PB_LTYPE_SUBMESSAGE:
713
936k
        case PB_LTYPE_SUBMSG_W_CB:
714
7.64M
        case PB_LTYPE_FIXED_LENGTH_BYTES:
715
7.64M
            wiretype = PB_WT_STRING;
716
7.64M
            break;
717
        
718
0
        default:
719
0
            PB_RETURN_ERROR(stream, "invalid field type");
720
7.65M
    }
721
    
722
7.65M
    return pb_encode_tag(stream, wiretype, field->tag);
723
7.65M
}
724
725
bool checkreturn pb_encode_string(pb_ostream_t *stream, const pb_byte_t *buffer, size_t size)
726
6.89M
{
727
6.89M
    if (!pb_encode_varint(stream, (pb_uint64_t)size))
728
15
        return false;
729
    
730
6.89M
    return pb_write(stream, buffer, size);
731
6.89M
}
732
733
bool checkreturn pb_encode_submessage(pb_ostream_t *stream, const pb_msgdesc_t *fields, const void *src_struct)
734
749k
{
735
    /* First calculate the message size using a non-writing substream. */
736
749k
    pb_ostream_t substream = PB_OSTREAM_SIZING;
737
749k
#if !defined(PB_NO_ENCODE_SIZE_CHECK) || PB_NO_ENCODE_SIZE_CHECK == 0
738
749k
    bool status;
739
749k
    size_t size;
740
749k
#endif
741
    
742
749k
    if (!pb_encode(&substream, fields, src_struct))
743
0
    {
744
0
#ifndef PB_NO_ERRMSG
745
0
        stream->errmsg = substream.errmsg;
746
0
#endif
747
0
        return false;
748
0
    }
749
    
750
749k
    if (!pb_encode_varint(stream, (pb_uint64_t)substream.bytes_written))
751
10
        return false;
752
    
753
749k
    if (stream->callback == NULL)
754
0
        return pb_write(stream, NULL, substream.bytes_written); /* Just sizing */
755
    
756
749k
    if (stream->bytes_written + substream.bytes_written > stream->max_size)
757
9
        PB_RETURN_ERROR(stream, "stream full");
758
        
759
#if defined(PB_NO_ENCODE_SIZE_CHECK) && PB_NO_ENCODE_SIZE_CHECK == 1
760
    return pb_encode(stream, fields, src_struct);
761
#else
762
749k
    size = substream.bytes_written;
763
    /* Use a substream to verify that a callback doesn't write more than
764
     * what it did the first time. */
765
749k
    substream.callback = stream->callback;
766
749k
    substream.state = stream->state;
767
749k
    substream.max_size = size;
768
749k
    substream.bytes_written = 0;
769
749k
#ifndef PB_NO_ERRMSG
770
749k
    substream.errmsg = NULL;
771
749k
#endif
772
    
773
749k
    status = pb_encode(&substream, fields, src_struct);
774
    
775
749k
    stream->bytes_written += substream.bytes_written;
776
749k
    stream->state = substream.state;
777
749k
#ifndef PB_NO_ERRMSG
778
749k
    stream->errmsg = substream.errmsg;
779
749k
#endif
780
    
781
749k
    if (substream.bytes_written != size)
782
0
        PB_RETURN_ERROR(stream, "submsg size changed");
783
784
749k
    return status;
785
749k
#endif
786
749k
}
787
788
/* Field encoders */
789
790
static bool checkreturn pb_enc_bool(pb_ostream_t *stream, const pb_field_iter_t *field)
791
288
{
792
288
    uint32_t value = safe_read_bool(field->pData) ? 1 : 0;
793
288
    PB_UNUSED(field);
794
288
    return pb_encode_varint(stream, value);
795
288
}
796
797
static bool checkreturn pb_enc_varint(pb_ostream_t *stream, const pb_field_iter_t *field)
798
16.3M
{
799
16.3M
    if (PB_LTYPE(field->type) == PB_LTYPE_UVARINT)
800
1.24M
    {
801
        /* Perform unsigned integer extension */
802
1.24M
        pb_uint64_t value = 0;
803
804
1.24M
        if (field->data_size == sizeof(uint_least8_t))
805
0
            value = *(const uint_least8_t*)field->pData;
806
1.24M
        else if (field->data_size == sizeof(uint_least16_t))
807
0
            value = *(const uint_least16_t*)field->pData;
808
1.24M
        else if (field->data_size == sizeof(uint32_t))
809
116k
            value = *(const uint32_t*)field->pData;
810
1.12M
        else if (field->data_size == sizeof(pb_uint64_t))
811
1.12M
            value = *(const pb_uint64_t*)field->pData;
812
0
        else
813
0
            PB_RETURN_ERROR(stream, "invalid data_size");
814
815
1.24M
        return pb_encode_varint(stream, value);
816
1.24M
    }
817
15.0M
    else
818
15.0M
    {
819
        /* Perform signed integer extension */
820
15.0M
        pb_int64_t value = 0;
821
822
15.0M
        if (field->data_size == sizeof(int_least8_t))
823
4.99M
            value = *(const int_least8_t*)field->pData;
824
10.0M
        else if (field->data_size == sizeof(int_least16_t))
825
0
            value = *(const int_least16_t*)field->pData;
826
10.0M
        else if (field->data_size == sizeof(int32_t))
827
8.71M
            value = *(const int32_t*)field->pData;
828
1.35M
        else if (field->data_size == sizeof(pb_int64_t))
829
1.35M
            value = *(const pb_int64_t*)field->pData;
830
0
        else
831
0
            PB_RETURN_ERROR(stream, "invalid data_size");
832
833
15.0M
        if (PB_LTYPE(field->type) == PB_LTYPE_SVARINT)
834
1.16M
            return pb_encode_svarint(stream, value);
835
#ifdef PB_WITHOUT_64BIT
836
        else if (value < 0)
837
            return pb_encode_varint_32(stream, (uint32_t)value, (uint32_t)-1);
838
#endif
839
13.9M
        else
840
13.9M
            return pb_encode_varint(stream, (pb_uint64_t)value);
841
842
15.0M
    }
843
16.3M
}
844
845
static bool checkreturn pb_enc_fixed(pb_ostream_t *stream, const pb_field_iter_t *field)
846
30.6k
{
847
#ifdef PB_CONVERT_DOUBLE_FLOAT
848
    if (field->data_size == sizeof(float) && PB_LTYPE(field->type) == PB_LTYPE_FIXED64)
849
    {
850
        return pb_encode_float_as_double(stream, *(float*)field->pData);
851
    }
852
#endif
853
854
30.6k
    if (field->data_size == sizeof(uint32_t))
855
14.5k
    {
856
14.5k
        return pb_encode_fixed32(stream, field->pData);
857
14.5k
    }
858
16.0k
#ifndef PB_WITHOUT_64BIT
859
16.0k
    else if (field->data_size == sizeof(uint64_t))
860
16.0k
    {
861
16.0k
        return pb_encode_fixed64(stream, field->pData);
862
16.0k
    }
863
0
#endif
864
0
    else
865
0
    {
866
0
        PB_RETURN_ERROR(stream, "invalid data_size");
867
0
    }
868
30.6k
}
869
870
static bool checkreturn pb_enc_bytes(pb_ostream_t *stream, const pb_field_iter_t *field)
871
151k
{
872
151k
    const pb_bytes_array_t *bytes = NULL;
873
874
151k
    bytes = (const pb_bytes_array_t*)field->pData;
875
    
876
151k
    if (bytes == NULL)
877
0
    {
878
        /* Treat null pointer as an empty bytes field */
879
0
        return pb_encode_string(stream, NULL, 0);
880
0
    }
881
    
882
151k
    if (PB_ATYPE(field->type) == PB_ATYPE_STATIC &&
883
0
        bytes->size > field->data_size - offsetof(pb_bytes_array_t, bytes))
884
0
    {
885
0
        PB_RETURN_ERROR(stream, "bytes size exceeded");
886
0
    }
887
    
888
151k
    return pb_encode_string(stream, bytes->bytes, (size_t)bytes->size);
889
151k
}
890
891
static bool checkreturn pb_enc_string(pb_ostream_t *stream, const pb_field_iter_t *field)
892
34.6k
{
893
34.6k
    size_t size = 0;
894
34.6k
    size_t max_size = (size_t)field->data_size;
895
34.6k
    const char *str = (const char*)field->pData;
896
    
897
34.6k
    if (PB_ATYPE(field->type) == PB_ATYPE_POINTER)
898
34.6k
    {
899
34.6k
        max_size = (size_t)-1;
900
34.6k
    }
901
0
    else
902
0
    {
903
        /* pb_dec_string() assumes string fields end with a null
904
         * terminator when the type isn't PB_ATYPE_POINTER, so we
905
         * shouldn't allow more than max-1 bytes to be written to
906
         * allow space for the null terminator.
907
         */
908
0
        if (max_size == 0)
909
0
            PB_RETURN_ERROR(stream, "zero-length string");
910
911
0
        max_size -= 1;
912
0
    }
913
914
915
34.6k
    if (str == NULL)
916
0
    {
917
0
        size = 0; /* Treat null pointer as an empty string */
918
0
    }
919
34.6k
    else
920
34.6k
    {
921
34.6k
        const char *p = str;
922
923
        /* strnlen() is not always available, so just use a loop */
924
1.76M
        while (size < max_size && *p != '\0')
925
1.73M
        {
926
1.73M
            size++;
927
1.73M
            p++;
928
1.73M
        }
929
930
34.6k
        if (*p != '\0')
931
0
        {
932
0
            PB_RETURN_ERROR(stream, "unterminated string");
933
0
        }
934
34.6k
    }
935
936
#ifdef PB_VALIDATE_UTF8
937
    if (!pb_validate_utf8(str))
938
        PB_RETURN_ERROR(stream, "invalid utf8");
939
#endif
940
941
34.6k
    return pb_encode_string(stream, (const pb_byte_t*)str, size);
942
34.6k
}
943
944
static bool checkreturn pb_enc_submessage(pb_ostream_t *stream, const pb_field_iter_t *field)
945
749k
{
946
749k
    if (field->submsg_desc == NULL)
947
0
        PB_RETURN_ERROR(stream, "invalid field descriptor");
948
949
749k
    if (PB_LTYPE(field->type) == PB_LTYPE_SUBMSG_W_CB && field->pSize != NULL)
950
0
    {
951
        /* Message callback is stored right before pSize. */
952
0
        pb_callback_t *callback = (pb_callback_t*)field->pSize - 1;
953
0
        if (callback->funcs.encode)
954
0
        {
955
0
            if (!callback->funcs.encode(stream, field, &callback->arg))
956
0
                return false;
957
0
        }
958
0
    }
959
    
960
749k
    return pb_encode_submessage(stream, field->submsg_desc, field->pData);
961
749k
}
962
963
static bool checkreturn pb_enc_fixed_length_bytes(pb_ostream_t *stream, const pb_field_iter_t *field)
964
6.70M
{
965
6.70M
    return pb_encode_string(stream, (const pb_byte_t*)field->pData, (size_t)field->data_size);
966
6.70M
}
967
968
#ifdef PB_CONVERT_DOUBLE_FLOAT
969
bool pb_encode_float_as_double(pb_ostream_t *stream, float value)
970
{
971
    union { float f; uint32_t i; } in;
972
    uint_least8_t sign;
973
    int exponent;
974
    uint64_t mantissa;
975
976
    in.f = value;
977
978
    /* Decompose input value */
979
    sign = (uint_least8_t)((in.i >> 31) & 1);
980
    exponent = (int)((in.i >> 23) & 0xFF) - 127;
981
    mantissa = in.i & 0x7FFFFF;
982
983
    if (exponent == 128)
984
    {
985
        /* Special value (NaN etc.) */
986
        exponent = 1024;
987
    }
988
    else if (exponent == -127)
989
    {
990
        if (!mantissa)
991
        {
992
            /* Zero */
993
            exponent = -1023;
994
        }
995
        else
996
        {
997
            /* Denormalized */
998
            mantissa <<= 1;
999
            while (!(mantissa & 0x800000))
1000
            {
1001
                mantissa <<= 1;
1002
                exponent--;
1003
            }
1004
            mantissa &= 0x7FFFFF;
1005
        }
1006
    }
1007
1008
    /* Combine fields */
1009
    mantissa <<= 29;
1010
    mantissa |= (uint64_t)(exponent + 1023) << 52;
1011
    mantissa |= (uint64_t)sign << 63;
1012
1013
    return pb_encode_fixed64(stream, &mantissa);
1014
}
1015
#endif