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 141 : int bf_marsh_new(struct bf_marsh **marsh, const void *data, size_t data_len)
15 : {
16 : struct bf_marsh *_marsh = NULL;
17 :
18 141 : bf_assert(marsh);
19 140 : bf_assert(!data ? !data_len : 1);
20 :
21 139 : _marsh = malloc(sizeof(struct bf_marsh) + data_len);
22 139 : if (!_marsh)
23 : return -ENOMEM;
24 :
25 136 : _marsh->data_len = data_len;
26 136 : bf_memcpy(_marsh->data, data, data_len);
27 :
28 136 : *marsh = TAKE_PTR(_marsh);
29 :
30 136 : return 0;
31 : }
32 :
33 394 : void bf_marsh_free(struct bf_marsh **marsh)
34 : {
35 394 : bf_assert(marsh);
36 :
37 394 : if (!*marsh)
38 : return;
39 :
40 249 : free(*marsh);
41 249 : *marsh = NULL;
42 : }
43 :
44 116 : int bf_marsh_add_child_obj(struct bf_marsh **marsh, const struct bf_marsh *obj)
45 : {
46 114 : _cleanup_bf_marsh_ struct bf_marsh *new = NULL;
47 : size_t new_data_len;
48 :
49 117 : bf_assert(marsh && *marsh);
50 115 : bf_assert(obj);
51 :
52 114 : new_data_len = (*marsh)->data_len + bf_marsh_size(obj);
53 :
54 114 : new = malloc(sizeof(struct bf_marsh) + new_data_len);
55 114 : if (!new)
56 : return -ENOMEM;
57 :
58 113 : memcpy(new->data, (*marsh)->data, (*marsh)->data_len);
59 113 : memcpy(new->data + (*marsh)->data_len, obj, bf_marsh_size(obj));
60 113 : new->data_len = new_data_len;
61 :
62 113 : bf_marsh_free(marsh);
63 113 : *marsh = TAKE_PTR(new);
64 :
65 113 : return 0;
66 : }
67 :
68 85 : int bf_marsh_add_child_raw(struct bf_marsh **marsh, const void *data,
69 : size_t data_len)
70 : {
71 83 : _cleanup_bf_marsh_ struct bf_marsh *child = NULL;
72 : int r;
73 :
74 86 : bf_assert(marsh && *marsh);
75 84 : bf_assert(!data ? !data_len : 1);
76 :
77 83 : r = bf_marsh_new(&child, data, data_len);
78 83 : if (r < 0)
79 : return r;
80 :
81 83 : r = bf_marsh_add_child_obj(marsh, child);
82 83 : if (r < 0)
83 : return r;
84 :
85 : return 0;
86 : }
|