开发者

Efficient memcspn

开发者 https://www.devze.com 2023-01-13 13:37 出处:网络
Does anyone know of an efficie开发者_如何学Cnt implementation of a memcspn function?? It should behave like strcspn but look for the span in a memory buffer and not in a null terminated string. The ta

Does anyone know of an efficie开发者_如何学Cnt implementation of a memcspn function?? It should behave like strcspn but look for the span in a memory buffer and not in a null terminated string. The target compiler is visualC++ .

Thanks, Luca


One near-optimal implementation:

size_t memcspan(const unsigned char *buf, size_t len, const unsigned char *set, size_t n)
{
    size_t i;
    char set2[1<<CHAR_BIT] = {0};
    while (n--) set2[set[n]] = 1;
    for (i=0; i<len && !set2[buf[i]]; i++);
    return i;
}

It might be better to use a bit array instead of a byte array for set2, depending on whether arithmetic or a little bit more cache thrashing is more expensive on your machine.


It would seem pretty difficult to write an inefficient implementation of this function, TBH - the implementation seems pretty straightforward, so I'd suggest writing this yourself if you can't find an implementation in a reasonable timeframe.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号