Skip to content

Instantly share code, notes, and snippets.

@brewski
Last active May 10, 2018 22:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brewski/ce11632292514319924cdec42217cb05 to your computer and use it in GitHub Desktop.
Save brewski/ce11632292514319924cdec42217cb05 to your computer and use it in GitHub Desktop.
piece spec hash implementation in ruby
require "digest"
def av_hash_62bit(av_components)
av_components.
map(&Digest::SHA256.method(:digest)).
reduce(Digest::SHA256.new, &:update).
digest.
unpack("Q>").
first & 0x3fffffffffffffff
end
def piece_spec_hash(sku_id, av_components)
return sku_id if av_components.empty?
sha256 = Digest::SHA256.new
[sku_id, *av_components.map(&method(:av_hash_62bit)).sort.uniq].each do |int|
sha256.update([int].pack("Q>"))
end
sha256.digest[0,4].unpack("N").first
end
components = [
[[4242].pack("Q>"), "", ""],
[[2].pack("Q>"), "qualifier 1 value", "qualifier 2 value"]
]
puts "av1 62-bit hash: #{av_hash_62bit(components[0])}"
puts "av2 62-bit hash: #{av_hash_62bit(components[1])}"
puts "piece_spec_hash: #{piece_spec_hash(88662, components)}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment