4 ms·
fn is_token(c: u8) -> bool { // roughly follows the order of ascii chars: "\"(),/:;<=>?@[\\]{} \t" c < 128 && c > 32 && c != b'\t' && c != b'"'
by chrisdew 11y ago
fn is_token(c: u8) -> bool {
// roughly follows the order of ascii chars: "\"(),/:;<=>?@[\\]{} \t"
c < 128 && c > 32 && c != b'\t' && c != b'"' && c != b'(' && c != b')' &&
c != b',' && c != b'/' && !(c > 57 && c < 65) && !(c > 90 && c < 94) &&
c != b'{' && c != b'}'
}
I've not done much with Rust, but why is it stated: “LOOK && AT && ALL && THOSE && BRANCHES!”
I don't see branches, just the evaluation of a complex bool expression.
If there were lots of "ifs" and "elses" I would see branches.
Can someone explain?
- masklinn 11y ago> Can someone explain? && short-circuits, so before each &&, if the LHS is false it will jump to the end of the whole thing with a `false` result If you plug the function into goldbot (http://rust.godbolt.org http://rust.godbolt.org) you see a bunch of conditional jumps: cmpl $7, %ecx jb .LBB0_10 movzbl %dil, %ecx cmpl $47, %ecx je .LBB0_10 cmpl $44, %ecx je .LBB0_10 movb %dil, %dl andb $-2, %dl movzbl %dl, %edx cmpl $40, %edx je .LBB0_10 cmpl $34, %ecx je .LBB0_10 cmpl $33, %ecx jb .LBB0_10 testb %dil, %dil js .LBB0_10
- chrisdew 11y agoThanks, I'd not seen godbolt before - this is very useful.
- userbinator 11y agoShort-circuit evaluation. The structure of the flow looks like a ladder. The (x86) assembly produced would look something like this: cmp al, 128 jae false cmp al, 32 jbe false cmp al, 9 jz false cmp al, '"' jz false cmp al, '(' jz false cmp al, ')' jz false ... Edit: yes, I know 9 is less than 32 and would've been caught by the condition before it; I was just "mentally compiling" the expression directly without thinking much about optimising it.
- chrisdew 11y agoThanks for that. Would adding extra brackets (turning it into a tree structure) allow the CPU to use multiple ALUs to evaluate branches in parallel? ( ( ( c < 128 && c > 32 ) && ( c != b'\t' && c != b'"' ) ) && ( ( c != b',' && c != b'/' ) && ( !(c > 57 && c < 65) && !(c > 90 && c < 94) ) && ( c != b'{' && c != b'}' ) ) )
- alricb 11y agoA better name for the short-circuiting && operator is "andthen". Since "false && X" is false for all X, && does not evaluate its right operand if the left operand is false; this translates into branches in the assembly code, as if you had written nested "if" statements.