1 /* $OpenBSD: strtoltest.c,v 1.4 2017/07/15 17:08:26 jsing Exp $ */
2 /*
3 * Copyright (c) 2012 Joel Sing <jsing@openbsd.org>
4 *
5 * Permission to use, copy, modify, and distribute this software for any
6 * purpose with or without fee is hereby granted, provided that the above
7 * copyright notice and this permission notice appear in all copies.
8 *
9 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
16 */
17
18 #include <errno.h>
19 #include <limits.h>
20 #include <stdlib.h>
21 #include <stdio.h>
22 #include <string.h>
23
24 struct strtol_test {
25 char *input;
26 long output;
27 char end;
28 int base;
29 int err;
30 };
31
32 struct strtol_test strtol_tests[] = {
33 {"1234567890", 1234567890L, '\0', 0, 0},
34 {"0755", 493L, '\0', 0, 0},
35 {"0x7fFFffFf", 2147483647L, '\0', 0, 0},
36 {"1234567890", 0L, '1', 1, EINVAL},
37 {"10101010", 170L, '\0', 2, 0},
38 {"755", 493L, '\0', 8, 0},
39 {"1234567890", 1234567890L, '\0', 10, 0},
40 {"abc", 0L, 'a', 10, 0},
41 {"123xyz", 123L, 'x', 10, 0},
42 {"-080000000", -2147483648L, '\0', 16, 0},
43 {"deadbeefdeadbeef", LONG_MAX, '\0', 16, ERANGE},
44 {"deadzbeef", 57005L, 'z', 16, 0},
45 {"0xy", 0L, 'x', 16, 0},
46 {"-quitebigmchuge", LONG_MIN, '\0', 32, ERANGE},
47 {"zzz", 46655L, '\0', 36, 0},
48 {"1234567890", 0L, '1', 37, EINVAL},
49 {"1234567890", 0L, '1', 123, EINVAL},
50 };
51
52 int
main(int argc,char ** argv)53 main(int argc, char **argv)
54 {
55 struct strtol_test *test;
56 int failure = 0;
57 char *end;
58 u_int i;
59 long n;
60
61 for (i = 0; i < (sizeof(strtol_tests) / sizeof(strtol_tests[0])); i++) {
62 test = &strtol_tests[i];
63 errno = 0;
64 n = strtol(test->input, &end, test->base);
65 if (n != test->output) {
66 fprintf(stderr, "TEST %i FAILED: %s base %i: %li\n",
67 i, test->input, test->base, n);
68 failure = 1;
69 } else if (*end != test->end) {
70 fprintf(stderr, "TEST %i FAILED: end is not %c: %c\n",
71 i, test->end, *end);
72 failure = 1;
73 } else if (errno != test->err) {
74 fprintf(stderr, "TEST %i FAILED: errno is not %i: %i\n",
75 i, test->err, errno);
76 failure = 1;
77 }
78 }
79
80 return failure;
81 }
82