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/summary.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_summary, CONFIG_PROMETHEUS_LOG_LEVEL);
16 
prometheus_summary_observe(struct prometheus_summary * summary,double value)17 int prometheus_summary_observe(struct prometheus_summary *summary, double value)
18 {
19 	if (!summary) {
20 		return -EINVAL;
21 	}
22 
23 	/* increment count */
24 	summary->count++;
25 
26 	/* update sum */
27 	summary->sum += value;
28 
29 	return 0;
30 }
31 
prometheus_summary_observe_set(struct prometheus_summary * summary,double value,unsigned long count)32 int prometheus_summary_observe_set(struct prometheus_summary *summary,
33 				   double value, unsigned long count)
34 {
35 	unsigned long old_count;
36 	double old_sum;
37 
38 	if (summary == NULL) {
39 		return -EINVAL;
40 	}
41 
42 	if (value == summary->sum && count == summary->count) {
43 		return 0;
44 	}
45 
46 	old_count = summary->count;
47 	if (count < old_count) {
48 		LOG_DBG("Cannot set summary count to a lower value");
49 		return -EINVAL;
50 	}
51 
52 	summary->count += (count - old_count);
53 
54 	old_sum = summary->sum;
55 	summary->sum += (value - old_sum);
56 
57 	return 0;
58 }
59