aboutsummaryrefslogtreecommitdiffstats
path: root/lib/plum/client/decoders.rb
blob: a1578f903d90d835b0d0aa04129f6722a757c6bf (plain)
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
module Plum
  module Decoders
    class Base
      def decode(chunk)
        chunk
      end

      def finish
      end
    end

    # `deflate` is not just deflate, wrapped by zlib format (RFC 1950)
    class Deflate < Base
      def initialize
        @inflate = Zlib::Inflate.new(Zlib::MAX_WBITS)
      end

      def decode(chunk)
        @inflate.inflate(chunk)
      rescue Zlib::Error
        raise DecoderError.new("failed to decode chunk", $!)
      end

      def finish
        @inflate.finish
      rescue Zlib::Error
        raise DecoderError.new("failed to finalize", $!)
      end
    end

    class GZip < Base
      def initialize
        @stream = Zlib::Inflate.new(Zlib::MAX_WBITS + 16)
      end

      def decode(chunk)
        @stream.inflate(chunk)
      rescue Zlib::Error
        raise DecoderError.new("failed to decode chunk", $!)
      end

      def finish
        @stream.finish
      rescue Zlib::Error
        raise DecoderError.new("failed to finalize", $!)
      end
    end

    DECODERS = { "gzip" => GZip, "deflate" => Deflate }
  end
end