-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathcrc64_ecma182.js
102 lines (82 loc) · 2.6 KB
/
crc64_ecma182.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
/**
* Kaidi ZHU <[email protected]> created at 2017-09-07 16:02:19 with ❤
*
* Copyright (c) 2017 Souche.com, all rights reserved.
*/
'use strict';
const fs = require('fs');
const binding = require('./dist/crc');
const raw = {
crc64: binding.cwrap('crc64', 'null', [ 'number', 'number', 'number' ]),
crc64Init: binding.cwrap('crc64_init', 'null', []),
strToUint64Ptr: binding.cwrap('str_to_uint64', 'null', [ 'number', 'number' ]),
uint64PtrToStr: binding.cwrap('uint64_to_str', 'null', [ 'number', 'number' ])
};
raw.crc64Init();
function strToUint64Ptr(str) {
const strPtr = binding._malloc(str.length + 1);
binding.stringToUTF8(str, strPtr, str.length + 1);
const uint64Ptr = binding._malloc(8);
raw.strToUint64Ptr(strPtr, uint64Ptr);
binding._free(strPtr);
return uint64Ptr;
}
function uint64PtrToStr(uint64Ptr) {
const strPtr = binding._malloc(32);
raw.uint64PtrToStr(strPtr, uint64Ptr);
const str = binding.UTF8ToString(strPtr);
binding._free(strPtr);
return str;
}
function buffToPtr(buff) {
if(typeof buff === 'string') {
buff = new Buffer(buff);
} else if(!Buffer.isBuffer(buff)) {
throw new Error('Invalid buffer type.');
}
const buffPtr = binding._malloc(buff.length);
binding.writeArrayToMemory(buff, buffPtr);
return buffPtr;
}
module.exports.crc64 = function(buff, prev) {
if(!prev) prev = '0';
if(typeof prev !== 'string' || !/\d+/.test(prev)) {
throw new Error('Invlid previous value.');
}
const prevPtr = strToUint64Ptr(prev);
const buffPtr = buffToPtr(buff);
raw.crc64(prevPtr, buffPtr, buff.length);
const ret = uint64PtrToStr(prevPtr);
binding._free(prevPtr);
binding._free(buffPtr);
return ret;
};
module.exports.crc64File = function(filename, callback) {
let errored = false;
const stream = fs.createReadStream(filename);
const crcPtr = strToUint64Ptr('0');
let crcPtrFreed = false;
stream.on('error', function(err) {
errored = true;
stream.destroy();
if(!crcPtrFreed) {
binding._free(crcPtr);
crcPtrFreed = true;
}
return callback(err);
});
stream.on('data', function(chunk) {
const buffPtr = buffToPtr(chunk);
raw.crc64(crcPtr, buffPtr, chunk.length);
binding._free(buffPtr);
});
stream.on('end', function() {
if(errored) return;
const ret = uint64PtrToStr(crcPtr);
if(!crcPtrFreed) {
binding._free(crcPtr);
crcPtrFreed = true;
}
return callback(undefined, ret);
});
};