Class: DHT::Key

Inherits:
Object
  • Object
show all
Defined in:
lib/dht/key.rb

Constant Summary collapse

Digest =
::Digest::SHA1
Size =
Digest.new.digest_length

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(key) ⇒ Key

Returns a new instance of Key.



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/dht/key.rb', line 12

def initialize(key)
  @key =
    if Key === key
      key.to_binary
    elsif Integer === key
      @key_i = key
      k = @key_i.to_s(16)
      [('0' * ((Size * 2) - k.size)) + k].pack('H*')
    else
      key = key.to_s
      case key.size
        when Size      then  key
        when Size * 2  then  [key].pack('H*')
        else           raise "Invalid key: #{key}"
      end
    end
end

Class Method Details

.for_content(content) ⇒ Object



8
9
10
# File 'lib/dht/key.rb', line 8

def self.for_content(content)
  Key.new Digest.digest(content.to_s)
end

Instance Method Details

#==(that) ⇒ Object



30
31
32
# File 'lib/dht/key.rb', line 30

def ==(that)
  self.eql? that
end

#distance_to(that) ⇒ Object



62
63
64
# File 'lib/dht/key.rb', line 62

def distance_to(that)
  self.to_i ^ that.to_i
end

#eql?(that) ⇒ Boolean

Returns:

  • (Boolean)


46
47
48
49
50
51
52
# File 'lib/dht/key.rb', line 46

def eql?(that)
  if Key === that
    @key == that.to_binary
  else
    @key.to_s == that.to_s
  end
end

#hashObject



42
43
44
# File 'lib/dht/key.rb', line 42

def hash
  @key.hash
end

#inspectObject



54
55
56
# File 'lib/dht/key.rb', line 54

def inspect
  to_s
end

#to_binaryObject



34
35
36
# File 'lib/dht/key.rb', line 34

def to_binary
  @key
end

#to_iObject



58
59
60
# File 'lib/dht/key.rb', line 58

def to_i
  @key_i ||= eval( '0x' + self.to_s )
end

#to_sObject



38
39
40
# File 'lib/dht/key.rb', line 38

def to_s
  to_binary.unpack('H*').first
end