Sha256: d1dbaf7db770ca9974cea8715d36e30cf30e0c198e0bc58c4abbcc42ab962065

Contents?: true

Size: 1.94 KB

Versions: 2

Compression:

Stored size: 1.94 KB

Contents

require "neovim/logging"
require "msgpack"

module Neovim
  # Handles serializing RPC messages to MessagePack and passing them to
  # the event loop.
  #
  # @api private
  class MsgpackStream
    include Logging

    def initialize(event_loop)
      @event_loop = event_loop
      @unpacker = MessagePack::Unpacker.new
    end

    # Serialize an RPC message to and write it to the event loop.
    #
    # @param msg [Array] The RPC message
    # @return [self]
    # @example Write an RPC request
    #   msgpack_stream.write([0, 1, :vim_strwidth, ["foobar"]])
    def write(msg)
      debug("writing #{msg.inspect}")
      @event_loop.write(MessagePack.pack(msg))
      self
    end

    # Run the event loop, yielding deserialized messages to the block.
    #
    # @param session [Session] Used for registering msgpack +ext+ types as
    #   described by the +vim_get_api_info+ call
    # @return [void]
    # @see EventLoop#run
    def run
      @event_loop.run do |data|
        @unpacker.feed_each(data) do |msg|
          debug("received #{msg.inspect}")
          yield msg if block_given?
        end
      end
    rescue => e
      fatal("got unexpected error #{e.inspect}")
      debug(e.backtrace.join("\n"))
    end

    # Stop the event loop.
    #
    # @return [void]
    # @see EventLoop#stop
    def stop
      @event_loop.stop
    end

    # Shut down the event loop.
    #
    # @return [void]
    # @see EventLoop#shutdown
    def shutdown
      @event_loop.shutdown
    end

    # Register msgpack ext types using the provided API and session
    #
    # @param api [API]
    # @param session [Session]
    # @see Session#discover_api
    def register_types(api, session)
      info("registering msgpack ext types")
      api.types.each do |type, info|
        klass = Neovim.const_get(type)
        id = info.fetch("id")

        @unpacker.register_type(id) do |data|
          klass.new(MessagePack.unpack(data), session)
        end
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
neovim-0.2.5 lib/neovim/msgpack_stream.rb
neovim-0.2.4 lib/neovim/msgpack_stream.rb