Class: Paquito::ConditionalCompressor

Inherits:
Object
  • Object
show all
Defined in:
lib/paquito/conditional_compressor.rb

Constant Summary collapse

UNCOMPRESSED =
0
COMPRESSED =
1

Instance Method Summary collapse

Constructor Details

#initialize(compressor, compress_threshold) ⇒ ConditionalCompressor

Returns a new instance of ConditionalCompressor.



8
9
10
11
# File 'lib/paquito/conditional_compressor.rb', line 8

def initialize(compressor, compress_threshold)
  @compressor = Paquito.cast(compressor)
  @compress_threshold = compress_threshold
end

Instance Method Details

#dump(uncompressed) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/paquito/conditional_compressor.rb', line 13

def dump(uncompressed)
  uncompressed_size = uncompressed.bytesize
  version = UNCOMPRESSED
  value = uncompressed

  if @compress_threshold && uncompressed_size > @compress_threshold
    compressed = @compressor.dump(uncompressed)
    if compressed.bytesize < uncompressed_size
      version = COMPRESSED
      value = compressed
    end
  end

  version.chr(Encoding::BINARY) << value
end

#load(payload) ⇒ Object



29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/paquito/conditional_compressor.rb', line 29

def load(payload)
  payload_version = payload.getbyte(0)
  data = payload.byteslice(1..-1)
  case payload_version
  when UNCOMPRESSED
    data
  when COMPRESSED
    @compressor.load(data)
  else
    raise UnpackError, "invalid ConditionalCompressor version"
  end
end