File: math.c

package info (click to toggle)
uwsgi 2.0.31-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 6,624 kB
  • sloc: ansic: 87,072; python: 7,010; cpp: 1,133; java: 708; perl: 678; sh: 585; ruby: 555; makefile: 148; xml: 130; cs: 121; objc: 37; php: 28; erlang: 20; javascript: 11
file content (52 lines) | stat: -rw-r--r-- 1,860 bytes parent folder | download | duplicates (8)
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
#include <uwsgi.h>
#include <matheval.h>

static char *uwsgi_route_var_math(struct wsgi_request *wsgi_req, char *key, uint16_t keylen, uint16_t *vallen) {
        char *ret = NULL;
        // avoid crash
        if (!wsgi_req->var_cnt) return NULL;
        // we make a bit of fun here, we do a copy of the vars buffer (+1 byte for final zero) and zeor-pad all of the strings
        char *vars_buf = uwsgi_malloc(wsgi_req->uh->pktsize + keylen + 1);
        char **names = uwsgi_malloc(sizeof(char *) * (wsgi_req->var_cnt/2));
        double *values = uwsgi_calloc(sizeof(double) * (wsgi_req->var_cnt/2));
        int i,j = 0;
        char *ptr = vars_buf;
        for (i = wsgi_req->var_cnt-1; i > 0; i -= 2) {
                memcpy(ptr, wsgi_req->hvec[i-1].iov_base, wsgi_req->hvec[i-1].iov_len);
                names[j] = ptr;
                ptr += wsgi_req->hvec[i-1].iov_len;
                *ptr++=0;
                char *num = ptr;
                memcpy(ptr, wsgi_req->hvec[i].iov_base, wsgi_req->hvec[i].iov_len);
                ptr += wsgi_req->hvec[i].iov_len;
                *ptr++=0;
                values[j] = strtod(num, NULL);
                j++;
        }

        char *expr = ptr;
        memcpy(ptr, key, keylen); ptr += keylen;
        *ptr++=0;

        void *e = evaluator_create(expr);
        if (!e) goto end;
        double n = evaluator_evaluate(e, j, names, values);
        evaluator_destroy(e);
        ret = uwsgi_num2str((int)n);
        *vallen = strlen(ret);
end:
        free(vars_buf);
        free(names);
        free(values);
        return ret;
}

static void router_matheval_register() {
	struct uwsgi_route_var *urv = uwsgi_register_route_var("math", uwsgi_route_var_math);
        urv->need_free = 1;
}

struct uwsgi_plugin matheval_plugin = {
	.name = "matheval",
	.on_load = router_matheval_register,	
};