]> pd.if.org Git - pdclib/blob - functions/_PDCLIB/_PDCLIB_strtox_prelim.c
Moving branches closer together.
[pdclib] / functions / _PDCLIB / _PDCLIB_strtox_prelim.c
1 /* _PDCLIB_strtox_prelim( const char *, char *, 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 <ctype.h>
8 #include <stddef.h>
9 #include <string.h>
10
11 #ifndef REGTEST
12
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
54 #endif
55
56 #ifdef TEST
57
58 #include "_PDCLIB_test.h"
59
60 int main( void )
61 {
62 #ifndef REGTEST
63     int base = 0;
64     char sign = '\0';
65     char test1[] = "  123";
66     char test2[] = "\t+0123";
67     char test3[] = "\v-0x123";
68     TESTCASE( _PDCLIB_strtox_prelim( test1, &sign, &base ) == &test1[2] );
69     TESTCASE( sign == '+' );
70     TESTCASE( base == 10 );
71     base = 0;
72     sign = '\0';
73     TESTCASE( _PDCLIB_strtox_prelim( test2, &sign, &base ) == &test2[3] );
74     TESTCASE( sign == '+' );
75     TESTCASE( base == 8 );
76     base = 0;
77     sign = '\0';
78     TESTCASE( _PDCLIB_strtox_prelim( test3, &sign, &base ) == &test3[4] );
79     TESTCASE( sign == '-' );
80     TESTCASE( base == 16 );
81     base = 10;
82     sign = '\0';
83     TESTCASE( _PDCLIB_strtox_prelim( test3, &sign, &base ) == &test3[2] );
84     TESTCASE( sign == '-' );
85     TESTCASE( base == 10 );
86     base = 1;
87     TESTCASE( _PDCLIB_strtox_prelim( test3, &sign, &base ) == NULL );
88     base = 37;
89     TESTCASE( _PDCLIB_strtox_prelim( test3, &sign, &base ) == NULL );
90 #endif
91     return TEST_RESULTS;
92 }
93
94 #endif