Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
130 changes: 92 additions & 38 deletions lib/internal/streams/fast-utf8-stream.js
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,10 @@ class Utf8Stream extends EventEmitter {
#maxWriteRetries = 0;
#writeRetries = 0;
#writingBuf = '';
// In utf8 mode, the bytes of a character that a partial write split and that
// are still to be written. Its leading bytes are already in the destination,
// so these must follow them before anything else is written.
#partialChar = kEmptyBuffer;
#write;
#flush;
#flushSync;
Expand Down Expand Up @@ -246,11 +250,20 @@ class Utf8Stream extends EventEmitter {
this.#flush = (...args) => this.#flushUtf8(...args);
this.#flushSync = (...args) => this.#flushSyncUtf8(...args);
this.#actualWrite = (...args) => this.#actualWriteUtf8(...args);
this.#fsWriteSync = () => this.#fs.writeSync(this.#fd, this.#writingBuf, 'utf8');
this.#fsWriteSync = () => {
if (this.#partialChar.length > 0) {
return this.#fs.writeSync(this.#fd, this.#partialChar);
}
return this.#fs.writeSync(this.#fd, this.#writingBuf, 'utf8');
};
this.#fsWrite = () => {
this.#writeInFlight = true;
try {
this.#fs.write(this.#fd, this.#writingBuf, 'utf8', (err, n) => this.#writeDone(err, n));
if (this.#partialChar.length > 0) {
this.#fs.write(this.#fd, this.#partialChar, (err, n) => this.#writeDone(err, n));
} else {
this.#fs.write(this.#fd, this.#writingBuf, 'utf8', (err, n) => this.#writeDone(err, n));
}
} catch (err) {
this.#writeInFlight = false;
throw err;
Expand Down Expand Up @@ -385,7 +398,7 @@ class Utf8Stream extends EventEmitter {
return;
}

if (this.#len > 0 && this.#fd >= 0) {
if ((this.#len > 0 || this.#partialChar.length > 0) && this.#fd >= 0) {
this.#actualWrite();
} else {
this.#finishEnding();
Expand Down Expand Up @@ -486,9 +499,7 @@ class Utf8Stream extends EventEmitter {
this.#writeRetries = 0;
}

const releasedBufObj = releaseWritingBuf(this.#writingBuf, this.#len, n);
this.#len = releasedBufObj.len;
this.#writingBuf = releasedBufObj.writingBuf;
this.#releaseWritten(n);

// Emit 'write' after the written bytes have been released so that a
// listener calling flushSync() sees a consistent state with no I/O in
Expand All @@ -500,19 +511,16 @@ class Utf8Stream extends EventEmitter {
this.#emittingWrite = false;
}

if (this.#writingBuf.length) {
if (this.#writingBuf.length || this.#partialChar.length) {
if (!this.#sync) {
this.#fsWrite();
return;
}

try {
do {
const n = this.#fsWriteSync();
const releasedBufObj = releaseWritingBuf(this.#writingBuf, this.#len, n);
this.#len = releasedBufObj.len;
this.#writingBuf = releasedBufObj.writingBuf;
} while (this.#writingBuf.length);
this.#releaseWritten(this.#fsWriteSync());
} while (this.#writingBuf.length || this.#partialChar.length);
} catch (err) {
this.#release(err);
return;
Expand Down Expand Up @@ -556,6 +564,22 @@ class Utf8Stream extends EventEmitter {
}
}

/**
* Accounts for the `n` bytes that the last write of #partialChar or
* #writingBuf committed.
* @param {number} n
*/
#releaseWritten(n) {
if (this.#partialChar.length > 0) {
this.#partialChar = this.#partialChar.subarray(n);
return;
}
const releasedBufObj = releaseWritingBuf(this.#writingBuf, this.#len, n);
this.#len = releasedBufObj.len;
this.#writingBuf = releasedBufObj.writingBuf;
this.#partialChar = releasedBufObj.partialChar;
}

#openFile(file) {
this.#opening = true;
this.#writing = true;
Expand Down Expand Up @@ -656,7 +680,7 @@ class Utf8Stream extends EventEmitter {

#finishEnding() {
if (!this.#ending || this.#writing || this.#destroyed) return;
if (this.#len > 0) {
if (this.#len > 0 || this.#partialChar.length > 0) {
this.#actualWrite();
return;
}
Expand Down Expand Up @@ -732,7 +756,8 @@ class Utf8Stream extends EventEmitter {
}

// destroy() may have dropped buffered data or a failed write.
if (this.#ending && !this.#writing && this.#len === 0) {
if (this.#ending && !this.#writing && this.#len === 0 &&
this.#partialChar.length === 0) {
this.emit('finish');
}
this.emit('close');
Expand Down Expand Up @@ -780,7 +805,7 @@ class Utf8Stream extends EventEmitter {

if (this.#sync) {
try {
const written = this.#fs.writeSync(this.#fd, this.#writingBuf, 'utf8');
const written = this.#fsWriteSync();
this.#release(null, written);
} catch (err) {
this.#release(err);
Expand Down Expand Up @@ -838,8 +863,9 @@ class Utf8Stream extends EventEmitter {
this.reopen();
} else if (this.#ending) {
this.#finishEnding();
} else if (this.#len > 0 &&
(this.#len > this.#minLength || this.#flushPending)) {
} else if (this.#partialChar.length > 0 ||
(this.#len > 0 &&
(this.#len > this.#minLength || this.#flushPending))) {
this.#actualWrite();
} else {
this.#emitDrain();
Expand Down Expand Up @@ -915,19 +941,33 @@ class Utf8Stream extends EventEmitter {
this.#writingBuf = '';
}

// The rest of a split character goes out before any queued string. While
// an fs.write() is in flight it is left to that write, like #writingBuf.
let partialChar = kEmptyBuffer;
if (state !== kFlushSyncInFlight) {
partialChar = this.#partialChar;
this.#partialChar = kEmptyBuffer;
}

// The string being written is taken out of #bufs and, if a write throws,
// what is left of it is put back.
let buf = '';
while (this.#bufs.length || buf) {
if (buf.length <= 0) {
buf = this.#bufs[0];
while (this.#bufs.length || buf.length || partialChar.length) {
if (buf.length <= 0 && partialChar.length <= 0) {
buf = this.#bufs.shift();
}
try {
const n = this.#fs.writeSync(this.#fd, buf, 'utf8');
this.#writeRetries = 0;
const releasedBufObj = releaseWritingBuf(buf, this.#len, n);
buf = releasedBufObj.writingBuf;
this.#len = releasedBufObj.len;
if (buf.length <= 0) {
this.#bufs.shift();
if (partialChar.length > 0) {
const n = this.#fs.writeSync(this.#fd, partialChar);
this.#writeRetries = 0;
partialChar = partialChar.subarray(n);
} else {
const n = this.#fs.writeSync(this.#fd, buf, 'utf8');
this.#writeRetries = 0;
const releasedBufObj = releaseWritingBuf(buf, this.#len, n);
buf = releasedBufObj.writingBuf;
this.#len = releasedBufObj.len;
partialChar = releasedBufObj.partialChar;
}
} catch (err) {
const shouldRetry = err.code === 'EAGAIN' || err.code === 'EBUSY';
Expand All @@ -936,6 +976,13 @@ class Utf8Stream extends EventEmitter {
}
const retriesExhausted = this.#maxWriteRetries > 0 && this.#writeRetries > this.#maxWriteRetries;
if (!shouldRetry || retriesExhausted || !this.#retryEAGAIN(err, buf.length, this.#len - buf.length)) {
if (buf.length > 0) {
ArrayPrototypeUnshift(this.#bufs, buf);
}
if (state !== kFlushSyncInFlight) {
// Keep the rest of the character so that a later write completes it.
this.#partialChar = partialChar;
}
throw err;
}

Expand Down Expand Up @@ -1048,7 +1095,8 @@ class Utf8Stream extends EventEmitter {
throw error;
}

if (this.#minLength <= 0 && !this.#writing && this.#len === 0) {
if (this.#minLength <= 0 && !this.#writing && this.#len === 0 &&
this.#partialChar.length === 0) {
cb?.();
return;
}
Expand Down Expand Up @@ -1150,9 +1198,11 @@ class Utf8Stream extends EventEmitter {
* @param {string | Buffer} writingBuf - currently writing buffer, usually be instance._writingBuf.
* @param {number} len - currently buffer length, usually be instance._len.
* @param {number} n - number of bytes fs already written
* @returns {{writingBuf: string | Buffer, len: number}} released writingBuf and length
* @returns {{writingBuf: string | Buffer, len: number, partialChar: Buffer}} released writingBuf
* and length, and the unwritten bytes of the character that the write split, if any
*/
function releaseWritingBuf(writingBuf, len, n) {
let partialChar = kEmptyBuffer;
if (typeof writingBuf === 'string') {
const byteLength = Buffer.byteLength(writingBuf);
// `fs.write` returns the number of bytes written, but `len` is tracked in
Expand All @@ -1162,22 +1212,26 @@ function releaseWritingBuf(writingBuf, len, n) {
// The whole string was written: advance past every character.
n = writingBuf.length;
} else {
// A partial write may split a multi-byte UTF-8 character, so we must back
// up to the start of that character to avoid data corruption.
const buf = Buffer.from(writingBuf);
// Back up from position n to find a valid UTF-8 character boundary.
// UTF-8 continuation bytes have the pattern 10xxxxxx (0x80-0xBF).
// We need to find the start of the character that was split.
while (n > 0 && (buf[n] & 0xC0) === 0x80) {
n--;
// UTF-8 continuation bytes have the pattern 10xxxxxx (0x80-0xBF). If the
// first unwritten byte is one, the write split a multi-byte character.
// Its leading bytes are already in the destination and can't be taken
// back, so writing the character again would duplicate them. Release the
// whole character and hand its unwritten bytes back to the caller.
let end = n;
while (end < byteLength && (buf[end] & 0xC0) === 0x80) {
end++;
}
if (end > n) {
partialChar = buf.subarray(n, end);
}
// Decode the properly-aligned bytes to get the character count.
n = buf.subarray(0, n).toString().length;
n = buf.subarray(0, end).toString().length;
}
}
len = MathMax(len - n, 0);
writingBuf = writingBuf.slice(n);
return { writingBuf, len };
return { writingBuf, len, partialChar };
}

function mergeBuf(bufs, len) {
Expand Down
Loading