Class: WebSocket::Frame::Data

Inherits:
String
  • Object
show all
Defined in:
lib/websocket/frame/data.rb

Instance Method Summary collapse

Constructor Details

#initialize(*args) ⇒ Data

Returns a new instance of Data.



6
7
8
9
# File 'lib/websocket/frame/data.rb', line 6

def initialize(*args)
  super(*convert_args(args))
  @masking_key = nil
end

Instance Method Details

#<<(*args) ⇒ Object



11
12
13
# File 'lib/websocket/frame/data.rb', line 11

def <<(*args)
  super(*convert_args(args))
end

#convert_args(args) ⇒ Object

Convert all arguments to ASCII-8BIT for easier traversing



16
17
18
# File 'lib/websocket/frame/data.rb', line 16

def convert_args(args)
  args.collect { |arg| arg.dup.force_encoding('ASCII-8BIT') }
end

#getbytes(start_index, count) ⇒ Object

Extract ‘count` bytes starting from `start_index` and unmask it if needed.



32
33
34
35
36
# File 'lib/websocket/frame/data.rb', line 32

def getbytes(start_index, count)
  data = self[start_index, count]
  data = mask(data.bytes.to_a, @masking_key).pack('C*') if @masking_key
  data
end

#mask(payload, mask) ⇒ Object

Mask whole payload using mask key



39
40
41
42
43
44
45
46
# File 'lib/websocket/frame/data.rb', line 39

def mask(payload, mask)
  return mask_native(payload, mask) if respond_to?(:mask_native)
  result = []
  payload.each_with_index do |byte, i|
    result[i] = byte ^ mask[i % 4]
  end
  result
end

#set_maskObject

Extract mask from 4 first bytes according to spec



21
22
23
24
# File 'lib/websocket/frame/data.rb', line 21

def set_mask
  raise WebSocket::Error::Frame::MaskTooShort if bytesize < 4
  @masking_key = self[0..3].bytes.to_a
end

#unset_maskObject

Remove mask flag - it will still be present in payload



27
28
29
# File 'lib/websocket/frame/data.rb', line 27

def unset_mask
  @masking_key = nil
end