1
0
Fork 0
mirror of https://github.com/ruby/ruby.git synced 2022-11-09 12:17:21 -05:00

[ruby/zlib] Mask checksums to lower 32bits

Upper bits affect the result of `crc32` in zlib 1.2.12.

https://github.com/ruby/zlib/commit/9ab6d04af1
This commit is contained in:
Nobuyoshi Nakada 2022-04-02 16:06:11 +09:00 committed by git
parent 729b9a8543
commit 1cbdedec89
2 changed files with 11 additions and 3 deletions

View file

@ -374,18 +374,24 @@ rb_zlib_version(VALUE klass)
return rb_str_new2(zlibVersion()); return rb_str_new2(zlibVersion());
} }
#if SIZEOF_LONG * CHAR_BIT > 32
# define mask32(x) ((x) & 0xffffffff)
#else
# define mask32(x) (x)
#endif
#if SIZEOF_LONG > SIZEOF_INT #if SIZEOF_LONG > SIZEOF_INT
static uLong static uLong
checksum_long(uLong (*func)(uLong, const Bytef*, uInt), uLong sum, const Bytef *ptr, long len) checksum_long(uLong (*func)(uLong, const Bytef*, uInt), uLong sum, const Bytef *ptr, long len)
{ {
if (len > UINT_MAX) { if (len > UINT_MAX) {
do { do {
sum = func(sum, ptr, UINT_MAX); sum = func(mask32(sum), ptr, UINT_MAX);
ptr += UINT_MAX; ptr += UINT_MAX;
len -= UINT_MAX; len -= UINT_MAX;
} while (len >= UINT_MAX); } while (len >= UINT_MAX);
} }
if (len > 0) sum = func(sum, ptr, (uInt)len); if (len > 0) sum = func(mask32(sum), ptr, (uInt)len);
return sum; return sum;
} }
#else #else
@ -411,7 +417,7 @@ do_checksum(int argc, VALUE *argv, uLong (*func)(uLong, const Bytef*, uInt))
} }
if (NIL_P(str)) { if (NIL_P(str)) {
sum = func(sum, Z_NULL, 0); sum = func(mask32(sum), Z_NULL, 0);
} }
else if (rb_obj_is_kind_of(str, rb_cIO)) { else if (rb_obj_is_kind_of(str, rb_cIO)) {
VALUE buf; VALUE buf;

View file

@ -1303,6 +1303,7 @@ if defined? Zlib
assert_equal(0x02820145, Zlib.adler32("foo")) assert_equal(0x02820145, Zlib.adler32("foo"))
assert_equal(0x02820145, Zlib.adler32("o", Zlib.adler32("fo"))) assert_equal(0x02820145, Zlib.adler32("o", Zlib.adler32("fo")))
assert_equal(0x8a62c964, Zlib.adler32("abc\x01\x02\x03" * 10000)) assert_equal(0x8a62c964, Zlib.adler32("abc\x01\x02\x03" * 10000))
assert_equal(0x97d1a9f7, Zlib.adler32("p", -305419897))
Tempfile.create("test_zlib_gzip_file_to_io") {|t| Tempfile.create("test_zlib_gzip_file_to_io") {|t|
File.binwrite(t.path, "foo") File.binwrite(t.path, "foo")
t.rewind t.rewind
@ -1338,6 +1339,7 @@ if defined? Zlib
assert_equal(0x8c736521, Zlib.crc32("foo")) assert_equal(0x8c736521, Zlib.crc32("foo"))
assert_equal(0x8c736521, Zlib.crc32("o", Zlib.crc32("fo"))) assert_equal(0x8c736521, Zlib.crc32("o", Zlib.crc32("fo")))
assert_equal(0x07f0d68f, Zlib.crc32("abc\x01\x02\x03" * 10000)) assert_equal(0x07f0d68f, Zlib.crc32("abc\x01\x02\x03" * 10000))
assert_equal(0xf136439b, Zlib.crc32("p", -305419897))
Tempfile.create("test_zlib_gzip_file_to_io") {|t| Tempfile.create("test_zlib_gzip_file_to_io") {|t|
File.binwrite(t.path, "foo") File.binwrite(t.path, "foo")
t.rewind t.rewind