1 #include <ccan/opt/opt.h>
8 /* Upper bound to sprintf this simple type? Each 3 bits < 1 digit. */
9 #define CHAR_SIZE(type) (((sizeof(type)*CHAR_BIT + 2) / 3) + 1)
11 /* FIXME: asprintf module? */
12 static char *arg_bad(const char *fmt, const char *arg)
14 char *str = malloc(strlen(fmt) + strlen(arg));
15 sprintf(str, fmt, arg);
19 char *opt_set_bool(bool *b)
25 char *opt_set_invbool(bool *b)
31 char *opt_set_bool_arg(const char *arg, bool *b)
33 if (!strcasecmp(arg, "yes") || !strcasecmp(arg, "true"))
34 return opt_set_bool(b);
35 if (!strcasecmp(arg, "no") || !strcasecmp(arg, "false"))
36 return opt_set_invbool(b);
38 return opt_invalid_argument(arg);
41 char *opt_set_invbool_arg(const char *arg, bool *b)
43 char *err = opt_set_bool_arg(arg, b);
51 char *opt_set_charp(const char *arg, char **p)
57 /* Set an integer value, various forms. Sets to 1 on arg == NULL. */
58 char *opt_set_intval(const char *arg, int *i)
61 char *err = opt_set_longval(arg, &l);
66 /* Beware truncation... */
68 return arg_bad("value '%s' does not fit into an integer", arg);
72 char *opt_set_uintval(const char *arg, unsigned int *ui)
75 char *err = opt_set_intval(arg, &i);
80 return arg_bad("'%s' is negative", arg);
85 char *opt_set_longval(const char *arg, long *l)
89 /* This is how the manpage says to do it. Yech. */
91 *l = strtol(arg, &endp, 0);
93 return arg_bad("'%s' is not a number", arg);
95 return arg_bad("'%s' is out of range", arg);
99 char *opt_set_ulongval(const char *arg, unsigned long *ul)
104 err = opt_set_longval(arg, &l);
109 return arg_bad("'%s' is negative", arg);
113 char *opt_inc_intval(int *i)
119 /* Display version string. */
120 char *opt_version_and_exit(const char *version)
122 printf("%s\n", version);
126 char *opt_usage_and_exit(const char *extra)
128 printf("%s", opt_usage(opt_argv0, extra));
132 void opt_show_bool(char buf[OPT_SHOW_LEN], const bool *b)
134 strncpy(buf, *b ? "true" : "false", OPT_SHOW_LEN);
137 void opt_show_invbool(char buf[OPT_SHOW_LEN], const bool *b)
139 strncpy(buf, *b ? "false" : "true", OPT_SHOW_LEN);
142 void opt_show_charp(char buf[OPT_SHOW_LEN], char *const *p)
144 size_t len = strlen(*p);
146 if (len > OPT_SHOW_LEN - 2)
147 len = OPT_SHOW_LEN - 2;
148 strncpy(buf+1, *p, len);
150 if (len < OPT_SHOW_LEN - 2)
154 /* Set an integer value, various forms. Sets to 1 on arg == NULL. */
155 void opt_show_intval(char buf[OPT_SHOW_LEN], const int *i)
157 snprintf(buf, OPT_SHOW_LEN, "%i", *i);
160 void opt_show_uintval(char buf[OPT_SHOW_LEN], const unsigned int *ui)
162 snprintf(buf, OPT_SHOW_LEN, "%u", *ui);
165 void opt_show_longval(char buf[OPT_SHOW_LEN], const long *l)
167 snprintf(buf, OPT_SHOW_LEN, "%li", *l);
170 void opt_show_ulongval(char buf[OPT_SHOW_LEN], const unsigned long *ul)
172 snprintf(buf, OPT_SHOW_LEN, "%lu", *ul);