## How much code does it take to implement an associative array? ## About 24 instructions for lookup, a bit more for upsert. ## Associative array pointer (pointer to pointer to first ## node) in %rdi, return value in %rax, key in %rsi. ## temp registers in %rcx, %rdx, %r8, %r9 ## call-preserved registers in %rbx, %rbp, %r12-r15. ## Subroutine `comkey` takes two keys to compare in rsi and rdi; ## sets zero flag if equal, clears if unequal. ## Returns with zero flag set for not-found, clear for found. .intel_syntax noprefix lookup: push rbx push rbp mov rbx, rdi # pointer to alist node pointer mov rbp, rsi # key 2: mov rdi, [rbx] # load pointer to alist node test rdi, rdi # is it null? jnz 3f # if not null, skip not-found case mov rax, rbx # pointer to null pointer is return value xor rdx, rdx # but associated value is null (sets zero flag) jmp 4f # jump to shared epilogue 3: mov rdi, [rdi] # load pointer from key field of alist node mov rsi, rbp # pass key from callee-saved register as param call comkey # sets zero flag if rsi and rdi are equal keys jne 1f # skip following return-value case code if != mov rax, rbx # pointer to node pointer is return value mov rdx, [rbx] # also let’s follow that pointer to the node mov rdx, [rdx + 16] # and return its value field too in rdx test rax, rax # clear zero flag (valid pointer is not null) 4: pop rbp pop rbx ret 1: mov rbx, [rbx] # load pointer to alist node again add rbx, 8 # load pointer to next-node pointer field jmp 2b