Skip to content

Instantly share code, notes, and snippets.

@jozip
Created March 17, 2011 19:49
Show Gist options
  • Save jozip/874993 to your computer and use it in GitHub Desktop.
Save jozip/874993 to your computer and use it in GitHub Desktop.
require 'digest/sha2'
class Key < Binary 'H*'
unit :to_s
class << self
def hexdigest(src, bitlen = 256)
Digest::SHA2.new(bitlen).update(src.to_s).to_s
end
def gen(src)
new(hexdigest(src))
end
end
def initialize(key = nil)
if key.nil?
@key_s = Key.hexdigest(rand(Time.now.to_i)) # Fixme
else
if key.is_a?(Integer)
@key_i = key
elsif key.is_a?(String)
@key_s = key
else
raise "Invalid key #{key}"
end
end
end
def to_i
@key_i ||= @key_s.to_i(16)
end
def to_s
@key_s ||= @key_i.to_s(16)
end
def ^(key)
self.to_i ^ key.to_i
end
def ==(key)
key.is_a?(Key) && (to_i == key.to_i) || key.is_a?(Integer) && (to_i == key)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment