Pelles C forum

C language => Tips & tricks => Topic started by: TimoVJL on November 04, 2025, 12:55:43 PM

Title: Railgun_Doublet
Post by: TimoVJL on November 04, 2025, 12:55:43 PM
http://www.sanmayce.com/Railgun/index.html (http://www.sanmayce.com/Railgun/index.html)

An interesting function to replace strstr for special cases.
#include <stdlib.h>
#include <stdint.h>
// All Railgun variants are written by Georgi 'Kaze', they are free, however I expect the user to mention its homepage, that is: http://www.sanmayce.com/Railgun/index.html
// Author's email: sanmayce@sanmayce.com
// Caution: For better speed the case 'if (cbPattern==1)' was removed, so Pattern must be longer than 1 char.
char * Railgun_Doublet (char * pbTarget, char * pbPattern, uint32_t cbTarget, uint32_t cbPattern)
{
    char * pbTargetMax = pbTarget + cbTarget;
    register uint32_t ulHashPattern;
    uint32_t ulHashTarget, count, countSTATIC;

    if (cbPattern > cbTarget) return(NULL);

    countSTATIC = cbPattern-2;

    pbTarget = pbTarget+cbPattern;
    ulHashPattern = (*(uint16_t *)(pbPattern));

    for ( ;; ) {
        if ( ulHashPattern == (*(uint16_t *)(pbTarget-cbPattern)) ) {
            count = countSTATIC;
            while ( count && *(char *)(pbPattern+2+(countSTATIC-count)) == *(char *)(pbTarget-cbPattern+2+(countSTATIC-count)) ) {
                count--;
            }
            if ( count == 0 ) return((pbTarget-cbPattern));
        }
        pbTarget++;
        if (pbTarget > pbTargetMax) return(NULL);
    }
}