Skip to content

Commit

Permalink
simplify/fix utf8 text splitting (#171)
Browse files Browse the repository at this point in the history
  • Loading branch information
davehorton authored May 9, 2024
1 parent d4a8ca5 commit 8a59477
Showing 1 changed file with 10 additions and 13 deletions.
23 changes: 10 additions & 13 deletions lib/wire-protocol.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,30 +10,27 @@ const DEFAULT_PING_INTERVAL = 15000;
const MIN_PING_INTERVAL = 5000;
const MAX_PING_INTERVAL = 300000;

const containsEmoji = (str) => {
const regex = /[\uD800-\uDBFF][\uDC00-\uDFFF]/;
return regex.test(str);
};

const countSymbols = (text) => {
return containsEmoji(text) ? [...text].length : text.length;
};

const parseMessageLengthSpecifier = (str) => {
let start = -1;
for (let i = 0; i < 5; i++) {
if (start === -1 && (str[i] === ' ' || str[i] == '\n' || str[i] === '\r')) {
continue;
}
if (start === -1) start = i;
const x = str[i];
if (i > 0 && x === '#') {
return {
numChars: i,
len: parseInt(str.slice(0, i))
len: parseInt(str.slice(start, i))
};
}
if (x < '0' || x > '9') return;
}
return str[5] === '#' ?
{
numChars: 5,
len: parseInt(str.slice(0, 5))
len: parseInt(str.slice(start, 5))
} : undefined;
};

Expand Down Expand Up @@ -298,7 +295,7 @@ module.exports = class WireProtocol extends Emitter {
if (arr) {
length = parseInt(arr[1]);
start = arr[1].length + 1;
haveMsg = countSymbols(obj.incomingMsg) >= length + start;
haveMsg = [...obj.incomingMsg].length >= length + start;
}
else haveMsg = false;
} while (haveMsg);
Expand All @@ -322,7 +319,7 @@ module.exports = class WireProtocol extends Emitter {
// check if we have a full message to process
const {numChars, len} = parseMessageLengthSpecifier(obj.incomingMsg) || {};
if (len) {
if (countSymbols(obj.incomingMsg) >= len + numChars + 1) {
if ([...obj.incomingMsg].length >= len + numChars + 1) {
this.processMessageBuffer(socket, obj, len, numChars + 1);
}
return;
Expand All @@ -332,7 +329,7 @@ module.exports = class WireProtocol extends Emitter {
return;
}

const err = new Error(`invalid message from server, did not start with length specifier: ${obj.incomingMsg}`);
const err = new Error(`invalid message, missing length specifier: '${obj.incomingMsg}'`);
if (this.isServer) {
console.error(`invalid client message, closing socket: ${err}`);
this.disconnect(socket);
Expand Down

0 comments on commit 8a59477

Please sign in to comment.