Writing an OS in Rust: Catching CPU Exceptions
Haven't been following this blog, but one thing caught my eye while skimming the post:<p>>The implementations of these methods need to modify the correct bits of the u16 without touching the other bits. For example, we would need the following bit-fiddling to set the stack index:<p><pre><code>    self.0 = (self.0 & 0xfff8) | stack_index;
</code></pre>
>Or alternatively:<p><pre><code>    self.0 = (self.0 & (!0b111)) | stack_index;
</code></pre>
>Or:<p><pre><code>    self.0 = ((self.0 >> 3) << 3) | stack_index;
</code></pre>
>Well, none of these variants is really readable and it’s very easy to make mistakes somewhere. Therefore I created a BitField type with the following API:<p><pre><code>    self.0.set_range(0..3, stack_index);
</code></pre>
>I think it is much more readable, since we abstracted away all bit-masking details.<p>Personally, I disagree. Whilst it is easy to make mistakes when writing bit-fiddling code (there seems to be one in the second example, unless Rust has on of the more weird !-operators in programming languages), or any code for that matter, the meaning of all the bitwise operations is easy to recognise.<p>Without knowing the API, the transformed line rings no bells. How many APIs do you want to learn?