Efficient memcspn

二次信任 提交于 2019-12-11 02:31:09

问题


Does anyone know of an efficient 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


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/3602534/efficient-memcspn

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!