linux内核的atoi测试
v_JULY_v君的问题非常好(请见文章的评论)! 每次都让我思考. 现将linux内核的atoi测试代码贴出来, 为了区别了C标准库的atoi函数, 我把测试的函数名改为matoi:
#include <ctype.h>
#include <string.h>
#include <stdio.h>
/*http://lxr.free-electrons.com/source/lib/kstrtox.h#L4*/
#define KSTRTOX_OVERFLOW (1U << 31)
const char *_parse_integer_fixup_radix(const char *s, unsigned int *base);
unsigned int _parse_integer(const char *s, unsigned int base, unsigned long long *res);
/*http://lxr.free-electrons.com/source/arch/powerpc/boot/types.h#L12*/
typedef int s32;
typedef unsigned int u32;
typedef unsigned long long u64;
/*http://lxr.free-electrons.com/source/drivers/media/pci/ngene/ngene-dvb.c#L127*/
static u32 overflow;
/*http://lxr.free-electrons.com/source/include/linux/kernel.h#L29*/
#define ULLONG_MAX (~0ULL)
#define unlikely(cond) (cond)
/*http://lxr.free-electrons.com/source/lib/kstrtox.c#L23*/
const char *_parse_integer_fixup_radix(const char *s, unsigned int *base)
{
if (*base == 0) {
if (s[0] == '0') {
if (_tolower(s[1]) == 'x' && isxdigit(s[2]))
*base = 16;
else
*base = 8;
} else
*base = 10;
}
if (*base == 16 && s[0] == '0' && _tolower(s[1]) == 'x')
s += 2;
return s;
}
/*http://lxr.free-electrons.com/source/lib/kstrtox.c#L47*/
/*
* Convert non-negative integer string representation in explicitly given radix
* to an integer.
* Return number of characters consumed maybe or-ed with overflow bit.
* If overflow occurs, result integer (incorrect) is still returned.
*
* Don't you dare use this function.
*/
unsigned int _parse_integer(const char *s, unsigned int base, unsigned long lon