Julian Hall | df86fce | 2020-11-23 18:09:55 +0100 | [diff] [blame] | 1 | /* |
| 2 | * Copyright (c) 2020, Arm Limited and Contributors. All rights reserved. |
| 3 | * |
| 4 | * SPDX-License-Identifier: BSD-3-Clause |
| 5 | */ |
| 6 | |
| 7 | #include <stdlib.h> |
| 8 | #include <string.h> |
| 9 | #include "pb_helper.h" |
| 10 | #include <pb_encode.h> |
| 11 | #include <pb_decode.h> |
| 12 | |
| 13 | static bool pb_encode_byte_array(pb_ostream_t *stream, const pb_field_t *field, void * const *arg) { |
| 14 | |
| 15 | const pb_bytes_array_t *byte_array = (const pb_bytes_array_t *)*arg; |
| 16 | if (!pb_encode_tag_for_field(stream, field)) return false; |
| 17 | |
| 18 | return pb_encode_string(stream, byte_array->bytes, byte_array->size); |
| 19 | } |
| 20 | |
| 21 | static bool pb_decode_byte_array(pb_istream_t *stream, const pb_field_t *field, void **arg) { |
| 22 | |
| 23 | (void)field; |
| 24 | pb_bytes_array_t *byte_array = (pb_bytes_array_t *)*arg; |
| 25 | if (stream->bytes_left > byte_array->size) return false; |
| 26 | |
| 27 | byte_array->size = stream->bytes_left; |
| 28 | |
| 29 | return pb_read(stream, byte_array->bytes, stream->bytes_left); |
| 30 | } |
| 31 | |
| 32 | pb_callback_t pb_out_byte_array(const pb_bytes_array_t *byte_array) { |
| 33 | |
| 34 | pb_callback_t callback; |
| 35 | callback.funcs.encode = pb_encode_byte_array; |
| 36 | callback.arg = (void*)byte_array; |
| 37 | |
| 38 | return callback; |
| 39 | } |
| 40 | |
| 41 | pb_callback_t pb_in_byte_array(pb_bytes_array_t *byte_array) { |
| 42 | |
| 43 | pb_callback_t callback; |
| 44 | callback.funcs.decode = pb_decode_byte_array; |
| 45 | callback.arg = (void*)byte_array; |
| 46 | return callback; |
| 47 | } |
| 48 | |
| 49 | pb_bytes_array_t *pb_malloc_byte_array(size_t num_bytes) { |
| 50 | |
| 51 | pb_bytes_array_t *byte_array = (pb_bytes_array_t*)malloc(offsetof(pb_bytes_array_t, bytes) + num_bytes); |
| 52 | |
| 53 | if (byte_array) { |
| 54 | |
| 55 | byte_array->size = num_bytes; |
| 56 | } |
| 57 | |
| 58 | return byte_array; |
| 59 | } |
| 60 | |
| 61 | pb_bytes_array_t *pb_malloc_byte_array_containing_string(const char *str) { |
| 62 | |
| 63 | pb_bytes_array_t *byte_array; |
| 64 | size_t required_space = strlen(str) + 1; |
| 65 | |
| 66 | byte_array = pb_malloc_byte_array(required_space); |
| 67 | |
| 68 | if (byte_array) { |
| 69 | |
| 70 | memcpy(byte_array->bytes, str, required_space); |
| 71 | } |
| 72 | |
| 73 | return byte_array; |
| 74 | } |
| 75 | |
| 76 | pb_bytes_array_t *pb_malloc_byte_array_containing_bytes(const uint8_t *buf, size_t num_bytes) { |
| 77 | |
| 78 | pb_bytes_array_t *byte_array = pb_malloc_byte_array(num_bytes); |
| 79 | |
| 80 | if (byte_array) { |
| 81 | |
| 82 | memcpy(byte_array->bytes, buf, num_bytes); |
| 83 | } |
| 84 | |
| 85 | return byte_array; |
| 86 | } |