Class: Dcha::MPT::Trie

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/dcha/mpt/trie.rb

Overview

:nodoc:

Instance Method Summary collapse

Constructor Details

#initialize(hash = nil) ⇒ Trie

Returns a new instance of Trie.



7
8
9
10
11
12
13
# File 'lib/dcha/mpt/trie.rb', line 7

def initialize(hash = nil)
  @root = if hash.nil?
            Node::BLANK
          else
            Node.decode(hash)
          end
end

Instance Method Details

#delete(key) ⇒ Object



36
37
38
39
40
# File 'lib/dcha/mpt/trie.rb', line 36

def delete(key)
  @root = @root.delete(NibbleKey.from_string(key))

  update_root_hash
end

#each(&block) ⇒ Object



53
54
55
# File 'lib/dcha/mpt/trie.rb', line 53

def each(&block)
  to_h.each(&block)
end

#get(key) ⇒ Object Also known as: []



21
22
23
# File 'lib/dcha/mpt/trie.rb', line 21

def get(key)
  @root.find NibbleKey.from_string(key)
end

#key?(key) ⇒ Boolean Also known as: include?

Returns:

  • (Boolean)


57
58
59
# File 'lib/dcha/mpt/trie.rb', line 57

def key?(key)
  self[key] != Node::BLANK.first
end

#root_hashObject Also known as: update_root_hash



15
16
17
18
# File 'lib/dcha/mpt/trie.rb', line 15

def root_hash
  return blank_root if @root == Node::BLANK
  @root.save(true)
end

#set(key, value) ⇒ Object Also known as: []=



26
27
28
29
30
31
32
33
# File 'lib/dcha/mpt/trie.rb', line 26

def set(key, value)
  @root = @root.update(
    NibbleKey.from_string(key),
    value
  )

  update_root_hash
end

#sizeObject



62
63
64
# File 'lib/dcha/mpt/trie.rb', line 62

def size
  @root.tree_size
end

#to_hObject



42
43
44
45
46
47
48
49
50
51
# File 'lib/dcha/mpt/trie.rb', line 42

def to_h
  Hash[
    @root.to_h.map do |key, value|
      [
        key.terminate(false).to_s,
        value
      ]
    end
  ]
end