2017-07-09 08:06:36 -04:00
|
|
|
# frozen_string_literal: true
|
2017-07-10 09:39:13 -04:00
|
|
|
|
2016-08-06 11:58:50 -04:00
|
|
|
require "zlib"
|
|
|
|
require "stringio"
|
2008-01-03 16:05:12 -05:00
|
|
|
|
|
|
|
module ActiveSupport
|
2012-06-05 00:43:43 -04:00
|
|
|
# A convenient wrapper for the zlib standard library that allows
|
|
|
|
# compression/decompression of strings with gzip.
|
|
|
|
#
|
|
|
|
# gzip = ActiveSupport::Gzip.compress('compress me!')
|
|
|
|
# # => "\x1F\x8B\b\x00o\x8D\xCDO\x00\x03K\xCE\xCF-(J-.V\xC8MU\x04\x00R>n\x83\f\x00\x00\x00"
|
|
|
|
#
|
|
|
|
# ActiveSupport::Gzip.decompress(gzip)
|
2016-08-06 13:55:02 -04:00
|
|
|
# # => "compress me!"
|
2008-01-03 16:05:12 -05:00
|
|
|
module Gzip
|
|
|
|
class Stream < StringIO
|
2011-02-09 04:23:45 -05:00
|
|
|
def initialize(*)
|
2011-02-09 16:47:32 -05:00
|
|
|
super
|
2011-12-24 07:57:54 -05:00
|
|
|
set_encoding "BINARY"
|
2011-02-09 16:47:32 -05:00
|
|
|
end
|
2008-01-03 16:05:12 -05:00
|
|
|
def close; rewind; end
|
|
|
|
end
|
|
|
|
|
2008-03-26 08:27:52 -04:00
|
|
|
# Decompresses a gzipped string.
|
2008-01-03 16:05:12 -05:00
|
|
|
def self.decompress(source)
|
2017-02-24 17:26:54 -05:00
|
|
|
Zlib::GzipReader.wrap(StringIO.new(source), &:read)
|
2008-01-03 16:05:12 -05:00
|
|
|
end
|
|
|
|
|
2008-03-26 08:27:52 -04:00
|
|
|
# Compresses a string using gzip.
|
2016-10-28 23:05:58 -04:00
|
|
|
def self.compress(source, level = Zlib::DEFAULT_COMPRESSION, strategy = Zlib::DEFAULT_STRATEGY)
|
2008-01-03 16:05:12 -05:00
|
|
|
output = Stream.new
|
2012-09-22 05:07:50 -04:00
|
|
|
gz = Zlib::GzipWriter.new(output, level, strategy)
|
2008-01-03 16:05:12 -05:00
|
|
|
gz.write(source)
|
|
|
|
gz.close
|
|
|
|
output.string
|
|
|
|
end
|
|
|
|
end
|
2011-02-09 16:47:32 -05:00
|
|
|
end
|