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