]> pd.if.org Git - pdclib/blob - functions/_PDCLIB/strtox_main.c
Helper functions for strto...() functions.
[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, int limdigit )
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             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()
50 {
51     const char * p;
52     char test[] = "123_";
53     char fail[] = "xxx";
54     BEGIN_TESTS;
55     /* basic functionality */
56     p = test;
57     errno = 0;
58     TESTCASE( _PDCLIB_strtox_main( &p, 10, 999, 12, 3 ) == 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, 8, 999, 12, 3 ) == 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, 4, 999, 1, 2 ) == 999 );
69     TESTCASE( errno == ERANGE );
70     TESTCASE( p == &test[3] );
71     /* testing conversion failure */
72     errno = 0;
73     p = fail;
74     TESTCASE( _PDCLIB_strtox_main( &p, 10, 999, 99, 8 ) == 0 );
75     TESTCASE( p == NULL );
76     return TEST_RESULTS;
77 }
78
79 #endif