Line data Source code
1 : /* SPDX-License-Identifier: GPL-2.0-only */
2 : /*
3 : * Copyright (c) 2023 Meta Platforms, Inc. and affiliates.
4 : */
5 :
6 : #include "core/marsh.h"
7 :
8 : #include <errno.h>
9 : #include <stdlib.h>
10 : #include <string.h>
11 :
12 : #include "core/helper.h"
13 :
14 234 : int bf_marsh_new(struct bf_marsh **marsh, const void *data, size_t data_len)
15 : {
16 : struct bf_marsh *_marsh = NULL;
17 :
18 234 : bf_assert(marsh);
19 233 : bf_assert(!data ? !data_len : 1);
20 :
21 232 : _marsh = malloc(sizeof(struct bf_marsh) + data_len);
22 232 : if (!_marsh)
23 : return -ENOMEM;
24 :
25 229 : _marsh->data_len = data_len;
26 229 : bf_memcpy(_marsh->data, data, data_len);
27 :
28 229 : *marsh = TAKE_PTR(_marsh);
29 :
30 229 : return 0;
31 : }
32 :
33 692 : void bf_marsh_free(struct bf_marsh **marsh)
34 : {
35 692 : bf_assert(marsh);
36 :
37 692 : if (!*marsh)
38 : return;
39 :
40 432 : free(*marsh);
41 432 : *marsh = NULL;
42 : }
43 :
44 206 : int bf_marsh_add_child_obj(struct bf_marsh **marsh, const struct bf_marsh *obj)
45 : {
46 204 : _free_bf_marsh_ struct bf_marsh *new = NULL;
47 : size_t new_data_len;
48 :
49 207 : bf_assert(marsh && *marsh);
50 205 : bf_assert(obj);
51 :
52 204 : new_data_len = (*marsh)->data_len + bf_marsh_size(obj);
53 :
54 204 : new = malloc(sizeof(struct bf_marsh) + new_data_len);
55 204 : if (!new)
56 : return -ENOMEM;
57 :
58 203 : memcpy(new->data, (*marsh)->data, (*marsh)->data_len);
59 203 : memcpy(new->data + (*marsh)->data_len, obj, bf_marsh_size(obj));
60 203 : new->data_len = new_data_len;
61 :
62 203 : bf_marsh_free(marsh);
63 203 : *marsh = TAKE_PTR(new);
64 :
65 203 : return 0;
66 : }
67 :
68 154 : int bf_marsh_add_child_raw(struct bf_marsh **marsh, const void *data,
69 : size_t data_len)
70 : {
71 152 : _free_bf_marsh_ struct bf_marsh *child = NULL;
72 : int r;
73 :
74 155 : bf_assert(marsh && *marsh);
75 153 : bf_assert(!data ? !data_len : 1);
76 :
77 152 : r = bf_marsh_new(&child, data, data_len);
78 152 : if (r < 0)
79 : return r;
80 :
81 152 : r = bf_marsh_add_child_obj(marsh, child);
82 152 : if (r < 0)
83 : return r;
84 :
85 : return 0;
86 : }
|