Sha256: c1044c3943a170dce4447f00255c78e131a13f3744b80b334cb895cbd9654859

Contents?: true

Size: 1.09 KB

Versions: 6

Compression:

Stored size: 1.09 KB

Contents

module WebSocket
  class Driver

    class StreamReader
      # Try to minimise the number of reallocations done:
      MINIMUM_AUTOMATIC_PRUNE_OFFSET = 128

      def initialize
        @buffer = Driver.encode('', :binary)
        @offset = 0
      end

      def put(chunk)
        return unless chunk and chunk.bytesize > 0
        @buffer << Driver.encode(chunk, :binary)
      end

      # Read bytes from the data:
      def read(length)
        return nil if (@offset + length) > @buffer.bytesize

        chunk = @buffer.byteslice(@offset, length)
        @offset += chunk.bytesize

        prune if @offset > MINIMUM_AUTOMATIC_PRUNE_OFFSET

        return chunk
      end

      def each_byte
        prune

        @buffer.each_byte do |octet|
          @offset += 1
          yield octet
        end
      end

    private

      def prune
        buffer_size = @buffer.bytesize

        if @offset > buffer_size
          @buffer = Driver.encode('', :binary)
        else
          @buffer = @buffer.byteslice(@offset, buffer_size - @offset)
        end

        @offset = 0
      end
    end

  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
websocket-driver-0.6.3-java lib/websocket/driver/stream_reader.rb
websocket-driver-0.6.3 lib/websocket/driver/stream_reader.rb
websocket-driver-0.6.2-java lib/websocket/driver/stream_reader.rb
websocket-driver-0.6.2 lib/websocket/driver/stream_reader.rb
websocket-driver-0.6.1-java lib/websocket/driver/stream_reader.rb
websocket-driver-0.6.1 lib/websocket/driver/stream_reader.rb