ca79125210fdefbad0b3c9f4c684e259427e5292
[cascardo/declara.git] / lib / totais.c
1 /*
2  *  Copyright (C) 2015  Thadeu Lima de Souza Cascardo <cascardo@cascardo.eti.br>
3  *
4  *  This program is free software; you can redistribute it and/or modify
5  *  it under the terms of the GNU General Public License as published by
6  *  the Free Software Foundation; either version 3 of the License, or
7  *  (at your option) any later version.
8  *
9  *  This program is distributed in the hope that it will be useful,
10  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
11  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  *  GNU General Public License for more details.
13  *
14  *  You should have received a copy of the GNU General Public License along
15  *  with this program; if not, write to the Free Software Foundation, Inc.,
16  *  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
17  */
18
19 #include "totais.h"
20 #include <stdlib.h>
21 #include <string.h>
22 #include <errno.h>
23 #include "pmhash.h"
24
25 int totais_add(struct declaracao *dec, char *key, long long val)
26 {
27         long long *p;
28         int r = -ENOMEM;
29         p = pmhash_get(dec->totais, key);
30         if (!p) {
31                 p = malloc(sizeof(*p));
32                 if (!p)
33                         goto out_p;
34                 key = strdup(key);
35                 if (!key)
36                         goto out_key;
37                 r = pmhash_add(&dec->totais, key, p);
38                 if (r)
39                         goto out_hash;
40                 *p = 0;
41         }
42         *p += val;
43         return 0;
44 out_hash:
45         free(key);
46 out_key:
47         free(p);
48 out_p:
49         return r;
50 }
51
52 long long totais_get(struct declaracao *dec, char *key)
53 {
54         long long *p;
55         p = pmhash_get(dec->totais, key);
56         if (!p)
57                 return 0;
58         return *p;
59 }