Class: PacketFlags

Inherits:
Object
  • Object
show all
Defined in:
lib/models/packet_flags.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(data) ⇒ PacketFlags

Returns a new instance of PacketFlags.



6
7
8
9
10
11
12
13
14
15
16
17
18
# File 'lib/models/packet_flags.rb', line 6

def initialize(data)
  @hash = {}
  @bits = ''
  if data.instance_of?(Hash)
    @bits = parse_hash(data)
    @hash = data
  elsif data.instance_of?(String)
    @hash = parse_bits(data)
    @bits = data
  else
    raise 'Flags have to be hash or string'
  end
end

Instance Attribute Details

#bitsObject (readonly)

Returns the value of attribute bits.



4
5
6
# File 'lib/models/packet_flags.rb', line 4

def bits
  @bits
end

#hashObject (readonly)

Returns the value of attribute hash.



4
5
6
# File 'lib/models/packet_flags.rb', line 4

def hash
  @hash
end

Instance Method Details

#parse_bits(four_bit_str) ⇒ Object



29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/models/packet_flags.rb', line 29

def parse_bits(four_bit_str)
  # takes a 4 character string
  # representing the middle of the first byte sent
  # in binary representation
  #
  # and creates a hash out of it
  hash = {}
  hash[:connection] = four_bit_str[0] == '1'
  hash[:compressed] = four_bit_str[1] == '1'
  hash[:resend] = four_bit_str[2] == '1'
  hash[:control] = four_bit_str[3] == '1'
  hash
end

#parse_hash(hash) ⇒ Object



20
21
22
23
24
25
26
27
# File 'lib/models/packet_flags.rb', line 20

def parse_hash(hash)
  bits = ''
  bits += hash[:connection] ? '1' : '0'
  bits += hash[:compressed] ? '1' : '0'
  bits += hash[:resend] ? '1' : '0'
  bits += hash[:control] ? '1' : '0'
  bits
end