Class: Rfmt::LSP::MessageIO

Inherits:
Object
  • Object
show all
Defined in:
lib/rfmt/lsp/message_io.rb

Overview

Reads and writes LSP JSON-RPC messages over an IO pair.

Constant Summary collapse

HEADER_SEPARATOR =
"\r\n\r\n"
CONTENT_LENGTH =
/\AContent-Length:\s*(\d+)\z/i

Instance Method Summary collapse

Constructor Details

#initialize(input: $stdin, output: $stdout) ⇒ MessageIO

Returns a new instance of MessageIO.



12
13
14
15
# File 'lib/rfmt/lsp/message_io.rb', line 12

def initialize(input: $stdin, output: $stdout)
  @input = input
  @output = output
end

Instance Method Details

#read_messageObject



17
18
19
20
21
22
23
# File 'lib/rfmt/lsp/message_io.rb', line 17

def read_message
  headers = read_headers
  return nil if headers.nil?

  content_length = headers.fetch('content-length').to_i
  JSON.parse(@input.read(content_length))
end

#write_message(payload) ⇒ Object



25
26
27
28
29
# File 'lib/rfmt/lsp/message_io.rb', line 25

def write_message(payload)
  body = JSON.generate(payload)
  @output.write("Content-Length: #{body.bytesize}#{HEADER_SEPARATOR}#{body}")
  @output.flush if @output.respond_to?(:flush)
end