search.c
/// super-fast for short strings (less than about 8 bytes), else use searchSimple or searchBoyerMooreHorspool
super-fast for short strings (less than about 8 bytes), else use searchSimple or searchBoyerMooreHorspool
super - fast for short strings ( less than about 8 bytes ) else use searchSimple or searchBoyerMooreHorspool
const char* searchNative(const char* haystack, size_t haystackLength,
                         const char* needle,   size_t needleLength)
{
  if (!haystack || !needle || haystackLength < needleLength)
    return NULL;
  if (needleLength == 0)
    return haystack;
  if (needleLength == 1)
    return (const char*)memchr(haystack, *needle, haystackLength);
  haystackLength -= needleLength - 1;
  const char* haystackEnd = haystack + haystackLength;
  while ((haystack = (const char*)memchr(haystack, *needle, haystackLength)) != NULL)
  {
    if (haystack[needleLength - 1] == needle[needleLength - 1])
      if (needleLength == 2 || memcmp(haystack + 1, needle + 1, needleLength - 2) == 0)
        return haystack;
    haystackLength = haystackEnd - haystack;
    if (haystackLength == 0)
      return NULL;
    haystack++;
    haystackLength--;
  }
  return NULL;
}
const char * searchNative ( const char * haystack , size_t haystackLength , const char * needle , size_t needleLength ) { if ( ! haystack || ! needle || haystackLength < needleLength ) return NULL ; if ( needleLength == 0 ) return haystack ; if ( needleLength == 1 ) return ( const char * ) memchr ( haystack , * needle , haystackLength ) ; haystackLength -= needleLength - 1 ; const char * haystackEnd = haystack + haystackLength ; while ( ( haystack = ( const char * ) memchr ( haystack , * needle , haystackLength ) ) != NULL ) { if ( haystack [ needleLength - 1 ] == needle [ needleLength - 1 ] ) if ( needleLength == 2 || memcmp ( haystack + 1 , needle + 1 , needleLength - 2 ) == 0 ) return haystack ; haystackLength = haystackEnd - haystack ; if ( haystackLength == 0 ) return NULL ; haystack ++ ; haystackLength -- ; } return NULL ; }
super-fast for short strings (less than about 8 bytes), else use searchSimple or searchBoyerMooreHorspool
super - fast for short strings ( less than about 8 bytes ) else use searchSimple or searchBoyerMooreHorspool
// uses memchr() for the first byte, then memcmp to verify it's a valid match // detect invalid input // empty needle matches everything // shorter code for just one character // points beyond last considered byte // look for first byte // does last byte match, too ? // okay, perform full comparison, skip first and last byte (if just 2 bytes => already finished) // compute number of remaining bytes // keep going // needle not found in haystack