3 ms·
Considering how common it is to use indices in lieu of pointers in Rust, it would be nice if it had native NonMax integer types similar to the NonZero types it
by jsheard 3y ago
Considering how common it is to use indices in lieu of pointers in Rust, it would be nice if it had native NonMax integer types similar to the NonZero types it already has. NonZero gives you the niche-filling optimization (e.g. Option<NonZero> and NonZero are the same size) but with indices you want zero to be a valid value, so it would be natural to use the maximum as the illegal value instead. You can kind of do it by offsetting the index by 1 or inverting the bits then putting it in a NonZero but that's a small extra runtime cost on every use.
- joseluis 3y agoYou can do a handy struct wrapper over a private Nonzero that xors the given value with the prohibited value (max in this case) at the new constructor. And like so for the get method. Xoring is very cheap. That's my favorite way of storing indices/links for nodes, since you can wrap them in Option for free.
- o11c 3y agoAddition/subtraction are more likely to optimize well I think, since pointer arithmetic already uses those.
- deleted 3y ago[deleted]
- deleted 3y ago[deleted]
- jsheard 3y agoGood point, on x86 at least the mov instruction can add/subtract a constant from the address by itself since that pattern is so common.