-
Notifications
You must be signed in to change notification settings - Fork 1
/
utils.js
63 lines (54 loc) · 1.63 KB
/
utils.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
'use strict';
let sleep = ms => new Promise(r => setTimeout(r, ms));
let waitFor = async function waitFor(f) {
while (!f()) await sleep(100 + Math.random() * 25);
return f();
};
let waitForTimeout = async function waitFor(f, timeoutSec) {
var totalTimeMs = 0;
while (!f() && totalTimeMs < timeoutSec * 1000) {
var delayMs = 100 + Math.random() * 25;
totalTimeMs += delayMs;
await sleep(delayMs);
}
return f();
};
/**
* Helper function to convert a value into an enum value
*
* @param {type} enumtype
* @param {number} enumvalue
*/
function Parse(enumtype, enumvalue) {
for (var enumName in enumtype) {
if (enumtype[enumName] == enumvalue) {
/*jshint -W061 */
return eval([enumtype + "." + enumName]);
}
}
return null;
}
/**
* Helper function to dump arraybuffer as hex string
* @param {ArrayBuffer} buffer
*/
function buf2hex(buffer) { // buffer is an ArrayBuffer
return [...new Uint8Array(buffer)]
.map(x => x.toString(16).padStart(2, '0'))
.join(' ');
}
function hex2buf (input) {
if (typeof input !== 'string') {
throw new TypeError('Expected input to be a string')
}
var hexstr = input.replace(/\s+/g, '');
if ((hexstr.length % 2) !== 0) {
throw new RangeError('Expected string to be an even number of characters')
}
const view = new Uint8Array(hexstr.length / 2)
for (let i = 0; i < hexstr.length; i += 2) {
view[i / 2] = parseInt(hexstr.substring(i, i + 2), 16)
}
return view.buffer
}
module.exports = { sleep, waitFor, waitForTimeout, Parse, buf2hex, hex2buf };