Commit b57b51e

Browse files
Renegade334aduh95
authored andcommitted
stream: minor stream/iter implementation edits
Signed-off-by: Renegade334 <contact.9a5d6388@renegade334.me.uk> PR-URL: #63132 Backport-PR-URL: #64675 Reviewed-By: James M Snell <jasnell@gmail.com> Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
1 parent 274b3a2 commit b57b51e

5 files changed

Lines changed: 63 additions & 47 deletions

File tree

β€Žlib/internal/streams/iter/classic.jsβ€Ž

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313

1414
const{
1515
ArrayIsArray,
16+
ArrayPrototypePush,
1617
MathMax,
1718
NumberMAX_SAFE_INTEGER,
1819
Promise,
@@ -107,14 +108,14 @@ async function normalizeBatch(raw) {
107108
for(leti=0;i<raw.length;i++){
108109
constvalue=raw[i];
109110
if(isUint8Array(value)){
110-
batch.push(value);
111+
ArrayPrototypePush(batch,value);
111112
}else{
112113
// normalizeAsyncValue may await for async protocols (e.g.
113114
// toAsyncStreamable on yielded objects). Stream events during
114115
// the suspension are queued, not lost -- errors will surface
115116
// on the next loop iteration after this yield completes.
116117
forawait(constnormalizedofnormalizeAsyncValue(value)){
117-
batch.push(normalized);
118+
ArrayPrototypePush(batch,normalized);
118119
}
119120
}
120121
}
@@ -163,7 +164,7 @@ async function* createBatchedAsyncIterator(stream, normalize) {
163164
stream._readableState?.length>0){
164165
constc=stream.read();
165166
if(c===null)break;
166-
batch.push(c);
167+
ArrayPrototypePush(batch,c);
167168
}
168169
if(normalize!==null){
169170
constresult=awaitnormalize(batch);
@@ -495,7 +496,7 @@ function fromWritable(writable, options = kNullPrototype) {
495496

496497
functionwaitForDrain(){
497498
const{ promise, resolve, reject }=PromiseWithResolvers();
498-
waiters.push({__proto__: null, resolve, reject });
499+
ArrayPrototypePush(waiters,{__proto__: null, resolve, reject });
499500
installListeners();
500501
returnpromise;
501502
}
@@ -686,7 +687,7 @@ function fromWritable(writable, options = kNullPrototype) {
686687
returnPromiseResolve(true);
687688
}
688689
const{ promise, resolve }=PromiseWithResolvers();
689-
waiters.push({
690+
ArrayPrototypePush(waiters,{
690691
__proto__: null,
691692
resolve(){resolve(true);},
692693
reject(){resolve(false);},

β€Žlib/internal/streams/iter/consumers.jsβ€Ž

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ const {
1212
ArrayBufferPrototypeSlice,
1313
ArrayPrototypeMap,
1414
ArrayPrototypePush,
15+
ArrayPrototypeShift,
1516
ArrayPrototypeSlice,
1617
Promise,
1718
PromisePrototypeThen,
@@ -477,7 +478,7 @@ function merge(...args) {
477478

478479
// Drain ready queue synchronously
479480
while(ready.length>0){
480-
constitem=ready.shift();
481+
constitem=ArrayPrototypeShift(ready);
481482
if(item?.error){
482483
throwitem.error;
483484
}

β€Žlib/internal/streams/iter/from.jsβ€Ž

Lines changed: 13 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -31,8 +31,8 @@ const {
3131

3232
const{
3333
isAnyArrayBuffer,
34-
isDataView,
3534
isPromise,
35+
isTypedArray,
3636
isUint8Array,
3737
}=require('internal/util/types');
3838

@@ -106,17 +106,21 @@ function primitiveToUint8Array(chunk) {
106106
returnchunk;
107107
}
108108
// Other ArrayBufferView types (Int8Array, DataView, etc.)
109-
if(isDataView(chunk)){
109+
returnarrayBufferViewToUint8Array(chunk);
110+
}
111+
112+
functionarrayBufferViewToUint8Array(chunk){
113+
if(isTypedArray(chunk)){
110114
returnnewUint8Array(
111-
DataViewPrototypeGetBuffer(chunk),
112-
DataViewPrototypeGetByteOffset(chunk),
113-
DataViewPrototypeGetByteLength(chunk),
115+
TypedArrayPrototypeGetBuffer(chunk),
116+
TypedArrayPrototypeGetByteOffset(chunk),
117+
TypedArrayPrototypeGetByteLength(chunk),
114118
);
115119
}
116120
returnnewUint8Array(
117-
TypedArrayPrototypeGetBuffer(chunk),
118-
TypedArrayPrototypeGetByteOffset(chunk),
119-
TypedArrayPrototypeGetByteLength(chunk),
121+
DataViewPrototypeGetBuffer(chunk),
122+
DataViewPrototypeGetByteOffset(chunk),
123+
DataViewPrototypeGetByteLength(chunk),
120124
);
121125
}
122126

@@ -580,6 +584,7 @@ function from(input) {
580584
// =============================================================================
581585

582586
module.exports={
587+
arrayBufferViewToUint8Array,
583588
from,
584589
fromSync,
585590
isAsyncIterable,

β€Žlib/internal/streams/iter/pull.jsβ€Ž

Lines changed: 15 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -33,9 +33,9 @@ const {
3333
const{ AbortController }=require('internal/abort_controller');
3434

3535
const{
36+
arrayBufferViewToUint8Array,
3637
from,
3738
fromSync,
38-
primitiveToUint8Array,
3939
isSyncIterable,
4040
isAsyncIterable,
4141
isUint8ArrayBatch,
@@ -136,7 +136,7 @@ function* flattenTransformYieldSync(value) {
136136
return;
137137
}
138138
if(ArrayBufferIsView(value)){
139-
yieldprimitiveToUint8Array(value);
139+
yieldarrayBufferViewToUint8Array(value);
140140
return;
141141
}
142142
// Must be Iterable<TransformYield>
@@ -170,7 +170,7 @@ async function* flattenTransformYieldAsync(value) {
170170
return;
171171
}
172172
if(ArrayBufferIsView(value)){
173-
yieldprimitiveToUint8Array(value);
173+
yieldarrayBufferViewToUint8Array(value);
174174
return;
175175
}
176176
// Check for async iterable first
@@ -180,10 +180,10 @@ async function* flattenTransformYieldAsync(value) {
180180
}
181181
return;
182182
}
183-
// Must be sync Iterable<TransformYield>
183+
// Must be sync Iterable<TransformYield>, no nested async iterables
184184
if(isSyncIterable(value)){
185185
for(constitemofvalue){
186-
yield*flattenTransformYieldAsync(item);
186+
yield*flattenTransformYieldSync(item);
187187
}
188188
return;
189189
}
@@ -218,7 +218,7 @@ function* processTransformResultSync(result) {
218218
return;
219219
}
220220
if(ArrayBufferIsView(result)){
221-
yield[primitiveToUint8Array(result)];
221+
yield[arrayBufferViewToUint8Array(result)];
222222
return;
223223
}
224224
// Uint8Array[] batch
@@ -278,7 +278,7 @@ async function* processTransformResultAsync(result) {
278278
return;
279279
}
280280
if(ArrayBufferIsView(result)){
281-
yield[primitiveToUint8Array(result)];
281+
yield[arrayBufferViewToUint8Array(result)];
282282
return;
283283
}
284284
// Uint8Array[] batch
@@ -313,7 +313,9 @@ async function* processTransformResultAsync(result) {
313313
ArrayPrototypePush(batch,item);
314314
continue;
315315
}
316-
forawait(constchunkofflattenTransformYieldAsync(item)){
316+
// Note: This iteration is synchronous, since async iterables
317+
// may not be nested within sync iterables.
318+
for(constchunkofflattenTransformYieldSync(item)){
317319
ArrayPrototypePush(batch,chunk);
318320
}
319321
}
@@ -366,7 +368,7 @@ function* applyFusedStatelessSyncTransforms(source, run) {
366368
}elseif(isAnyArrayBuffer(current)){
367369
yield[newUint8Array(current)];
368370
}elseif(ArrayBufferIsView(current)){
369-
yield[primitiveToUint8Array(current)];
371+
yield[arrayBufferViewToUint8Array(current)];
370372
}else{
371373
yield*processTransformResultSync(current);
372374
}
@@ -428,7 +430,7 @@ function* createSyncPipeline(source, transforms) {
428430
}
429431
current=applyStatefulSyncTransform(current,transform.transform);
430432
}else{
431-
statelessRun.push(transform);
433+
ArrayPrototypePush(statelessRun,transform);
432434
}
433435
}
434436
if(statelessRun.length>0){
@@ -490,7 +492,7 @@ async function* applyFusedStatelessAsyncTransforms(source, run, signal) {
490492
}elseif(isAnyArrayBuffer(current)){
491493
yield[newUint8Array(current)];
492494
}elseif(ArrayBufferIsView(current)){
493-
yield[primitiveToUint8Array(current)];
495+
yield[arrayBufferViewToUint8Array(current)];
494496
}else{
495497
yield*processTransformResultAsync(current);
496498
}
@@ -531,9 +533,7 @@ async function* applyFusedStatelessAsyncTransforms(source, run, signal) {
531533
* @yields {Uint8Array[]}
532534
*/
533535
asyncfunction*withFlushAsync(source){
534-
forawait(constbatchofsource){
535-
yieldbatch;
536-
}
536+
yield*source;
537537
yieldnull;
538538
}
539539

@@ -647,7 +647,7 @@ async function* createAsyncPipeline(source, transforms, signal) {
647647
current,transform.transform,opts);
648648
}
649649
}else{
650-
statelessRun.push(transform);
650+
ArrayPrototypePush(statelessRun,transform);
651651
}
652652
}
653653
// Flush remaining stateless run

β€Žlib/internal/streams/iter/utils.jsβ€Ž

Lines changed: 27 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ const {
1212
TypedArrayPrototypeGetBuffer,
1313
TypedArrayPrototypeGetByteLength,
1414
TypedArrayPrototypeGetByteOffset,
15+
TypedArrayPrototypeSet,
1516
Uint8Array,
1617
}=primordials;
1718

@@ -24,8 +25,6 @@ const {
2425
}=require('internal/errors');
2526
const{ isError }=require('internal/util');
2627

27-
const{ Buffer }=require('buffer');
28-
2928
const{ isSharedArrayBuffer, isUint8Array }=require('internal/util/types');
3029

3130
const{ validateOneOf }=require('internal/validators');
@@ -127,26 +126,36 @@ function concatBytes(chunks) {
127126
if(chunks.length===0){
128127
returnnewUint8Array(0);
129128
}
130-
// Single chunk: return directly if it covers the entire backing buffer
129+
// Single chunk: return directly if it covers the entire backing buffer,
130+
// otherwise return a copy
131131
if(chunks.length===1){
132132
constchunk=chunks[0];
133-
constbuf=TypedArrayPrototypeGetBuffer(chunk);
134-
// SharedArrayBuffer is not available in primordials, so use
135-
// direct property access for its byteLength.
136-
constbufByteLength=isSharedArrayBuffer(buf) ?
137-
buf.byteLength :
138-
ArrayBufferPrototypeGetByteLength(buf);
139-
if(TypedArrayPrototypeGetByteOffset(chunk)===0&&
140-
TypedArrayPrototypeGetByteLength(chunk)===bufByteLength){
141-
returnchunk;
133+
// If non-zero offset, skip the remaining buffer checks.
134+
if(TypedArrayPrototypeGetByteOffset(chunk)===0){
135+
constbuf=TypedArrayPrototypeGetBuffer(chunk);
136+
// SharedArrayBuffer is not available in primordials, so use
137+
// direct property access for its byteLength.
138+
constbufByteLength=isSharedArrayBuffer(buf) ?
139+
buf.byteLength :
140+
ArrayBufferPrototypeGetByteLength(buf);
141+
if(TypedArrayPrototypeGetByteLength(chunk)===bufByteLength){
142+
returnchunk;
143+
}
142144
}
145+
returnnewUint8Array(chunk);
146+
}
147+
// Multiple chunks: concatenate
148+
lettotalByteLength=0;
149+
for(leti=0;i<chunks.length;i++){
150+
totalByteLength+=TypedArrayPrototypeGetByteLength(chunks[i]);
151+
}
152+
constconcatenated=newUint8Array(totalByteLength);
153+
letoffset=0;
154+
for(leti=0;i<chunks.length;i++){
155+
TypedArrayPrototypeSet(concatenated,chunks[i],offset);
156+
offset+=TypedArrayPrototypeGetByteLength(chunks[i]);
143157
}
144-
// Multiple chunks or shared buffer: concatenate
145-
constbuf=Buffer.concat(chunks);
146-
returnnewUint8Array(
147-
TypedArrayPrototypeGetBuffer(buf),
148-
TypedArrayPrototypeGetByteOffset(buf),
149-
TypedArrayPrototypeGetByteLength(buf));
158+
returnconcatenated;
150159
}
151160

152161
/**

0 commit comments

Comments
Β (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content

Commit b57b51e

Browse files
Renegade334aduh95
authored andcommitted
stream: minor stream/iter implementation edits
Signed-off-by: Renegade334 <contact.9a5d6388@renegade334.me.uk> PR-URL: #63132 Backport-PR-URL: #64675 Reviewed-By: James M Snell <jasnell@gmail.com> Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
1 parent 274b3a2 commit b57b51e

5 files changed

Lines changed: 63 additions & 47 deletions

File tree

β€Žlib/internal/streams/iter/classic.jsβ€Ž

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313

1414
const{
1515
ArrayIsArray,
16+
ArrayPrototypePush,
1617
MathMax,
1718
NumberMAX_SAFE_INTEGER,
1819
Promise,
@@ -107,14 +108,14 @@ async function normalizeBatch(raw) {
107108
for(leti=0;i<raw.length;i++){
108109
constvalue=raw[i];
109110
if(isUint8Array(value)){
110-
batch.push(value);
111+
ArrayPrototypePush(batch,value);
111112
}else{
112113
// normalizeAsyncValue may await for async protocols (e.g.
113114
// toAsyncStreamable on yielded objects). Stream events during
114115
// the suspension are queued, not lost -- errors will surface
115116
// on the next loop iteration after this yield completes.
116117
forawait(constnormalizedofnormalizeAsyncValue(value)){
117-
batch.push(normalized);
118+
ArrayPrototypePush(batch,normalized);
118119
}
119120
}
120121
}
@@ -163,7 +164,7 @@ async function* createBatchedAsyncIterator(stream, normalize) {
163164
stream._readableState?.length>0){
164165
constc=stream.read();
165166
if(c===null)break;
166-
batch.push(c);
167+
ArrayPrototypePush(batch,c);
167168
}
168169
if(normalize!==null){
169170
constresult=awaitnormalize(batch);
@@ -495,7 +496,7 @@ function fromWritable(writable, options = kNullPrototype) {
495496

496497
functionwaitForDrain(){
497498
const{ promise, resolve, reject }=PromiseWithResolvers();
498-
waiters.push({__proto__: null, resolve, reject });
499+
ArrayPrototypePush(waiters,{__proto__: null, resolve, reject });
499500
installListeners();
500501
returnpromise;
501502
}
@@ -686,7 +687,7 @@ function fromWritable(writable, options = kNullPrototype) {
686687
returnPromiseResolve(true);
687688
}
688689
const{ promise, resolve }=PromiseWithResolvers();
689-
waiters.push({
690+
ArrayPrototypePush(waiters,{
690691
__proto__: null,
691692
resolve(){resolve(true);},
692693
reject(){resolve(false);},

β€Žlib/internal/streams/iter/consumers.jsβ€Ž

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ const {
1212
ArrayBufferPrototypeSlice,
1313
ArrayPrototypeMap,
1414
ArrayPrototypePush,
15+
ArrayPrototypeShift,
1516
ArrayPrototypeSlice,
1617
Promise,
1718
PromisePrototypeThen,
@@ -477,7 +478,7 @@ function merge(...args) {
477478

478479
// Drain ready queue synchronously
479480
while(ready.length>0){
480-
constitem=ready.shift();
481+
constitem=ArrayPrototypeShift(ready);
481482
if(item?.error){
482483
throwitem.error;
483484
}

β€Žlib/internal/streams/iter/from.jsβ€Ž

Lines changed: 13 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -31,8 +31,8 @@ const {
3131

3232
const{
3333
isAnyArrayBuffer,
34-
isDataView,
3534
isPromise,
35+
isTypedArray,
3636
isUint8Array,
3737
}=require('internal/util/types');
3838

@@ -106,17 +106,21 @@ function primitiveToUint8Array(chunk) {
106106
returnchunk;
107107
}
108108
// Other ArrayBufferView types (Int8Array, DataView, etc.)
109-
if(isDataView(chunk)){
109+
returnarrayBufferViewToUint8Array(chunk);
110+
}
111+
112+
functionarrayBufferViewToUint8Array(chunk){
113+
if(isTypedArray(chunk)){
110114
returnnewUint8Array(
111-
DataViewPrototypeGetBuffer(chunk),
112-
DataViewPrototypeGetByteOffset(chunk),
113-
DataViewPrototypeGetByteLength(chunk),
115+
TypedArrayPrototypeGetBuffer(chunk),
116+
TypedArrayPrototypeGetByteOffset(chunk),
117+
TypedArrayPrototypeGetByteLength(chunk),
114118
);
115119
}
116120
returnnewUint8Array(
117-
TypedArrayPrototypeGetBuffer(chunk),
118-
TypedArrayPrototypeGetByteOffset(chunk),
119-
TypedArrayPrototypeGetByteLength(chunk),
121+
DataViewPrototypeGetBuffer(chunk),
122+
DataViewPrototypeGetByteOffset(chunk),
123+
DataViewPrototypeGetByteLength(chunk),
120124
);
121125
}
122126

@@ -580,6 +584,7 @@ function from(input) {
580584
// =============================================================================
581585

582586
module.exports={
587+
arrayBufferViewToUint8Array,
583588
from,
584589
fromSync,
585590
isAsyncIterable,

β€Žlib/internal/streams/iter/pull.jsβ€Ž

Lines changed: 15 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -33,9 +33,9 @@ const {
3333
const{ AbortController }=require('internal/abort_controller');
3434

3535
const{
36+
arrayBufferViewToUint8Array,
3637
from,
3738
fromSync,
38-
primitiveToUint8Array,
3939
isSyncIterable,
4040
isAsyncIterable,
4141
isUint8ArrayBatch,
@@ -136,7 +136,7 @@ function* flattenTransformYieldSync(value) {
136136
return;
137137
}
138138
if(ArrayBufferIsView(value)){
139-
yieldprimitiveToUint8Array(value);
139+
yieldarrayBufferViewToUint8Array(value);
140140
return;
141141
}
142142
// Must be Iterable<TransformYield>
@@ -170,7 +170,7 @@ async function* flattenTransformYieldAsync(value) {
170170
return;
171171
}
172172
if(ArrayBufferIsView(value)){
173-
yieldprimitiveToUint8Array(value);
173+
yieldarrayBufferViewToUint8Array(value);
174174
return;
175175
}
176176
// Check for async iterable first
@@ -180,10 +180,10 @@ async function* flattenTransformYieldAsync(value) {
180180
}
181181
return;
182182
}
183-
// Must be sync Iterable<TransformYield>
183+
// Must be sync Iterable<TransformYield>, no nested async iterables
184184
if(isSyncIterable(value)){
185185
for(constitemofvalue){
186-
yield*flattenTransformYieldAsync(item);
186+
yield*flattenTransformYieldSync(item);
187187
}
188188
return;
189189
}
@@ -218,7 +218,7 @@ function* processTransformResultSync(result) {
218218
return;
219219
}
220220
if(ArrayBufferIsView(result)){
221-
yield[primitiveToUint8Array(result)];
221+
yield[arrayBufferViewToUint8Array(result)];
222222
return;
223223
}
224224
// Uint8Array[] batch
@@ -278,7 +278,7 @@ async function* processTransformResultAsync(result) {
278278
return;
279279
}
280280
if(ArrayBufferIsView(result)){
281-
yield[primitiveToUint8Array(result)];
281+
yield[arrayBufferViewToUint8Array(result)];
282282
return;
283283
}
284284
// Uint8Array[] batch
@@ -313,7 +313,9 @@ async function* processTransformResultAsync(result) {
313313
ArrayPrototypePush(batch,item);
314314
continue;
315315
}
316-
forawait(constchunkofflattenTransformYieldAsync(item)){
316+
// Note: This iteration is synchronous, since async iterables
317+
// may not be nested within sync iterables.
318+
for(constchunkofflattenTransformYieldSync(item)){
317319
ArrayPrototypePush(batch,chunk);
318320
}
319321
}
@@ -366,7 +368,7 @@ function* applyFusedStatelessSyncTransforms(source, run) {
366368
}elseif(isAnyArrayBuffer(current)){
367369
yield[newUint8Array(current)];
368370
}elseif(ArrayBufferIsView(current)){
369-
yield[primitiveToUint8Array(current)];
371+
yield[arrayBufferViewToUint8Array(current)];
370372
}else{
371373
yield*processTransformResultSync(current);
372374
}
@@ -428,7 +430,7 @@ function* createSyncPipeline(source, transforms) {
428430
}
429431
current=applyStatefulSyncTransform(current,transform.transform);
430432
}else{
431-
statelessRun.push(transform);
433+
ArrayPrototypePush(statelessRun,transform);
432434
}
433435
}
434436
if(statelessRun.length>0){
@@ -490,7 +492,7 @@ async function* applyFusedStatelessAsyncTransforms(source, run, signal) {
490492
}elseif(isAnyArrayBuffer(current)){
491493
yield[newUint8Array(current)];
492494
}elseif(ArrayBufferIsView(current)){
493-
yield[primitiveToUint8Array(current)];
495+
yield[arrayBufferViewToUint8Array(current)];
494496
}else{
495497
yield*processTransformResultAsync(current);
496498
}
@@ -531,9 +533,7 @@ async function* applyFusedStatelessAsyncTransforms(source, run, signal) {
531533
* @yields {Uint8Array[]}
532534
*/
533535
asyncfunction*withFlushAsync(source){
534-
forawait(constbatchofsource){
535-
yieldbatch;
536-
}
536+
yield*source;
537537
yieldnull;
538538
}
539539

@@ -647,7 +647,7 @@ async function* createAsyncPipeline(source, transforms, signal) {
647647
current,transform.transform,opts);
648648
}
649649
}else{
650-
statelessRun.push(transform);
650+
ArrayPrototypePush(statelessRun,transform);
651651
}
652652
}
653653
// Flush remaining stateless run

β€Žlib/internal/streams/iter/utils.jsβ€Ž

Lines changed: 27 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ const {
1212
TypedArrayPrototypeGetBuffer,
1313
TypedArrayPrototypeGetByteLength,
1414
TypedArrayPrototypeGetByteOffset,
15+
TypedArrayPrototypeSet,
1516
Uint8Array,
1617
}=primordials;
1718

@@ -24,8 +25,6 @@ const {
2425
}=require('internal/errors');
2526
const{ isError }=require('internal/util');
2627

27-
const{ Buffer }=require('buffer');
28-
2928
const{ isSharedArrayBuffer, isUint8Array }=require('internal/util/types');
3029

3130
const{ validateOneOf }=require('internal/validators');
@@ -127,26 +126,36 @@ function concatBytes(chunks) {
127126
if(chunks.length===0){
128127
returnnewUint8Array(0);
129128
}
130-
// Single chunk: return directly if it covers the entire backing buffer
129+
// Single chunk: return directly if it covers the entire backing buffer,
130+
// otherwise return a copy
131131
if(chunks.length===1){
132132
constchunk=chunks[0];
133-
constbuf=TypedArrayPrototypeGetBuffer(chunk);
134-
// SharedArrayBuffer is not available in primordials, so use
135-
// direct property access for its byteLength.
136-
constbufByteLength=isSharedArrayBuffer(buf) ?
137-
buf.byteLength :
138-
ArrayBufferPrototypeGetByteLength(buf);
139-
if(TypedArrayPrototypeGetByteOffset(chunk)===0&&
140-
TypedArrayPrototypeGetByteLength(chunk)===bufByteLength){
141-
returnchunk;
133+
// If non-zero offset, skip the remaining buffer checks.
134+
if(TypedArrayPrototypeGetByteOffset(chunk)===0){
135+
constbuf=TypedArrayPrototypeGetBuffer(chunk);
136+
// SharedArrayBuffer is not available in primordials, so use
137+
// direct property access for its byteLength.
138+
constbufByteLength=isSharedArrayBuffer(buf) ?
139+
buf.byteLength :
140+
ArrayBufferPrototypeGetByteLength(buf);
141+
if(TypedArrayPrototypeGetByteLength(chunk)===bufByteLength){
142+
returnchunk;
143+
}
142144
}
145+
returnnewUint8Array(chunk);
146+
}
147+
// Multiple chunks: concatenate
148+
lettotalByteLength=0;
149+
for(leti=0;i<chunks.length;i++){
150+
totalByteLength+=TypedArrayPrototypeGetByteLength(chunks[i]);
151+
}
152+
constconcatenated=newUint8Array(totalByteLength);
153+
letoffset=0;
154+
for(leti=0;i<chunks.length;i++){
155+
TypedArrayPrototypeSet(concatenated,chunks[i],offset);
156+
offset+=TypedArrayPrototypeGetByteLength(chunks[i]);
143157
}
144-
// Multiple chunks or shared buffer: concatenate
145-
constbuf=Buffer.concat(chunks);
146-
returnnewUint8Array(
147-
TypedArrayPrototypeGetBuffer(buf),
148-
TypedArrayPrototypeGetByteOffset(buf),
149-
TypedArrayPrototypeGetByteLength(buf));
158+
returnconcatenated;
150159
}
151160

152161
/**

0 commit comments

Comments
Β (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Commit b57b51e

Browse files
Renegade334aduh95
authored andcommitted
stream: minor stream/iter implementation edits
Signed-off-by: Renegade334 <contact.9a5d6388@renegade334.me.uk> PR-URL: #63132 Backport-PR-URL: #64675 Reviewed-By: James M Snell <jasnell@gmail.com> Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
1 parent 274b3a2 commit b57b51e

5 files changed

Lines changed: 63 additions & 47 deletions

File tree

β€Žlib/internal/streams/iter/classic.jsβ€Ž

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313

1414
const{
1515
ArrayIsArray,
16+
ArrayPrototypePush,
1617
MathMax,
1718
NumberMAX_SAFE_INTEGER,
1819
Promise,
@@ -107,14 +108,14 @@ async function normalizeBatch(raw) {
107108
for(leti=0;i<raw.length;i++){
108109
constvalue=raw[i];
109110
if(isUint8Array(value)){
110-
batch.push(value);
111+
ArrayPrototypePush(batch,value);
111112
}else{
112113
// normalizeAsyncValue may await for async protocols (e.g.
113114
// toAsyncStreamable on yielded objects). Stream events during
114115
// the suspension are queued, not lost -- errors will surface
115116
// on the next loop iteration after this yield completes.
116117
forawait(constnormalizedofnormalizeAsyncValue(value)){
117-
batch.push(normalized);
118+
ArrayPrototypePush(batch,normalized);
118119
}
119120
}
120121
}
@@ -163,7 +164,7 @@ async function* createBatchedAsyncIterator(stream, normalize) {
163164
stream._readableState?.length>0){
164165
constc=stream.read();
165166
if(c===null)break;
166-
batch.push(c);
167+
ArrayPrototypePush(batch,c);
167168
}
168169
if(normalize!==null){
169170
constresult=awaitnormalize(batch);
@@ -495,7 +496,7 @@ function fromWritable(writable, options = kNullPrototype) {
495496

496497
functionwaitForDrain(){
497498
const{ promise, resolve, reject }=PromiseWithResolvers();
498-
waiters.push({__proto__: null, resolve, reject });
499+
ArrayPrototypePush(waiters,{__proto__: null, resolve, reject });
499500
installListeners();
500501
returnpromise;
501502
}
@@ -686,7 +687,7 @@ function fromWritable(writable, options = kNullPrototype) {
686687
returnPromiseResolve(true);
687688
}
688689
const{ promise, resolve }=PromiseWithResolvers();
689-
waiters.push({
690+
ArrayPrototypePush(waiters,{
690691
__proto__: null,
691692
resolve(){resolve(true);},
692693
reject(){resolve(false);},

β€Žlib/internal/streams/iter/consumers.jsβ€Ž

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ const {
1212
ArrayBufferPrototypeSlice,
1313
ArrayPrototypeMap,
1414
ArrayPrototypePush,
15+
ArrayPrototypeShift,
1516
ArrayPrototypeSlice,
1617
Promise,
1718
PromisePrototypeThen,
@@ -477,7 +478,7 @@ function merge(...args) {
477478

478479
// Drain ready queue synchronously
479480
while(ready.length>0){
480-
constitem=ready.shift();
481+
constitem=ArrayPrototypeShift(ready);
481482
if(item?.error){
482483
throwitem.error;
483484
}

β€Žlib/internal/streams/iter/from.jsβ€Ž

Lines changed: 13 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -31,8 +31,8 @@ const {
3131

3232
const{
3333
isAnyArrayBuffer,
34-
isDataView,
3534
isPromise,
35+
isTypedArray,
3636
isUint8Array,
3737
}=require('internal/util/types');
3838

@@ -106,17 +106,21 @@ function primitiveToUint8Array(chunk) {
106106
returnchunk;
107107
}
108108
// Other ArrayBufferView types (Int8Array, DataView, etc.)
109-
if(isDataView(chunk)){
109+
returnarrayBufferViewToUint8Array(chunk);
110+
}
111+
112+
functionarrayBufferViewToUint8Array(chunk){
113+
if(isTypedArray(chunk)){
110114
returnnewUint8Array(
111-
DataViewPrototypeGetBuffer(chunk),
112-
DataViewPrototypeGetByteOffset(chunk),
113-
DataViewPrototypeGetByteLength(chunk),
115+
TypedArrayPrototypeGetBuffer(chunk),
116+
TypedArrayPrototypeGetByteOffset(chunk),
117+
TypedArrayPrototypeGetByteLength(chunk),
114118
);
115119
}
116120
returnnewUint8Array(
117-
TypedArrayPrototypeGetBuffer(chunk),
118-
TypedArrayPrototypeGetByteOffset(chunk),
119-
TypedArrayPrototypeGetByteLength(chunk),
121+
DataViewPrototypeGetBuffer(chunk),
122+
DataViewPrototypeGetByteOffset(chunk),
123+
DataViewPrototypeGetByteLength(chunk),
120124
);
121125
}
122126

@@ -580,6 +584,7 @@ function from(input) {
580584
// =============================================================================
581585

582586
module.exports={
587+
arrayBufferViewToUint8Array,
583588
from,
584589
fromSync,
585590
isAsyncIterable,

β€Žlib/internal/streams/iter/pull.jsβ€Ž

Lines changed: 15 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -33,9 +33,9 @@ const {
3333
const{ AbortController }=require('internal/abort_controller');
3434

3535
const{
36+
arrayBufferViewToUint8Array,
3637
from,
3738
fromSync,
38-
primitiveToUint8Array,
3939
isSyncIterable,
4040
isAsyncIterable,
4141
isUint8ArrayBatch,
@@ -136,7 +136,7 @@ function* flattenTransformYieldSync(value) {
136136
return;
137137
}
138138
if(ArrayBufferIsView(value)){
139-
yieldprimitiveToUint8Array(value);
139+
yieldarrayBufferViewToUint8Array(value);
140140
return;
141141
}
142142
// Must be Iterable<TransformYield>
@@ -170,7 +170,7 @@ async function* flattenTransformYieldAsync(value) {
170170
return;
171171
}
172172
if(ArrayBufferIsView(value)){
173-
yieldprimitiveToUint8Array(value);
173+
yieldarrayBufferViewToUint8Array(value);
174174
return;
175175
}
176176
// Check for async iterable first
@@ -180,10 +180,10 @@ async function* flattenTransformYieldAsync(value) {
180180
}
181181
return;
182182
}
183-
// Must be sync Iterable<TransformYield>
183+
// Must be sync Iterable<TransformYield>, no nested async iterables
184184
if(isSyncIterable(value)){
185185
for(constitemofvalue){
186-
yield*flattenTransformYieldAsync(item);
186+
yield*flattenTransformYieldSync(item);
187187
}
188188
return;
189189
}
@@ -218,7 +218,7 @@ function* processTransformResultSync(result) {
218218
return;
219219
}
220220
if(ArrayBufferIsView(result)){
221-
yield[primitiveToUint8Array(result)];
221+
yield[arrayBufferViewToUint8Array(result)];
222222
return;
223223
}
224224
// Uint8Array[] batch
@@ -278,7 +278,7 @@ async function* processTransformResultAsync(result) {
278278
return;
279279
}
280280
if(ArrayBufferIsView(result)){
281-
yield[primitiveToUint8Array(result)];
281+
yield[arrayBufferViewToUint8Array(result)];
282282
return;
283283
}
284284
// Uint8Array[] batch
@@ -313,7 +313,9 @@ async function* processTransformResultAsync(result) {
313313
ArrayPrototypePush(batch,item);
314314
continue;
315315
}
316-
forawait(constchunkofflattenTransformYieldAsync(item)){
316+
// Note: This iteration is synchronous, since async iterables
317+
// may not be nested within sync iterables.
318+
for(constchunkofflattenTransformYieldSync(item)){
317319
ArrayPrototypePush(batch,chunk);
318320
}
319321
}
@@ -366,7 +368,7 @@ function* applyFusedStatelessSyncTransforms(source, run) {
366368
}elseif(isAnyArrayBuffer(current)){
367369
yield[newUint8Array(current)];
368370
}elseif(ArrayBufferIsView(current)){
369-
yield[primitiveToUint8Array(current)];
371+
yield[arrayBufferViewToUint8Array(current)];
370372
}else{
371373
yield*processTransformResultSync(current);
372374
}
@@ -428,7 +430,7 @@ function* createSyncPipeline(source, transforms) {
428430
}
429431
current=applyStatefulSyncTransform(current,transform.transform);
430432
}else{
431-
statelessRun.push(transform);
433+
ArrayPrototypePush(statelessRun,transform);
432434
}
433435
}
434436
if(statelessRun.length>0){
@@ -490,7 +492,7 @@ async function* applyFusedStatelessAsyncTransforms(source, run, signal) {
490492
}elseif(isAnyArrayBuffer(current)){
491493
yield[newUint8Array(current)];
492494
}elseif(ArrayBufferIsView(current)){
493-
yield[primitiveToUint8Array(current)];
495+
yield[arrayBufferViewToUint8Array(current)];
494496
}else{
495497
yield*processTransformResultAsync(current);
496498
}
@@ -531,9 +533,7 @@ async function* applyFusedStatelessAsyncTransforms(source, run, signal) {
531533
* @yields {Uint8Array[]}
532534
*/
533535
asyncfunction*withFlushAsync(source){
534-
forawait(constbatchofsource){
535-
yieldbatch;
536-
}
536+
yield*source;
537537
yieldnull;
538538
}
539539

@@ -647,7 +647,7 @@ async function* createAsyncPipeline(source, transforms, signal) {
647647
current,transform.transform,opts);
648648
}
649649
}else{
650-
statelessRun.push(transform);
650+
ArrayPrototypePush(statelessRun,transform);
651651
}
652652
}
653653
// Flush remaining stateless run

β€Žlib/internal/streams/iter/utils.jsβ€Ž

Lines changed: 27 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ const {
1212
TypedArrayPrototypeGetBuffer,
1313
TypedArrayPrototypeGetByteLength,
1414
TypedArrayPrototypeGetByteOffset,
15+
TypedArrayPrototypeSet,
1516
Uint8Array,
1617
}=primordials;
1718

@@ -24,8 +25,6 @@ const {
2425
}=require('internal/errors');
2526
const{ isError }=require('internal/util');
2627

27-
const{ Buffer }=require('buffer');
28-
2928
const{ isSharedArrayBuffer, isUint8Array }=require('internal/util/types');
3029

3130
const{ validateOneOf }=require('internal/validators');
@@ -127,26 +126,36 @@ function concatBytes(chunks) {
127126
if(chunks.length===0){
128127
returnnewUint8Array(0);
129128
}
130-
// Single chunk: return directly if it covers the entire backing buffer
129+
// Single chunk: return directly if it covers the entire backing buffer,
130+
// otherwise return a copy
131131
if(chunks.length===1){
132132
constchunk=chunks[0];
133-
constbuf=TypedArrayPrototypeGetBuffer(chunk);
134-
// SharedArrayBuffer is not available in primordials, so use
135-
// direct property access for its byteLength.
136-
constbufByteLength=isSharedArrayBuffer(buf) ?
137-
buf.byteLength :
138-
ArrayBufferPrototypeGetByteLength(buf);
139-
if(TypedArrayPrototypeGetByteOffset(chunk)===0&&
140-
TypedArrayPrototypeGetByteLength(chunk)===bufByteLength){
141-
returnchunk;
133+
// If non-zero offset, skip the remaining buffer checks.
134+
if(TypedArrayPrototypeGetByteOffset(chunk)===0){
135+
constbuf=TypedArrayPrototypeGetBuffer(chunk);
136+
// SharedArrayBuffer is not available in primordials, so use
137+
// direct property access for its byteLength.
138+
constbufByteLength=isSharedArrayBuffer(buf) ?
139+
buf.byteLength :
140+
ArrayBufferPrototypeGetByteLength(buf);
141+
if(TypedArrayPrototypeGetByteLength(chunk)===bufByteLength){
142+
returnchunk;
143+
}
142144
}
145+
returnnewUint8Array(chunk);
146+
}
147+
// Multiple chunks: concatenate
148+
lettotalByteLength=0;
149+
for(leti=0;i<chunks.length;i++){
150+
totalByteLength+=TypedArrayPrototypeGetByteLength(chunks[i]);
151+
}
152+
constconcatenated=newUint8Array(totalByteLength);
153+
letoffset=0;
154+
for(leti=0;i<chunks.length;i++){
155+
TypedArrayPrototypeSet(concatenated,chunks[i],offset);
156+
offset+=TypedArrayPrototypeGetByteLength(chunks[i]);
143157
}
144-
// Multiple chunks or shared buffer: concatenate
145-
constbuf=Buffer.concat(chunks);
146-
returnnewUint8Array(
147-
TypedArrayPrototypeGetBuffer(buf),
148-
TypedArrayPrototypeGetByteOffset(buf),
149-
TypedArrayPrototypeGetByteLength(buf));
158+
returnconcatenated;
150159
}
151160

152161
/**

0 commit comments

Comments
Β (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Commit b57b51e

Browse files
Renegade334aduh95
authored andcommitted
stream: minor stream/iter implementation edits
Signed-off-by: Renegade334 <contact.9a5d6388@renegade334.me.uk> PR-URL: #63132 Backport-PR-URL: #64675 Reviewed-By: James M Snell <jasnell@gmail.com> Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
1 parent 274b3a2 commit b57b51e

5 files changed

Lines changed: 63 additions & 47 deletions

File tree

β€Žlib/internal/streams/iter/classic.jsβ€Ž

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313

1414
const{
1515
ArrayIsArray,
16+
ArrayPrototypePush,
1617
MathMax,
1718
NumberMAX_SAFE_INTEGER,
1819
Promise,
@@ -107,14 +108,14 @@ async function normalizeBatch(raw) {
107108
for(leti=0;i<raw.length;i++){
108109
constvalue=raw[i];
109110
if(isUint8Array(value)){
110-
batch.push(value);
111+
ArrayPrototypePush(batch,value);
111112
}else{
112113
// normalizeAsyncValue may await for async protocols (e.g.
113114
// toAsyncStreamable on yielded objects). Stream events during
114115
// the suspension are queued, not lost -- errors will surface
115116
// on the next loop iteration after this yield completes.
116117
forawait(constnormalizedofnormalizeAsyncValue(value)){
117-
batch.push(normalized);
118+
ArrayPrototypePush(batch,normalized);
118119
}
119120
}
120121
}
@@ -163,7 +164,7 @@ async function* createBatchedAsyncIterator(stream, normalize) {
163164
stream._readableState?.length>0){
164165
constc=stream.read();
165166
if(c===null)break;
166-
batch.push(c);
167+
ArrayPrototypePush(batch,c);
167168
}
168169
if(normalize!==null){
169170
constresult=awaitnormalize(batch);
@@ -495,7 +496,7 @@ function fromWritable(writable, options = kNullPrototype) {
495496

496497
functionwaitForDrain(){
497498
const{ promise, resolve, reject }=PromiseWithResolvers();
498-
waiters.push({__proto__: null, resolve, reject });
499+
ArrayPrototypePush(waiters,{__proto__: null, resolve, reject });
499500
installListeners();
500501
returnpromise;
501502
}
@@ -686,7 +687,7 @@ function fromWritable(writable, options = kNullPrototype) {
686687
returnPromiseResolve(true);
687688
}
688689
const{ promise, resolve }=PromiseWithResolvers();
689-
waiters.push({
690+
ArrayPrototypePush(waiters,{
690691
__proto__: null,
691692
resolve(){resolve(true);},
692693
reject(){resolve(false);},

β€Žlib/internal/streams/iter/consumers.jsβ€Ž

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ const {
1212
ArrayBufferPrototypeSlice,
1313
ArrayPrototypeMap,
1414
ArrayPrototypePush,
15+
ArrayPrototypeShift,
1516
ArrayPrototypeSlice,
1617
Promise,
1718
PromisePrototypeThen,
@@ -477,7 +478,7 @@ function merge(...args) {
477478

478479
// Drain ready queue synchronously
479480
while(ready.length>0){
480-
constitem=ready.shift();
481+
constitem=ArrayPrototypeShift(ready);
481482
if(item?.error){
482483
throwitem.error;
483484
}

β€Žlib/internal/streams/iter/from.jsβ€Ž

Lines changed: 13 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -31,8 +31,8 @@ const {
3131

3232
const{
3333
isAnyArrayBuffer,
34-
isDataView,
3534
isPromise,
35+
isTypedArray,
3636
isUint8Array,
3737
}=require('internal/util/types');
3838

@@ -106,17 +106,21 @@ function primitiveToUint8Array(chunk) {
106106
returnchunk;
107107
}
108108
// Other ArrayBufferView types (Int8Array, DataView, etc.)
109-
if(isDataView(chunk)){
109+
returnarrayBufferViewToUint8Array(chunk);
110+
}
111+
112+
functionarrayBufferViewToUint8Array(chunk){
113+
if(isTypedArray(chunk)){
110114
returnnewUint8Array(
111-
DataViewPrototypeGetBuffer(chunk),
112-
DataViewPrototypeGetByteOffset(chunk),
113-
DataViewPrototypeGetByteLength(chunk),
115+
TypedArrayPrototypeGetBuffer(chunk),
116+
TypedArrayPrototypeGetByteOffset(chunk),
117+
TypedArrayPrototypeGetByteLength(chunk),
114118
);
115119
}
116120
returnnewUint8Array(
117-
TypedArrayPrototypeGetBuffer(chunk),
118-
TypedArrayPrototypeGetByteOffset(chunk),
119-
TypedArrayPrototypeGetByteLength(chunk),
121+
DataViewPrototypeGetBuffer(chunk),
122+
DataViewPrototypeGetByteOffset(chunk),
123+
DataViewPrototypeGetByteLength(chunk),
120124
);
121125
}
122126

@@ -580,6 +584,7 @@ function from(input) {
580584
// =============================================================================
581585

582586
module.exports={
587+
arrayBufferViewToUint8Array,
583588
from,
584589
fromSync,
585590
isAsyncIterable,

β€Žlib/internal/streams/iter/pull.jsβ€Ž

Lines changed: 15 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -33,9 +33,9 @@ const {
3333
const{ AbortController }=require('internal/abort_controller');
3434

3535
const{
36+
arrayBufferViewToUint8Array,
3637
from,
3738
fromSync,
38-
primitiveToUint8Array,
3939
isSyncIterable,
4040
isAsyncIterable,
4141
isUint8ArrayBatch,
@@ -136,7 +136,7 @@ function* flattenTransformYieldSync(value) {
136136
return;
137137
}
138138
if(ArrayBufferIsView(value)){
139-
yieldprimitiveToUint8Array(value);
139+
yieldarrayBufferViewToUint8Array(value);
140140
return;
141141
}
142142
// Must be Iterable<TransformYield>
@@ -170,7 +170,7 @@ async function* flattenTransformYieldAsync(value) {
170170
return;
171171
}
172172
if(ArrayBufferIsView(value)){
173-
yieldprimitiveToUint8Array(value);
173+
yieldarrayBufferViewToUint8Array(value);
174174
return;
175175
}
176176
// Check for async iterable first
@@ -180,10 +180,10 @@ async function* flattenTransformYieldAsync(value) {
180180
}
181181
return;
182182
}
183-
// Must be sync Iterable<TransformYield>
183+
// Must be sync Iterable<TransformYield>, no nested async iterables
184184
if(isSyncIterable(value)){
185185
for(constitemofvalue){
186-
yield*flattenTransformYieldAsync(item);
186+
yield*flattenTransformYieldSync(item);
187187
}
188188
return;
189189
}
@@ -218,7 +218,7 @@ function* processTransformResultSync(result) {
218218
return;
219219
}
220220
if(ArrayBufferIsView(result)){
221-
yield[primitiveToUint8Array(result)];
221+
yield[arrayBufferViewToUint8Array(result)];
222222
return;
223223
}
224224
// Uint8Array[] batch
@@ -278,7 +278,7 @@ async function* processTransformResultAsync(result) {
278278
return;
279279
}
280280
if(ArrayBufferIsView(result)){
281-
yield[primitiveToUint8Array(result)];
281+
yield[arrayBufferViewToUint8Array(result)];
282282
return;
283283
}
284284
// Uint8Array[] batch
@@ -313,7 +313,9 @@ async function* processTransformResultAsync(result) {
313313
ArrayPrototypePush(batch,item);
314314
continue;
315315
}
316-
forawait(constchunkofflattenTransformYieldAsync(item)){
316+
// Note: This iteration is synchronous, since async iterables
317+
// may not be nested within sync iterables.
318+
for(constchunkofflattenTransformYieldSync(item)){
317319
ArrayPrototypePush(batch,chunk);
318320
}
319321
}
@@ -366,7 +368,7 @@ function* applyFusedStatelessSyncTransforms(source, run) {
366368
}elseif(isAnyArrayBuffer(current)){
367369
yield[newUint8Array(current)];
368370
}elseif(ArrayBufferIsView(current)){
369-
yield[primitiveToUint8Array(current)];
371+
yield[arrayBufferViewToUint8Array(current)];
370372
}else{
371373
yield*processTransformResultSync(current);
372374
}
@@ -428,7 +430,7 @@ function* createSyncPipeline(source, transforms) {
428430
}
429431
current=applyStatefulSyncTransform(current,transform.transform);
430432
}else{
431-
statelessRun.push(transform);
433+
ArrayPrototypePush(statelessRun,transform);
432434
}
433435
}
434436
if(statelessRun.length>0){
@@ -490,7 +492,7 @@ async function* applyFusedStatelessAsyncTransforms(source, run, signal) {
490492
}elseif(isAnyArrayBuffer(current)){
491493
yield[newUint8Array(current)];
492494
}elseif(ArrayBufferIsView(current)){
493-
yield[primitiveToUint8Array(current)];
495+
yield[arrayBufferViewToUint8Array(current)];
494496
}else{
495497
yield*processTransformResultAsync(current);
496498
}
@@ -531,9 +533,7 @@ async function* applyFusedStatelessAsyncTransforms(source, run, signal) {
531533
* @yields {Uint8Array[]}
532534
*/
533535
asyncfunction*withFlushAsync(source){
534-
forawait(constbatchofsource){
535-
yieldbatch;
536-
}
536+
yield*source;
537537
yieldnull;
538538
}
539539

@@ -647,7 +647,7 @@ async function* createAsyncPipeline(source, transforms, signal) {
647647
current,transform.transform,opts);
648648
}
649649
}else{
650-
statelessRun.push(transform);
650+
ArrayPrototypePush(statelessRun,transform);
651651
}
652652
}
653653
// Flush remaining stateless run

β€Žlib/internal/streams/iter/utils.jsβ€Ž

Lines changed: 27 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ const {
1212
TypedArrayPrototypeGetBuffer,
1313
TypedArrayPrototypeGetByteLength,
1414
TypedArrayPrototypeGetByteOffset,
15+
TypedArrayPrototypeSet,
1516
Uint8Array,
1617
}=primordials;
1718

@@ -24,8 +25,6 @@ const {
2425
}=require('internal/errors');
2526
const{ isError }=require('internal/util');
2627

27-
const{ Buffer }=require('buffer');
28-
2928
const{ isSharedArrayBuffer, isUint8Array }=require('internal/util/types');
3029

3130
const{ validateOneOf }=require('internal/validators');
@@ -127,26 +126,36 @@ function concatBytes(chunks) {
127126
if(chunks.length===0){
128127
returnnewUint8Array(0);
129128
}
130-
// Single chunk: return directly if it covers the entire backing buffer
129+
// Single chunk: return directly if it covers the entire backing buffer,
130+
// otherwise return a copy
131131
if(chunks.length===1){
132132
constchunk=chunks[0];
133-
constbuf=TypedArrayPrototypeGetBuffer(chunk);
134-
// SharedArrayBuffer is not available in primordials, so use
135-
// direct property access for its byteLength.
136-
constbufByteLength=isSharedArrayBuffer(buf) ?
137-
buf.byteLength :
138-
ArrayBufferPrototypeGetByteLength(buf);
139-
if(TypedArrayPrototypeGetByteOffset(chunk)===0&&
140-
TypedArrayPrototypeGetByteLength(chunk)===bufByteLength){
141-
returnchunk;
133+
// If non-zero offset, skip the remaining buffer checks.
134+
if(TypedArrayPrototypeGetByteOffset(chunk)===0){
135+
constbuf=TypedArrayPrototypeGetBuffer(chunk);
136+
// SharedArrayBuffer is not available in primordials, so use
137+
// direct property access for its byteLength.
138+
constbufByteLength=isSharedArrayBuffer(buf) ?
139+
buf.byteLength :
140+
ArrayBufferPrototypeGetByteLength(buf);
141+
if(TypedArrayPrototypeGetByteLength(chunk)===bufByteLength){
142+
returnchunk;
143+
}
142144
}
145+
returnnewUint8Array(chunk);
146+
}
147+
// Multiple chunks: concatenate
148+
lettotalByteLength=0;
149+
for(leti=0;i<chunks.length;i++){
150+
totalByteLength+=TypedArrayPrototypeGetByteLength(chunks[i]);
151+
}
152+
constconcatenated=newUint8Array(totalByteLength);
153+
letoffset=0;
154+
for(leti=0;i<chunks.length;i++){
155+
TypedArrayPrototypeSet(concatenated,chunks[i],offset);
156+
offset+=TypedArrayPrototypeGetByteLength(chunks[i]);
143157
}
144-
// Multiple chunks or shared buffer: concatenate
145-
constbuf=Buffer.concat(chunks);
146-
returnnewUint8Array(
147-
TypedArrayPrototypeGetBuffer(buf),
148-
TypedArrayPrototypeGetByteOffset(buf),
149-
TypedArrayPrototypeGetByteLength(buf));
158+
returnconcatenated;
150159
}
151160

152161
/**

0 commit comments

Comments
Β (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content

Commit b57b51e

Browse files
Renegade334aduh95
authored andcommitted
stream: minor stream/iter implementation edits
Signed-off-by: Renegade334 <contact.9a5d6388@renegade334.me.uk> PR-URL: #63132 Backport-PR-URL: #64675 Reviewed-By: James M Snell <jasnell@gmail.com> Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
1 parent 274b3a2 commit b57b51e

5 files changed

Lines changed: 63 additions & 47 deletions

File tree

β€Žlib/internal/streams/iter/classic.jsβ€Ž

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313

1414
const{
1515
ArrayIsArray,
16+
ArrayPrototypePush,
1617
MathMax,
1718
NumberMAX_SAFE_INTEGER,
1819
Promise,
@@ -107,14 +108,14 @@ async function normalizeBatch(raw) {
107108
for(leti=0;i<raw.length;i++){
108109
constvalue=raw[i];
109110
if(isUint8Array(value)){
110-
batch.push(value);
111+
ArrayPrototypePush(batch,value);
111112
}else{
112113
// normalizeAsyncValue may await for async protocols (e.g.
113114
// toAsyncStreamable on yielded objects). Stream events during
114115
// the suspension are queued, not lost -- errors will surface
115116
// on the next loop iteration after this yield completes.
116117
forawait(constnormalizedofnormalizeAsyncValue(value)){
117-
batch.push(normalized);
118+
ArrayPrototypePush(batch,normalized);
118119
}
119120
}
120121
}
@@ -163,7 +164,7 @@ async function* createBatchedAsyncIterator(stream, normalize) {
163164
stream._readableState?.length>0){
164165
constc=stream.read();
165166
if(c===null)break;
166-
batch.push(c);
167+
ArrayPrototypePush(batch,c);
167168
}
168169
if(normalize!==null){
169170
constresult=awaitnormalize(batch);
@@ -495,7 +496,7 @@ function fromWritable(writable, options = kNullPrototype) {
495496

496497
functionwaitForDrain(){
497498
const{ promise, resolve, reject }=PromiseWithResolvers();
498-
waiters.push({__proto__: null, resolve, reject });
499+
ArrayPrototypePush(waiters,{__proto__: null, resolve, reject });
499500
installListeners();
500501
returnpromise;
501502
}
@@ -686,7 +687,7 @@ function fromWritable(writable, options = kNullPrototype) {
686687
returnPromiseResolve(true);
687688
}
688689
const{ promise, resolve }=PromiseWithResolvers();
689-
waiters.push({
690+
ArrayPrototypePush(waiters,{
690691
__proto__: null,
691692
resolve(){resolve(true);},
692693
reject(){resolve(false);},

β€Žlib/internal/streams/iter/consumers.jsβ€Ž

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ const {
1212
ArrayBufferPrototypeSlice,
1313
ArrayPrototypeMap,
1414
ArrayPrototypePush,
15+
ArrayPrototypeShift,
1516
ArrayPrototypeSlice,
1617
Promise,
1718
PromisePrototypeThen,
@@ -477,7 +478,7 @@ function merge(...args) {
477478

478479
// Drain ready queue synchronously
479480
while(ready.length>0){
480-
constitem=ready.shift();
481+
constitem=ArrayPrototypeShift(ready);
481482
if(item?.error){
482483
throwitem.error;
483484
}

β€Žlib/internal/streams/iter/from.jsβ€Ž

Lines changed: 13 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -31,8 +31,8 @@ const {
3131

3232
const{
3333
isAnyArrayBuffer,
34-
isDataView,
3534
isPromise,
35+
isTypedArray,
3636
isUint8Array,
3737
}=require('internal/util/types');
3838

@@ -106,17 +106,21 @@ function primitiveToUint8Array(chunk) {
106106
returnchunk;
107107
}
108108
// Other ArrayBufferView types (Int8Array, DataView, etc.)
109-
if(isDataView(chunk)){
109+
returnarrayBufferViewToUint8Array(chunk);
110+
}
111+
112+
functionarrayBufferViewToUint8Array(chunk){
113+
if(isTypedArray(chunk)){
110114
returnnewUint8Array(
111-
DataViewPrototypeGetBuffer(chunk),
112-
DataViewPrototypeGetByteOffset(chunk),
113-
DataViewPrototypeGetByteLength(chunk),
115+
TypedArrayPrototypeGetBuffer(chunk),
116+
TypedArrayPrototypeGetByteOffset(chunk),
117+
TypedArrayPrototypeGetByteLength(chunk),
114118
);
115119
}
116120
returnnewUint8Array(
117-
TypedArrayPrototypeGetBuffer(chunk),
118-
TypedArrayPrototypeGetByteOffset(chunk),
119-
TypedArrayPrototypeGetByteLength(chunk),
121+
DataViewPrototypeGetBuffer(chunk),
122+
DataViewPrototypeGetByteOffset(chunk),
123+
DataViewPrototypeGetByteLength(chunk),
120124
);
121125
}
122126

@@ -580,6 +584,7 @@ function from(input) {
580584
// =============================================================================
581585

582586
module.exports={
587+
arrayBufferViewToUint8Array,
583588
from,
584589
fromSync,
585590
isAsyncIterable,

β€Žlib/internal/streams/iter/pull.jsβ€Ž

Lines changed: 15 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -33,9 +33,9 @@ const {
3333
const{ AbortController }=require('internal/abort_controller');
3434

3535
const{
36+
arrayBufferViewToUint8Array,
3637
from,
3738
fromSync,
38-
primitiveToUint8Array,
3939
isSyncIterable,
4040
isAsyncIterable,
4141
isUint8ArrayBatch,
@@ -136,7 +136,7 @@ function* flattenTransformYieldSync(value) {
136136
return;
137137
}
138138
if(ArrayBufferIsView(value)){
139-
yieldprimitiveToUint8Array(value);
139+
yieldarrayBufferViewToUint8Array(value);
140140
return;
141141
}
142142
// Must be Iterable<TransformYield>
@@ -170,7 +170,7 @@ async function* flattenTransformYieldAsync(value) {
170170
return;
171171
}
172172
if(ArrayBufferIsView(value)){
173-
yieldprimitiveToUint8Array(value);
173+
yieldarrayBufferViewToUint8Array(value);
174174
return;
175175
}
176176
// Check for async iterable first
@@ -180,10 +180,10 @@ async function* flattenTransformYieldAsync(value) {
180180
}
181181
return;
182182
}
183-
// Must be sync Iterable<TransformYield>
183+
// Must be sync Iterable<TransformYield>, no nested async iterables
184184
if(isSyncIterable(value)){
185185
for(constitemofvalue){
186-
yield*flattenTransformYieldAsync(item);
186+
yield*flattenTransformYieldSync(item);
187187
}
188188
return;
189189
}
@@ -218,7 +218,7 @@ function* processTransformResultSync(result) {
218218
return;
219219
}
220220
if(ArrayBufferIsView(result)){
221-
yield[primitiveToUint8Array(result)];
221+
yield[arrayBufferViewToUint8Array(result)];
222222
return;
223223
}
224224
// Uint8Array[] batch
@@ -278,7 +278,7 @@ async function* processTransformResultAsync(result) {
278278
return;
279279
}
280280
if(ArrayBufferIsView(result)){
281-
yield[primitiveToUint8Array(result)];
281+
yield[arrayBufferViewToUint8Array(result)];
282282
return;
283283
}
284284
// Uint8Array[] batch
@@ -313,7 +313,9 @@ async function* processTransformResultAsync(result) {
313313
ArrayPrototypePush(batch,item);
314314
continue;
315315
}
316-
forawait(constchunkofflattenTransformYieldAsync(item)){
316+
// Note: This iteration is synchronous, since async iterables
317+
// may not be nested within sync iterables.
318+
for(constchunkofflattenTransformYieldSync(item)){
317319
ArrayPrototypePush(batch,chunk);
318320
}
319321
}
@@ -366,7 +368,7 @@ function* applyFusedStatelessSyncTransforms(source, run) {
366368
}elseif(isAnyArrayBuffer(current)){
367369
yield[newUint8Array(current)];
368370
}elseif(ArrayBufferIsView(current)){
369-
yield[primitiveToUint8Array(current)];
371+
yield[arrayBufferViewToUint8Array(current)];
370372
}else{
371373
yield*processTransformResultSync(current);
372374
}
@@ -428,7 +430,7 @@ function* createSyncPipeline(source, transforms) {
428430
}
429431
current=applyStatefulSyncTransform(current,transform.transform);
430432
}else{
431-
statelessRun.push(transform);
433+
ArrayPrototypePush(statelessRun,transform);
432434
}
433435
}
434436
if(statelessRun.length>0){
@@ -490,7 +492,7 @@ async function* applyFusedStatelessAsyncTransforms(source, run, signal) {
490492
}elseif(isAnyArrayBuffer(current)){
491493
yield[newUint8Array(current)];
492494
}elseif(ArrayBufferIsView(current)){
493-
yield[primitiveToUint8Array(current)];
495+
yield[arrayBufferViewToUint8Array(current)];
494496
}else{
495497
yield*processTransformResultAsync(current);
496498
}
@@ -531,9 +533,7 @@ async function* applyFusedStatelessAsyncTransforms(source, run, signal) {
531533
* @yields {Uint8Array[]}
532534
*/
533535
asyncfunction*withFlushAsync(source){
534-
forawait(constbatchofsource){
535-
yieldbatch;
536-
}
536+
yield*source;
537537
yieldnull;
538538
}
539539

@@ -647,7 +647,7 @@ async function* createAsyncPipeline(source, transforms, signal) {
647647
current,transform.transform,opts);
648648
}
649649
}else{
650-
statelessRun.push(transform);
650+
ArrayPrototypePush(statelessRun,transform);
651651
}
652652
}
653653
// Flush remaining stateless run

β€Žlib/internal/streams/iter/utils.jsβ€Ž

Lines changed: 27 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ const {
1212
TypedArrayPrototypeGetBuffer,
1313
TypedArrayPrototypeGetByteLength,
1414
TypedArrayPrototypeGetByteOffset,
15+
TypedArrayPrototypeSet,
1516
Uint8Array,
1617
}=primordials;
1718

@@ -24,8 +25,6 @@ const {
2425
}=require('internal/errors');
2526
const{ isError }=require('internal/util');
2627

27-
const{ Buffer }=require('buffer');
28-
2928
const{ isSharedArrayBuffer, isUint8Array }=require('internal/util/types');
3029

3130
const{ validateOneOf }=require('internal/validators');
@@ -127,26 +126,36 @@ function concatBytes(chunks) {
127126
if(chunks.length===0){
128127
returnnewUint8Array(0);
129128
}
130-
// Single chunk: return directly if it covers the entire backing buffer
129+
// Single chunk: return directly if it covers the entire backing buffer,
130+
// otherwise return a copy
131131
if(chunks.length===1){
132132
constchunk=chunks[0];
133-
constbuf=TypedArrayPrototypeGetBuffer(chunk);
134-
// SharedArrayBuffer is not available in primordials, so use
135-
// direct property access for its byteLength.
136-
constbufByteLength=isSharedArrayBuffer(buf) ?
137-
buf.byteLength :
138-
ArrayBufferPrototypeGetByteLength(buf);
139-
if(TypedArrayPrototypeGetByteOffset(chunk)===0&&
140-
TypedArrayPrototypeGetByteLength(chunk)===bufByteLength){
141-
returnchunk;
133+
// If non-zero offset, skip the remaining buffer checks.
134+
if(TypedArrayPrototypeGetByteOffset(chunk)===0){
135+
constbuf=TypedArrayPrototypeGetBuffer(chunk);
136+
// SharedArrayBuffer is not available in primordials, so use
137+
// direct property access for its byteLength.
138+
constbufByteLength=isSharedArrayBuffer(buf) ?
139+
buf.byteLength :
140+
ArrayBufferPrototypeGetByteLength(buf);
141+
if(TypedArrayPrototypeGetByteLength(chunk)===bufByteLength){
142+
returnchunk;
143+
}
142144
}
145+
returnnewUint8Array(chunk);
146+
}
147+
// Multiple chunks: concatenate
148+
lettotalByteLength=0;
149+
for(leti=0;i<chunks.length;i++){
150+
totalByteLength+=TypedArrayPrototypeGetByteLength(chunks[i]);
151+
}
152+
constconcatenated=newUint8Array(totalByteLength);
153+
letoffset=0;
154+
for(leti=0;i<chunks.length;i++){
155+
TypedArrayPrototypeSet(concatenated,chunks[i],offset);
156+
offset+=TypedArrayPrototypeGetByteLength(chunks[i]);
143157
}
144-
// Multiple chunks or shared buffer: concatenate
145-
constbuf=Buffer.concat(chunks);
146-
returnnewUint8Array(
147-
TypedArrayPrototypeGetBuffer(buf),
148-
TypedArrayPrototypeGetByteOffset(buf),
149-
TypedArrayPrototypeGetByteLength(buf));
158+
returnconcatenated;
150159
}
151160

152161
/**

0 commit comments

Comments
Β (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Commit b57b51e

Browse files
Renegade334aduh95
authored andcommitted
stream: minor stream/iter implementation edits
Signed-off-by: Renegade334 <contact.9a5d6388@renegade334.me.uk> PR-URL: #63132 Backport-PR-URL: #64675 Reviewed-By: James M Snell <jasnell@gmail.com> Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
1 parent 274b3a2 commit b57b51e

5 files changed

Lines changed: 63 additions & 47 deletions

File tree

β€Žlib/internal/streams/iter/classic.jsβ€Ž

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313

1414
const{
1515
ArrayIsArray,
16+
ArrayPrototypePush,
1617
MathMax,
1718
NumberMAX_SAFE_INTEGER,
1819
Promise,
@@ -107,14 +108,14 @@ async function normalizeBatch(raw) {
107108
for(leti=0;i<raw.length;i++){
108109
constvalue=raw[i];
109110
if(isUint8Array(value)){
110-
batch.push(value);
111+
ArrayPrototypePush(batch,value);
111112
}else{
112113
// normalizeAsyncValue may await for async protocols (e.g.
113114
// toAsyncStreamable on yielded objects). Stream events during
114115
// the suspension are queued, not lost -- errors will surface
115116
// on the next loop iteration after this yield completes.
116117
forawait(constnormalizedofnormalizeAsyncValue(value)){
117-
batch.push(normalized);
118+
ArrayPrototypePush(batch,normalized);
118119
}
119120
}
120121
}
@@ -163,7 +164,7 @@ async function* createBatchedAsyncIterator(stream, normalize) {
163164
stream._readableState?.length>0){
164165
constc=stream.read();
165166
if(c===null)break;
166-
batch.push(c);
167+
ArrayPrototypePush(batch,c);
167168
}
168169
if(normalize!==null){
169170
constresult=awaitnormalize(batch);
@@ -495,7 +496,7 @@ function fromWritable(writable, options = kNullPrototype) {
495496

496497
functionwaitForDrain(){
497498
const{ promise, resolve, reject }=PromiseWithResolvers();
498-
waiters.push({__proto__: null, resolve, reject });
499+
ArrayPrototypePush(waiters,{__proto__: null, resolve, reject });
499500
installListeners();
500501
returnpromise;
501502
}
@@ -686,7 +687,7 @@ function fromWritable(writable, options = kNullPrototype) {
686687
returnPromiseResolve(true);
687688
}
688689
const{ promise, resolve }=PromiseWithResolvers();
689-
waiters.push({
690+
ArrayPrototypePush(waiters,{
690691
__proto__: null,
691692
resolve(){resolve(true);},
692693
reject(){resolve(false);},

β€Žlib/internal/streams/iter/consumers.jsβ€Ž

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ const {
1212
ArrayBufferPrototypeSlice,
1313
ArrayPrototypeMap,
1414
ArrayPrototypePush,
15+
ArrayPrototypeShift,
1516
ArrayPrototypeSlice,
1617
Promise,
1718
PromisePrototypeThen,
@@ -477,7 +478,7 @@ function merge(...args) {
477478

478479
// Drain ready queue synchronously
479480
while(ready.length>0){
480-
constitem=ready.shift();
481+
constitem=ArrayPrototypeShift(ready);
481482
if(item?.error){
482483
throwitem.error;
483484
}

β€Žlib/internal/streams/iter/from.jsβ€Ž

Lines changed: 13 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -31,8 +31,8 @@ const {
3131

3232
const{
3333
isAnyArrayBuffer,
34-
isDataView,
3534
isPromise,
35+
isTypedArray,
3636
isUint8Array,
3737
}=require('internal/util/types');
3838

@@ -106,17 +106,21 @@ function primitiveToUint8Array(chunk) {
106106
returnchunk;
107107
}
108108
// Other ArrayBufferView types (Int8Array, DataView, etc.)
109-
if(isDataView(chunk)){
109+
returnarrayBufferViewToUint8Array(chunk);
110+
}
111+
112+
functionarrayBufferViewToUint8Array(chunk){
113+
if(isTypedArray(chunk)){
110114
returnnewUint8Array(
111-
DataViewPrototypeGetBuffer(chunk),
112-
DataViewPrototypeGetByteOffset(chunk),
113-
DataViewPrototypeGetByteLength(chunk),
115+
TypedArrayPrototypeGetBuffer(chunk),
116+
TypedArrayPrototypeGetByteOffset(chunk),
117+
TypedArrayPrototypeGetByteLength(chunk),
114118
);
115119
}
116120
returnnewUint8Array(
117-
TypedArrayPrototypeGetBuffer(chunk),
118-
TypedArrayPrototypeGetByteOffset(chunk),
119-
TypedArrayPrototypeGetByteLength(chunk),
121+
DataViewPrototypeGetBuffer(chunk),
122+
DataViewPrototypeGetByteOffset(chunk),
123+
DataViewPrototypeGetByteLength(chunk),
120124
);
121125
}
122126

@@ -580,6 +584,7 @@ function from(input) {
580584
// =============================================================================
581585

582586
module.exports={
587+
arrayBufferViewToUint8Array,
583588
from,
584589
fromSync,
585590
isAsyncIterable,

β€Žlib/internal/streams/iter/pull.jsβ€Ž

Lines changed: 15 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -33,9 +33,9 @@ const {
3333
const{ AbortController }=require('internal/abort_controller');
3434

3535
const{
36+
arrayBufferViewToUint8Array,
3637
from,
3738
fromSync,
38-
primitiveToUint8Array,
3939
isSyncIterable,
4040
isAsyncIterable,
4141
isUint8ArrayBatch,
@@ -136,7 +136,7 @@ function* flattenTransformYieldSync(value) {
136136
return;
137137
}
138138
if(ArrayBufferIsView(value)){
139-
yieldprimitiveToUint8Array(value);
139+
yieldarrayBufferViewToUint8Array(value);
140140
return;
141141
}
142142
// Must be Iterable<TransformYield>
@@ -170,7 +170,7 @@ async function* flattenTransformYieldAsync(value) {
170170
return;
171171
}
172172
if(ArrayBufferIsView(value)){
173-
yieldprimitiveToUint8Array(value);
173+
yieldarrayBufferViewToUint8Array(value);
174174
return;
175175
}
176176
// Check for async iterable first
@@ -180,10 +180,10 @@ async function* flattenTransformYieldAsync(value) {
180180
}
181181
return;
182182
}
183-
// Must be sync Iterable<TransformYield>
183+
// Must be sync Iterable<TransformYield>, no nested async iterables
184184
if(isSyncIterable(value)){
185185
for(constitemofvalue){
186-
yield*flattenTransformYieldAsync(item);
186+
yield*flattenTransformYieldSync(item);
187187
}
188188
return;
189189
}
@@ -218,7 +218,7 @@ function* processTransformResultSync(result) {
218218
return;
219219
}
220220
if(ArrayBufferIsView(result)){
221-
yield[primitiveToUint8Array(result)];
221+
yield[arrayBufferViewToUint8Array(result)];
222222
return;
223223
}
224224
// Uint8Array[] batch
@@ -278,7 +278,7 @@ async function* processTransformResultAsync(result) {
278278
return;
279279
}
280280
if(ArrayBufferIsView(result)){
281-
yield[primitiveToUint8Array(result)];
281+
yield[arrayBufferViewToUint8Array(result)];
282282
return;
283283
}
284284
// Uint8Array[] batch
@@ -313,7 +313,9 @@ async function* processTransformResultAsync(result) {
313313
ArrayPrototypePush(batch,item);
314314
continue;
315315
}
316-
forawait(constchunkofflattenTransformYieldAsync(item)){
316+
// Note: This iteration is synchronous, since async iterables
317+
// may not be nested within sync iterables.
318+
for(constchunkofflattenTransformYieldSync(item)){
317319
ArrayPrototypePush(batch,chunk);
318320
}
319321
}
@@ -366,7 +368,7 @@ function* applyFusedStatelessSyncTransforms(source, run) {
366368
}elseif(isAnyArrayBuffer(current)){
367369
yield[newUint8Array(current)];
368370
}elseif(ArrayBufferIsView(current)){
369-
yield[primitiveToUint8Array(current)];
371+
yield[arrayBufferViewToUint8Array(current)];
370372
}else{
371373
yield*processTransformResultSync(current);
372374
}
@@ -428,7 +430,7 @@ function* createSyncPipeline(source, transforms) {
428430
}
429431
current=applyStatefulSyncTransform(current,transform.transform);
430432
}else{
431-
statelessRun.push(transform);
433+
ArrayPrototypePush(statelessRun,transform);
432434
}
433435
}
434436
if(statelessRun.length>0){
@@ -490,7 +492,7 @@ async function* applyFusedStatelessAsyncTransforms(source, run, signal) {
490492
}elseif(isAnyArrayBuffer(current)){
491493
yield[newUint8Array(current)];
492494
}elseif(ArrayBufferIsView(current)){
493-
yield[primitiveToUint8Array(current)];
495+
yield[arrayBufferViewToUint8Array(current)];
494496
}else{
495497
yield*processTransformResultAsync(current);
496498
}
@@ -531,9 +533,7 @@ async function* applyFusedStatelessAsyncTransforms(source, run, signal) {
531533
* @yields {Uint8Array[]}
532534
*/
533535
asyncfunction*withFlushAsync(source){
534-
forawait(constbatchofsource){
535-
yieldbatch;
536-
}
536+
yield*source;
537537
yieldnull;
538538
}
539539

@@ -647,7 +647,7 @@ async function* createAsyncPipeline(source, transforms, signal) {
647647
current,transform.transform,opts);
648648
}
649649
}else{
650-
statelessRun.push(transform);
650+
ArrayPrototypePush(statelessRun,transform);
651651
}
652652
}
653653
// Flush remaining stateless run

β€Žlib/internal/streams/iter/utils.jsβ€Ž

Lines changed: 27 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ const {
1212
TypedArrayPrototypeGetBuffer,
1313
TypedArrayPrototypeGetByteLength,
1414
TypedArrayPrototypeGetByteOffset,
15+
TypedArrayPrototypeSet,
1516
Uint8Array,
1617
}=primordials;
1718

@@ -24,8 +25,6 @@ const {
2425
}=require('internal/errors');
2526
const{ isError }=require('internal/util');
2627

27-
const{ Buffer }=require('buffer');
28-
2928
const{ isSharedArrayBuffer, isUint8Array }=require('internal/util/types');
3029

3130
const{ validateOneOf }=require('internal/validators');
@@ -127,26 +126,36 @@ function concatBytes(chunks) {
127126
if(chunks.length===0){
128127
returnnewUint8Array(0);
129128
}
130-
// Single chunk: return directly if it covers the entire backing buffer
129+
// Single chunk: return directly if it covers the entire backing buffer,
130+
// otherwise return a copy
131131
if(chunks.length===1){
132132
constchunk=chunks[0];
133-
constbuf=TypedArrayPrototypeGetBuffer(chunk);
134-
// SharedArrayBuffer is not available in primordials, so use
135-
// direct property access for its byteLength.
136-
constbufByteLength=isSharedArrayBuffer(buf) ?
137-
buf.byteLength :
138-
ArrayBufferPrototypeGetByteLength(buf);
139-
if(TypedArrayPrototypeGetByteOffset(chunk)===0&&
140-
TypedArrayPrototypeGetByteLength(chunk)===bufByteLength){
141-
returnchunk;
133+
// If non-zero offset, skip the remaining buffer checks.
134+
if(TypedArrayPrototypeGetByteOffset(chunk)===0){
135+
constbuf=TypedArrayPrototypeGetBuffer(chunk);
136+
// SharedArrayBuffer is not available in primordials, so use
137+
// direct property access for its byteLength.
138+
constbufByteLength=isSharedArrayBuffer(buf) ?
139+
buf.byteLength :
140+
ArrayBufferPrototypeGetByteLength(buf);
141+
if(TypedArrayPrototypeGetByteLength(chunk)===bufByteLength){
142+
returnchunk;
143+
}
142144
}
145+
returnnewUint8Array(chunk);
146+
}
147+
// Multiple chunks: concatenate
148+
lettotalByteLength=0;
149+
for(leti=0;i<chunks.length;i++){
150+
totalByteLength+=TypedArrayPrototypeGetByteLength(chunks[i]);
151+
}
152+
constconcatenated=newUint8Array(totalByteLength);
153+
letoffset=0;
154+
for(leti=0;i<chunks.length;i++){
155+
TypedArrayPrototypeSet(concatenated,chunks[i],offset);
156+
offset+=TypedArrayPrototypeGetByteLength(chunks[i]);
143157
}
144-
// Multiple chunks or shared buffer: concatenate
145-
constbuf=Buffer.concat(chunks);
146-
returnnewUint8Array(
147-
TypedArrayPrototypeGetBuffer(buf),
148-
TypedArrayPrototypeGetByteOffset(buf),
149-
TypedArrayPrototypeGetByteLength(buf));
158+
returnconcatenated;
150159
}
151160

152161
/**

0 commit comments

Comments
Β (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Commit b57b51e

Browse files
Renegade334aduh95
authored andcommitted
stream: minor stream/iter implementation edits
Signed-off-by: Renegade334 <contact.9a5d6388@renegade334.me.uk> PR-URL: #63132 Backport-PR-URL: #64675 Reviewed-By: James M Snell <jasnell@gmail.com> Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
1 parent 274b3a2 commit b57b51e

5 files changed

Lines changed: 63 additions & 47 deletions

File tree

β€Žlib/internal/streams/iter/classic.jsβ€Ž

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313

1414
const{
1515
ArrayIsArray,
16+
ArrayPrototypePush,
1617
MathMax,
1718
NumberMAX_SAFE_INTEGER,
1819
Promise,
@@ -107,14 +108,14 @@ async function normalizeBatch(raw) {
107108
for(leti=0;i<raw.length;i++){
108109
constvalue=raw[i];
109110
if(isUint8Array(value)){
110-
batch.push(value);
111+
ArrayPrototypePush(batch,value);
111112
}else{
112113
// normalizeAsyncValue may await for async protocols (e.g.
113114
// toAsyncStreamable on yielded objects). Stream events during
114115
// the suspension are queued, not lost -- errors will surface
115116
// on the next loop iteration after this yield completes.
116117
forawait(constnormalizedofnormalizeAsyncValue(value)){
117-
batch.push(normalized);
118+
ArrayPrototypePush(batch,normalized);
118119
}
119120
}
120121
}
@@ -163,7 +164,7 @@ async function* createBatchedAsyncIterator(stream, normalize) {
163164
stream._readableState?.length>0){
164165
constc=stream.read();
165166
if(c===null)break;
166-
batch.push(c);
167+
ArrayPrototypePush(batch,c);
167168
}
168169
if(normalize!==null){
169170
constresult=awaitnormalize(batch);
@@ -495,7 +496,7 @@ function fromWritable(writable, options = kNullPrototype) {
495496

496497
functionwaitForDrain(){
497498
const{ promise, resolve, reject }=PromiseWithResolvers();
498-
waiters.push({__proto__: null, resolve, reject });
499+
ArrayPrototypePush(waiters,{__proto__: null, resolve, reject });
499500
installListeners();
500501
returnpromise;
501502
}
@@ -686,7 +687,7 @@ function fromWritable(writable, options = kNullPrototype) {
686687
returnPromiseResolve(true);
687688
}
688689
const{ promise, resolve }=PromiseWithResolvers();
689-
waiters.push({
690+
ArrayPrototypePush(waiters,{
690691
__proto__: null,
691692
resolve(){resolve(true);},
692693
reject(){resolve(false);},

β€Žlib/internal/streams/iter/consumers.jsβ€Ž

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ const {
1212
ArrayBufferPrototypeSlice,
1313
ArrayPrototypeMap,
1414
ArrayPrototypePush,
15+
ArrayPrototypeShift,
1516
ArrayPrototypeSlice,
1617
Promise,
1718
PromisePrototypeThen,
@@ -477,7 +478,7 @@ function merge(...args) {
477478

478479
// Drain ready queue synchronously
479480
while(ready.length>0){
480-
constitem=ready.shift();
481+
constitem=ArrayPrototypeShift(ready);
481482
if(item?.error){
482483
throwitem.error;
483484
}

β€Žlib/internal/streams/iter/from.jsβ€Ž

Lines changed: 13 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -31,8 +31,8 @@ const {
3131

3232
const{
3333
isAnyArrayBuffer,
34-
isDataView,
3534
isPromise,
35+
isTypedArray,
3636
isUint8Array,
3737
}=require('internal/util/types');
3838

@@ -106,17 +106,21 @@ function primitiveToUint8Array(chunk) {
106106
returnchunk;
107107
}
108108
// Other ArrayBufferView types (Int8Array, DataView, etc.)
109-
if(isDataView(chunk)){
109+
returnarrayBufferViewToUint8Array(chunk);
110+
}
111+
112+
functionarrayBufferViewToUint8Array(chunk){
113+
if(isTypedArray(chunk)){
110114
returnnewUint8Array(
111-
DataViewPrototypeGetBuffer(chunk),
112-
DataViewPrototypeGetByteOffset(chunk),
113-
DataViewPrototypeGetByteLength(chunk),
115+
TypedArrayPrototypeGetBuffer(chunk),
116+
TypedArrayPrototypeGetByteOffset(chunk),
117+
TypedArrayPrototypeGetByteLength(chunk),
114118
);
115119
}
116120
returnnewUint8Array(
117-
TypedArrayPrototypeGetBuffer(chunk),
118-
TypedArrayPrototypeGetByteOffset(chunk),
119-
TypedArrayPrototypeGetByteLength(chunk),
121+
DataViewPrototypeGetBuffer(chunk),
122+
DataViewPrototypeGetByteOffset(chunk),
123+
DataViewPrototypeGetByteLength(chunk),
120124
);
121125
}
122126

@@ -580,6 +584,7 @@ function from(input) {
580584
// =============================================================================
581585

582586
module.exports={
587+
arrayBufferViewToUint8Array,
583588
from,
584589
fromSync,
585590
isAsyncIterable,

β€Žlib/internal/streams/iter/pull.jsβ€Ž

Lines changed: 15 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -33,9 +33,9 @@ const {
3333
const{ AbortController }=require('internal/abort_controller');
3434

3535
const{
36+
arrayBufferViewToUint8Array,
3637
from,
3738
fromSync,
38-
primitiveToUint8Array,
3939
isSyncIterable,
4040
isAsyncIterable,
4141
isUint8ArrayBatch,
@@ -136,7 +136,7 @@ function* flattenTransformYieldSync(value) {
136136
return;
137137
}
138138
if(ArrayBufferIsView(value)){
139-
yieldprimitiveToUint8Array(value);
139+
yieldarrayBufferViewToUint8Array(value);
140140
return;
141141
}
142142
// Must be Iterable<TransformYield>
@@ -170,7 +170,7 @@ async function* flattenTransformYieldAsync(value) {
170170
return;
171171
}
172172
if(ArrayBufferIsView(value)){
173-
yieldprimitiveToUint8Array(value);
173+
yieldarrayBufferViewToUint8Array(value);
174174
return;
175175
}
176176
// Check for async iterable first
@@ -180,10 +180,10 @@ async function* flattenTransformYieldAsync(value) {
180180
}
181181
return;
182182
}
183-
// Must be sync Iterable<TransformYield>
183+
// Must be sync Iterable<TransformYield>, no nested async iterables
184184
if(isSyncIterable(value)){
185185
for(constitemofvalue){
186-
yield*flattenTransformYieldAsync(item);
186+
yield*flattenTransformYieldSync(item);
187187
}
188188
return;
189189
}
@@ -218,7 +218,7 @@ function* processTransformResultSync(result) {
218218
return;
219219
}
220220
if(ArrayBufferIsView(result)){
221-
yield[primitiveToUint8Array(result)];
221+
yield[arrayBufferViewToUint8Array(result)];
222222
return;
223223
}
224224
// Uint8Array[] batch
@@ -278,7 +278,7 @@ async function* processTransformResultAsync(result) {
278278
return;
279279
}
280280
if(ArrayBufferIsView(result)){
281-
yield[primitiveToUint8Array(result)];
281+
yield[arrayBufferViewToUint8Array(result)];
282282
return;
283283
}
284284
// Uint8Array[] batch
@@ -313,7 +313,9 @@ async function* processTransformResultAsync(result) {
313313
ArrayPrototypePush(batch,item);
314314
continue;
315315
}
316-
forawait(constchunkofflattenTransformYieldAsync(item)){
316+
// Note: This iteration is synchronous, since async iterables
317+
// may not be nested within sync iterables.
318+
for(constchunkofflattenTransformYieldSync(item)){
317319
ArrayPrototypePush(batch,chunk);
318320
}
319321
}
@@ -366,7 +368,7 @@ function* applyFusedStatelessSyncTransforms(source, run) {
366368
}elseif(isAnyArrayBuffer(current)){
367369
yield[newUint8Array(current)];
368370
}elseif(ArrayBufferIsView(current)){
369-
yield[primitiveToUint8Array(current)];
371+
yield[arrayBufferViewToUint8Array(current)];
370372
}else{
371373
yield*processTransformResultSync(current);
372374
}
@@ -428,7 +430,7 @@ function* createSyncPipeline(source, transforms) {
428430
}
429431
current=applyStatefulSyncTransform(current,transform.transform);
430432
}else{
431-
statelessRun.push(transform);
433+
ArrayPrototypePush(statelessRun,transform);
432434
}
433435
}
434436
if(statelessRun.length>0){
@@ -490,7 +492,7 @@ async function* applyFusedStatelessAsyncTransforms(source, run, signal) {
490492
}elseif(isAnyArrayBuffer(current)){
491493
yield[newUint8Array(current)];
492494
}elseif(ArrayBufferIsView(current)){
493-
yield[primitiveToUint8Array(current)];
495+
yield[arrayBufferViewToUint8Array(current)];
494496
}else{
495497
yield*processTransformResultAsync(current);
496498
}
@@ -531,9 +533,7 @@ async function* applyFusedStatelessAsyncTransforms(source, run, signal) {
531533
* @yields {Uint8Array[]}
532534
*/
533535
asyncfunction*withFlushAsync(source){
534-
forawait(constbatchofsource){
535-
yieldbatch;
536-
}
536+
yield*source;
537537
yieldnull;
538538
}
539539

@@ -647,7 +647,7 @@ async function* createAsyncPipeline(source, transforms, signal) {
647647
current,transform.transform,opts);
648648
}
649649
}else{
650-
statelessRun.push(transform);
650+
ArrayPrototypePush(statelessRun,transform);
651651
}
652652
}
653653
// Flush remaining stateless run

β€Žlib/internal/streams/iter/utils.jsβ€Ž

Lines changed: 27 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ const {
1212
TypedArrayPrototypeGetBuffer,
1313
TypedArrayPrototypeGetByteLength,
1414
TypedArrayPrototypeGetByteOffset,
15+
TypedArrayPrototypeSet,
1516
Uint8Array,
1617
}=primordials;
1718

@@ -24,8 +25,6 @@ const {
2425
}=require('internal/errors');
2526
const{ isError }=require('internal/util');
2627

27-
const{ Buffer }=require('buffer');
28-
2928
const{ isSharedArrayBuffer, isUint8Array }=require('internal/util/types');
3029

3130
const{ validateOneOf }=require('internal/validators');
@@ -127,26 +126,36 @@ function concatBytes(chunks) {
127126
if(chunks.length===0){
128127
returnnewUint8Array(0);
129128
}
130-
// Single chunk: return directly if it covers the entire backing buffer
129+
// Single chunk: return directly if it covers the entire backing buffer,
130+
// otherwise return a copy
131131
if(chunks.length===1){
132132
constchunk=chunks[0];
133-
constbuf=TypedArrayPrototypeGetBuffer(chunk);
134-
// SharedArrayBuffer is not available in primordials, so use
135-
// direct property access for its byteLength.
136-
constbufByteLength=isSharedArrayBuffer(buf) ?
137-
buf.byteLength :
138-
ArrayBufferPrototypeGetByteLength(buf);
139-
if(TypedArrayPrototypeGetByteOffset(chunk)===0&&
140-
TypedArrayPrototypeGetByteLength(chunk)===bufByteLength){
141-
returnchunk;
133+
// If non-zero offset, skip the remaining buffer checks.
134+
if(TypedArrayPrototypeGetByteOffset(chunk)===0){
135+
constbuf=TypedArrayPrototypeGetBuffer(chunk);
136+
// SharedArrayBuffer is not available in primordials, so use
137+
// direct property access for its byteLength.
138+
constbufByteLength=isSharedArrayBuffer(buf) ?
139+
buf.byteLength :
140+
ArrayBufferPrototypeGetByteLength(buf);
141+
if(TypedArrayPrototypeGetByteLength(chunk)===bufByteLength){
142+
returnchunk;
143+
}
142144
}
145+
returnnewUint8Array(chunk);
146+
}
147+
// Multiple chunks: concatenate
148+
lettotalByteLength=0;
149+
for(leti=0;i<chunks.length;i++){
150+
totalByteLength+=TypedArrayPrototypeGetByteLength(chunks[i]);
151+
}
152+
constconcatenated=newUint8Array(totalByteLength);
153+
letoffset=0;
154+
for(leti=0;i<chunks.length;i++){
155+
TypedArrayPrototypeSet(concatenated,chunks[i],offset);
156+
offset+=TypedArrayPrototypeGetByteLength(chunks[i]);
143157
}
144-
// Multiple chunks or shared buffer: concatenate
145-
constbuf=Buffer.concat(chunks);
146-
returnnewUint8Array(
147-
TypedArrayPrototypeGetBuffer(buf),
148-
TypedArrayPrototypeGetByteOffset(buf),
149-
TypedArrayPrototypeGetByteLength(buf));
158+
returnconcatenated;
150159
}
151160

152161
/**

0 commit comments

Comments
Β (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content

Commit b57b51e

Browse files
Renegade334aduh95
authored andcommitted
stream: minor stream/iter implementation edits
Signed-off-by: Renegade334 <contact.9a5d6388@renegade334.me.uk> PR-URL: #63132 Backport-PR-URL: #64675 Reviewed-By: James M Snell <jasnell@gmail.com> Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
1 parent 274b3a2 commit b57b51e

5 files changed

Lines changed: 63 additions & 47 deletions

File tree

β€Žlib/internal/streams/iter/classic.jsβ€Ž

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313

1414
const{
1515
ArrayIsArray,
16+
ArrayPrototypePush,
1617
MathMax,
1718
NumberMAX_SAFE_INTEGER,
1819
Promise,
@@ -107,14 +108,14 @@ async function normalizeBatch(raw) {
107108
for(leti=0;i<raw.length;i++){
108109
constvalue=raw[i];
109110
if(isUint8Array(value)){
110-
batch.push(value);
111+
ArrayPrototypePush(batch,value);
111112
}else{
112113
// normalizeAsyncValue may await for async protocols (e.g.
113114
// toAsyncStreamable on yielded objects). Stream events during
114115
// the suspension are queued, not lost -- errors will surface
115116
// on the next loop iteration after this yield completes.
116117
forawait(constnormalizedofnormalizeAsyncValue(value)){
117-
batch.push(normalized);
118+
ArrayPrototypePush(batch,normalized);
118119
}
119120
}
120121
}
@@ -163,7 +164,7 @@ async function* createBatchedAsyncIterator(stream, normalize) {
163164
stream._readableState?.length>0){
164165
constc=stream.read();
165166
if(c===null)break;
166-
batch.push(c);
167+
ArrayPrototypePush(batch,c);
167168
}
168169
if(normalize!==null){
169170
constresult=awaitnormalize(batch);
@@ -495,7 +496,7 @@ function fromWritable(writable, options = kNullPrototype) {
495496

496497
functionwaitForDrain(){
497498
const{ promise, resolve, reject }=PromiseWithResolvers();
498-
waiters.push({__proto__: null, resolve, reject });
499+
ArrayPrototypePush(waiters,{__proto__: null, resolve, reject });
499500
installListeners();
500501
returnpromise;
501502
}
@@ -686,7 +687,7 @@ function fromWritable(writable, options = kNullPrototype) {
686687
returnPromiseResolve(true);
687688
}
688689
const{ promise, resolve }=PromiseWithResolvers();
689-
waiters.push({
690+
ArrayPrototypePush(waiters,{
690691
__proto__: null,
691692
resolve(){resolve(true);},
692693
reject(){resolve(false);},

β€Žlib/internal/streams/iter/consumers.jsβ€Ž

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ const {
1212
ArrayBufferPrototypeSlice,
1313
ArrayPrototypeMap,
1414
ArrayPrototypePush,
15+
ArrayPrototypeShift,
1516
ArrayPrototypeSlice,
1617
Promise,
1718
PromisePrototypeThen,
@@ -477,7 +478,7 @@ function merge(...args) {
477478

478479
// Drain ready queue synchronously
479480
while(ready.length>0){
480-
constitem=ready.shift();
481+
constitem=ArrayPrototypeShift(ready);
481482
if(item?.error){
482483
throwitem.error;
483484
}

β€Žlib/internal/streams/iter/from.jsβ€Ž

Lines changed: 13 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -31,8 +31,8 @@ const {
3131

3232
const{
3333
isAnyArrayBuffer,
34-
isDataView,
3534
isPromise,
35+
isTypedArray,
3636
isUint8Array,
3737
}=require('internal/util/types');
3838

@@ -106,17 +106,21 @@ function primitiveToUint8Array(chunk) {
106106
returnchunk;
107107
}
108108
// Other ArrayBufferView types (Int8Array, DataView, etc.)
109-
if(isDataView(chunk)){
109+
returnarrayBufferViewToUint8Array(chunk);
110+
}
111+
112+
functionarrayBufferViewToUint8Array(chunk){
113+
if(isTypedArray(chunk)){
110114
returnnewUint8Array(
111-
DataViewPrototypeGetBuffer(chunk),
112-
DataViewPrototypeGetByteOffset(chunk),
113-
DataViewPrototypeGetByteLength(chunk),
115+
TypedArrayPrototypeGetBuffer(chunk),
116+
TypedArrayPrototypeGetByteOffset(chunk),
117+
TypedArrayPrototypeGetByteLength(chunk),
114118
);
115119
}
116120
returnnewUint8Array(
117-
TypedArrayPrototypeGetBuffer(chunk),
118-
TypedArrayPrototypeGetByteOffset(chunk),
119-
TypedArrayPrototypeGetByteLength(chunk),
121+
DataViewPrototypeGetBuffer(chunk),
122+
DataViewPrototypeGetByteOffset(chunk),
123+
DataViewPrototypeGetByteLength(chunk),
120124
);
121125
}
122126

@@ -580,6 +584,7 @@ function from(input) {
580584
// =============================================================================
581585

582586
module.exports={
587+
arrayBufferViewToUint8Array,
583588
from,
584589
fromSync,
585590
isAsyncIterable,

β€Žlib/internal/streams/iter/pull.jsβ€Ž

Lines changed: 15 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -33,9 +33,9 @@ const {
3333
const{ AbortController }=require('internal/abort_controller');
3434

3535
const{
36+
arrayBufferViewToUint8Array,
3637
from,
3738
fromSync,
38-
primitiveToUint8Array,
3939
isSyncIterable,
4040
isAsyncIterable,
4141
isUint8ArrayBatch,
@@ -136,7 +136,7 @@ function* flattenTransformYieldSync(value) {
136136
return;
137137
}
138138
if(ArrayBufferIsView(value)){
139-
yieldprimitiveToUint8Array(value);
139+
yieldarrayBufferViewToUint8Array(value);
140140
return;
141141
}
142142
// Must be Iterable<TransformYield>
@@ -170,7 +170,7 @@ async function* flattenTransformYieldAsync(value) {
170170
return;
171171
}
172172
if(ArrayBufferIsView(value)){
173-
yieldprimitiveToUint8Array(value);
173+
yieldarrayBufferViewToUint8Array(value);
174174
return;
175175
}
176176
// Check for async iterable first
@@ -180,10 +180,10 @@ async function* flattenTransformYieldAsync(value) {
180180
}
181181
return;
182182
}
183-
// Must be sync Iterable<TransformYield>
183+
// Must be sync Iterable<TransformYield>, no nested async iterables
184184
if(isSyncIterable(value)){
185185
for(constitemofvalue){
186-
yield*flattenTransformYieldAsync(item);
186+
yield*flattenTransformYieldSync(item);
187187
}
188188
return;
189189
}
@@ -218,7 +218,7 @@ function* processTransformResultSync(result) {
218218
return;
219219
}
220220
if(ArrayBufferIsView(result)){
221-
yield[primitiveToUint8Array(result)];
221+
yield[arrayBufferViewToUint8Array(result)];
222222
return;
223223
}
224224
// Uint8Array[] batch
@@ -278,7 +278,7 @@ async function* processTransformResultAsync(result) {
278278
return;
279279
}
280280
if(ArrayBufferIsView(result)){
281-
yield[primitiveToUint8Array(result)];
281+
yield[arrayBufferViewToUint8Array(result)];
282282
return;
283283
}
284284
// Uint8Array[] batch
@@ -313,7 +313,9 @@ async function* processTransformResultAsync(result) {
313313
ArrayPrototypePush(batch,item);
314314
continue;
315315
}
316-
forawait(constchunkofflattenTransformYieldAsync(item)){
316+
// Note: This iteration is synchronous, since async iterables
317+
// may not be nested within sync iterables.
318+
for(constchunkofflattenTransformYieldSync(item)){
317319
ArrayPrototypePush(batch,chunk);
318320
}
319321
}
@@ -366,7 +368,7 @@ function* applyFusedStatelessSyncTransforms(source, run) {
366368
}elseif(isAnyArrayBuffer(current)){
367369
yield[newUint8Array(current)];
368370
}elseif(ArrayBufferIsView(current)){
369-
yield[primitiveToUint8Array(current)];
371+
yield[arrayBufferViewToUint8Array(current)];
370372
}else{
371373
yield*processTransformResultSync(current);
372374
}
@@ -428,7 +430,7 @@ function* createSyncPipeline(source, transforms) {
428430
}
429431
current=applyStatefulSyncTransform(current,transform.transform);
430432
}else{
431-
statelessRun.push(transform);
433+
ArrayPrototypePush(statelessRun,transform);
432434
}
433435
}
434436
if(statelessRun.length>0){
@@ -490,7 +492,7 @@ async function* applyFusedStatelessAsyncTransforms(source, run, signal) {
490492
}elseif(isAnyArrayBuffer(current)){
491493
yield[newUint8Array(current)];
492494
}elseif(ArrayBufferIsView(current)){
493-
yield[primitiveToUint8Array(current)];
495+
yield[arrayBufferViewToUint8Array(current)];
494496
}else{
495497
yield*processTransformResultAsync(current);
496498
}
@@ -531,9 +533,7 @@ async function* applyFusedStatelessAsyncTransforms(source, run, signal) {
531533
* @yields {Uint8Array[]}
532534
*/
533535
asyncfunction*withFlushAsync(source){
534-
forawait(constbatchofsource){
535-
yieldbatch;
536-
}
536+
yield*source;
537537
yieldnull;
538538
}
539539

@@ -647,7 +647,7 @@ async function* createAsyncPipeline(source, transforms, signal) {
647647
current,transform.transform,opts);
648648
}
649649
}else{
650-
statelessRun.push(transform);
650+
ArrayPrototypePush(statelessRun,transform);
651651
}
652652
}
653653
// Flush remaining stateless run

β€Žlib/internal/streams/iter/utils.jsβ€Ž

Lines changed: 27 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ const {
1212
TypedArrayPrototypeGetBuffer,
1313
TypedArrayPrototypeGetByteLength,
1414
TypedArrayPrototypeGetByteOffset,
15+
TypedArrayPrototypeSet,
1516
Uint8Array,
1617
}=primordials;
1718

@@ -24,8 +25,6 @@ const {
2425
}=require('internal/errors');
2526
const{ isError }=require('internal/util');
2627

27-
const{ Buffer }=require('buffer');
28-
2928
const{ isSharedArrayBuffer, isUint8Array }=require('internal/util/types');
3029

3130
const{ validateOneOf }=require('internal/validators');
@@ -127,26 +126,36 @@ function concatBytes(chunks) {
127126
if(chunks.length===0){
128127
returnnewUint8Array(0);
129128
}
130-
// Single chunk: return directly if it covers the entire backing buffer
129+
// Single chunk: return directly if it covers the entire backing buffer,
130+
// otherwise return a copy
131131
if(chunks.length===1){
132132
constchunk=chunks[0];
133-
constbuf=TypedArrayPrototypeGetBuffer(chunk);
134-
// SharedArrayBuffer is not available in primordials, so use
135-
// direct property access for its byteLength.
136-
constbufByteLength=isSharedArrayBuffer(buf) ?
137-
buf.byteLength :
138-
ArrayBufferPrototypeGetByteLength(buf);
139-
if(TypedArrayPrototypeGetByteOffset(chunk)===0&&
140-
TypedArrayPrototypeGetByteLength(chunk)===bufByteLength){
141-
returnchunk;
133+
// If non-zero offset, skip the remaining buffer checks.
134+
if(TypedArrayPrototypeGetByteOffset(chunk)===0){
135+
constbuf=TypedArrayPrototypeGetBuffer(chunk);
136+
// SharedArrayBuffer is not available in primordials, so use
137+
// direct property access for its byteLength.
138+
constbufByteLength=isSharedArrayBuffer(buf) ?
139+
buf.byteLength :
140+
ArrayBufferPrototypeGetByteLength(buf);
141+
if(TypedArrayPrototypeGetByteLength(chunk)===bufByteLength){
142+
returnchunk;
143+
}
142144
}
145+
returnnewUint8Array(chunk);
146+
}
147+
// Multiple chunks: concatenate
148+
lettotalByteLength=0;
149+
for(leti=0;i<chunks.length;i++){
150+
totalByteLength+=TypedArrayPrototypeGetByteLength(chunks[i]);
151+
}
152+
constconcatenated=newUint8Array(totalByteLength);
153+
letoffset=0;
154+
for(leti=0;i<chunks.length;i++){
155+
TypedArrayPrototypeSet(concatenated,chunks[i],offset);
156+
offset+=TypedArrayPrototypeGetByteLength(chunks[i]);
143157
}
144-
// Multiple chunks or shared buffer: concatenate
145-
constbuf=Buffer.concat(chunks);
146-
returnnewUint8Array(
147-
TypedArrayPrototypeGetBuffer(buf),
148-
TypedArrayPrototypeGetByteOffset(buf),
149-
TypedArrayPrototypeGetByteLength(buf));
158+
returnconcatenated;
150159
}
151160

152161
/**

0 commit comments

Comments
Β (0)