Created
November 18, 2015 02:27
-
-
Save amosr/3eab25e77fbbeedb7174 to your computer and use it in GitHub Desktop.
12 instruction case-insensitive string equality (for reading booleans)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
int read_bool (char *p) | |
{ | |
static const uint64_t true_mask = 0x00000000ffffffff; | |
static const uint64_t true_bits = 0x0000000065757274; | |
static const uint64_t false_mask = 0x000000ffffffffff; | |
static const uint64_t false_bits = 0x00000065736c6166; | |
static const uint64_t to_lower = 0x2020202020202020; | |
uint64_t next8 = *(uint64_t *)p | to_lower; | |
int is_true = (next8 & true_mask) == true_bits; | |
int is_false = (next8 & false_mask) == false_bits; | |
if (is_true) { | |
return 1; | |
} else if (is_false) { | |
return 0; | |
} else { | |
return -1; | |
} | |
} | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
_read_bool: ## @read_bool | |
.cfi_startproc | |
## BB#0: | |
pushq %rbp | |
Ltmp0: | |
.cfi_def_cfa_offset 16 | |
Ltmp1: | |
.cfi_offset %rbp, -16 | |
movq %rsp, %rbp | |
Ltmp2: | |
.cfi_def_cfa_register %rbp | |
movabsq $2314885530818453536, %rcx ## imm = 0x2020202020202020 | |
orq (%rdi), %rcx | |
movl $1, %eax | |
cmpl $1702195828, %ecx ## imm = 0x65757274 | |
je LBB0_2 | |
## BB#1: | |
movb $40, %al | |
bzhiq %rax, %rcx, %rax | |
xorl %ecx, %ecx | |
movabsq $435728179558, %rdx ## imm = 0x65736C6166 | |
cmpq %rdx, %rax | |
movl $-1, %eax | |
cmovel %ecx, %eax | |
LBB0_2: | |
popq %rbp | |
retq | |
.cfi_endproc | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment