MCPcopy Create free account
hub / github.com/nodejs/node / releaseWritingBuf

Function releaseWritingBuf

lib/internal/streams/fast-utf8-stream.js:878–904  ·  view source on GitHub ↗

* Release the writingBuf after fs.write n bytes data * @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, len, n)

Source from the content-addressed store, hash-verified

876 * @returns {{writingBuf: string | Buffer, len: number}} released writingBuf and length
877 */
878function releaseWritingBuf(writingBuf, len, n) {
879 if (typeof writingBuf === 'string') {
880 const byteLength = Buffer.byteLength(writingBuf);
881 // `fs.write` returns the number of bytes written, but `len` is tracked in
882 // characters and `writingBuf` is sliced by character index below, so `n`
883 // must be converted from bytes to characters in both cases.
884 if (byteLength === n) {
885 // The whole string was written: advance past every character.
886 n = writingBuf.length;
887 } else {
888 // A partial write may split a multi-byte UTF-8 character, so we must back
889 // up to the start of that character to avoid data corruption.
890 const buf = Buffer.from(writingBuf);
891 // Back up from position n to find a valid UTF-8 character boundary.
892 // UTF-8 continuation bytes have the pattern 10xxxxxx (0x80-0xBF).
893 // We need to find the start of the character that was split.
894 while (n > 0 && (buf[n] & 0xC0) === 0x80) {
895 n--;
896 }
897 // Decode the properly-aligned bytes to get the character count.
898 n = buf.subarray(0, n).toString().length;
899 }
900 }
901 len = MathMax(len - n, 0);
902 writingBuf = writingBuf.slice(n);
903 return { writingBuf, len };
904}
905
906function mergeBuf(bufs, len) {
907 if (bufs.length === 0) {

Callers 2

#releaseMethod · 0.85
#flushSyncUtf8Method · 0.85

Calls 3

sliceMethod · 0.65
fromMethod · 0.45
toStringMethod · 0.45

Tested by

no test coverage detected