Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

stream: ensure text() stream consumer flushes correctly #39737

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
3 changes: 3 additions & 0 deletions lib/stream/consumers.js
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,9 @@ async function text(stream) {
else
str += dec.decode(chunk, { stream: true });
}
// Flush the streaming TextDecoder so that any pending
// incomplete multibyte characters are handled.
str += dec.decode(undefined, { stream: false });
return str;
}

Expand Down
17 changes: 15 additions & 2 deletions src/node_i18n.cc
Original file line number Diff line number Diff line change
Expand Up @@ -442,11 +442,24 @@ void ConverterObject::Decode(const FunctionCallbackInfo<Value>& args) {
UErrorCode status = U_ZERO_ERROR;
MaybeStackBuffer<UChar> result;
MaybeLocal<Object> ret;
size_t limit = converter->min_char_size() * input.length();

UBool flush = (flags & CONVERTER_FLAGS_FLUSH) == CONVERTER_FLAGS_FLUSH;

// When flushing the final chunk, the limit is the maximum
// of either the input buffer length or the number of pending
// characters times the min char size.
size_t limit = converter->min_char_size() *
(!flush ?
input.length() :
std::max(
input.length(),
static_cast<size_t>(
ucnv_toUCountPending(converter->conv(), &status))));
status = U_ZERO_ERROR;

if (limit > 0)
result.AllocateSufficientStorage(limit);

UBool flush = (flags & CONVERTER_FLAGS_FLUSH) == CONVERTER_FLAGS_FLUSH;
auto cleanup = OnScopeLeave([&]() {
if (flush) {
// Reset the converter state.
Expand Down
14 changes: 14 additions & 0 deletions test/parallel/test-stream-consumers.js
Original file line number Diff line number Diff line change
Expand Up @@ -232,3 +232,17 @@ const kArrayBuffer =
stream.write({});
stream.end({});
}

{
const stream = new TransformStream();
text(stream.readable).then(common.mustCall((str) => {
// Incomplete utf8 character is flushed as a replacement char
assert.strictEqual(str.charCodeAt(0), 0xfffd);
}));
const writer = stream.writable.getWriter();
Promise.all([
writer.write(new Uint8Array([0xe2])),
writer.write(new Uint8Array([0x82])),
writer.close(),
]).then(common.mustCall());
}