Module: Suby::MovieHasher

Defined in:
lib/suby/movie_hasher.rb

Overview

Constant Summary collapse

CHUNK_SIZE =

in bytes

64 * 1024
MASK64 =

2^64 - 1

0xffffffffffffffff

Class Method Summary collapse

Class Method Details

.compute_hash(file) ⇒ Object



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

def self.compute_hash(file)
  filesize = file.size
  hash = filesize

  # Read 64 kbytes, divide up into 64 bits and add each
  # to hash. Do for beginning and end of file.
  file.open('rb') do |f|
    # Q = unsigned long long = 64 bit
    f.read(CHUNK_SIZE).unpack("Q*").each do |n|
      hash = (hash + n) & MASK64
    end

    f.seek([0, filesize - CHUNK_SIZE].max, IO::SEEK_SET)

    # And again for the end of the file
    f.read(CHUNK_SIZE).unpack("Q*").each do |n|
      hash = (hash + n) & MASK64
    end
  end

  "%016x" % hash
end