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 0 : 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 0 : bf_assert(counter);
20 :
21 0 : _counter = malloc(sizeof(*_counter));
22 0 : if (!_counter)
23 : return -ENOMEM;
24 :
25 0 : _counter->bytes = bytes;
26 0 : _counter->packets = packets;
27 :
28 0 : *counter = TAKE_PTR(_counter);
29 :
30 0 : return 0;
31 : }
32 :
33 0 : int bf_counter_new_from_pack(struct bf_counter **counter, bf_rpack_node_t node)
34 : {
35 0 : _free_bf_counter_ struct bf_counter *_counter = NULL;
36 : int r;
37 :
38 0 : bf_assert(counter);
39 :
40 0 : r = bf_counter_new(&_counter, 0, 0);
41 0 : if (r)
42 : return r;
43 :
44 0 : r = bf_rpack_kv_u64(node, "packets", &_counter->packets);
45 0 : if (r)
46 0 : return bf_rpack_key_err(r, "bf_counter.packets");
47 :
48 0 : r = bf_rpack_kv_u64(node, "bytes", &_counter->bytes);
49 0 : if (r)
50 0 : return bf_rpack_key_err(r, "bf_counter.bytes");
51 :
52 0 : *counter = TAKE_PTR(_counter);
53 :
54 0 : return 0;
55 : }
56 :
57 0 : void bf_counter_free(struct bf_counter **counter)
58 : {
59 0 : bf_assert(counter);
60 :
61 0 : if (!*counter)
62 : return;
63 :
64 : freep((void *)counter);
65 : }
66 :
67 0 : int bf_counter_pack(const struct bf_counter *counter, bf_wpack_t *pack)
68 : {
69 0 : bf_assert(counter);
70 0 : bf_assert(pack);
71 :
72 0 : bf_wpack_kv_u64(pack, "packets", counter->packets);
73 0 : bf_wpack_kv_u64(pack, "bytes", counter->bytes);
74 :
75 0 : return bf_wpack_is_valid(pack) ? 0 : -EINVAL;
76 : }
|