File: stream_reader.rb

package info (click to toggle)
ruby-websocket-driver 0.8.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 204 kB
  • sloc: ruby: 1,236; java: 46; ansic: 25; makefile: 3
file content (55 lines) | stat: -rw-r--r-- 1,167 bytes parent folder | download
1
2
3
4
5
6
7
8
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
module WebSocket
  class Driver

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

      def initialize
        @buffer = String.new('').force_encoding(Encoding::BINARY)
        @offset = 0
      end

      def put(chunk)
        return unless chunk and chunk.bytesize > 0
        @buffer << chunk.force_encoding(Encoding::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 = String.new('').force_encoding(Encoding::BINARY)
        else
          @buffer = @buffer.byteslice(@offset, buffer_size - @offset)
        end

        @offset = 0
      end
    end

  end
end