Branch data Line data Source code
1 : : /* SPDX-License-Identifier: GPL-2.0-only */
2 : : /*
3 : : * Copyright (c) 2023 Meta Platforms, Inc. and affiliates.
4 : : */
5 : : #include "bpfilter/counter.h"
6 : :
7 : : #include <errno.h>
8 : : #include <stdint.h>
9 : : #include <stdlib.h>
10 : : #include <string.h>
11 : :
12 : : #include "bpfilter/helper.h"
13 : :
14 : 70 : int bf_counter_new(struct bf_counter **counter, uint64_t packets,
15 : : uint64_t bytes)
16 : : {
17 : : _cleanup_free_ struct bf_counter *_counter = NULL;
18 : :
19 : : bf_assert(counter);
20 : :
21 : 70 : _counter = malloc(sizeof(*_counter));
22 [ + - ]: 70 : if (!_counter)
23 : : return -ENOMEM;
24 : :
25 : 70 : _counter->bytes = bytes;
26 : 70 : _counter->packets = packets;
27 : :
28 : 70 : *counter = TAKE_PTR(_counter);
29 : :
30 : 70 : return 0;
31 : : }
32 : :
33 : 35 : int bf_counter_new_from_pack(struct bf_counter **counter, bf_rpack_node_t node)
34 : : {
35 : 35 : _free_bf_counter_ struct bf_counter *_counter = NULL;
36 : : int r;
37 : :
38 : : bf_assert(counter);
39 : :
40 : 35 : r = bf_counter_new(&_counter, 0, 0);
41 [ + - ]: 35 : if (r)
42 : : return r;
43 : :
44 : 35 : r = bf_rpack_kv_u64(node, "packets", &_counter->packets);
45 [ + + ]: 35 : if (r)
46 [ + - ]: 1 : return bf_rpack_key_err(r, "bf_counter.packets");
47 : :
48 : 34 : r = bf_rpack_kv_u64(node, "bytes", &_counter->bytes);
49 [ + + ]: 34 : if (r)
50 [ + - ]: 1 : return bf_rpack_key_err(r, "bf_counter.bytes");
51 : :
52 : 33 : *counter = TAKE_PTR(_counter);
53 : :
54 : 33 : return 0;
55 : : }
56 : :
57 : 169 : void bf_counter_free(struct bf_counter **counter)
58 : : {
59 : : bf_assert(counter);
60 : :
61 [ + + ]: 169 : if (!*counter)
62 : : return;
63 : :
64 : : freep((void *)counter);
65 : : }
66 : :
67 : 33 : int bf_counter_pack(const struct bf_counter *counter, bf_wpack_t *pack)
68 : : {
69 : : bf_assert(counter);
70 : : bf_assert(pack);
71 : :
72 : 33 : bf_wpack_kv_u64(pack, "packets", counter->packets);
73 : 33 : bf_wpack_kv_u64(pack, "bytes", counter->bytes);
74 : :
75 [ - + ]: 33 : return bf_wpack_is_valid(pack) ? 0 : -EINVAL;
76 : : }
|