#!/usr/bin/env node const djb2a = require('djb2a') const farmhash = require('farmhash') const fnv1a = require('@sindresorhus/fnv1a'); const fs = require('fs') const hex2dec = require('hex2dec') const jenkins2 = require('hash-jenkins'); const jenkins3 = require('jenkins-hash'); const murmurhash = require('murmurhash') const program = require('commander') const sdbm = require('sdbm') const version = require(__dirname + '/../package.json').version const XXHash = require('xxhash') function hashInput(algorithm, input, seed) { switch (algorithm) { case 'djb2a': return djb2a(input) case 'fnv1a': return fnv1a(input) case 'farmhash32': if (seed === undefined || seed === null) { return farmhash.hash32(input) } else { return farmhash.hash32WithSeed(input, seed) } case 'farmhash64': if (seed === undefined || seed === null) { return farmhash.hash64(input) } else { return farmhash.hash64WithSeed(input, seed) } case 'jenkins-oaat': return jenkins2.oaat(input) case 'jenkins-lookup2': if (seed === undefined || seed === null) { seed = 0 } return jenkins2.lookup2(input, seed) case 'jenkins-lookup3': if (seed === undefined || seed === null) { seed = 0 } return jenkins3.hashlittle(input, seed) case 'murmurhash': case 'murmurhash2': if (seed === undefined || seed === null) { return murmurhash.v2(input) } else { return murmurhash.v2(input, seed) } case 'murmurhash3': if (seed === undefined || seed === null) { return murmurhash.v3(input) } else { return murmurhash.v3(input, seed) } case 'sdbm': return sdbm(input) case 'xxhash32': if (seed === undefined || seed === null) { return hex2dec.hexToDec(XXHash.hash(Buffer.from(input, 'binary'), 0, 'hex')) } else { return hex2dec.hexToDec(XXHash.hash(Buffer.from(input, 'binary'), seed, 'hex')) } case 'xxhash64': if (seed === undefined || seed === null) { return hex2dec.hexToDec(XXHash.hash64(Buffer.from(input, 'binary'), 0, 'hex')) } else { return hex2dec.hexToDec(XXHash.hash64(Buffer.from(input, 'binary'), seed, 'hex')) } default: throw new Error(`unknown algorithm: ${algorithm}`) } } function hashAndPrint(algorithm, seed, filename, data) { const hash = hashInput(algorithm, data, seed) const hashHex = hex2dec.decToHex(hash.toString(), {prefix: false}) console.log(`${hashHex} ${filename}`) } program .version(version) .usage('[options]') .option('-a, --algorithm [ALGORITHM]', 'the hash algorithm to use') .option('-s, --seed [SEED]', 'the seed to use (if any)') .parse(process.argv) const algorithm = program.algorithm const seed = program.seed === undefined ? undefined : parseInt(program.seed) if (program.args.length > 0) { program.args.forEach((filename) => { const data = fs.readFileSync(filename, 'binary') hashAndPrint(algorithm, seed, filename, data) }) } else { const stdin = process.stdin const chunks = [] stdin.resume() stdin.setEncoding('binary') stdin.on('data', function (chunk) { chunks.push(chunk) }) stdin.on('end', function () { const data = chunks.join() hashAndPrint(algorithm, seed, '-', data) }) }