Fix compilation on systems with older compilers.
[tor.git] / src / lib / metrics / metrics_store_entry.c
blob44ebb5cb847f2ef51db1c6e9bf3c94194b0846ca
1 /* Copyright (c) 2020, The Tor Project, Inc. */
2 /* See LICENSE for licensing information */
4 /**
5 * @file metrics_store_entry.c
6 * @brief Metrics store entry which contains the gathered data.
7 **/
9 #define METRICS_STORE_ENTRY_PRIVATE
11 #include <string.h>
13 #include "orconfig.h"
15 #include "lib/container/smartlist.h"
16 #include "lib/log/util_bug.h"
17 #include "lib/malloc/malloc.h"
19 #include "lib/metrics/metrics_store_entry.h"
22 * Public API.
25 /** Return newly allocated store entry of type COUNTER. */
26 metrics_store_entry_t *
27 metrics_store_entry_new(const metrics_type_t type, const char *name,
28 const char *help)
30 metrics_store_entry_t *entry = tor_malloc_zero(sizeof(*entry));
32 tor_assert(name);
34 entry->type = type;
35 entry->name = tor_strdup(name);
36 entry->labels = smartlist_new();
37 if (help) {
38 entry->help = tor_strdup(help);
41 return entry;
44 /** Free a store entry. */
45 void
46 metrics_store_entry_free_(metrics_store_entry_t *entry)
48 if (!entry) {
49 return;
51 SMARTLIST_FOREACH(entry->labels, char *, l, tor_free(l));
52 smartlist_free(entry->labels);
53 tor_free(entry->name);
54 tor_free(entry->help);
55 tor_free(entry);
58 /** Update a store entry with value. */
59 void
60 metrics_store_entry_update(metrics_store_entry_t *entry, const int64_t value)
62 tor_assert(entry);
64 switch (entry->type) {
65 case METRICS_TYPE_COUNTER:
66 /* Counter can ONLY be positive. */
67 if (BUG(value < 0)) {
68 return;
70 entry->u.counter.value += value;
71 break;
72 case METRICS_TYPE_GAUGE:
73 /* Gauge can increment or decrement. And can be positive or negative. */
74 entry->u.gauge.value += value;
75 break;
79 /** Reset a store entry that is set its metric data to 0. */
80 void
81 metrics_store_entry_reset(metrics_store_entry_t *entry)
83 tor_assert(entry);
84 /* Everything back to 0. */
85 memset(&entry->u, 0, sizeof(entry->u));
88 /** Return store entry value. */
89 int64_t
90 metrics_store_entry_get_value(const metrics_store_entry_t *entry)
92 tor_assert(entry);
94 switch (entry->type) {
95 case METRICS_TYPE_COUNTER:
96 if (entry->u.counter.value > INT64_MAX) {
97 return INT64_MAX;
99 return entry->u.counter.value;
100 case METRICS_TYPE_GAUGE:
101 return entry->u.gauge.value;
104 // LCOV_EXCL_START
105 tor_assert_unreached();
106 // LCOV_EXCL_STOP
109 /** Add a label into the given entry.*/
110 void
111 metrics_store_entry_add_label(metrics_store_entry_t *entry,
112 const char *label)
114 tor_assert(entry);
115 tor_assert(label);
117 smartlist_add(entry->labels, tor_strdup(label));
120 /** Return true iff the given entry has the given label. */
121 bool
122 metrics_store_entry_has_label(const metrics_store_entry_t *entry,
123 const char *label)
125 tor_assert(entry);
126 tor_assert(label);
128 return smartlist_contains_string(entry->labels, label);