1 /* $OpenBSD: strtoltest.c,v 1.3 2015/03/15 07:26:27 phessler 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 {"-quitebigmchuge", LONG_MIN, '\0', 32, ERANGE}, 46 {"zzz", 46655L, '\0', 36, 0}, 47 {"1234567890", 0L, '1', 37, EINVAL}, 48 {"1234567890", 0L, '1', 123, EINVAL}, 49 }; 50 51 int 52 main(int argc, char **argv) 53 { 54 struct strtol_test *test; 55 int failure = 0; 56 char *end; 57 u_int i; 58 long n; 59 60 for (i = 0; i < (sizeof(strtol_tests) / sizeof(strtol_tests[0])); i++) { 61 test = &strtol_tests[i]; 62 errno = 0; 63 n = strtol(test->input, &end, test->base); 64 if (n != test->output) { 65 fprintf(stderr, "TEST %i FAILED: %s base %i: %li\n", 66 i, test->input, test->base, n); 67 failure = 1; 68 } else if (*end != test->end) { 69 fprintf(stderr, "TEST %i FAILED: end is not %c: %c\n", 70 i, test->end, *end); 71 failure = 1; 72 } else if (errno != test->err) { 73 fprintf(stderr, "TEST %i FAILED: errno is not %i: %i\n", 74 i, test->err, errno); 75 failure = 1; 76 } 77 } 78 79 return failure; 80 } 81