Skip to content

Commit

Permalink
add hat trie
Browse files Browse the repository at this point in the history
  • Loading branch information
chenkovsky committed Mar 15, 2018
1 parent 04ceb72 commit a6ea135
Show file tree
Hide file tree
Showing 4 changed files with 413 additions and 9 deletions.
24 changes: 24 additions & 0 deletions spec/hat_spec.cr
@@ -0,0 +1,24 @@
require "./spec_helper"

describe Aha do
it "hat trie" do
v1 = Bytes.new [3_u8, 4_u8].to_unsafe, 2
v2 = Bytes.new [5_u8, 6_u8].to_unsafe, 2
v3 = Bytes.new [7_u8, 8_u8].to_unsafe, 2
v4 = Bytes.new [9_u8, 10_u8].to_unsafe, 2
trie = Aha::Hat(2).new
trie["ab"] = v1
trie["bc"] = v2
trie["abc"] = v3
trie["abcd"] = v4
trie["ab"].should eq(v1)
trie["bc"].should eq(v2)
trie["abc"].should eq(v3)
trie["abcd"].should eq(v4)
arr = [] of String
trie.each do |kv|
arr << (String.new kv.key)
end
arr.sort.should eq(["ab", "abc", "abcd", "bc"])
end
end
20 changes: 11 additions & 9 deletions src/aha/array_hash.cr
Expand Up @@ -197,7 +197,7 @@ module Aha
return Pointer(UInt8).null
end

private def get(key : Bytes | Array(UInt8))
def get(key : Bytes | Array(UInt8))
if key.size > 32767
raise "HAT-trie/AH-table cannot store keys longer than 32768"
end
Expand Down Expand Up @@ -241,11 +241,11 @@ module Aha
return ret
end

private def try_get(key : Bytes | Array(UInt8)) : UInt8*
def try_get(key : Bytes | Array(UInt8)) : UInt8*
get_key(key, false)
end

private def delete(key : Bytes | Array(UInt8))
def delete(key : Bytes | Array(UInt8)) : Bool
i = MurMur.hash(key) % @n
s_start = s = @slots[i]
slot_size = @slot_sizes[i]
Expand All @@ -263,21 +263,23 @@ module Aha
s.move_from(t, slot_size - (t - s_start))
@slot_sizes[i] -= t - s
@m -= 1
return 0
return true
end
s += k + N
next
end
return -1
return false
end

def each(sorted : Bool)
if sorted
arr = [] of Bytes
each do |k, v|
arr << (KV.new k, v)
arr = [] of KV
each do |kv|
arr << kv
end
arr.sort! do |e1, e2|
Aha.bytes_cmp(e1.key, e2.key)
end
arr.sort_by! { |e| e.key }
arr.each do |kv|
yield kv
end
Expand Down

0 comments on commit a6ea135

Please sign in to comment.