File: gzip.rb

package info (click to toggle)
ruby-httpx 1.7.2-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,816 kB
  • sloc: ruby: 12,209; makefile: 4
file content (76 lines) | stat: -rw-r--r-- 1,666 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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# frozen_string_literal: true

require "zlib"

module HTTPX
  module Transcoder
    module GZIP
      class Deflater < Transcoder::Deflater
        def initialize(body)
          @compressed_chunk = "".b
          @deflater = nil
          super
        end

        def deflate(chunk)
          @deflater ||= Zlib::GzipWriter.new(self)

          if chunk.nil?
            unless @deflater.closed?
              @deflater.flush
              @deflater.close
              compressed_chunk
            end
          else
            @deflater.write(chunk)
            compressed_chunk
          end
        end

        private

        def write(*chunks)
          chunks.sum do |chunk|
            chunk = chunk.to_s
            @compressed_chunk << chunk
            chunk.bytesize
          end
        end

        def compressed_chunk
          @compressed_chunk.dup
        ensure
          @compressed_chunk.clear
        end
      end

      class Inflater
        def initialize(bytesize)
          @inflater = Zlib::Inflate.new(Zlib::MAX_WBITS + 32)
          @bytesize = bytesize
        end

        def call(chunk)
          buffer = @inflater.inflate(chunk)
          @bytesize -= chunk.bytesize
          if @bytesize <= 0
            buffer << @inflater.finish
            @inflater.close
          end
          buffer
        end
      end

      module_function

      def encode(body)
        Deflater.new(body)
      end

      def decode(response, bytesize: nil)
        bytesize ||= response.headers.key?("content-length") ? response.headers["content-length"].to_i : Float::INFINITY
        Inflater.new(bytesize)
      end
    end
  end
end