Return the length of the null-terminated string STR. Scan for the null terminator quickly by testing four bytes at a time. */
| 16 | /* Return the length of the null-terminated string STR. Scan for |
| 17 | the null terminator quickly by testing four bytes at a time. */ |
| 18 | size_t strlen (const char *str) |
| 19 | { |
| 20 | #ifdef MAP_TO_EDK_STRLEN |
| 21 | return (size_t)(AsciiStrLen(str)); |
| 22 | #endif |
| 23 | |
| 24 | const char *char_ptr; |
| 25 | const unsigned long int *longword_ptr; |
| 26 | unsigned long int longword, himagic, lomagic; |
| 27 | |
| 28 | /* Handle the first few characters by reading one character at a time. |
| 29 | Do this until CHAR_PTR is aligned on a longword boundary. */ |
| 30 | for (char_ptr = str; ((uintptr_t) char_ptr |
| 31 | & (sizeof (longword) - 1)) != 0; |
| 32 | ++char_ptr) |
| 33 | if (*char_ptr == '\0') { |
| 34 | return DOWN_CAST_TO_SIZE_T(char_ptr - str); |
| 35 | } |
| 36 | |
| 37 | /* All these elucidatory comments refer to 4-byte longwords, |
| 38 | but the theory applies equally well to 8-byte longwords. */ |
| 39 | |
| 40 | longword_ptr = (unsigned long int *) char_ptr; |
| 41 | |
| 42 | /* Bits 31, 24, 16, and 8 of this number are zero. Call these bits |
| 43 | the "holes." Note that there is a hole just to the left of |
| 44 | each byte, with an extra at the end: |
| 45 | |
| 46 | bits: 01111110 11111110 11111110 11111111 |
| 47 | bytes: AAAAAAAA BBBBBBBB CCCCCCCC DDDDDDDD |
| 48 | |
| 49 | The 1-bits make sure that carries propagate to the next 0-bit. |
| 50 | The 0-bits provide holes for carries to fall into. */ |
| 51 | himagic = 0x80808080L; |
| 52 | lomagic = 0x01010101L; |
| 53 | if (sizeof (longword) > 4) |
| 54 | { |
| 55 | /* 64-bit version of the magic. */ |
| 56 | /* Do the shift in two steps to avoid a warning if long has 32 bits. */ |
| 57 | himagic = ((himagic << 16) << 16) | himagic; |
| 58 | lomagic = ((lomagic << 16) << 16) | lomagic; |
| 59 | } |
| 60 | if (sizeof (longword) > 8) |
| 61 | abort (); |
| 62 | |
| 63 | /* Instead of the traditional loop which tests each character, |
| 64 | we will test a longword at a time. The tricky part is testing |
| 65 | if *any of the four* bytes in the longword in question are zero. */ |
| 66 | for (;;) |
| 67 | { |
| 68 | longword = *longword_ptr++; |
| 69 | |
| 70 | if (((longword - lomagic) & ~longword & himagic) != 0) |
| 71 | { |
| 72 | /* Which of the bytes was the zero? If none of them were, it was |
| 73 | a misfire; continue the search. */ |
| 74 | |
| 75 | const char *cp = (const char *) (longword_ptr - 1); |