4 ms·
Using a switch on an encoded value was my first thought too after seeing the pattern, and I think it's actually quite an elegant way of doing it - forming an ar
by userbinator 12y ago
Using a switch on an encoded value was my first thought too after seeing the pattern, and I think it's actually quite an elegant way of doing it - forming an array index from booleans and doing a table lookup with that. It's even clearer when the cases are ordered as
(false, false, false) => { ... } // 0
(false, false, true ) => { ... } // 1
(false, true , false) => { ... } // 2
(false, true , true ) => { ... } // 3
(true , _ , _ ) => { ... } // 4-7 (could be the default case)
Here's a possible small improvement that could, depending on the compiler, get rid of a few branches:
#define WIDTH_BIT 2
#define WIDTH (1<<WIDTH_BIT)
#define MARGIN_LEFT_BIT 1
#define MARGIN_LEFT (1<<MARGIN_LEFT_BIT)
#define MARGIN_RIGHT_BIT 0
#define MARGIN_RIGHT (1<<MARGIN_RIGHT_BIT)
...
unsigned int flags = !!width << WIDTH_BIT
| !!margin_left << MARGIN_LEFT_BIT
| !!margin_right << MARGIN_RIGHT_BIT;
...
I'm not too familiar with Rust and Google isn't being helpful, so does anyone know how the Rust compiler implements pattern matching? Does it do something like the above or does it resort to if/else conversion?
- pcwalton 12y agoRust uses OCaml's algorithm for pattern matching, which is basically a dynamic programming algorithm that minimizes the number of branches. (It's really clever, worth reading about if you're bored.) The Rust compiler also contains heuristics to decide whether to use a jump table (LLVM switch statement) or not.
- akavel 12y agoIs it 100% sure that !! gives only 0 or 1? I'd be very grateful for some hard citations/references for that (across various standards, C89/99/..., C++98/03/11...), I'd be happy to learn if I can safely rely on that?
- ben0x539 12y agoC99: 6.5.3.3 p5: The result of the logical negation operator ! is 0 if the value of its operand compares unequal to 0, 1 if the value of its operand compares equal to 0. The result has type int. The expression !E is equivalent to (0==E). C++11 (or a near enough draft): 5.3.1 p9: The operand of the logical negation operator ! is contextually converted to bool (Clause 4); its value is true if the converted operand is false and false otherwise. The type of the result is bool. and 4.7 p4 on integral conversion: If the source type is bool, the value false is converted to zero and the value true is converted to one. Both seem to suggest that when you apply !, you end up with something that is 0 or 1 when used as a number, and adding more ! won't get you out of that.
- akavel 12y agoThanks a lot! And still interested in earlier C/C++ standards, I'm much more likely to encounter them in the wild for long time.