Permalink
Browse files

[crc32] ensure results are always unsigned

With longer inputs, previous crc-32 can give signed (negative) results,
which are incorrect. This patch shifts the result right-wise, filling in
the left with zeros, to ensure the result is unsigned (unlike the C++
implementation, JS lacks a standard unsigned type).

I used OS X's "cksum -o3" command to get the expected CRC-32 output for
the test file.
  • Loading branch information...
1 parent b21d53b commit 8c8aa2724d7a7623af7352571625abcb4c61635b @alunny committed Sep 14, 2012
Showing with 37 additions and 3 deletions.
  1. +2 −2 lib/crc.js
  2. +17 −1 test/crc.js
  3. +18 −0 test/index.html
View
@@ -326,7 +326,7 @@
for(i = 0; i < len; i++)
crc = crc32Add(crc, str.charCodeAt(i));
- return crc^0xFFFFFFFF;
+ return (crc^0xFFFFFFFF) >>> 0;
};
function crc32Buffer(buf)
@@ -338,7 +338,7 @@
crc = crc32Add(crc, buf[i]);
}
- return crc ^ 0xFFFFFFFF;
+ return (crc ^ 0xFFFFFFFF) >>> 0;
}
/**
View
@@ -1,6 +1,8 @@
#!/usr/bin/env ./nodeunit/bin/nodeunit
-var crc = require('../lib/crc');
+var crc = require('../lib/crc'),
+ fs = require('fs'),
+ format = require('util').format;
describe('crc8()', function(){
it('should work with strings', function(){
@@ -27,9 +29,23 @@ describe('crc32()', function(){
crc.crc32('hello world').should.equal(222957957);
})
+ it('should work with bigger strings', function(){
+ var path = format("%s/index.html", __dirname),
+ fileContents = fs.readFileSync(path, 'utf-8');
+
+ crc.crc32(fileContents).should.equal(3026001449);
+ });
+
it('should work with Buffers', function(){
crc.buffer.crc32(new Buffer('hello world')).should.equal(222957957);
})
+
+ it('should work with bigger Buffers', function(){
+ var path = format("%s/index.html", __dirname),
+ fileContents = fs.readFileSync(path);
+
+ crc.buffer.crc32(fileContents).should.equal(3026001449);
+ });
})
describe('crcArc()', function(){
View
@@ -0,0 +1,18 @@
+<html>
+ <head></head>
+ <body>
+ <h1>Child Browser Demo</h1>
+
+ <a onClick="launchBrowser()" href="#">What does it do?</a>
+
+ </body>
+ <script src="phonegap.js"></script>
+ <script src="childbrowser.js"></script>
+ <script>
+ var url = 'http://www.youtube.com/watch?v=R4vpXS5BKyc'
+ function launchBrowser() {
+ window.plugins.childBrowser.showWebPage(url,
+ { showLocationBar: true });
+ }
+ </script>
+</html>

0 comments on commit 8c8aa27

Please sign in to comment.