Last active
October 16, 2021 11:37
-
-
Save junderw/4933a1725a214a19025a3e3b2cab1e16 to your computer and use it in GitHub Desktop.
This is very bad. Don't do this. but hey... if no one's looking... ;-)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Mimics Buffer.from(x, 'hex') logic | |
// Stops on first non-hex string and returns | |
// https://github.com/nodejs/node/blob/v14.18.1/src/string_bytes.cc#L246-L261 | |
Uint8Array.fromHex = function (hexString) { | |
const MAP_HEX = {0:0,1:1,2:2,3:3,4:4,5:5,6:6,7:7,8:8,9:9,a:10,b:11,c:12,d:13,e:14,f:15,A:10,B:11,C:12,D:13,E:14,F:15}; | |
const bytes = new this(Math.floor((hexString || "").length / 2)); | |
let finalLen = bytes.length; | |
for (let i = 0; i < finalLen; i++) { | |
const a = MAP_HEX[hexString[i * 2]]; | |
const b = MAP_HEX[hexString[i * 2 + 1]]; | |
if (a === undefined || b === undefined) { | |
finalLen = i; | |
break; | |
} | |
bytes[i] = (a << 4) | b; | |
} | |
return finalLen === bytes.length ? bytes : bytes.slice(0, finalLen); | |
}; | |
Uint8Array.prototype.toHex = function () { | |
const HEX_STRINGS = "0123456789abcdef"; | |
return Array.from(this) | |
.map((b) => HEX_STRINGS[b >> 4] + HEX_STRINGS[b & 15]) | |
.join(""); | |
}; | |
Uint8Array.prototype.compare = function (v2) { | |
const minLength = Math.min(this.length, v2.length); | |
for (let i = 0; i < minLength; ++i) { | |
if (this[i] !== v2[i]) { | |
return this[i] < v2[i] ? -1 : 1; | |
} | |
} | |
return this.length === v2.length ? 0 : this.length > v2.length ? 1 : -1; | |
}; | |
Uint8Array.prototype.equals = function (v2) { | |
return this.compare(v2) === 0; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment