]> pd.if.org Git - pdclib/blob - functions/_PDCLIB/strtox_main.c
Ugly workaround to keep wrappers from negating error value.
[pdclib] / functions / _PDCLIB / strtox_main.c
1 /* $Id$ */
2
3 /* Release $Name$ */
4
5 /* _PDCLIB_strtox_main( const char * *, int, _PDCLIB_uintmax_t, _PDCLIB_uintmax_t, int )
6
7    This file is part of the Public Domain C Library (PDCLib).
8    Permission is granted to use, modify, and / or redistribute at will.
9 */
10
11 #include <_PDCLIB_int.h>
12 #include <ctype.h>
13 #include <errno.h>
14 #include <string.h>
15
16 _PDCLIB_uintmax_t _PDCLIB_strtox_main( const char ** p, int base, _PDCLIB_uintmax_t error, _PDCLIB_uintmax_t limval, _PDCLIB_uintmax_t limdigit, char * sign )
17 {
18     _PDCLIB_uintmax_t rc = 0;
19     int digit = -1;
20     const char * x;
21     while ( ( x = memchr( _PDCLIB_digits, toupper(**p), base ) ) != NULL )
22     {
23         digit = x - _PDCLIB_digits;
24         if ( ( rc < limval ) || ( ( rc == limval ) && ( digit <= limdigit ) ) )
25         {
26             rc = rc * base + ( x - _PDCLIB_digits );
27             ++(*p);
28         }
29         else
30         {
31             errno = ERANGE;
32             /* TODO: Only if endptr != NULL */
33             while ( memchr( _PDCLIB_digits, **p, base ) != NULL ) ++(*p);
34             /* TODO: This is ugly, but keeps caller from negating the error value */
35             *sign = '+';
36             return error;
37         }
38     }
39     if ( digit == -1 )
40     {
41         *p = NULL;
42         return 0;
43     }
44     return rc;
45 }
46
47 #ifdef TEST
48 #include <_PDCLIB_test.h>
49 #include <errno.h>
50
51 int main()
52 {
53     const char * p;
54     char test[] = "123_";
55     char fail[] = "xxx";
56     char sign = '-';
57     BEGIN_TESTS;
58     /* basic functionality */
59     p = test;
60     errno = 0;
61     TESTCASE( _PDCLIB_strtox_main( &p, 10, 999, 12, 3, &sign ) == 123 );
62     TESTCASE( errno == 0 );
63     TESTCASE( p == &test[3] );
64     /* proper functioning to smaller base */
65     p = test;
66     TESTCASE( _PDCLIB_strtox_main( &p, 8, 999, 12, 3, &sign ) == 0123 );
67     TESTCASE( errno == 0 );
68     TESTCASE( p == &test[3] );
69     /* overflowing subject sequence must still return proper endptr */
70     p = test;
71     TESTCASE( _PDCLIB_strtox_main( &p, 4, 999, 1, 2, &sign ) == 999 );
72     TESTCASE( errno == ERANGE );
73     TESTCASE( p == &test[3] );
74     TESTCASE( sign == '+' );
75     /* testing conversion failure */
76     errno = 0;
77     p = fail;
78     sign = '-';
79     TESTCASE( _PDCLIB_strtox_main( &p, 10, 999, 99, 8, &sign ) == 0 );
80     TESTCASE( p == NULL );
81     return TEST_RESULTS;
82 }
83
84 #endif