Skip to content

Commit

Permalink
feat!: replace djb2 with xored version in asm
Browse files Browse the repository at this point in the history
  • Loading branch information
f1zm0 committed Apr 23, 2023
1 parent 6be7b5a commit 4c2cd88
Show file tree
Hide file tree
Showing 3 changed files with 53 additions and 9 deletions.
2 changes: 1 addition & 1 deletion acheron.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ type options struct {
// New returns a new Acheron instance with the given options, or an error if initialization fails.
func New(opts ...Option) (*Acheron, error) {
options := &options{
hashFunction: hashing.DJB2, // default
hashFunction: hashing.XorDjb2Hash, // default
}
for _, o := range opts {
o(options)
Expand Down
10 changes: 2 additions & 8 deletions pkg/hashing/hashing.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,5 @@ package hashing
// HashFunction is a type alias for a function that takes a byte slice and returns a uint64.
type HashFunction func([]byte) uint64

// DJB2 is an implementation of the djb2 hash function. Ref: http://www.cse.yorku.ca/~oz/hash.html
func DJB2(s []byte) uint64 {
var hash uint64 = 5381
for _, c := range s {
hash = ((hash << 5) + hash) + uint64(c)
}
return hash
}
// XorDjb2Hash XORes the byte slice and calc its djb2 hash.
func XorDjb2Hash(s []byte) uint64
50 changes: 50 additions & 0 deletions pkg/hashing/xordjb2.s
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
#include "textflag.h"

// func XorDjb2Hash(data []byte) uint64
TEXT ·XorDjb2Hash(SB),NOSPLIT,$0-24
MOVQ data+0(FP), DI
MOVQ DI, R9
MOVQ len+8(FP), SI
MOVQ SI, R10

// djb2 magic number
XORQ AX, AX
MOVL $5381, AX

// xor byte
XORQ R15, R15
MOVB $0xf1, R15

// if data slice is empty, return 0
CMPQ SI, $0
JEQ done

loop_xor:
// data[i] = data[i] ^ 0xf1
XORB R15, (DI)

INCQ DI
DECQ SI
CMPQ SI, $0
JNE loop_xor

// restore start ptr and length
MOVQ R9, DI
MOVQ R10, SI

loop_hash:
// move nth byte to BX
MOVB (DI), BX
INCQ DI

// hash = hash * 33 + data[i]
IMULQ $33, AX
ADDQ BX, AX

DECQ SI
CMPQ SI, $0
JNE loop_hash

done:
MOVQ AX, ret+24(FP)
RET

0 comments on commit 4c2cd88

Please sign in to comment.