Skip to content

Commit 085941a

Browse files
araujoguiaduh95
authored andcommitted
src: write strings to streams without flattening
StreamBase::WriteString() created a String::ValueView twice, the first time in StringBytes::StorageSize() only to read the length. A ValueView flattens the string, so writing a string built by concatenation, such as the header of an HTTP response, allocated a flat copy on the V8 heap before copying it again into the write buffer. Read the length from the string in StorageSize(), and copy one-byte strings that fit the stack buffer with String::WriteOneByte(), which does not flatten. For UTF-8 the characters go to the last third of the buffer and are converted into the rest of it: a Latin-1 character takes at most two bytes. Assisted-by: Claude Signed-off-by: Guilherme Araújo <arauujogui@gmail.com> PR-URL: #67435 Reviewed-By: James M Snell <jasnell@gmail.com> Reviewed-By: Philipp Dunkel <pip@pipobscure.com>
1 parent bfded15 commit 085941a

4 files changed

Lines changed: 170 additions & 24 deletions

File tree

‎src/stream_base.cc‎

Lines changed: 40 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
#include "node_buffer.h"
99
#include "node_errors.h"
1010
#include "node_external_reference.h"
11+
#include "simdutf.h"
1112
#include "string_bytes.h"
1213
#include "util-inl.h"
1314
#include "v8.h"
@@ -196,6 +197,38 @@ int StreamBase::FinishWrite(const v8::FunctionCallbackInfo<v8::Value>& args,
196197
return res.err;
197198
}
198199

200+
namespace {
201+
202+
// Same as StringBytes::Write(), but copies one-byte strings out with
203+
// String::WriteOneByte(), which does not flatten them: strings written to a
204+
// stream are often built by concatenation (e.g. HTTP headers) and not used
205+
// again.
206+
size_t WriteStringWithoutFlattening(Isolate* isolate,
207+
char* buf,
208+
size_t buflen,
209+
Local<String> string,
210+
enum encoding enc) {
211+
const size_t length = string->Length();
212+
if (length == 0) return 0;
213+
if (string->IsOneByte()) {
214+
if ((enc == ASCII || enc == LATIN1) && buflen >= length) {
215+
string->WriteOneByte(isolate, 0, length, reinterpret_cast<uint8_t*>(buf));
216+
return length;
217+
}
218+
if (enc == UTF8 && buflen >= 3 * length) {
219+
// Latin-1 takes at most 2 UTF-8 bytes per char: convert from the last
220+
// third into the first two.
221+
char* latin1 = buf + 2 * length;
222+
string->WriteOneByte(
223+
isolate, 0, length, reinterpret_cast<uint8_t*>(latin1));
224+
return simdutf::convert_latin1_to_utf8(latin1, length, buf);
225+
}
226+
}
227+
return StringBytes::Write(isolate, buf, buflen, string, enc);
228+
}
229+
230+
} // namespace
231+
199232
int StreamBase::Writev(const FunctionCallbackInfo<Value>& args) {
200233
Environment* env = Environment::GetCurrent(args);
201234
Isolate* isolate = env->isolate();
@@ -297,11 +330,8 @@ int StreamBase::Writev(const FunctionCallbackInfo<Value>& args) {
297330
if (!chunks->Get(context, i * 2 + 1).ToLocal(&next_chunk))
298331
return -1;
299332
enum encoding encoding = ParseEncoding(isolate, next_chunk);
300-
str_size = StringBytes::Write(isolate,
301-
str_storage,
302-
str_size,
303-
string,
304-
encoding);
333+
str_size = WriteStringWithoutFlattening(
334+
isolate, str_storage, str_size, string, encoding);
305335
bufs[i].base = str_storage;
306336
bufs[i].len = str_size;
307337
offset += str_size;
@@ -372,7 +402,7 @@ int StreamBase::WriteString(const FunctionCallbackInfo<Value>& args) {
372402
if (args[2]->IsObject())
373403
send_handle_obj = args[2].As<Object>();
374404

375-
// Compute the size of the storage that the string will be flattened into.
405+
// Compute the size of the storage that the string will be written into.
376406
// For UTF8 strings that are very long, go ahead and take the hit for
377407
// computing their actual size, rather than tripling the storage.
378408
size_t storage_size;
@@ -395,11 +425,8 @@ int StreamBase::WriteString(const FunctionCallbackInfo<Value>& args) {
395425
bool try_write = HasDoTryWrite() && storage_size <= sizeof(stack_storage) &&
396426
(!IsIPCPipe() || send_handle_obj.IsEmpty());
397427
if (try_write) {
398-
data_size = StringBytes::Write(isolate,
399-
stack_storage,
400-
storage_size,
401-
string,
402-
enc);
428+
data_size = WriteStringWithoutFlattening(
429+
isolate, stack_storage, storage_size, string, enc);
403430
buf = uv_buf_init(stack_storage, data_size);
404431

405432
uv_buf_t* bufs = &buf;
@@ -433,11 +460,8 @@ int StreamBase::WriteString(const FunctionCallbackInfo<Value>& args) {
433460
// Write it
434461
bs = ArrayBuffer::NewBackingStore(
435462
isolate, storage_size, BackingStoreInitializationMode::kUninitialized);
436-
data_size = StringBytes::Write(isolate,
437-
static_cast<char*>(bs->Data()),
438-
storage_size,
439-
string,
440-
enc);
463+
data_size = WriteStringWithoutFlattening(
464+
isolate, static_cast<char*>(bs->Data()), storage_size, string, enc);
441465
}
442466

443467
CHECK_LE(data_size, storage_size);

‎src/string_bytes.cc‎

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -468,38 +468,38 @@ Maybe<size_t> StringBytes::StorageSize(Isolate* isolate,
468468
Local<String> str;
469469
if (!val->ToString(isolate->GetCurrentContext()).ToLocal(&str))
470470
return Nothing<size_t>();
471-
String::ValueView view(isolate, str);
471+
const size_t length = str->Length();
472472
size_t data_size = 0;
473473

474474
switch (encoding) {
475475
case ASCII:
476476
case LATIN1:
477-
data_size = view.length();
477+
data_size = length;
478478
break;
479479

480480
case BUFFER:
481481
case UTF8:
482482
// A single UCS2 codepoint never takes up more than 3 utf8 bytes.
483483
// It is an exercise for the caller to decide when a string is
484484
// long enough to justify calling Size() instead of StorageSize()
485-
data_size = 3 * view.length();
485+
data_size = 3 * length;
486486
break;
487487

488488
case UCS2:
489-
data_size = view.length() * sizeof(uint16_t);
489+
data_size = length * sizeof(uint16_t);
490490
break;
491491

492492
case BASE64URL:
493-
data_size = simdutf::base64_length_from_binary(view.length(),
494-
simdutf::base64_url);
493+
data_size =
494+
simdutf::base64_length_from_binary(length, simdutf::base64_url);
495495
break;
496496

497497
case BASE64:
498-
data_size = simdutf::base64_length_from_binary(view.length());
498+
data_size = simdutf::base64_length_from_binary(length);
499499
break;
500500

501501
case HEX:
502-
data_size = view.length() / 2;
502+
data_size = length / 2;
503503
break;
504504

505505
default:
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
'use strict';
2+
const common = require('../common');
3+
const assert = require('assert');
4+
const net = require('net');
5+
6+
// Writes concatenated strings around the size limits of the stack buffer used
7+
// by StreamBase::WriteString() and checks the bytes on the wire.
8+
9+
function concat(length, base) {
10+
let str = '';
11+
for (let i = 0; i < length; i++)
12+
str += String.fromCharCode(base + i % 16);
13+
return str;
14+
}
15+
16+
const cases = [];
17+
for (const length of [0, 13, 5461, 5462, 16384, 16385]) {
18+
// ASCII, non-ASCII Latin-1, two-byte.
19+
for (const base of [0x61, 0xe0, 0x2000]) {
20+
for (const encoding of ['utf8', 'latin1', 'ascii']) {
21+
cases.push({ length, base, encoding });
22+
}
23+
}
24+
}
25+
26+
const expected = [];
27+
28+
const server = net.createServer(common.mustCall((socket) => {
29+
const chunks = [];
30+
socket.on('data', (chunk) => chunks.push(chunk));
31+
socket.on('end', common.mustCall(() => {
32+
const actual = Buffer.concat(chunks);
33+
let offset = 0;
34+
for (const [i, buf] of expected.entries()) {
35+
const { length, base, encoding } = cases[i];
36+
assert.deepStrictEqual(
37+
actual.subarray(offset, offset + buf.length),
38+
buf,
39+
`length ${length}, base 0x${base.toString(16)}, ${encoding}`);
40+
offset += buf.length;
41+
}
42+
assert.strictEqual(offset, actual.length);
43+
server.close();
44+
}));
45+
}));
46+
47+
server.listen(0, common.mustCall(() => {
48+
const socket = net.connect(server.address().port);
49+
let i = 0;
50+
function next() {
51+
if (i === cases.length) return socket.end();
52+
const { length, base, encoding } = cases[i++];
53+
const str = concat(length, base);
54+
// Each write waits for the previous one so that it goes through
55+
// WriteString() and not Writev().
56+
socket.write(str, encoding, common.mustSucceed(next));
57+
expected.push(Buffer.from(str, encoding));
58+
}
59+
socket.on('connect', common.mustCall(next));
60+
}));
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
'use strict';
2+
const common = require('../common');
3+
const assert = require('assert');
4+
const net = require('net');
5+
6+
// Writes concatenated strings with a Buffer after each of them in a single
7+
// StreamBase::Writev() call, like an HTTP response header followed by a Buffer
8+
// body, and checks the bytes on the wire.
9+
10+
function concat(length, base) {
11+
let str = '';
12+
for (let i = 0; i < length; i++)
13+
str += String.fromCharCode(base + i % 16);
14+
return str;
15+
}
16+
17+
const separator = Buffer.from('|');
18+
const writes = [];
19+
// Writev() reserves 3 bytes per character for UTF-8 strings of up to 65535
20+
// characters and the exact size for longer ones.
21+
for (const length of [0, 13, 5461, 16385, 65535, 65536]) {
22+
// ASCII, non-ASCII Latin-1, two-byte.
23+
for (const base of [0x61, 0xe0, 0x2000]) {
24+
for (const encoding of ['utf8', 'latin1', 'ascii']) {
25+
writes.push({
26+
label: `length ${length}, base 0x${base.toString(16)}, ${encoding}`,
27+
str: concat(length, base),
28+
encoding,
29+
});
30+
}
31+
}
32+
}
33+
34+
const server = net.createServer(common.mustCall((socket) => {
35+
const chunks = [];
36+
socket.on('data', (chunk) => chunks.push(chunk));
37+
socket.on('end', common.mustCall(() => {
38+
const actual = Buffer.concat(chunks);
39+
let offset = 0;
40+
for (const { label, str, encoding } of writes) {
41+
const expected = Buffer.concat([Buffer.from(str, encoding), separator]);
42+
assert.deepStrictEqual(
43+
actual.subarray(offset, offset + expected.length), expected, label);
44+
offset += expected.length;
45+
}
46+
assert.strictEqual(offset, actual.length);
47+
server.close();
48+
}));
49+
}));
50+
51+
server.listen(0, common.mustCall(() => {
52+
const socket = net.connect(server.address().port, common.mustCall(() => {
53+
// Corked writes are flushed together with Writev().
54+
socket.cork();
55+
for (const { str, encoding } of writes) {
56+
socket.write(str, encoding);
57+
socket.write(separator);
58+
}
59+
socket.uncork();
60+
socket.end();
61+
}));
62+
}));

0 commit comments

Comments
 (0)