Skip to content

Commit 9ab6d04

Browse files
committed
Mask checksums to lower 32bits
Upper bits affect the result of `crc32` in zlib 1.2.12.
1 parent d66eaa6 commit 9ab6d04

File tree

2 files changed

+11
-3
lines changed

2 files changed

+11
-3
lines changed

ext/zlib/zlib.c

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -374,18 +374,24 @@ rb_zlib_version(VALUE klass)
374374
return rb_str_new2(zlibVersion());
375375
}
376376

377+
#if SIZEOF_LONG * CHAR_BIT > 32
378+
# define mask32(x) ((x) & 0xffffffff)
379+
#else
380+
# define mask32(x) (x)
381+
#endif
382+
377383
#if SIZEOF_LONG > SIZEOF_INT
378384
static uLong
379385
checksum_long(uLong (*func)(uLong, const Bytef*, uInt), uLong sum, const Bytef *ptr, long len)
380386
{
381387
if (len > UINT_MAX) {
382388
do {
383-
sum = func(sum, ptr, UINT_MAX);
389+
sum = func(mask32(sum), ptr, UINT_MAX);
384390
ptr += UINT_MAX;
385391
len -= UINT_MAX;
386392
} while (len >= UINT_MAX);
387393
}
388-
if (len > 0) sum = func(sum, ptr, (uInt)len);
394+
if (len > 0) sum = func(mask32(sum), ptr, (uInt)len);
389395
return sum;
390396
}
391397
#else
@@ -411,7 +417,7 @@ do_checksum(int argc, VALUE *argv, uLong (*func)(uLong, const Bytef*, uInt))
411417
}
412418

413419
if (NIL_P(str)) {
414-
sum = func(sum, Z_NULL, 0);
420+
sum = func(mask32(sum), Z_NULL, 0);
415421
}
416422
else if (rb_obj_is_kind_of(str, rb_cIO)) {
417423
VALUE buf;

test/zlib/test_zlib.rb

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1303,6 +1303,7 @@ def test_adler32
13031303
assert_equal(0x02820145, Zlib.adler32("foo"))
13041304
assert_equal(0x02820145, Zlib.adler32("o", Zlib.adler32("fo")))
13051305
assert_equal(0x8a62c964, Zlib.adler32("abc\x01\x02\x03" * 10000))
1306+
assert_equal(0x97d1a9f7, Zlib.adler32("p", -305419897))
13061307
Tempfile.create("test_zlib_gzip_file_to_io") {|t|
13071308
File.binwrite(t.path, "foo")
13081309
t.rewind
@@ -1338,6 +1339,7 @@ def test_crc32
13381339
assert_equal(0x8c736521, Zlib.crc32("foo"))
13391340
assert_equal(0x8c736521, Zlib.crc32("o", Zlib.crc32("fo")))
13401341
assert_equal(0x07f0d68f, Zlib.crc32("abc\x01\x02\x03" * 10000))
1342+
assert_equal(0xf136439b, Zlib.crc32("p", -305419897))
13411343
Tempfile.create("test_zlib_gzip_file_to_io") {|t|
13421344
File.binwrite(t.path, "foo")
13431345
t.rewind

0 commit comments

Comments
 (0)