Skip to content

Commit 97a4d4f

Browse files
committed
Make ActiveSupport::Gzip.compress deterministic
`ActiveSupport::Gzip.compress` used to include the current timestamp in the gzipped output (the default behavior of Zlib), causing multiple calls with the same input data to output different results depending on when it was called. In many situations (such as caching), ensuring that the output is always the same for a given input is useful, so this helper now always sets the timestamp to `0` instead.
1 parent f4ec7e8 commit 97a4d4f

File tree

3 files changed

+15
-0
lines changed

3 files changed

+15
-0
lines changed

activesupport/CHANGELOG.md

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,12 @@
1+
* Make `ActiveSupport::Gzip.compress` deterministic based on input.
2+
3+
`ActiveSupport::Gzip.compress` used to include a timestamp in the output,
4+
causing consecutive calls with the same input data to have different output
5+
if called during different seconds. It now always sets the timestamp to `0`
6+
so that the output is identical for any given input.
7+
8+
*Rob Brackett*
9+
110
* Given an array of `Thread::Backtrace::Location` objects, the new method
211
`ActiveSupport::BacktraceCleaner#clean_locations` returns an array with the
312
clean ones:

activesupport/lib/active_support/gzip.rb

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ def self.decompress(source)
3232
def self.compress(source, level = Zlib::DEFAULT_COMPRESSION, strategy = Zlib::DEFAULT_STRATEGY)
3333
output = Stream.new
3434
gz = Zlib::GzipWriter.new(output, level, strategy)
35+
gz.mtime = 0
3536
gz.write(source)
3637
gz.close
3738
output.string

activesupport/test/gzip_test.rb

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,4 +42,9 @@ def test_decompress_checks_crc
4242
ActiveSupport::Gzip.decompress(compressed)
4343
end
4444
end
45+
46+
def test_sets_mtime_to_zero
47+
compressed = ActiveSupport::Gzip.compress("Hello World")
48+
assert_equal Time.at(0), Zlib::GzipReader.new(StringIO.new(compressed)).mtime
49+
end
4550
end

0 commit comments

Comments
 (0)