summaryrefslogtreecommitdiffstats
path: root/nserver/src/protocol.c
blob: adcfc21c45696031ffe5edfc7353badcbfa5f739 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
#include <protocol.h>

static Hashmap *hash;

int ssinit()
{
    if (hash == NULL) {
        hash = Hashmap_create(NULL, NULL);
        check(hash != NULL, "unable to create hashmap");
    }

    return 0;
 error:
    return -1;
}

int sscreate(char *key)
{
    int rc = 0;

    check(ssinit() == 0, "ssinit failed");

    // 1. create bstring from 'key'.
    bstring k = bfromcstr(key);
    check(k != NULL, "key creation failed");

    // 2. allocate fresh Stats.
    Stats *st = Stats_create();
    check(st != NULL, "stats creation failed");

    // 3. add to hashmap.
    rc = Hashmap_set(hash, k, st);
    check(rc == 0, "hashmap set failed");

    return 0;
 error:
    return -1;
}

int ssdelete(char *key)
{
    check(hash != NULL, "hash not initialized");

    // 1. create bstring from 'key'.
    bstring k = bfromcstr(key);
    check(k != NULL, "key creation failed");

    // 2. check if key exists.
    Stats *st = (Stats *) Hashmap_get(hash, k);
    if (st == NULL) {
        // key does not exists.
        return 0;
    }

    // 3. delete key.
    st = (Stats *) Hashmap_delete(hash, k);
    check(st != NULL, "hash key delete failed");

    // 4. clean up the stats for this key.
    free(st);

    return 0;
 error:
    return -1;
}

int sssample(char *key, double s)
{
    check(hash != NULL, "hash not initialized");

    // 1. create bstring from 'key'.
    bstring k = bfromcstr(key);
    check(k != NULL, "key creation failed");

    // 2. try to get Stats for key.
    Stats *st = (Stats *) Hashmap_get(hash, k);
    check(st != NULL, "stats not found for key");

    // 3. sample!
    Stats_sample(st, s);

    return 0;
 error:
    return -1;
}

double ssmean(char *key)
{
    check(hash != NULL, "hash not initialized");

    // 1. create bstring from 'key'.
    bstring k = bfromcstr(key);

    // 2. try to Stats for key.
    Stats *st = (Stats *) Hashmap_get(hash, k);
    check(st != NULL, "stats not found for key");

    // 3. get mean.
    double m = Stats_mean(st);

    return m;
 error:
    return -1;
}