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 "core/counter.h"
6 :
7 : #include <errno.h>
8 : #include <stdint.h>
9 : #include <stdlib.h>
10 : #include <string.h>
11 :
12 : #include "core/helper.h"
13 : #include "core/marsh.h"
14 :
15 0 : int bf_counter_new(struct bf_counter **counter, uint64_t packets,
16 : uint64_t bytes)
17 : {
18 : _cleanup_free_ struct bf_counter *_counter = NULL;
19 :
20 0 : bf_assert(counter);
21 :
22 0 : _counter = malloc(sizeof(*_counter));
23 0 : if (!_counter)
24 : return -ENOMEM;
25 :
26 0 : _counter->bytes = bytes;
27 0 : _counter->packets = packets;
28 :
29 0 : *counter = TAKE_PTR(_counter);
30 :
31 0 : return 0;
32 : }
33 :
34 0 : int bf_counter_new_from_marsh(struct bf_counter **counter,
35 : const struct bf_marsh *marsh)
36 : {
37 0 : _cleanup_bf_counter_ struct bf_counter *_counter = NULL;
38 : struct bf_marsh *elem = NULL;
39 :
40 0 : bf_assert(counter && marsh);
41 :
42 0 : _counter = malloc(sizeof(*_counter));
43 0 : if (!_counter)
44 : return -ENOMEM;
45 :
46 0 : if (!(elem = bf_marsh_next_child(marsh, elem)))
47 : return -EINVAL;
48 0 : memcpy(&_counter->packets, elem->data, sizeof(_counter->packets));
49 :
50 0 : if (!(elem = bf_marsh_next_child(marsh, elem)))
51 : return -EINVAL;
52 0 : memcpy(&_counter->bytes, elem->data, sizeof(_counter->bytes));
53 :
54 0 : *counter = TAKE_PTR(_counter);
55 :
56 0 : return 0;
57 : }
58 :
59 0 : void bf_counter_free(struct bf_counter **counter)
60 : {
61 0 : bf_assert(counter);
62 :
63 0 : if (!*counter)
64 : return;
65 :
66 : freep((void *)counter);
67 : }
68 :
69 0 : int bf_counter_marsh(const struct bf_counter *counter, struct bf_marsh **marsh)
70 : {
71 0 : _cleanup_bf_marsh_ struct bf_marsh *_marsh = NULL;
72 : int r;
73 :
74 0 : bf_assert(counter && marsh);
75 :
76 0 : r = bf_marsh_new(&_marsh, NULL, 0);
77 0 : if (r < 0)
78 : return r;
79 :
80 0 : r = bf_marsh_add_child_raw(&_marsh, &counter->packets,
81 : sizeof(counter->packets));
82 0 : if (r < 0)
83 : return r;
84 :
85 0 : r = bf_marsh_add_child_raw(&_marsh, &counter->bytes,
86 : sizeof(counter->bytes));
87 0 : if (r < 0)
88 : return r;
89 :
90 0 : *marsh = TAKE_PTR(_marsh);
91 :
92 0 : return 0;
93 : }
|