@@ -15,6 +15,8 @@ const {
1515 DataViewPrototypeGetByteOffset,
1616 FunctionPrototypeCall,
1717 ObjectFreeze,
18+ ObjectGetOwnPropertyDescriptor,
19+ ObjectGetPrototypeOf,
1820 ObjectSetPrototypeOf,
1921 PromisePrototypeThen,
2022 PromiseReject,
@@ -41,6 +43,7 @@ const { lazyDOMException } = require('internal/util');
4143
4244const {
4345 isAnyArrayBuffer,
46+ isGeneratorObject,
4447 isPromise,
4548 isTypedArray,
4649 isUint8Array,
@@ -1119,63 +1122,237 @@ function normalizeAsyncSource(source, context) {
11191122}
11201123
11211124// A value of a sync source that is not a Uint8Array or a Uint8Array[]
1122- // batch, yielded by readSyncSource() to be normalized asynchronously.
1125+ // batch, returned by SyncSourceReader to be normalized asynchronously.
11231126function SyncSourceValue ( value ) {
11241127 this . value = value ;
11251128}
11261129SyncSourceValue . prototype = ObjectFreeze ( { __proto__ : null } ) ;
11271130
11281131/**
1129- * Read a sync iterable source for from(): yields Uint8Array[] batches,
1132+ * Read a sync iterable source for from(): returns Uint8Array[] batches,
11301133 * collecting single Uint8Arrays into batches of up to FROM_BATCH_SIZE
11311134 * chunks, and a SyncSourceValue for any other value, after the chunks
11321135 * collected before it.
1133- * @param {Iterable } source
1134- * @param {object } context
1135- * @yields {Uint8Array[]|SyncSourceValue}
1136+ *
1137+ * This is what a sync generator doing `for (const value of source)` would
1138+ * yield, written out by hand, as it runs for every batch: next(), return()
1139+ * and throw() behave as that generator's do. The source is closed, as
1140+ * for...of closes it, when the reader is returned or thrown into while it
1141+ * is reading the source, or when the normalization is found cancelled;
1142+ * errors closing it are ignored for throw() and cancellation. An error from
1143+ * the source's next() or [Symbol.iterator]() ends the reader without
1144+ * closing the source.
11361145 */
1137- function * readSyncSource ( source , context ) {
1138- throwIfNormalizationCancelled ( context ) ;
1139- if ( ! isSyncIterable ( source ) ) {
1140- throw new ERR_INVALID_ARG_TYPE (
1141- 'source' , [ 'Iterable' , 'AsyncIterable' ] , source ) ;
1142- }
1143- let batch = [ ] ;
1144- for ( const value of source ) {
1145- throwIfNormalizationCancelled ( context ) ;
1146- // Fast path 1: value is already a Uint8Array[] batch
1147- if ( isUint8ArrayBatch ( value ) ) {
1148- // Flush any accumulated batch first
1149- if ( batch . length > 0 ) {
1150- yield batch ;
1151- batch = [ ] ;
1146+ // %GeneratorPrototype%.next, taken before user code runs.
1147+ const GeneratorPrototypeNext =
1148+ ObjectGetPrototypeOf ( function * ( ) { } ) . prototype . next ;
1149+
1150+ // How a SyncSourceReader calls the next() of its source's iterator.
1151+ const kNextOwn = 1 ;
1152+ const kNextGenerator = 2 ;
1153+
1154+ // The states of a SyncSourceReader: not started, reading the source, done.
1155+ const kReaderStart = 0 ;
1156+ const kReaderActive = 1 ;
1157+ const kReaderDone = 2 ;
1158+
1159+ class SyncSourceReader {
1160+ #source;
1161+ #context;
1162+ #iterator = null ;
1163+ #next = null ;
1164+ // kNextGenerator if the source's iterator is a generator whose next() is
1165+ // %GeneratorPrototype%.next, which is then called as a constant; kNextOwn
1166+ // if its next() is an own data property, which is then called as
1167+ // `iterator.next()`; otherwise 0, and #next is called with
1168+ // FunctionPrototypeCall(). Calls V8 can inline make reading single chunks
1169+ // faster. (Generators of different generator functions don't share a map,
1170+ // so for them `iterator.next()` would be a megamorphic load per chunk.)
1171+ #direct = 0 ;
1172+ #state = kReaderStart ;
1173+ // Single Uint8Arrays read and not yet returned.
1174+ #batch = [ ] ;
1175+ // A value to return on the next call, after the batch returned before it.
1176+ #pending = undefined ;
1177+ // A batch larger than FROM_BATCH_SIZE being returned in slices, and the
1178+ // offset of the next slice.
1179+ #large = null ;
1180+ #offset = 0 ;
1181+
1182+ constructor ( source , context ) {
1183+ this . #source = source ;
1184+ this . #context = context ;
1185+ }
1186+
1187+ next ( ) {
1188+ switch ( this . #state) {
1189+ case kReaderDone :
1190+ return new IterResult ( true , undefined ) ;
1191+ case kReaderStart :
1192+ this . #start( ) ;
1193+ break ;
1194+ }
1195+ if ( this . #pending !== undefined ) {
1196+ const value = this . #pending;
1197+ this . #pending = undefined ;
1198+ return new IterResult ( false , value ) ;
1199+ }
1200+ if ( this . #large !== null ) return new IterResult ( false , this . #nextSlice( ) ) ;
1201+ // Read into locals: the loop runs for every chunk of the source.
1202+ const iterator = this . #iterator;
1203+ const next = this . #next;
1204+ const direct = this . #direct;
1205+ const context = this . #context;
1206+ const batch = this . #batch;
1207+ for ( ; ; ) {
1208+ let value ;
1209+ try {
1210+ const result = direct === kNextGenerator ?
1211+ FunctionPrototypeCall ( GeneratorPrototypeNext , iterator ) :
1212+ direct === kNextOwn ? iterator . next ( ) :
1213+ FunctionPrototypeCall ( next , iterator ) ;
1214+ if ( ( typeof result !== 'object' && typeof result !== 'function' ) ||
1215+ result === null ) {
1216+ throw new ERR_INVALID_RETURN_VALUE (
1217+ 'an object' , 'iterator.next()' , result ) ;
1218+ }
1219+ if ( result . done ) {
1220+ this . #state = kReaderDone ;
1221+ if ( batch . length > 0 ) {
1222+ return new IterResult ( false , this . #takeBatch( ) ) ;
1223+ }
1224+ return new IterResult ( true , undefined ) ;
1225+ }
1226+ value = result . value ;
1227+ } catch ( error ) {
1228+ this . #state = kReaderDone ;
1229+ throw error ;
11521230 }
1153- if ( value . length <= FROM_BATCH_SIZE ) {
1154- if ( value . length !== 0 ) yield value ;
1155- } else {
1156- yield * yieldBoundedBatch ( value ) ;
1231+ if ( context ?. cancelled ) {
1232+ this . #close( true ) ;
1233+ throw context . reason ;
11571234 }
1158- continue ;
1159- }
1160- // Fast path 2: value is a single Uint8Array (very common)
1161- if ( isUint8Array ( value ) ) {
1162- batch [ batch . length ] = value ;
1163- if ( batch . length === FROM_BATCH_SIZE ) {
1164- yield batch ;
1165- batch = [ ] ;
1235+ // Fast path 1: value is a single Uint8Array (very common). Checking
1236+ // ArrayIsArray() first keeps batches from paying for isUint8Array().
1237+ const isArray = ArrayIsArray ( value ) ;
1238+ if ( ! isArray && isUint8Array ( value ) ) {
1239+ batch [ batch . length ] = value ;
1240+ if ( batch . length === FROM_BATCH_SIZE ) {
1241+ return new IterResult ( false , this . #takeBatch( ) ) ;
1242+ }
1243+ continue ;
11661244 }
1167- continue ;
1245+ // Fast path 2: value is already a Uint8Array[] batch
1246+ if ( isArray && isUint8ArrayBatch ( value ) ) {
1247+ if ( value . length === 0 ) {
1248+ if ( batch . length > 0 ) {
1249+ return new IterResult ( false , this . #takeBatch( ) ) ;
1250+ }
1251+ continue ;
1252+ }
1253+ let ready = value ;
1254+ if ( value . length > FROM_BATCH_SIZE ) {
1255+ this . #large = value ;
1256+ this . #offset = 0 ;
1257+ ready = undefined ;
1258+ }
1259+ // Flush any accumulated batch first
1260+ if ( batch . length > 0 ) {
1261+ this . #pending = ready ;
1262+ return new IterResult ( false , this . #takeBatch( ) ) ;
1263+ }
1264+ return new IterResult ( false , ready ?? this . #nextSlice( ) ) ;
1265+ }
1266+ // Slow path: flush, then have the value normalized
1267+ const sourceValue = new SyncSourceValue ( value ) ;
1268+ if ( batch . length > 0 ) {
1269+ this . #pending = sourceValue ;
1270+ return new IterResult ( false , this . #takeBatch( ) ) ;
1271+ }
1272+ return new IterResult ( false , sourceValue ) ;
11681273 }
1169- // Slow path: flush, then have the value normalized
1170- if ( batch . length > 0 ) {
1171- yield batch ;
1172- batch = [ ] ;
1274+ }
1275+
1276+ return ( ) {
1277+ const state = this . #state;
1278+ this . #state = kReaderDone ;
1279+ this . #pending = undefined ;
1280+ this . #large = null ;
1281+ if ( state === kReaderActive ) this . #close( false ) ;
1282+ return new IterResult ( true , undefined ) ;
1283+ }
1284+
1285+ throw ( error ) {
1286+ const state = this . #state;
1287+ this . #state = kReaderDone ;
1288+ this . #pending = undefined ;
1289+ this . #large = null ;
1290+ if ( state === kReaderActive ) this . #close( true ) ;
1291+ throw error ;
1292+ }
1293+
1294+ #start( ) {
1295+ this . #state = kReaderActive ;
1296+ try {
1297+ throwIfNormalizationCancelled ( this . #context) ;
1298+ const source = this . #source;
1299+ if ( ! isSyncIterable ( source ) ) {
1300+ throw new ERR_INVALID_ARG_TYPE (
1301+ 'source' , [ 'Iterable' , 'AsyncIterable' ] , source ) ;
1302+ }
1303+ const iterator = source [ SymbolIterator ] ( ) ;
1304+ const next = iterator . next ;
1305+ this . #iterator = iterator ;
1306+ this . #next = next ;
1307+ if ( isGeneratorObject ( iterator ) && next === GeneratorPrototypeNext ) {
1308+ this . #direct = kNextGenerator ;
1309+ } else if ( typeof iterator === 'object' && iterator !== null ) {
1310+ const descriptor = ObjectGetOwnPropertyDescriptor ( iterator , 'next' ) ;
1311+ if ( descriptor !== undefined && descriptor . value === next ) {
1312+ this . #direct = kNextOwn ;
1313+ }
1314+ }
1315+ } catch ( error ) {
1316+ this . #state = kReaderDone ;
1317+ throw error ;
11731318 }
1174- yield new SyncSourceValue ( value ) ;
11751319 }
1176- // Yield any remaining batched values
1177- if ( batch . length > 0 ) {
1178- yield batch ;
1320+
1321+ #takeBatch( ) {
1322+ const batch = this . #batch;
1323+ this . #batch = [ ] ;
1324+ return batch ;
1325+ }
1326+
1327+ #nextSlice( ) {
1328+ const large = this . #large;
1329+ const offset = this . #offset;
1330+ this . #offset = offset + FROM_BATCH_SIZE ;
1331+ if ( this . #offset >= large . length ) this . #large = null ;
1332+ return ArrayPrototypeSlice ( large , offset , offset + FROM_BATCH_SIZE ) ;
1333+ }
1334+
1335+ // Close the source as for...of does: errors are ignored if `quiet` (an
1336+ // error is being thrown), and otherwise thrown, as is a result of
1337+ // return() that is not an object.
1338+ #close( quiet ) {
1339+ this . #state = kReaderDone ;
1340+ const iterator = this . #iterator;
1341+ let result ;
1342+ try {
1343+ const returnMethod = iterator . return ;
1344+ if ( returnMethod === undefined || returnMethod === null ) return ;
1345+ result = FunctionPrototypeCall ( returnMethod , iterator ) ;
1346+ } catch ( error ) {
1347+ if ( quiet ) return ;
1348+ throw error ;
1349+ }
1350+ if ( ! quiet &&
1351+ ( ( typeof result !== 'object' && typeof result !== 'function' ) ||
1352+ result === null ) ) {
1353+ throw new ERR_INVALID_RETURN_VALUE (
1354+ 'an object' , 'iterator.return()' , result ) ;
1355+ }
11791356 }
11801357}
11811358
@@ -1184,19 +1361,19 @@ function* readSyncSource(source, context) {
11841361 * Uint8Array, without an async generator layer for every batch (see
11851362 * createAsyncSourceNormalizer()).
11861363 *
1187- * The source is read by the sync generator readSyncSource(), so for...of
1188- * reads and closes it , and this iterator only adds the asynchronous
1189- * normalization of values that need it. Operations on the generator mirror
1190- * those on the async generator this replaces: return() and throw() are
1191- * passed to it, after closing the value being normalized, and an error
1192- * normalizing a value is thrown into it, so that for...of closes the source
1193- * as for an error in the loop body .
1364+ * The source is read by a SyncSourceReader, which reads and closes it as
1365+ * for...of does , and this iterator only adds the asynchronous normalization
1366+ * of values that need it. Operations on the reader mirror those on the
1367+ * async generator this replaces: return() and throw() are passed to it,
1368+ * after closing the value being normalized, and an error normalizing a
1369+ * value is thrown into it, so that the source is closed as for an error in
1370+ * the body of a for...of loop.
11941371 * @param {Iterable } source
11951372 * @param {object } context
11961373 * @returns {object } An object with next(), return() and throw().
11971374 */
11981375function createSyncSourceNormalizer ( source , context ) {
1199- const reader = readSyncSource ( source , context ) ;
1376+ const reader = new SyncSourceReader ( source , context ) ;
12001377 let done = false ;
12011378 // A normalizeAsyncSourceValue() generator for the value being normalized.
12021379 let valueBatches = null ;
@@ -1206,6 +1383,11 @@ function createSyncSourceNormalizer(source, context) {
12061383 // until the tick after a yield or return (both await their operand), so
12071384 // that a next(), return() or throw() made synchronously after this one is
12081385 // queued behind it; do the same.
1386+ // TODO(@jasnell): This costs a microtask per batch. Running a call made
1387+ // while the previous one has finished synchronously right away would make
1388+ // for-await over from(syncSource) about 1.3x faster, at the cost of this
1389+ // async generator parity for calls made back to back without awaiting
1390+ // (see testFromSyncSourceQueuesBehindReturn).
12091391 function finish ( result ) {
12101392 PromisePrototypeThen ( kResolvedPromise , release ) ;
12111393 return result ;
0 commit comments