aboutsummaryrefslogtreecommitdiff
path: root/components/service/common/serializer/protobuf/pb_helper.c
blob: d32b30c9fd8cacfd591f7cb537642be6b44cd59b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
/*
 * Copyright (c) 2020, Arm Limited and Contributors. All rights reserved.
 *
 * SPDX-License-Identifier: BSD-3-Clause
 */

#include <stdlib.h>
#include <string.h>
#include "pb_helper.h"
#include <pb_encode.h>
#include <pb_decode.h>

static bool pb_encode_byte_array(pb_ostream_t *stream, const pb_field_t *field, void * const *arg) {

    const pb_bytes_array_t *byte_array = (const pb_bytes_array_t *)*arg;
    if (!pb_encode_tag_for_field(stream, field)) return false;

    return pb_encode_string(stream, byte_array->bytes, byte_array->size);
}

static bool pb_decode_byte_array(pb_istream_t *stream, const pb_field_t *field, void **arg) {

    (void)field;
    pb_bytes_array_t *byte_array = (pb_bytes_array_t *)*arg;
    if (stream->bytes_left > byte_array->size) return false;

    byte_array->size = stream->bytes_left;

    return pb_read(stream, byte_array->bytes, stream->bytes_left);
}

pb_callback_t pb_out_byte_array(const pb_bytes_array_t *byte_array) {

    pb_callback_t callback;
    callback.funcs.encode = pb_encode_byte_array;
    callback.arg = (void*)byte_array;

    return callback;
}

pb_callback_t pb_in_byte_array(pb_bytes_array_t *byte_array) {

    pb_callback_t callback;
    callback.funcs.decode = pb_decode_byte_array;
    callback.arg = (void*)byte_array;
    return callback;
}

pb_bytes_array_t *pb_malloc_byte_array(size_t num_bytes) {

    pb_bytes_array_t *byte_array = (pb_bytes_array_t*)malloc(offsetof(pb_bytes_array_t, bytes) + num_bytes);

    if (byte_array) {

        byte_array->size = num_bytes;
    }

    return byte_array;
}

pb_bytes_array_t *pb_malloc_byte_array_containing_string(const char *str) {

    pb_bytes_array_t *byte_array;
    size_t required_space = strlen(str) + 1;

    byte_array = pb_malloc_byte_array(required_space);

    if (byte_array) {

        memcpy(byte_array->bytes, str, required_space);
    }

    return byte_array;
}

pb_bytes_array_t *pb_malloc_byte_array_containing_bytes(const uint8_t *buf, size_t num_bytes) {

    pb_bytes_array_t *byte_array = pb_malloc_byte_array(num_bytes);

    if (byte_array) {

        memcpy(byte_array->bytes, buf, num_bytes);
    }

    return byte_array;
}