资源简介
strchr的源码阅读,更加了解字符串的操作
代码片段和文件信息
/* Find the first occurrence of C in S. */
char *
strchr (s c_in)
const char *s;
int c_in;
{
const unsigned char *char_ptr;
const unsigned long int *longword_ptr;
unsigned long int longword magic_bits charmask;
unsigned reg_char c;
c = (unsigned char) c_in;
/* Handle the first few characters by reading one character at a time.
Do this until CHAR_PTR is aligned on a longword boundary. */
for (char_ptr = (const unsigned char *) s;
((unsigned long int) char_ptr & (sizeof (longword) - 1)) != 0;
++char_ptr)
if (*char_ptr == c)
return (void *) char_ptr;
else if (*char_ptr == ‘/0‘)
return NULL;
/* All these elucidatory comments refer to 4-byte longwords
but the theory applies equally well to 8-byte longwords. */
longword_ptr = (unsigned long int *) char_ptr;
/* Bits 31 24 16 and 8 of this number are zero. Call these bits
the “holes.“ Note that there is a hole just to the left of
each byte with an extra at the end:
bits: 01111110 11111110 11111110 11111111
bytes: AAAAAAAA BBBBBBBB CCCCCCCC DDDDDDDD
The 1-bits make sure that carries propagate to the next 0-bit.
The 0-bits provide holes for carries to fall into. */
switch (sizeof (longword))
{
case 4: magic_bits = 0x7efefeffL; break;
case 8: magic_bits = ((0x7efefefeL << 16) << 16) | 0xfefefeffL; break;
default:
abort ();
}
/* Set up a longword each of whose bytes is C. */
charmask = c | (c << 8);
charmask |= charmask << 16;
if (sizeof (longword) > 4)
/* Do the shift in two steps to avoid a warning if long has 32 bits. */
charmask |= (charmask << 16) << 16;
if (sizeof (longword) > 8)
abort ();
/* Instead of the traditional loop which tests each character
we will test a longword at a time. The tricky part is testing
if *any of the four* bytes in the longword in question are zero. */
for (;;)
{
/* We tentatively exit the loop if adding MAGIC_BITS to
LONGWORD fails to change any of the hole bits of LONGWORD.
1) Is this safe? Will it catch all the zero bytes?
Suppose there is a byte with all zeros. Any carry bits
propagating from its left will fall into the hole at its
least significant bit and stop. Since there will be no
carry from its most significant bit the LSB of the
byte to the left will be unchanged and the zero will be
detected.
2)
评论
共有 条评论