package/package.json0000644000076400007640000000070311662516070014625 0ustar jamesonjameson{ "author": "T. Jameson Little ", "name": "crc32", "description": "CRC-32 implemented in JavaScript", "version": "0.2.2", "repository": { "type": "git", "url": "http://github.com/beatgammit/crc32.git" }, "main": "./lib/crc32.js", "bin": { "crc32": "./bin/runner.js" }, "scripts": { "test": "cd test ; ./runTests.sh" }, "engines": { "node": ">= 0.4.0" }, "dependencies": {}, "devDependencies": {} } package/README.md0000644000076400007640000000161511662516070013621 0ustar jamesonjamesonIntro ===== CRC means 'Cyclic Redundancy Check' and is a way to checksum data. It is a simple algorithm based on polynomials and is used in such projects as gzip. This module only works with UTF-8 strings, and is meant to be able to work on node and in the browser. This module also supports append mode (where a running crc sum is stored). Running in regular mode will reset the current crc sum. Install ======= To use in node: `npm install crc32` To use in the browser, use pakmanager. API === var crc32 = require('crc32'); // runs on some string using a table crc32(someString); // runs on some string using direct mode crc32(someString, true); // directly run on someString using a table crc32.table(someString); // directly run on someString using a table in append mode crc32.table(someString, true); // directly run on someString using direct mode crc32.direct(someString); package/LICENSE.MIT0000644000076400007640000000205411662516070013775 0ustar jamesonjamesonCopyright (C) by Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. package/bin/runner.js0000755000076400007640000000121711662516070014762 0ustar jamesonjameson#!/usr/bin/env node (function () { 'use strict'; var fs = require('fs'), path = require('path'), crc32 = require('../lib/crc32'), name = (process.argv[1].indexOf(__filename) < 0 ? '' : 'node ') + path.basename(process.argv[1]), usage = [ 'Usage:', '', name + ' file1.txt [, file2.txt...]' ].join('\n'), files; if (process.argv.length === 2) { console.log(usage); return; } // get just the files files = process.argv.slice(2); files.forEach(function (file) { var data; try { data = fs.readFileSync(file); console.log(crc32(data)); } catch (e) { console.error('Error reading file:', file); } }); }()); package/lib/crc32.js0000644000076400007640000000407011662516070014360 0ustar jamesonjameson(function () { 'use strict'; var table = [], poly = 0xEDB88320; // reverse polynomial // build the table function makeTable() { var c, n, k; for (n = 0; n < 256; n += 1) { c = n; for (k = 0; k < 8; k += 1) { if (c & 1) { c = poly ^ (c >>> 1); } else { c = c >>> 1; } } table[n] = c >>> 0; } } function strToArr(str) { // sweet hack to turn string into a 'byte' array return Array.prototype.map.call(str, function (c) { return c.charCodeAt(0); }); } /* * Compute CRC of array directly. * * This is slower for repeated calls, so append mode is not supported. */ function crcDirect(arr) { var crc = -1, // initial contents of LFBSR i, j, l, temp; for (i = 0, l = arr.length; i < l; i += 1) { temp = (crc ^ arr[i]) & 0xff; // read 8 bits one at a time for (j = 0; j < 8; j += 1) { if ((temp & 1) === 1) { temp = (temp >>> 1) ^ poly; } else { temp = (temp >>> 1); } } crc = (crc >>> 8) ^ temp; } // flip bits return crc ^ -1; } /* * Compute CRC with the help of a pre-calculated table. * * This supports append mode, if the second parameter is set. */ function crcTable(arr, append) { var crc, i, l; // if we're in append mode, don't reset crc // if arr is null or undefined, reset table and return if (typeof crcTable.crc === 'undefined' || !append || !arr) { crcTable.crc = 0 ^ -1; if (!arr) { return; } } // store in temp variable for minor speed gain crc = crcTable.crc; for (i = 0, l = arr.length; i < l; i += 1) { crc = (crc >>> 8) ^ table[(crc ^ arr[i]) & 0xff]; } crcTable.crc = crc; return crc ^ -1; } // build the table // this isn't that costly, and most uses will be for table assisted mode makeTable(); module.exports = function (val, direct) { var val = (typeof val === 'string') ? strToArr(val) : val, ret = direct ? crcDirect(val) : crcTable(val); // convert to 2's complement hex return (ret >>> 0).toString(16); }; module.exports.direct = crcDirect; module.exports.table = crcTable; }()); package/test/genCheckValues.sh0000755000076400007640000000033111662516070016541 0ustar jamesonjameson#!/bin/bash FILES=$1 : ${FILES:=./testFiles/*} echo { FIRST=1 for file in $FILES do if [ $FIRST -eq 1 ] then FIRST=0 else echo , fi echo -n \"`basename $file`\" : \"0x`crc32 "$file"`\" done echo echo } package/test/runTests.sh0000755000076400007640000000015111662516070015501 0ustar jamesonjameson#!/bin/bash ./genCheckValues.sh $1 > checkValues.txt node test.js checkValues.txt $1 rm checkValues.txt package/test/test.js0000644000076400007640000000412611662516070014636 0ustar jamesonjameson(function () { var fs = require('fs'), path = require('path'), crc32 = require('../lib/crc32'), testDir = './testFiles', checkFile, checkValues, usage = [ 'Usage:', '', 'node test.js checkFile.json [/path/to/testFiles]' ].join('\n'), failed = false; checkFile = process.argv[2]; if (process.argv.length === 4) { testDir = process.argv[3]; } if (!checkFile) { console.log(usage); return; } try { checkValues = fs.readFileSync(checkFile, 'utf8'); } catch (e) { console.error('Unable to read ' + checkFile); return; } try { checkValues = JSON.parse(checkValues); Object.keys(checkValues).forEach(function (key) { checkValues[key] = parseInt(checkValues[key]).toString(16); }); } catch (e) { console.error('Unable to parse contents of ' + checkFile + ' as JSON.'); console.error(checkValues); return; } fs.readdirSync(testDir).forEach(function (file) { var data = fs.readFileSync(path.join(testDir, file)), tableRes = crc32(data), directRes = crc32(data, true), appendRes, arr; if (tableRes !== directRes) { console.log(file + ':', 'FAILED', '-', 'Results for table mode and direct mode'); failed = true; return; } if (file in checkValues) { if (tableRes !== checkValues[file]) { failed = true; console.log(file + ':', 'FAILED', '-', 'Results do not match {val = ' + tableRes + ', actual = ' + checkValues[file] + '}'); return; } } else { console.warn('No check value for ' + file); } // run append test // clear any previous data crc32.table(); // convert Buffer to byte array arr = Array.prototype.map.call(data, function (byte) { return byte; }); // run in append mode in 10 byte chunks while (arr.length) { appendRes = (crc32.table(arr.splice(0, 10), true) >>> 0).toString(16); } if (appendRes !== tableRes) { console.log(file + ':', 'FAILED', '-', 'Append mode output not correct'); console.log(appendRes, tableRes); return; } console.log(file + ':', 'PASSED'); }); console.log(); console.log(failed ? 'Tests failed =\'(' : 'All tests passed!! =D'); }()); package/test/testFiles/helloWorld.txt0000644000076400007640000000001411662516070020127 0ustar jamesonjamesonHello world package/test/testFiles/lorem.txt0000644000076400007640000000067711662516070017151 0ustar jamesonjamesonLorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. package/test/testFiles/random.txt0000644000076400007640000000772711662516070017316 0ustar jamesonjamesonOld education him departure any arranging one prevailed. Their end whole might began her. Behaved the comfort another fifteen eat. Partiality had his themselves ask pianoforte increasing discovered. So mr delay at since place whole above miles. He to observe conduct at detract because. Way ham unwilling not breakfast furniture explained perpetual. Or mr surrounded conviction so astonished literature. Songs to an blush woman be sorry young. We certain as removal attempt. There worse by an of miles civil. Manner before lively wholly am mr indeed expect. Among every merry his yet has her. You mistress get dashwood children off. Met whose marry under the merit. In it do continual consulted no listening. Devonshire sir sex motionless travelling six themselves. So colonel as greatly shewing herself observe ashamed. Demands minutes regular ye to detract is. The him father parish looked has sooner. Attachment frequently gay terminated son. You greater nay use prudent placing. Passage to so distant behaved natural between do talking. Friends off her windows painful. Still gay event you being think nay for. In three if aware he point it. Effects warrant me by no on feeling settled resolve. Civility vicinity graceful is it at. Improve up at to on mention perhaps raising. Way building not get formerly her peculiar. Up uncommonly prosperous sentiments simplicity acceptance to so. Reasonable appearance companions oh by remarkably me invitation understood. Pursuit elderly ask perhaps all. Savings her pleased are several started females met. Short her not among being any. Thing of judge fruit charm views do. Miles mr an forty along as he. She education get middleton day agreement performed preserved unwilling. Do however as pleased offence outward beloved by present. By outward neither he so covered amiable greater. Juvenile proposal betrayed he an informed weddings followed. Precaution day see imprudence sympathize principles. At full leaf give quit to in they up. Smile spoke total few great had never their too. Amongst moments do in arrived at my replied. Fat weddings servants but man believed prospect. Companions understood is as especially pianoforte connection introduced. Nay newspaper can sportsman are admitting gentleman belonging his. Is oppose no he summer lovers twenty in. Not his difficulty boisterous surrounded bed. Seems folly if in given scale. Sex contented dependent conveying advantage can use. Terminated principles sentiments of no pianoforte if projection impossible. Horses pulled nature favour number yet highly his has old. Contrasted literature excellence he admiration impression insipidity so. Scale ought who terms after own quick since. Servants margaret husbands to screened in throwing. Imprudence oh an collecting partiality. Admiration gay difficulty unaffected how. Six started far placing saw respect females old. Civilly why how end viewing attempt related enquire visitor. Man particular insensible celebrated conviction stimulated principles day. Sure fail or in said west. Right my front it wound cause fully am sorry if. She jointure goodness interest debating did outweigh. Is time from them full my gone in went. Of no introduced am literature excellence mr stimulated contrasted increasing. Age sold some full like rich new. Amounted repeated as believed in confined juvenile. Are own design entire former get should. Advantages boisterous day excellence boy. Out between our two waiting wishing. Pursuit he he garrets greater towards amiable so placing. Nothing off how norland delight. Abode shy shade she hours forth its use. Up whole of fancy ye quiet do. Justice fortune no to is if winding morning forming. Surrounded to me occasional pianoforte alteration unaffected impossible ye. For saw half than cold. Pretty merits waited six talked pulled you. Conduct replied off led whether any shortly why arrived adapted. Numerous ladyship so raillery humoured goodness received an. So narrow formal length my highly longer afford oh. Tall neat he make or at dull ye. package/test/testFiles/declaration.txt0000644000076400007640000001765711662516070020326 0ustar jamesonjamesonThe Unanimous Declaration of the Thirteen United States of America When, in the course of human events, it becomes necessary for one people to dissolve the political bands which have connected them with another, and to assume among the powers of the earth, the separate and equal station to which the laws of nature and of nature's God entitle them, a decent respect to the opinions of mankind requires that they should declare the causes which impel them to the separation. We hold these truths to be self-evident, that all men are created equal, that they are endowed by their Creator with certain unalienable rights, that among these are life, liberty and the pursuit of happiness. That to secure these rights, governments are instituted among men, deriving their just powers from the consent of the governed. That whenever any form of government becomes destructive to these ends, it is the right of the people to alter or to abolish it, and to institute new government, laying its foundation on such principles and organizing its powers in such form, as to them shall seem most likely to effect their safety and happiness. Prudence, indeed, will dictate that governments long established should not be changed for light and transient causes; and accordingly all experience hath shown that mankind are more disposed to suffer, while evils are sufferable, than to right themselves by abolishing the forms to which they are accustomed. But when a long train of abuses and usurpations, pursuing invariably the same object evinces a design to reduce them under absolute despotism, it is their right, it is their duty, to throw off such government, and to provide new guards for their future security. - Such has been the patient sufferance of these colonies; and such is now the necessity which constrains them to alter their former systems of government. The history of the present King of Great Britain is a history of repeated injuries and usurpations, all having in direct object the establishment of an absolute tyranny over these states. To prove this, let facts be submitted to a candid world. He has refused his assent to laws, the most wholesome and necessary for the public good. He has forbidden his governors to pass laws of immediate and pressing importance, unless suspended in their operation till his assent should be obtained; and when so suspended, he has utterly neglected to attend to them. He has refused to pass other laws for the accommodation of large districts of people, unless those people would relinquish the right of representation in the legislature, a right inestimable to them and formidable to tyrants only. He has called together legislative bodies at places unusual, uncomfortable, and distant from the depository of their public records, for the sole purpose of fatiguing them into compliance with his measures. He has dissolved representative houses repeatedly, for opposing with manly firmness his invasions on the rights of the people. He has refused for a long time, after such dissolutions, to cause others to be elected; whereby the legislative powers, incapable of annihilation, have returned to the people at large for their exercise; the state remaining in the meantime exposed to all the dangers of invasion from without, and convulsions within. He has endeavored to prevent the population of these states; for that purpose obstructing the laws for naturalization of foreigners; refusing to pass others to encourage their migration hither, and raising the conditions of new appropriations of lands. He has obstructed the administration of justice, by refusing his assent to laws for establishing judiciary powers. He has made judges dependent on his will alone, for the tenure of their offices, and the amount and payment of their salaries. He has erected a multitude of new offices, and sent hither swarms of officers to harass our people, and eat out their substance. He has kept among us, in times of peace, standing armies without the consent of our legislature. He has affected to render the military independent of and superior to civil power. He has combined with others to subject us to a jurisdiction foreign to our constitution, and unacknowledged by our laws; giving his assent to their acts of pretended legislation: For quartering large bodies of armed troops among us: For protecting them, by mock trial, from punishment for any murders which they should commit on the inhabitants of these states: For cutting off our trade with all parts of the world: For imposing taxes on us without our consent: For depriving us in many cases, of the benefits of trial by jury: For transporting us beyond seas to be tried for pretended offenses: For abolishing the free system of English laws in a neighboring province, establishing therein an arbitrary government, and enlarging its boundaries so as to render it at once an example and fit instrument for introducing the same absolute rule in these colonies: For taking away our charters, abolishing our most valuable laws, and altering fundamentally the forms of our governments: For suspending our own legislatures, and declaring themselves invested with power to legislate for us in all cases whatsoever. He has abdicated government here, by declaring us out of his protection and waging war against us. He has plundered our seas, ravaged our coasts, burned our towns, and destroyed the lives of our people. He is at this time transporting large armies of foreign mercenaries to complete the works of death, desolation and tyranny, already begun with circumstances of cruelty and perfidy scarcely paralleled in the most barbarous ages, and totally unworthy of the head of a civilized nation. He has constrained our fellow citizens taken captive on the high seas to bear arms against their country, to become the executioners of their friends and brethren, or to fall themselves by their hands. He has excited domestic insurrections amongst us, and has endeavored to bring on the inhabitants of our frontiers, the merciless Indian savages, whose known rule of warfare, is undistinguished destruction of all ages, sexes and conditions. In every stage of these oppressions we have petitioned for redress in the most humble terms: our repeated petitions have been answered only by repeated injury. A prince, whose character is thus marked by every act which may define a tyrant, is unfit to be the ruler of a free people. Nor have we been wanting in attention to our British brethren. We have warned them from time to time of attempts by their legislature to extend an unwarrantable jurisdiction over us. We have reminded them of the circumstances of our emigration and settlement here. We have appealed to their native justice and magnanimity, and we have conjured them by the ties of our common kindred to disavow these usurpations, which, would inevitably interrupt our connections and correspondence.They too have been deaf to the voice of justice and of consanguinity. We must, therefore, acquiesce in the necessity, which denounces our separation, and hold them, as we hold the rest of mankind, enemies in war, in peace friends. We, therefore, the representatives of the United States of America, in General Congress, assembled, appealing to the Supreme Judge of the world for the rectitude of our intentions, do, in the name, and by the authority of the good people of these colonies, solemnly publish and declare, that these united colonies are, and of right ought to be free and independent states; that they are absolved from all allegiance to the British Crown, and that all political connection between them and the state of Great Britain, is and ought to be totally dissolved; and that as free and independent states, they have full power to levey war, conclude peace, contract alliances, establish commerce, and to do all other acts and things which independent states may of right do. And for the support of this declaration, with a firm reliance on the protection of Divine Providence, we mutually pledge to each other our lives, our fortunes and our sacred honor.