90ca42666f7d20193cfaca1ab7e96cc6416695b9
[cascardo/declara.git] / lib / util.c
1 /*
2  *  Copyright (C) 2015  Thadeu Lima de Souza Cascardo <cascardo@minaslivre.org>
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 "util.h"
20 #include <stdlib.h>
21 #include <errno.h>
22 #include <string.h>
23
24 int set_llong(char *str, long long *val)
25 {
26         char *end = NULL;
27         errno = 0;
28         *val = strtoll(str, &end, 0);
29         if (end && *end)
30                 return -EINVAL;
31         if (errno == ERANGE)
32                 return -ERANGE;
33         return 0;
34 }
35
36 int set_int(char **args, int argc, int *val)
37 {
38         char *end = NULL;
39         if (argc != 2)
40                 return -EINVAL;
41         errno = 0;
42         *val = strtol(args[1], &end, 0);
43         if (end && *end)
44                 return -EINVAL;
45         if (errno == ERANGE)
46                 return -ERANGE;
47         return 0;
48 }
49
50 int set_string(char **args, int argc, char **str)
51 {
52         if (argc != 2)
53                 return -EINVAL;
54         *str = strdup(args[1]);
55         if (!*str)
56                 return -errno;
57         return 0;
58 }