4 ms·
A long-standing gripe of mine: When I clicked through to his example "cute little function" in Musl, I found myself mentally adding comments to work through all
by fisherjeff 10y ago
A long-standing gripe of mine: When I clicked through to his example "cute little function" in Musl, I found myself mentally adding comments to work through all the "cuteness". If that's the case, IMO, it's either too cute or needs more comments - not sure how much time I've spent picking apart kernel code just to figure out what the hell some of it does, but it's definitely not time well spent.
EDIT: Meant to add: fantastic article, wish my Intro to C instructor had read it...
- jakobegger 10y agoI spent about twenty minutes looking at this function trying to figure out what it does. It looks like it uses a neat trick to compare native integers instead of bytes for speed, but I just couldn't figure out what it does. Then I realised it's part of the standard library and "man memchr" told me what it does...
- fisherjeff 10y agoI mean, it's definitely a neat way to optimize comparisons for the CPU's word size. The problem is with completely unexplained things like: #define ONES ((size_t)-1/UCHAR_MAX) Reading through the loop, it seems as though it will create, e.g., 0x01010101 for a 32-bit machine with 8-bit bytes. And sure enough, if you calculate ((2^32)-1)/255 that's exactly what you get. But I never would've known that without going through the code and proving to myself that the definitely of ONES actually makes sense. If you write code like this and there are never any bugs then fine, I guess. But there will bugs.
- Kristine1975 10y agoThe whole ONES... HASZERO shenanigans is somewhat explained here: https://graphics.stanford.edu/~seander/bithacks.html#ZeroInWord https://graphics.stanford.edu/~seander/bithacks.html#ZeroInW... as well as the entry after it. Edit: And most likely in the excellent book "Hacker's Delight" as well.