forked from anandsuresh/sse4_crc32
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
62 lines (55 loc) · 1.47 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
/**
* @file Provides hardware-based CRC-32C calculation with software fallback
*
* @author Anand Suresh <anand.suresh@gmail.com>
* @copyright Copyright (C) 2018-present Anand Suresh. All rights reserved.
* @license MIT
*/
const Crc32C = require('bindings')('crc32c')
const stream = require('stream')
const util = require('util')
/**
* Calculates the CRC32C for a stream
*
* @param {Number} [crc] The initial CRC, if any
* @constructor
*/
function Crc32CStream (crc) {
if (!(this instanceof Crc32CStream)) {
return new Crc32CStream(crc)
}
if (crc == null) {
this.crc = 0
} else if (typeof crc !== 'number') {
throw new TypeError(`crc MUST be a number; got ${typeof crc}`)
} else {
this.crc = crc
}
Crc32CStream.super_.call(this, {
write: function (chunk, encoding, next) {
var err
try {
this.crc = module.exports.calculate(chunk, this.crc)
} catch (e) {
err = e
} finally {
next(err, chunk)
}
}
})
}
util.inherits(Crc32CStream, stream.Writable)
/**
* Export the interface
* @type {Object}
*/
module.exports = {
fromStream: function (stream, crc) { return stream.pipe(new Crc32CStream(crc)) },
calculate: Crc32C.hardware_support ? Crc32C.sse42_crc : Crc32C.table_crc
}
// for debugging/benchmarks
if (process.NODE_ENV !== 'production') {
module.exports.hardware_support = Crc32C.hardware_support
module.exports.sse42_crc = Crc32C.sse42_crc
module.exports.table_crc = Crc32C.table_crc
}