-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathindex.js
73 lines (66 loc) · 1.99 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
63
64
65
66
67
68
69
70
71
72
73
var bufferFactory = require('buffer-factory');
// eslint-disable-next-line import/no-unresolved
var crc16Native = require('./build/Release/crc16.node');
var parseParam = function (input, encoding, option) {
encoding = encoding || 'hex';
if (typeof encoding === 'object') {
option = encoding;
encoding = 'hex';
}
option = option || {};
var buf = (function () {
if (typeof input === 'string') {
try {
input = bufferFactory.create(input, encoding);
} catch (e) {
console.trace(e);
return null;
}
}
if (Buffer.isBuffer(input) && input.length > 0 && input.byteLength > 0) {
return input;
}
return null;
}());
if (buf === null) {
throw new TypeError(`crc16.${arguments.callee.caller.name} input param invalid!`);
}
return { buf, option };
};
var crc16 = {
/**
* checkSum
* @param input string | buffer
* @param encoding string 'hex' default
* @param option object
* @example checkSum('301a', 'hex')
* @example checkSum('301a')
* @example checkSum(Buffer.from('301a', 'hex'))
* @example checkSum('301a', {retType: 'int'}) default retType is hex
* @return
* hex string when option.retType == 'hex'
* array when option.retType == 'array'
* unsigned short int when option.retType == 'int'
* Buffer when option.retType == 'buffer'
*/
checkSum(input, encoding, option) {
var param = parseParam(input, encoding, option);
var sum = crc16Native.checkSum(param.buf, param.option);
return sum;
},
/**
* verifySum
* @param input string | buffer
* @param encoding string 'hex' default
* @param option object
* @example verifySum('301a947b', 'hex')
* @example verifySum('301a947b')
* @example checkSum(Buffer.from('301a947b', 'hex'))
* @return return bool true | false
*/
verifySum(input, encoding, option) {
var param = parseParam(input, encoding, option);
return crc16Native.verifySum(param.buf, param.option);
},
};
module.exports = crc16;