1 /* Licensed under GPLv3+ - see LICENSE file for details */
2 #include <ccan/opt/opt.h>
9 /* Upper bound to sprintf this simple type? Each 3 bits < 1 digit. */
10 #define CHAR_SIZE(type) (((sizeof(type)*CHAR_BIT + 2) / 3) + 1)
12 /* FIXME: asprintf module? */
13 static char *arg_bad(const char *fmt, const char *arg)
15 char *str = malloc(strlen(fmt) + strlen(arg));
16 sprintf(str, fmt, arg);
20 char *opt_set_bool(bool *b)
26 char *opt_set_invbool(bool *b)
32 char *opt_set_bool_arg(const char *arg, bool *b)
34 if (!strcasecmp(arg, "yes") || !strcasecmp(arg, "true"))
35 return opt_set_bool(b);
36 if (!strcasecmp(arg, "no") || !strcasecmp(arg, "false"))
37 return opt_set_invbool(b);
39 return opt_invalid_argument(arg);
42 char *opt_set_invbool_arg(const char *arg, bool *b)
44 char *err = opt_set_bool_arg(arg, b);
52 char *opt_set_charp(const char *arg, char **p)
58 /* Set an integer value, various forms. Sets to 1 on arg == NULL. */
59 char *opt_set_intval(const char *arg, int *i)
62 char *err = opt_set_longval(arg, &l);
67 /* Beware truncation... */
69 return arg_bad("value '%s' does not fit into an integer", arg);
73 char *opt_set_uintval(const char *arg, unsigned int *ui)
76 char *err = opt_set_intval(arg, &i);
81 return arg_bad("'%s' is negative", arg);
86 char *opt_set_longval(const char *arg, long *l)
90 /* This is how the manpage says to do it. Yech. */
92 *l = strtol(arg, &endp, 0);
94 return arg_bad("'%s' is not a number", arg);
96 return arg_bad("'%s' is out of range", arg);
100 char *opt_set_ulongval(const char *arg, unsigned long *ul)
105 err = opt_set_longval(arg, &l);
110 return arg_bad("'%s' is negative", arg);
114 char *opt_inc_intval(int *i)
120 /* Display version string. */
121 char *opt_version_and_exit(const char *version)
123 printf("%s\n", version);
127 char *opt_usage_and_exit(const char *extra)
129 printf("%s", opt_usage(opt_argv0, extra));
133 void opt_show_bool(char buf[OPT_SHOW_LEN], const bool *b)
135 strncpy(buf, *b ? "true" : "false", OPT_SHOW_LEN);
138 void opt_show_invbool(char buf[OPT_SHOW_LEN], const bool *b)
140 strncpy(buf, *b ? "false" : "true", OPT_SHOW_LEN);
143 void opt_show_charp(char buf[OPT_SHOW_LEN], char *const *p)
145 size_t len = strlen(*p);
147 if (len > OPT_SHOW_LEN - 2)
148 len = OPT_SHOW_LEN - 2;
149 strncpy(buf+1, *p, len);
151 if (len < OPT_SHOW_LEN - 2)
155 /* Set an integer value, various forms. Sets to 1 on arg == NULL. */
156 void opt_show_intval(char buf[OPT_SHOW_LEN], const int *i)
158 snprintf(buf, OPT_SHOW_LEN, "%i", *i);
161 void opt_show_uintval(char buf[OPT_SHOW_LEN], const unsigned int *ui)
163 snprintf(buf, OPT_SHOW_LEN, "%u", *ui);
166 void opt_show_longval(char buf[OPT_SHOW_LEN], const long *l)
168 snprintf(buf, OPT_SHOW_LEN, "%li", *l);
171 void opt_show_ulongval(char buf[OPT_SHOW_LEN], const unsigned long *ul)
173 snprintf(buf, OPT_SHOW_LEN, "%lu", *ul);