]> pd.if.org Git - pdclib/blob - functions/_PDCLIB/_PDCLIB_strtox_prelim.c
7be40309ed41931c09fc0302f94a2959e4a2c09f
[pdclib] / functions / _PDCLIB / _PDCLIB_strtox_prelim.c
1 /* $Id$ */
2
3 /* _PDCLIB_strtox_prelim( const char *, char *, int * )
4
5    This file is part of the Public Domain C Library (PDCLib).
6    Permission is granted to use, modify, and / or redistribute at will.
7 */
8
9 #include <ctype.h>
10 #include <stddef.h>
11 #include <string.h>
12 #ifndef REGTEST
13 const char * _PDCLIB_strtox_prelim( const char * p, char * sign, int * base )
14 {
15     /* skipping leading whitespace */
16     while ( isspace( *p ) ) ++p;
17     /* determining / skipping sign */
18     if ( *p != '+' && *p != '-' ) *sign = '+';
19     else *sign = *(p++);
20     /* determining base */
21     if ( *p == '0' )
22     {
23         ++p;
24         if ( ( *base == 0 || *base == 16 ) && ( *p == 'x' || *p == 'X' ) )
25         {
26             *base = 16;
27             ++p;
28             /* catching a border case here: "0x" followed by a non-digit should
29                be parsed as the unprefixed zero.
30                We have to "rewind" the parsing; having the base set to 16 if it
31                was zero previously does not hurt, as the result is zero anyway.
32             */
33             if ( memchr( _PDCLIB_digits, tolower(*p), *base ) == NULL )
34             {
35                 p -= 2;
36             }
37         }
38         else if ( *base == 0 )
39         {
40             *base = 8;
41         }
42         else
43         {
44             --p;
45         }
46     }
47     else if ( ! *base )
48     {
49         *base = 10;
50     }
51     return ( ( *base >= 2 ) && ( *base <= 36 ) ) ? p : NULL;
52 }
53 #endif
54
55 #ifdef TEST
56 #include <_PDCLIB_test.h>
57
58 int main( void )
59 {
60 #ifndef REGTEST
61     int base = 0;
62     char sign = '\0';
63     char test1[] = "  123";
64     char test2[] = "\t+0123";
65     char test3[] = "\v-0x123";
66     TESTCASE( _PDCLIB_strtox_prelim( test1, &sign, &base ) == &test1[2] );
67     TESTCASE( sign == '+' );
68     TESTCASE( base == 10 );
69     base = 0;
70     sign = '\0';
71     TESTCASE( _PDCLIB_strtox_prelim( test2, &sign, &base ) == &test2[3] );
72     TESTCASE( sign == '+' );
73     TESTCASE( base == 8 );
74     base = 0;
75     sign = '\0';
76     TESTCASE( _PDCLIB_strtox_prelim( test3, &sign, &base ) == &test3[4] );
77     TESTCASE( sign == '-' );
78     TESTCASE( base == 16 );
79     base = 10;
80     sign = '\0';
81     TESTCASE( _PDCLIB_strtox_prelim( test3, &sign, &base ) == &test3[2] );
82     TESTCASE( sign == '-' );
83     TESTCASE( base == 10 );
84     base = 1;
85     TESTCASE( _PDCLIB_strtox_prelim( test3, &sign, &base ) == NULL );
86     base = 37;
87     TESTCASE( _PDCLIB_strtox_prelim( test3, &sign, &base ) == NULL );
88 #endif
89     return TEST_RESULTS;
90 }
91
92 #endif