nserver

Unnamed repository; edit this file 'description' to name the repository.
Log | Files | Refs | LICENSE

commit 20cac9c3c438aac49d1dcd87fec24c17bdcbfa8c
parent d5cedc6f28a60301bad21a16fdb047fdb82ff883
Author: rsiddharth <s@ricketyspace.net>
Date:   Sat, 11 Apr 2020 00:53:05 -0400

nserver: Add Stats_stringify.

* nserver/src/stats.c (Stats_stringify): New function definition.
* nserver/src/stats.h (Stats_stringify): New function declaration.
* nserver/tests/stats_tests.c (test_tests_stringify): Test for
Stats_stringify.

Diffstat:
nserver/src/stats.c | 22++++++++++++++++++++++
nserver/src/stats.h | 2++
nserver/tests/stats_tests.c | 45+++++++++++++++++++++++++++++++++++++++++++++
3 files changed, 69 insertions(+), 0 deletions(-)

diff --git a/nserver/src/stats.c b/nserver/src/stats.c @@ -65,3 +65,25 @@ char *Stats_dump(Stats *st) error: return NULL; } + +char *Stats_stringify(Stats *st) +{ + size_t stats_str_len = 80; + + // allocate space for stringified stats. + char *stats_str = calloc(stats_str_len, sizeof(char)); + check_mem(stats_str); + + // stringify the stats + int rc = snprintf(stats_str, stats_str_len, + "%.2f::%.2f::%ld::%.2f::%.2f", + st->sum, st->sumsq, st->n, st->min, st->max); + check(rc > 0, "stringify stats failed"); + + return stats_str; + error: + if (stats_str) { + free(stats_str); + } + return NULL; +} diff --git a/nserver/src/stats.h b/nserver/src/stats.h @@ -19,6 +19,8 @@ void Stats_sample(Stats *st, double s); char *Stats_dump(Stats *st); +char *Stats_stringify(Stats *st); + static inline double Stats_mean(Stats *st) { return st->sum / st->n; diff --git a/nserver/tests/stats_tests.c b/nserver/tests/stats_tests.c @@ -0,0 +1,45 @@ +#include "minunit.h" +#include <stats.h> +#include <string.h> + +/** + * tests for other stats functions are in + * ../../liblcthw/tests/stats_tests.c + */ + +char *test_stats_stringify() +{ + Stats *st = Stats_create(); + mu_assert(st != NULL, "stats create failed"); + + // fill with dummy data. + st->sum = 8238.33892; + st->sumsq = 4260238.8292; + st->n = 28; + st->min = 28.3921; + st->max = 238.27; + + char *st_str = Stats_stringify(st); + mu_assert(st_str != NULL, "stats stringify failed"); + + char *expected_st_str = "8238.34::4260238.83::28::28.39::238.27"; + mu_assert(strncmp(st_str, expected_st_str, strlen(expected_st_str)) == 0, + "stringified str invalid"); + + // cleanup + free(st_str); + free(st); + + return NULL; +} + +char *all_tests() +{ + mu_suite_start(); + + mu_run_test(test_stats_stringify); + + return NULL; +} + +RUN_TESTS(all_tests);