Sha256: 00c565be9ab0ff2ebe49635019206c66c699d414c456dfcfd4cadb10649904ee

Contents?: true

Size: 1.36 KB

Versions: 6

Compression:

Stored size: 1.36 KB

Contents

module ASIR
  class Transport
    # !SLIDE
    # Payload IO for Transport
    #
    # Framing
    # * Header line containing the number of bytes in the payload.
    # * The payload bytes.
    # * Blank line.
    # * Footer.
    module PayloadIO
      class UnexpectedResponse < Error; end

      HEADER = "# asir_payload_size: "
      FOOTER = "\n# asir_payload_end"

      def _write payload, stream
        stream.write HEADER
        stream.puts payload.size
        stream.write payload
        stream.puts FOOTER
        stream.flush
        stream
      end

      def _read stream
        size = /\d+$/.match(stream.readline.chomp)[0].to_i # HEADER (size)
        payload = stream.read(size)
        stream.readline # FOOTER
        stream.readline
        payload
      end

      def _read_line_and_expect! stream, regexp
        line = stream.readline
        unless match = regexp.match(line)
          _log { "_read_line_and_expect! #{stream} #{regexp.inspect} !~ #{line.inspect}" }
          raise UnexpectedResponse, "expected #{regexp.inspect}, received #{line.inspect}"
        end
        match
      end

      # !SLIDE pause
      def close
        if @stream
          _before_close! stream if respond_to?(:_before_close!)
          @stream.close
        end
      ensure
        @stream = nil unless Channel === @stream
      end

      # !SLIDE resume
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
asir-1.0.8 lib/asir/transport/payload_io.rb
asir-1.0.7 lib/asir/transport/payload_io.rb
asir-1.0.6 lib/asir/transport/payload_io.rb
asir-1.0.5 lib/asir/transport/payload_io.rb
asir-1.0.4 lib/asir/transport/payload_io.rb
asir-1.0.1 lib/asir/transport/payload_io.rb