Stop using gnulib's flexmember module.
[upkg.git] / test / common.c
blob9919b1b66ea501126ccaf20fbaa2a0bf22afe481
1 /*
2 * Helper functions for test programs.
3 * Copyright © 2012, 2022 Nick Bowler
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, either version 3 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <https://www.gnu.org/licenses/>.
19 #include <config.h>
20 #include <stdio.h>
21 #include <stdlib.h>
22 #include <ctype.h>
23 #include <getopt.h>
25 #include "common.h"
26 #include "help.h"
29 * Decode a hexadecimal string into a sequence of bytes. If there are an
30 * odd number of nibbles, treat the first character as the least significant
31 * nibble of the first byte. The result is written to the buffer specified by
32 * buf. At most n bytes are written to the buffer.
34 * Returns the number of bytes that would be written provided that n was large
35 * enough, or (size_t)-1 if the input is not valid.
37 size_t test_decode_hex(const char *hex, unsigned char *buf, size_t n)
39 size_t len, count = 0;
40 char tmp[] = "00";
42 for (len = 0; hex[len]; len++) {
43 if (!isxdigit((unsigned char)hex[len]))
44 return -1;
47 if (!len)
48 return 0;
50 switch (len % 2) {
51 while (len > 0) {
52 case 0: tmp[0] = *hex++; len--;
53 case 1: tmp[1] = *hex++; len--;
55 if (count < n)
56 buf[count] = strtoul(tmp, NULL, 16);
57 count++;
61 return count;
64 void test_print_version(const char *program)
66 printf("%s (%s) %s\n", program, PACKAGE_NAME, PACKAGE_VERSION);
67 puts("Copyright (C) 2022 Nick Bowler.");
68 puts("License GPLv3+: GNU GPL version 3 or any later version.");
69 puts("This is free software: you are free to change and redistribute it.");
70 puts("There is NO WARRANTY, to the extent permitted by law.");
73 void test_print_options(const struct option *lopts)
75 const struct option *opt;
77 puts("\nOptions:");
78 for (opt = lopts; opt->val; opt++) {
79 if (help_print_optstring(opt, "ARG", 20))
80 putchar('\n');