Class: QuartzTorrent::UdpTrackerMessage

Inherits:
Object
  • Object
show all
Defined in:
lib/quartz_torrent/udptrackermsg.rb

Constant Summary collapse

ActionConnect =
0
ActionAnnounce =
1
ActionScrape =
2
ActionError =
3
EventNone =
0
EventCompleted =
1
EventStarted =
2
EventStopped =
3

Class Method Summary collapse

Class Method Details

.packAsNetworkOrder(num, len) ⇒ Object

Pack the number ‘num’ as a network byte order signed integer, ‘len’ bytes long. Negative numbers are written in two’s-compliment notation.



15
16
17
18
19
20
21
22
# File 'lib/quartz_torrent/udptrackermsg.rb', line 15

def self.packAsNetworkOrder(num, len)
  result = ""
  len.times do
    result << (num & 0xff)
    num >>= 8
  end
  result.reverse
end

.unpackNetworkOrder(str, len = nil) ⇒ Object

Unpack the number stored in ‘str’ assuming it is a network byte order signed integer. Negative numbers are assumed to be in two’s-compliment notation.



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/quartz_torrent/udptrackermsg.rb', line 26

def self.unpackNetworkOrder(str, len = nil)
  result = 0
  first = true
  negative = false
  index = 0
  str.each_byte do |b|
    if first
      negative = (b & 0x80) > 0
      first = false
    end
    result <<= 8
    result += b
    index += 1
    break if len && index == len
  end
  if negative
    # Internally the value is being represented unsigned. To make it signed,
    # we first take the ones compliment of the value, remove the sign bit, and add one.
    # This takes the two's compliment of the two's compliment of the number, which results
    # in the absolute value of the original number. Finally we use the unary - operator to
    # make the value negative.
    result = -(((~result) & 0x7fffffffffffffff) + 1)
  end
  result 
end