WebSocket-Node
WebSocket-Node copied to clipboard
pure JS alternative for validation.cc ?
Hi,
just out of curiosity: would it be possible to replace validation.cc by:
module.exports.Validation = {
isValidUTF8: function(buf) {
return buf.compare(Buffer.from(buff.toString())) === 0;
}
};
or if that takes to many cycles:
function utf8CheckByte(byte) {
if (byte <= 0x7f) return 0;
else if (byte >> 5 === 0x06) return 2;
else if (byte >> 4 === 0x0e) return 3;
else if (byte >> 3 === 0x1e) return 4;
return byte >> 6 === 0x02 ? -1 : -2;
}
module.exports.Validation = {
isValidUTF8: function(buf) {
let i = 0;
while (i < buf.length) {
let nb = utf8CheckByte(buf[i++]);
if (nb < 0 || i + nb > buf.length) return false;
if (nb > 0) {
for (let j = 1; j < nb; j++) {
let cb = utf8CheckByte(buf[i++]);
if (cb != -1) return false;
}
}
}
return true;
}
};
Where the utf8CheckByte() function is borrowed from nodejs string_decoder.js
Kind regards, Hans