Module: Treehash

Defined in:
lib/treehash.rb,
lib/treehash/version.rb

Constant Summary collapse

MEGA_BYTE =
1024 * 1024
VERSION =
"0.0.2"

Class Method Summary collapse

Class Method Details

.calculate_tree_hash(string_or_io) ⇒ Object



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/treehash.rb', line 8

def self.calculate_tree_hash(string_or_io)
  if string_or_io.is_a? String
    handle = StringIO.new(string_or_io)
  elsif string_or_io.is_a? IO
    handle = string_or_io
  else
    raise "must be called with string or IO handle"
  end

  shas = []
  while mega_byte = handle.read(MEGA_BYTE)
    shas << Digest::SHA256.new.digest(mega_byte)
  end

  return nil if shas.empty?

  while shas.size > 1
    shas = shas.each_slice(2).map do |pair|
      pair[1] ? Digest::SHA256.new.update(pair[0]).update(pair[1]).digest : pair[0]
    end
  end

  Digest.hexencode shas[0]
end