1 /*
2  * Copyright (c) 2024 Mustafa Abdullah Kus, Sparse Technology
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #include <zephyr/net/prometheus/counter.h>
8 
9 #include <stdlib.h>
10 #include <string.h>
11 
12 #include <zephyr/kernel.h>
13 
14 #include <zephyr/logging/log.h>
15 LOG_MODULE_REGISTER(pm_counter, CONFIG_PROMETHEUS_LOG_LEVEL);
16 
prometheus_counter_add(struct prometheus_counter * counter,uint64_t value)17 int prometheus_counter_add(struct prometheus_counter *counter, uint64_t value)
18 {
19 	if (counter == NULL) {
20 		return -EINVAL;
21 	}
22 
23 	counter->value += value;
24 
25 	return 0;
26 }
27 
prometheus_counter_set(struct prometheus_counter * counter,uint64_t value)28 int prometheus_counter_set(struct prometheus_counter *counter, uint64_t value)
29 {
30 	uint64_t old_value;
31 
32 	if (counter == NULL) {
33 		return -EINVAL;
34 	}
35 
36 	if (value == counter->value) {
37 		return 0;
38 	}
39 
40 	old_value = counter->value;
41 	if (value < old_value) {
42 		LOG_DBG("Cannot set counter to a lower value (%" PRIu64 " < %" PRIu64 ")",
43 			value, old_value);
44 		return -EINVAL;
45 	}
46 
47 	counter->value += (value - old_value);
48 
49 	return 0;
50 }
51