Module: DAP::Encoding

Defined in:
lib/dap/encoding.rb

Overview

Encoding and decoding for DAP messages

Constant Summary collapse

CONTENT_LENGTH_HEADER =

The name of the content length header.

'Content-Length'

Class Method Summary collapse

Class Method Details

.decode(s) ⇒ ProtocolMessage

Decode a DAP message from the stream.

Parameters:

  • s (IO)

    the stream

Returns:



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/dap/encoding.rb', line 9

def self.decode(s)
  headers = {}

  loop do
    l = s.gets
    raise EOFError if l.nil?

    l = l.strip
    break if l.empty?

    name, value = l.split(':', 2)
    raise "Invalid header '#{l}'" unless value

    headers[name.strip] = value.strip
  end

  raise "No headers" unless headers.size
  raise "Missing content length" unless headers.key?(CONTENT_LENGTH_HEADER)

  cl = headers[CONTENT_LENGTH_HEADER].to_i
  raise "Invalid content length" unless cl.to_s == headers[CONTENT_LENGTH_HEADER]

  body = s.read(cl)
  values = JSON.parse(body)
  DAP::ProtocolMessage.from(values)
end

.decode_all(s) { ... } ⇒ Object

Decode all DAP messages from the stream.

Parameters:

  • s (IO)

    the stream

Yields:

  • Invokes the block for each message



53
54
55
56
57
# File 'lib/dap/encoding.rb', line 53

def self.decode_all(s)
  loop do
    yield decode(s)
  end
end

.encode(message) ⇒ String

Encode a DAP message to a string.

Parameters:

Returns:

  • (String)

    the encoded message



39
40
41
42
43
44
45
46
47
48
# File 'lib/dap/encoding.rb', line 39

def self.encode(message)
  raise "Body must be a protocol message" unless message.is_a? DAP::ProtocolMessage

  headers = {}

  body = JSON.dump(message.to_wire)
  headers[CONTENT_LENGTH_HEADER] = body.bytesize

  headers.map { |name, value| "#{name}: #{value}\r\n" }.join + "\r\n" + body
end