| 1 | // SPDX-License-Identifier: GPL-3.0-or-later |
| 2 | |
| 3 | #ifndef NETDATA_API_QUERY_INCREMENTAL_SUM_H |
| 4 | #define NETDATA_API_QUERY_INCREMENTAL_SUM_H |
| 5 | |
| 6 | #include "../query.h" |
| 7 | #include "../rrdr.h" |
| 8 | |
| 9 | struct tg_incremental_sum { |
| 10 | NETDATA_DOUBLE first; |
| 11 | NETDATA_DOUBLE last; |
| 12 | size_t count; |
| 13 | }; |
| 14 | |
| 15 | // resets when switches dimensions |
| 16 | // so, clear everything to restart |
| 17 | static inline void tg_incremental_sum_reset(RRDR *r) { |
| 18 | struct tg_incremental_sum *g = (struct tg_incremental_sum *)r->time_grouping.data; |
| 19 | g->first = NAN; |
| 20 | g->last = NAN; |
| 21 | g->count = 0; |
| 22 | } |
| 23 | |
| 24 | static inline void tg_incremental_sum_create(RRDR *r, const char *options __maybe_unused) { |
| 25 | r->time_grouping.data = onewayalloc_mallocz(r->internal.owa, sizeof(struct tg_incremental_sum)); |
| 26 | tg_incremental_sum_reset(r); |
| 27 | } |
| 28 | |
| 29 | static inline void tg_incremental_sum_free(RRDR *r) { |
| 30 | onewayalloc_freez(r->internal.owa, r->time_grouping.data); |
| 31 | r->time_grouping.data = NULL; |
| 32 | } |
| 33 | |
| 34 | static inline void tg_incremental_sum_add(RRDR *r, NETDATA_DOUBLE value) { |
| 35 | struct tg_incremental_sum *g = (struct tg_incremental_sum *)r->time_grouping.data; |
| 36 | |
| 37 | if(unlikely(!g->count)) { |
| 38 | if(isnan(g->first)) |
| 39 | g->first = value; |
| 40 | else |
| 41 | g->last = value; |
| 42 | |
| 43 | g->count++; |
| 44 | } |
| 45 | else { |
| 46 | g->last = value; |
| 47 | g->count++; |
| 48 | } |
| 49 | } |
| 50 | |
| 51 | static inline NETDATA_DOUBLE tg_incremental_sum_flush(RRDR *r, RRDR_VALUE_FLAGS *rrdr_value_options_ptr) { |
| 52 | struct tg_incremental_sum *g = (struct tg_incremental_sum *)r->time_grouping.data; |
| 53 | |
| 54 | NETDATA_DOUBLE value; |
| 55 | |
| 56 | if(unlikely(!g->count || isnan(g->first) || isnan(g->last))) { |
| 57 | value = 0.0; |
| 58 | *rrdr_value_options_ptr |= RRDR_VALUE_EMPTY; |
| 59 | } |
| 60 | else { |
| 61 | value = g->last - g->first; |
| 62 | } |
| 63 | |
| 64 | g->first = g->last; |
| 65 | g->last = NAN; |
| 66 | g->count = 0; |
| 67 | |
| 68 | return value; |
| 69 | } |
| 70 | |
| 71 | #endif //NETDATA_API_QUERY_INCREMENTAL_SUM_H |