authorgravatar for michael.larouche@gmail.comMichaël Larouche <michael.larouche@gmail.com> 2020-03-31 16:52:16-04:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2020-03-31 20:08:42-04:00
loga5af78c376fc41424b81ea83766b38a0a1d17870
tree0df644dd190b25bdf7692e8e2a917682248ecbc8
parente3d12471a2554154b507ed675e35530b55259984

Fix porting of zlib alder32 with large input


1 files changed, 29 insertions(+), 8 deletions(-)

lib/std/hash/adler.zig+29-8
...@@ -42,18 +42,23 @@ pub const Adler32 = struct {...@@ -42,18 +42,23 @@ pub const Adler32 = struct {
4242
43 s2 %= base;43 s2 %= base;
44 } else {44 } else {
45 const n = nmax / 16; // note: 16 | nmax
46
45 var i: usize = 0;47 var i: usize = 0;
46 while (i + nmax <= input.len) : (i += nmax) {
47 const n = nmax / 16; // note: 16 | nmax
4848
49 while (i + nmax <= input.len) {
49 var rounds: usize = 0;50 var rounds: usize = 0;
50 while (rounds < n) : (rounds += 1) {51 while (rounds < n) : (rounds += 1) {
51 comptime var j: usize = 0;52 comptime var j: usize = 0;
52 inline while (j < 16) : (j += 1) {53 inline while (j < 16) : (j += 1) {
53 s1 +%= input[i + n * j];54 s1 +%= input[i + j];
54 s2 +%= s1;55 s2 +%= s1;
55 }56 }
57 i += 16;
56 }58 }
59
60 s1 %= base;
61 s2 %= base;
57 }62 }
5863
59 if (i < input.len) {64 if (i < input.len) {
...@@ -89,19 +94,35 @@ pub const Adler32 = struct {...@@ -89,19 +94,35 @@ pub const Adler32 = struct {
89};94};
9095
91test "adler32 sanity" {96test "adler32 sanity" {
92 testing.expect(Adler32.hash("a") == 0x620062);97 testing.expectEqual(@as(u32, 0x620062), Adler32.hash("a"));
93 testing.expect(Adler32.hash("example") == 0xbc002ed);98 testing.expectEqual(@as(u32, 0xbc002ed), Adler32.hash("example"));
94}99}
95100
96test "adler32 long" {101test "adler32 long" {
97 const long1 = [_]u8{1} ** 1024;102 const long1 = [_]u8{1} ** 1024;
98 testing.expect(Adler32.hash(long1[0..]) == 0x06780401);103 testing.expectEqual(@as(u32, 0x06780401), Adler32.hash(long1[0..]));
99104
100 const long2 = [_]u8{1} ** 1025;105 const long2 = [_]u8{1} ** 1025;
101 testing.expect(Adler32.hash(long2[0..]) == 0x0a7a0402);106 testing.expectEqual(@as(u32, 0x0a7a0402), Adler32.hash(long2[0..]));
102}107}
103108
104test "adler32 very long" {109test "adler32 very long" {
105 const long = [_]u8{1} ** 5553;110 const long = [_]u8{1} ** 5553;
106 testing.expect(Adler32.hash(long[0..]) == 0x707f15b2);111 testing.expectEqual(@as(u32, 0x707f15b2), Adler32.hash(long[0..]));
112}
113
114test "adler32 very long with variation" {
115 const long = comptime blk: {
116 @setEvalBranchQuota(7000);
117 var result: [6000]u8 = undefined;
118
119 var i: usize = 0;
120 while (i < result.len) : (i += 1) {
121 result[i] = @truncate(u8, i);
122 }
123
124 break :blk result;
125 };
126
127 testing.expectEqual(@as(u32, 0x5af38d6e), std.hash.Adler32.hash(long[0..]));
107}128}