Sha256: f6cea132dcd380371508b2e687f491ae131a96bc758f4bcd1d264278660bba7b

Contents?: true

Size: 1.3 KB

Versions: 5

Compression:

Stored size: 1.3 KB

Contents

module Dcha
  module MPT
    # :nodoc:
    class Trie
      include Enumerable

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

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

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

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

        update_root_hash
      end
      alias []= set

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

        update_root_hash
      end

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

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

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

      def size
        @root.tree_size
      end

      private

      def blank_root
        @blank_root ||= Config.digest.hexdigest(RLP.encode('')).freeze
      end
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
dcha-0.1.4 lib/dcha/mpt/trie.rb
dcha-0.1.3 lib/dcha/mpt/trie.rb
dcha-0.1.2 lib/dcha/mpt/trie.rb
dcha-0.1.1 lib/dcha/mpt/trie.rb
dcha-0.1.0 lib/dcha/mpt/trie.rb