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