Rust bitwise function: Comment says reading hurts, writing it was even worse
Description
Screenshot of a light-themed code editor showing a Rust function definition: "fn load_maj_min(block: [u8; 4 * 15]) -> (u16, u32) {". The if-branch simply swaps bytes when block[0] or block[1] is non-zero. The else-branch contains a single-line comment in red highlight: "// if you think reading this is bad, I had to write it". Below, several tightly packed expressions combine block[5]-block[7] with masks "0b0000_1111" and "0b1111_0000" and multiple left/right shifts to construct u16 and u32 values. The snippet showcases painful bit-fiddling, byte ordering, and mask-and-shift logic that sacrifices readability, a common low-level programming headache that seasoned developers will recognize and laugh at
Comments
16Comment deleted
Bit-twiddling in Rust is when I start missing C - at least in C the undefined behavior is upfront, not buried under four masks, two endiannesses, and a comment from past-me apologizing in advance
This is what happens when you need to parse a binary format that was clearly designed by someone who measured memory in punch cards and thought endianness was a personality trait - now you're writing Rust that looks like you're defusing a bomb made of pointers while blindfolded
This is the code equivalent of 'I'm sorry you had to see that' - when your bit-twiddling logic becomes so gnarly that you preemptively apologize to future maintainers. The real tragedy? This is probably the *cleanest* way to parse major/minor device numbers from a byte array without pulling in a dependency. Welcome to systems programming, where the comments are apologies and the bit shifts are nested deeper than your call stack during a production incident
Semver packed across nibbles with endian roulette - Rust guarantees memory safety, not spec sanity
Optimizations so tight, they escaped the event horizon of readability - good luck grepping for bugs
Saving two bytes in the wire format costs three casts, four shifts, and a headcount for maintenance
What the actual fuck Comment deleted
Look like some crypto calculations. Doesn't look terrible, looks usual. Comment deleted
sad but true Comment deleted
Actual comment would be more useful Comment deleted
Is it Rust Lisp? Comment deleted
https://t.me/dev_meme/3667 > Please use English in this chat. Fast translation (may be inaccurate): Is it Rust Lisp? Comment deleted
if 0 != block[0] || 0 != block[1] { These Yoda conditions are the most disturbing part of the snippet. Rust does not even compile misprints like block[0] = 0 =___=. Comment deleted
misprints like block[0] = 0 sometimes are not misprints Comment deleted
Yes, these are flaws of the language itself. Comment deleted
Still, neither Rust nor C++ with -Werror will let you make an unintentional mistake there (inside a condition expression). Comment deleted