Improved performance for our adler32 implementation

This commit is contained in:
Jim
2015-07-20 18:50:05 -07:00
parent c73f95292c
commit 57e9e5bf23
2 changed files with 65 additions and 7 deletions
@@ -0,0 +1,41 @@
/**
* Copyright 2014-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @emails react-core
*/
'use strict';
var adler32 = require('adler32');
describe('shallowEqual', function() {
it('generates differing checksums', function() {
expect(adler32('foo')).not.toBe(adler32('bar'));
});
it('generates consistent checksums', function() {
expect(adler32('linux')).toBe(adler32('linux'));
});
it('is case sensitive', function() {
expect(adler32('a')).not.toBe(adler32('A'));
});
it('doesn\'t barf on large inputs', function() {
var str = '';
for (var i = 0; i < 100000; i++) {
str = str + 'This will be repeated to be very large indeed. ';
}
expect(adler32(str)).toBe(692898118);
});
it('doesn\'t barf on international inputs', function() {
var str = 'Linux 是一個真棒操作系統!';
expect(adler32(str)).toBe(-1183804097);
});
});
+24 -7
View File
@@ -13,17 +13,34 @@
var MOD = 65521;
// This is a clean-room implementation of adler32 designed for detecting
// if markup is not what we expect it to be. It does not need to be
// cryptographically strong, only reasonably good at detecting if markup
// generated on the server is different than that on the client.
// adler32 is not cryptographically strong, and is only used to sanity check that
// markup generated on the server matches the markup generated on the client.
// This implementation (a modified version of the SheetJS version) has been optimized
// for our use case, at the expense of conforming to the adler32 specification
// for non-ascii inputs.
function adler32(data) {
var a = 1;
var b = 0;
for (var i = 0; i < data.length; i++) {
a = (a + data.charCodeAt(i)) % MOD;
b = (b + a) % MOD;
var i = 0;
var l = data.length;
var m = l & ~0x3;
while (i < m) {
for (; i < Math.min(i + 4096, m); i += 4) {
b += (
(a += data.charCodeAt(i)) +
(a += data.charCodeAt(i + 1)) +
(a += data.charCodeAt(i + 2)) +
(a += data.charCodeAt(i + 3))
);
}
a %= MOD;
b %= MOD;
}
for (; i < l; i++) {
b += (a += data.charCodeAt(i));
}
a %= MOD;
b %= MOD;
return a | (b << 16);
}