|
|
|
|
|
by sgmansfield
3681 days ago
|
|
I was just about to post this exact same thing. Now there's an introduction of ranges and another API that is necessary to understand in order to grok this code. Bit twiddling, ANDing, and ORing are specific and absolute. For example, what happens when I specify a range of 0..100 for a 32 bit int? what if the value is too big for the range? APIs around small operations like this introduce ambiguity that wasn't present before. |
|
So what? You could implement addition using bitwise operators, but it makes for much more readable and less error-prone code to abstract it into an addition operator. Code should clearly express intent, and if your intent is to set, say, bits 5 though 9 of some register to some value, the clearest expression of that is something like (given a right-open range convention, which is well-established in this particular language):
If I look at the above statement, I know what the author of the code intended it to do and can rely on (or manually verify once) the correctness of the implementation of "set_bits." If instead I'm reading code like I have to work out in my head what the bit fiddling is doing, and from that guess what the author meant the code to do. I can't know whether he or she made a mistake in translating the intent to bitwise operations (say I know from context that value is less than 8; did they really mean to clear bits 8 and 9?), because the intent isn't expressed anywhere.>For example, what happens when I specify a range of 0..100 for a 32 bit int?
What happens is that you've violated a precondition of the API. Because this is Rust, I would expect the operation to be implemented in such a way as to panic (in debug mode), or just fail to compile, since selecting a bit range like this at run time is extremely uncommon.
>what if the value is too big for the range?
Same thing as if you weren't using the abstraction around the bitwise operators: either you'd clobber higher bits, or the implementation would truncate the value.
Again, though, I would expect a debug-mode panic.
>APIs around small operations like this introduce ambiguity that wasn't present before.
I'm not sure what "ambiguity" you see here. There's the issue of whether the range is right-open or -closed, but again right-open ranges are well-established in Rust.