Best JavaScript code snippet using wpt
readable-stream.js
Source:readable-stream.js
...934 .catch(rethrowAssertionErrorRejection);935 }936 get byobRequest() {937 if (IsReadableByteStreamController(this) === false) {938 throw byteStreamControllerBrandCheckException('byobRequest');939 }940 if (this._byobRequest === undefined && this._pendingPullIntos.length > 0) {941 const firstDescriptor = this._pendingPullIntos[0];942 const view = new Uint8Array(firstDescriptor.buffer,943 firstDescriptor.byteOffset + firstDescriptor.bytesFilled,944 firstDescriptor.byteLength - firstDescriptor.bytesFilled);945 this._byobRequest = new ReadableStreamBYOBRequest(this, view);946 }947 return this._byobRequest;948 }949 get desiredSize() {950 if (IsReadableByteStreamController(this) === false) {951 throw byteStreamControllerBrandCheckException('desiredSize');952 }953 return ReadableByteStreamControllerGetDesiredSize(this);954 }955 close() {956 if (IsReadableByteStreamController(this) === false) {957 throw byteStreamControllerBrandCheckException('close');958 }959 if (this._closeRequested === true) {960 throw new TypeError('The stream has already been closed; do not close it again!');961 }962 const state = this._controlledReadableStream._state;963 if (state !== 'readable') {964 throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`);965 }966 ReadableByteStreamControllerClose(this);967 }968 enqueue(chunk) {969 if (IsReadableByteStreamController(this) === false) {970 throw byteStreamControllerBrandCheckException('enqueue');971 }972 if (this._closeRequested === true) {973 throw new TypeError('stream is closed or draining');974 }975 const state = this._controlledReadableStream._state;976 if (state !== 'readable') {977 throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`);978 }979 if (!ArrayBuffer.isView(chunk)) {980 throw new TypeError('You can only enqueue array buffer views when using a ReadableByteStreamController');981 }982 ReadableByteStreamControllerEnqueue(this, chunk);983 }984 error(e) {985 if (IsReadableByteStreamController(this) === false) {986 throw byteStreamControllerBrandCheckException('error');987 }988 const stream = this._controlledReadableStream;989 if (stream._state !== 'readable') {990 throw new TypeError(`The stream is ${stream._state} and so cannot be errored`);991 }992 ReadableByteStreamControllerError(this, e);993 }994 [InternalCancel](reason) {995 if (this._pendingPullIntos.length > 0) {996 const firstDescriptor = this._pendingPullIntos[0];997 firstDescriptor.bytesFilled = 0;998 }999 this._queue = [];1000 this._totalQueuedBytes = 0;1001 return PromiseInvokeOrNoop(this._underlyingByteSource, 'cancel', [reason]);1002 }1003 [InternalPull]() {1004 const stream = this._controlledReadableStream;1005 if (ReadableStreamGetNumReadRequests(stream) === 0) {1006 if (this._totalQueuedBytes > 0) {1007 const entry = this._queue.shift();1008 this._totalQueuedBytes -= entry.byteLength;1009 ReadableByteStreamControllerHandleQueueDrain(this);1010 let view;1011 try {1012 view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength);1013 } catch (viewE) {1014 return Promise.reject(viewE);1015 }1016 return Promise.resolve(CreateIterResultObject(view, false));1017 }1018 const autoAllocateChunkSize = this._autoAllocateChunkSize;1019 if (autoAllocateChunkSize !== undefined) {1020 let buffer;1021 try {1022 buffer = new ArrayBuffer(autoAllocateChunkSize);1023 } catch (bufferE) {1024 return Promise.reject(bufferE);1025 }1026 const pullIntoDescriptor = {1027 buffer,1028 byteOffset: 0,1029 byteLength: autoAllocateChunkSize,1030 bytesFilled: 0,1031 elementSize: 1,1032 ctor: Uint8Array,1033 readerType: 'default'1034 };1035 this._pendingPullIntos.push(pullIntoDescriptor);1036 }1037 } else {1038 assert(this._autoAllocateChunkSize === undefined);1039 }1040 const promise = ReadableStreamAddReadRequest(stream);1041 ReadableByteStreamControllerCallPullIfNeeded(this);1042 return promise;1043 }1044}1045// Abstract operations for the ReadableByteStreamController.1046function IsReadableByteStreamController(x) {1047 if (!typeIsObject(x)) {1048 return false;1049 }1050 if (!Object.prototype.hasOwnProperty.call(x, '_underlyingByteSource')) {1051 return false;1052 }1053 return true;1054}1055function IsReadableStreamBYOBRequest(x) {1056 if (!typeIsObject(x)) {1057 return false;1058 }1059 if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) {1060 return false;1061 }1062 return true;1063}1064function ReadableByteStreamControllerCallPullIfNeeded(controller) {1065 const shouldPull = ReadableByteStreamControllerShouldCallPull(controller);1066 if (shouldPull === false) {1067 return undefined;1068 }1069 if (controller._pulling === true) {1070 controller._pullAgain = true;1071 return undefined;1072 }1073 assert(controller._pullAgain === false);1074 controller._pulling = true;1075 // TODO: Test controller argument1076 const pullPromise = PromiseInvokeOrNoop(controller._underlyingByteSource, 'pull', [controller]);1077 pullPromise.then(1078 () => {1079 controller._pulling = false;1080 if (controller._pullAgain === true) {1081 controller._pullAgain = false;1082 ReadableByteStreamControllerCallPullIfNeeded(controller);1083 }1084 },1085 e => {1086 if (controller._controlledReadableStream._state === 'readable') {1087 ReadableByteStreamControllerError(controller, e);1088 }1089 }1090 )1091 .catch(rethrowAssertionErrorRejection);1092 return undefined;1093}1094function ReadableByteStreamControllerClearPendingPullIntos(controller) {1095 ReadableByteStreamControllerInvalidateBYOBRequest(controller);1096 controller._pendingPullIntos = [];1097}1098function ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor) {1099 assert(stream._state !== 'errored', 'state must not be errored');1100 let done = false;1101 if (stream._state === 'closed') {1102 assert(pullIntoDescriptor.bytesFilled === 0);1103 done = true;1104 }1105 const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);1106 if (pullIntoDescriptor.readerType === 'default') {1107 ReadableStreamFulfillReadRequest(stream, filledView, done);1108 } else {1109 assert(pullIntoDescriptor.readerType === 'byob');1110 ReadableStreamFulfillReadIntoRequest(stream, filledView, done);1111 }1112}1113function ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor) {1114 const bytesFilled = pullIntoDescriptor.bytesFilled;1115 const elementSize = pullIntoDescriptor.elementSize;1116 assert(bytesFilled <= pullIntoDescriptor.byteLength);1117 assert(bytesFilled % elementSize === 0);1118 return new pullIntoDescriptor.ctor(1119 pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize);1120}1121function ReadableByteStreamControllerEnqueueChunkToQueue(controller, buffer, byteOffset, byteLength) {1122 controller._queue.push({ buffer, byteOffset, byteLength });1123 controller._totalQueuedBytes += byteLength;1124}1125function ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor) {1126 const elementSize = pullIntoDescriptor.elementSize;1127 const currentAlignedBytes = pullIntoDescriptor.bytesFilled - pullIntoDescriptor.bytesFilled % elementSize;1128 const maxBytesToCopy = Math.min(controller._totalQueuedBytes,1129 pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled);1130 const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy;1131 const maxAlignedBytes = maxBytesFilled - maxBytesFilled % elementSize;1132 let totalBytesToCopyRemaining = maxBytesToCopy;1133 let ready = false;1134 if (maxAlignedBytes > currentAlignedBytes) {1135 totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled;1136 ready = true;1137 }1138 const queue = controller._queue;1139 while (totalBytesToCopyRemaining > 0) {1140 const headOfQueue = queue[0];1141 const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength);1142 const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;1143 ArrayBufferCopy(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy);1144 if (headOfQueue.byteLength === bytesToCopy) {1145 queue.shift();1146 } else {1147 headOfQueue.byteOffset += bytesToCopy;1148 headOfQueue.byteLength -= bytesToCopy;1149 }1150 controller._totalQueuedBytes -= bytesToCopy;1151 ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor);1152 totalBytesToCopyRemaining -= bytesToCopy;1153 }1154 if (ready === false) {1155 assert(controller._totalQueuedBytes === 0, 'queue must be empty');1156 assert(pullIntoDescriptor.bytesFilled > 0);1157 assert(pullIntoDescriptor.bytesFilled < pullIntoDescriptor.elementSize);1158 }1159 return ready;1160}1161function ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, size, pullIntoDescriptor) {1162 assert(controller._pendingPullIntos.length === 0 || controller._pendingPullIntos[0] === pullIntoDescriptor);1163 ReadableByteStreamControllerInvalidateBYOBRequest(controller);1164 pullIntoDescriptor.bytesFilled += size;1165}1166function ReadableByteStreamControllerHandleQueueDrain(controller) {1167 assert(controller._controlledReadableStream._state === 'readable');1168 if (controller._totalQueuedBytes === 0 && controller._closeRequested === true) {1169 ReadableStreamClose(controller._controlledReadableStream);1170 } else {1171 ReadableByteStreamControllerCallPullIfNeeded(controller);1172 }1173}1174function ReadableByteStreamControllerInvalidateBYOBRequest(controller) {1175 if (controller._byobRequest === undefined) {1176 return;1177 }1178 controller._byobRequest._associatedReadableByteStreamController = undefined;1179 controller._byobRequest._view = undefined;1180 controller._byobRequest = undefined;1181}1182function ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller) {1183 assert(controller._closeRequested === false);1184 while (controller._pendingPullIntos.length > 0) {1185 if (controller._totalQueuedBytes === 0) {1186 return;1187 }1188 const pullIntoDescriptor = controller._pendingPullIntos[0];1189 if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor) === true) {1190 ReadableByteStreamControllerShiftPendingPullInto(controller);1191 ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableStream, pullIntoDescriptor);1192 }1193 }1194}1195function ReadableByteStreamControllerPullInto(controller, view) {1196 const stream = controller._controlledReadableStream;1197 let elementSize = 1;1198 if (view.constructor !== DataView) {1199 elementSize = view.constructor.BYTES_PER_ELEMENT;1200 }1201 const ctor = view.constructor;1202 const pullIntoDescriptor = {1203 buffer: view.buffer,1204 byteOffset: view.byteOffset,1205 byteLength: view.byteLength,1206 bytesFilled: 0,1207 elementSize,1208 ctor,1209 readerType: 'byob'1210 };1211 if (controller._pendingPullIntos.length > 0) {1212 pullIntoDescriptor.buffer = SameRealmTransfer(pullIntoDescriptor.buffer);1213 controller._pendingPullIntos.push(pullIntoDescriptor);1214 // No ReadableByteStreamControllerCallPullIfNeeded() call since:1215 // - No change happens on desiredSize1216 // - The source has already been notified of that there's at least 1 pending read(view)1217 return ReadableStreamAddReadIntoRequest(stream);1218 }1219 if (stream._state === 'closed') {1220 const emptyView = new view.constructor(view.buffer, view.byteOffset, 0);1221 return Promise.resolve(CreateIterResultObject(emptyView, true));1222 }1223 if (controller._totalQueuedBytes > 0) {1224 if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor) === true) {1225 const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);1226 ReadableByteStreamControllerHandleQueueDrain(controller);1227 return Promise.resolve(CreateIterResultObject(filledView, false));1228 }1229 if (controller._closeRequested === true) {1230 const e = new TypeError('Insufficient bytes to fill elements in the given buffer');1231 ReadableByteStreamControllerError(controller, e);1232 return Promise.reject(e);1233 }1234 }1235 pullIntoDescriptor.buffer = SameRealmTransfer(pullIntoDescriptor.buffer);1236 controller._pendingPullIntos.push(pullIntoDescriptor);1237 const promise = ReadableStreamAddReadIntoRequest(stream);1238 ReadableByteStreamControllerCallPullIfNeeded(controller);1239 return promise;1240}1241function ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor) {1242 firstDescriptor.buffer = SameRealmTransfer(firstDescriptor.buffer);1243 assert(firstDescriptor.bytesFilled === 0, 'bytesFilled must be 0');1244 const stream = controller._controlledReadableStream;1245 while (ReadableStreamGetNumReadIntoRequests(stream) > 0) {1246 const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller);1247 ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor);1248 }1249}1250function ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, pullIntoDescriptor) {1251 if (pullIntoDescriptor.bytesFilled + bytesWritten > pullIntoDescriptor.byteLength) {1252 throw new RangeError('bytesWritten out of range');1253 }1254 ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor);1255 if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.elementSize) {1256 // TODO: Figure out whether we should detach the buffer or not here.1257 return;1258 }1259 ReadableByteStreamControllerShiftPendingPullInto(controller);1260 const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize;1261 if (remainderSize > 0) {1262 const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;1263 const remainder = pullIntoDescriptor.buffer.slice(end - remainderSize, end);1264 ReadableByteStreamControllerEnqueueChunkToQueue(controller, remainder, 0, remainder.byteLength);1265 }1266 pullIntoDescriptor.buffer = SameRealmTransfer(pullIntoDescriptor.buffer);1267 pullIntoDescriptor.bytesFilled -= remainderSize;1268 ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableStream, pullIntoDescriptor);1269 ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);1270}1271function ReadableByteStreamControllerRespondInternal(controller, bytesWritten) {1272 const firstDescriptor = controller._pendingPullIntos[0];1273 const stream = controller._controlledReadableStream;1274 if (stream._state === 'closed') {1275 if (bytesWritten !== 0) {1276 throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream');1277 }1278 ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor);1279 } else {1280 assert(stream._state === 'readable');1281 ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor);1282 }1283}1284function ReadableByteStreamControllerShiftPendingPullInto(controller) {1285 const descriptor = controller._pendingPullIntos.shift();1286 ReadableByteStreamControllerInvalidateBYOBRequest(controller);1287 return descriptor;1288}1289function ReadableByteStreamControllerShouldCallPull(controller) {1290 const stream = controller._controlledReadableStream;1291 if (stream._state !== 'readable') {1292 return false;1293 }1294 if (controller._closeRequested === true) {1295 return false;1296 }1297 if (controller._started === false) {1298 return false;1299 }1300 if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {1301 return true;1302 }1303 if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) {1304 return true;1305 }1306 if (ReadableByteStreamControllerGetDesiredSize(controller) > 0) {1307 return true;1308 }1309 return false;1310}1311// A client of ReadableByteStreamController may use these functions directly to bypass state check.1312function ReadableByteStreamControllerClose(controller) {1313 const stream = controller._controlledReadableStream;1314 assert(controller._closeRequested === false);1315 assert(stream._state === 'readable');1316 if (controller._totalQueuedBytes > 0) {1317 controller._closeRequested = true;1318 return;1319 }1320 if (controller._pendingPullIntos.length > 0) {1321 const firstPendingPullInto = controller._pendingPullIntos[0];1322 if (firstPendingPullInto.bytesFilled > 0) {1323 const e = new TypeError('Insufficient bytes to fill elements in the given buffer');1324 ReadableByteStreamControllerError(controller, e);1325 throw e;1326 }1327 }1328 ReadableStreamClose(stream);1329}1330function ReadableByteStreamControllerEnqueue(controller, chunk) {1331 const stream = controller._controlledReadableStream;1332 assert(controller._closeRequested === false);1333 assert(stream._state === 'readable');1334 const buffer = chunk.buffer;1335 const byteOffset = chunk.byteOffset;1336 const byteLength = chunk.byteLength;1337 const transferredBuffer = SameRealmTransfer(buffer);1338 if (ReadableStreamHasDefaultReader(stream) === true) {1339 if (ReadableStreamGetNumReadRequests(stream) === 0) {1340 ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);1341 } else {1342 assert(controller._queue.length === 0);1343 const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength);1344 ReadableStreamFulfillReadRequest(stream, transferredView, false);1345 }1346 } else if (ReadableStreamHasBYOBReader(stream) === true) {1347 // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully.1348 ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);1349 ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);1350 } else {1351 assert(IsReadableStreamLocked(stream) === false, 'stream must not be locked');1352 ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);1353 }1354}1355function ReadableByteStreamControllerError(controller, e) {1356 const stream = controller._controlledReadableStream;1357 assert(stream._state === 'readable');1358 ReadableByteStreamControllerClearPendingPullIntos(controller);1359 controller._queue = [];1360 ReadableStreamError(stream, e);1361}1362function ReadableByteStreamControllerGetDesiredSize(controller) {1363 return controller._strategyHWM - controller._totalQueuedBytes;1364}1365function ReadableByteStreamControllerRespond(controller, bytesWritten) {1366 bytesWritten = Number(bytesWritten);1367 if (IsFiniteNonNegativeNumber(bytesWritten) === false) {1368 throw new RangeError('bytesWritten must be a finite');1369 }1370 assert(controller._pendingPullIntos.length > 0);1371 ReadableByteStreamControllerRespondInternal(controller, bytesWritten);1372}1373function ReadableByteStreamControllerRespondWithNewView(controller, view) {1374 assert(controller._pendingPullIntos.length > 0);1375 const firstDescriptor = controller._pendingPullIntos[0];1376 if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) {1377 throw new RangeError('The region specified by view does not match byobRequest');1378 }1379 if (firstDescriptor.byteLength !== view.byteLength) {1380 throw new RangeError('The buffer of view has different capacity than byobRequest');1381 }1382 firstDescriptor.buffer = view.buffer;1383 ReadableByteStreamControllerRespondInternal(controller, view.byteLength);1384}1385// Helper functions for the ReadableStream.1386function streamBrandCheckException(name) {1387 return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`);1388}1389// Helper functions for the readers.1390function readerLockException(name) {1391 return new TypeError('Cannot ' + name + ' a stream using a released reader');1392}1393// Helper functions for the ReadableStreamDefaultReader.1394function defaultReaderBrandCheckException(name) {1395 return new TypeError(1396 `ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`);1397}1398function defaultReaderClosedPromiseInitialize(reader) {1399 reader._closedPromise = new Promise((resolve, reject) => {1400 reader._closedPromise_resolve = resolve;1401 reader._closedPromise_reject = reject;1402 });1403}1404function defaultReaderClosedPromiseInitializeAsRejected(reader, reason) {1405 reader._closedPromise = Promise.reject(reason);1406 reader._closedPromise_resolve = undefined;1407 reader._closedPromise_reject = undefined;1408}1409function defaultReaderClosedPromiseInitializeAsResolved(reader) {1410 reader._closedPromise = Promise.resolve(undefined);1411 reader._closedPromise_resolve = undefined;1412 reader._closedPromise_reject = undefined;1413}1414function defaultReaderClosedPromiseReject(reader, reason) {1415 assert(reader._closedPromise_resolve !== undefined);1416 assert(reader._closedPromise_reject !== undefined);1417 reader._closedPromise_reject(reason);1418 reader._closedPromise_resolve = undefined;1419 reader._closedPromise_reject = undefined;1420}1421function defaultReaderClosedPromiseResetToRejected(reader, reason) {1422 assert(reader._closedPromise_resolve === undefined);1423 assert(reader._closedPromise_reject === undefined);1424 reader._closedPromise = Promise.reject(reason);1425}1426function defaultReaderClosedPromiseResolve(reader) {1427 assert(reader._closedPromise_resolve !== undefined);1428 assert(reader._closedPromise_reject !== undefined);1429 reader._closedPromise_resolve(undefined);1430 reader._closedPromise_resolve = undefined;1431 reader._closedPromise_reject = undefined;1432}1433// Helper functions for the ReadableStreamDefaultReader.1434function byobReaderBrandCheckException(name) {1435 return new TypeError(1436 `ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`);1437}1438// Helper functions for the ReadableStreamDefaultController.1439function defaultControllerBrandCheckException(name) {1440 return new TypeError(1441 `ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`);1442}1443// Helper functions for the ReadableStreamBYOBRequest.1444function byobRequestBrandCheckException(name) {1445 return new TypeError(1446 `ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`);1447}1448// Helper functions for the ReadableByteStreamController.1449function byteStreamControllerBrandCheckException(name) {1450 return new TypeError(1451 `ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`);...
byte-stream-controller.ts
Source:byte-stream-controller.ts
...184 * Returns the current BYOB pull request, or `null` if there isn't one.185 */186 get byobRequest(): ReadableStreamBYOBRequest | null {187 if (!IsReadableByteStreamController(this)) {188 throw byteStreamControllerBrandCheckException('byobRequest');189 }190 if (this._byobRequest === null && this._pendingPullIntos.length > 0) {191 const firstDescriptor = this._pendingPullIntos.peek();192 const view = new Uint8Array(firstDescriptor.buffer,193 firstDescriptor.byteOffset + firstDescriptor.bytesFilled,194 firstDescriptor.byteLength - firstDescriptor.bytesFilled);195 const byobRequest: ReadableStreamBYOBRequest = Object.create(ReadableStreamBYOBRequest.prototype);196 SetUpReadableStreamBYOBRequest(byobRequest, this, view);197 this._byobRequest = byobRequest;198 }199 return this._byobRequest;200 }201 /**202 * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is203 * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure.204 */205 get desiredSize(): number | null {206 if (!IsReadableByteStreamController(this)) {207 throw byteStreamControllerBrandCheckException('desiredSize');208 }209 return ReadableByteStreamControllerGetDesiredSize(this);210 }211 /**212 * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from213 * the stream, but once those are read, the stream will become closed.214 */215 close(): void {216 if (!IsReadableByteStreamController(this)) {217 throw byteStreamControllerBrandCheckException('close');218 }219 if (this._closeRequested) {220 throw new TypeError('The stream has already been closed; do not close it again!');221 }222 const state = this._controlledReadableByteStream._state;223 if (state !== 'readable') {224 throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`);225 }226 ReadableByteStreamControllerClose(this);227 }228 /**229 * Enqueues the given chunk chunk in the controlled readable stream.230 * The chunk has to be an `ArrayBufferView` instance, or else a `TypeError` will be thrown.231 */232 enqueue(chunk: ArrayBufferView): void;233 enqueue(chunk: ArrayBufferView | undefined): void {234 if (!IsReadableByteStreamController(this)) {235 throw byteStreamControllerBrandCheckException('enqueue');236 }237 assertRequiredArgument(chunk, 1, 'enqueue');238 if (!ArrayBuffer.isView(chunk)) {239 throw new TypeError('chunk must be an array buffer view');240 }241 if (chunk.byteLength === 0) {242 throw new TypeError('chunk must have non-zero byteLength');243 }244 if (chunk.buffer.byteLength === 0) {245 throw new TypeError(`chunk's buffer must have non-zero byteLength`);246 }247 if (this._closeRequested) {248 throw new TypeError('stream is closed or draining');249 }250 const state = this._controlledReadableByteStream._state;251 if (state !== 'readable') {252 throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`);253 }254 ReadableByteStreamControllerEnqueue(this, chunk);255 }256 /**257 * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.258 */259 error(e: any = undefined): void {260 if (!IsReadableByteStreamController(this)) {261 throw byteStreamControllerBrandCheckException('error');262 }263 ReadableByteStreamControllerError(this, e);264 }265 /** @internal */266 [CancelSteps](reason: any): Promise<void> {267 if (this._pendingPullIntos.length > 0) {268 const firstDescriptor = this._pendingPullIntos.peek();269 firstDescriptor.bytesFilled = 0;270 }271 ResetQueue(this);272 const result = this._cancelAlgorithm(reason);273 ReadableByteStreamControllerClearAlgorithms(this);274 return result;275 }276 /** @internal */277 [PullSteps](readRequest: ReadRequest<Uint8Array>): void {278 const stream = this._controlledReadableByteStream;279 assert(ReadableStreamHasDefaultReader(stream));280 if (this._queueTotalSize > 0) {281 assert(ReadableStreamGetNumReadRequests(stream) === 0);282 const entry = this._queue.shift()!;283 this._queueTotalSize -= entry.byteLength;284 ReadableByteStreamControllerHandleQueueDrain(this);285 const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength);286 readRequest._chunkSteps(view);287 return;288 }289 const autoAllocateChunkSize = this._autoAllocateChunkSize;290 if (autoAllocateChunkSize !== undefined) {291 let buffer: ArrayBuffer;292 try {293 buffer = new ArrayBuffer(autoAllocateChunkSize);294 } catch (bufferE) {295 readRequest._errorSteps(bufferE);296 return;297 }298 const pullIntoDescriptor: DefaultPullIntoDescriptor = {299 buffer,300 byteOffset: 0,301 byteLength: autoAllocateChunkSize,302 bytesFilled: 0,303 elementSize: 1,304 viewConstructor: Uint8Array,305 readerType: 'default'306 };307 this._pendingPullIntos.push(pullIntoDescriptor);308 }309 ReadableStreamAddReadRequest(stream, readRequest);310 ReadableByteStreamControllerCallPullIfNeeded(this);311 }312}313Object.defineProperties(ReadableByteStreamController.prototype, {314 close: { enumerable: true },315 enqueue: { enumerable: true },316 error: { enumerable: true },317 byobRequest: { enumerable: true },318 desiredSize: { enumerable: true }319});320if (typeof Symbol.toStringTag === 'symbol') {321 Object.defineProperty(ReadableByteStreamController.prototype, Symbol.toStringTag, {322 value: 'ReadableByteStreamController',323 configurable: true324 });325}326// Abstract operations for the ReadableByteStreamController.327export function IsReadableByteStreamController(x: any): x is ReadableByteStreamController {328 if (!typeIsObject(x)) {329 return false;330 }331 if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) {332 return false;333 }334 return true;335}336function IsReadableStreamBYOBRequest(x: any): x is ReadableStreamBYOBRequest {337 if (!typeIsObject(x)) {338 return false;339 }340 if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) {341 return false;342 }343 return true;344}345function ReadableByteStreamControllerCallPullIfNeeded(controller: ReadableByteStreamController): void {346 const shouldPull = ReadableByteStreamControllerShouldCallPull(controller);347 if (!shouldPull) {348 return;349 }350 if (controller._pulling) {351 controller._pullAgain = true;352 return;353 }354 assert(!controller._pullAgain);355 controller._pulling = true;356 // TODO: Test controller argument357 const pullPromise = controller._pullAlgorithm();358 uponPromise(359 pullPromise,360 () => {361 controller._pulling = false;362 if (controller._pullAgain) {363 controller._pullAgain = false;364 ReadableByteStreamControllerCallPullIfNeeded(controller);365 }366 },367 e => {368 ReadableByteStreamControllerError(controller, e);369 }370 );371}372function ReadableByteStreamControllerClearPendingPullIntos(controller: ReadableByteStreamController) {373 ReadableByteStreamControllerInvalidateBYOBRequest(controller);374 controller._pendingPullIntos = new SimpleQueue();375}376function ReadableByteStreamControllerCommitPullIntoDescriptor<T extends ArrayBufferView>(stream: ReadableByteStream,377 pullIntoDescriptor: PullIntoDescriptor<T>) {378 assert(stream._state !== 'errored');379 let done = false;380 if (stream._state === 'closed') {381 assert(pullIntoDescriptor.bytesFilled === 0);382 done = true;383 }384 const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor<T>(pullIntoDescriptor);385 if (pullIntoDescriptor.readerType === 'default') {386 ReadableStreamFulfillReadRequest(stream, filledView as unknown as Uint8Array, done);387 } else {388 assert(pullIntoDescriptor.readerType === 'byob');389 ReadableStreamFulfillReadIntoRequest(stream, filledView, done);390 }391}392function ReadableByteStreamControllerConvertPullIntoDescriptor<T extends ArrayBufferView>(pullIntoDescriptor: PullIntoDescriptor<T>): T {393 const bytesFilled = pullIntoDescriptor.bytesFilled;394 const elementSize = pullIntoDescriptor.elementSize;395 assert(bytesFilled <= pullIntoDescriptor.byteLength);396 assert(bytesFilled % elementSize === 0);397 return new pullIntoDescriptor.viewConstructor(398 pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize) as T;399}400function ReadableByteStreamControllerEnqueueChunkToQueue(controller: ReadableByteStreamController,401 buffer: ArrayBufferLike,402 byteOffset: number,403 byteLength: number) {404 controller._queue.push({ buffer, byteOffset, byteLength });405 controller._queueTotalSize += byteLength;406}407function ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller: ReadableByteStreamController,408 pullIntoDescriptor: PullIntoDescriptor) {409 const elementSize = pullIntoDescriptor.elementSize;410 const currentAlignedBytes = pullIntoDescriptor.bytesFilled - pullIntoDescriptor.bytesFilled % elementSize;411 const maxBytesToCopy = Math.min(controller._queueTotalSize,412 pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled);413 const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy;414 const maxAlignedBytes = maxBytesFilled - maxBytesFilled % elementSize;415 let totalBytesToCopyRemaining = maxBytesToCopy;416 let ready = false;417 if (maxAlignedBytes > currentAlignedBytes) {418 totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled;419 ready = true;420 }421 const queue = controller._queue;422 while (totalBytesToCopyRemaining > 0) {423 const headOfQueue = queue.peek();424 const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength);425 const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;426 CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy);427 if (headOfQueue.byteLength === bytesToCopy) {428 queue.shift();429 } else {430 headOfQueue.byteOffset += bytesToCopy;431 headOfQueue.byteLength -= bytesToCopy;432 }433 controller._queueTotalSize -= bytesToCopy;434 ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor);435 totalBytesToCopyRemaining -= bytesToCopy;436 }437 if (!ready) {438 assert(controller._queueTotalSize === 0);439 assert(pullIntoDescriptor.bytesFilled > 0);440 assert(pullIntoDescriptor.bytesFilled < pullIntoDescriptor.elementSize);441 }442 return ready;443}444function ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller: ReadableByteStreamController,445 size: number,446 pullIntoDescriptor: PullIntoDescriptor) {447 assert(controller._pendingPullIntos.length === 0 || controller._pendingPullIntos.peek() === pullIntoDescriptor);448 ReadableByteStreamControllerInvalidateBYOBRequest(controller);449 pullIntoDescriptor.bytesFilled += size;450}451function ReadableByteStreamControllerHandleQueueDrain(controller: ReadableByteStreamController) {452 assert(controller._controlledReadableByteStream._state === 'readable');453 if (controller._queueTotalSize === 0 && controller._closeRequested) {454 ReadableByteStreamControllerClearAlgorithms(controller);455 ReadableStreamClose(controller._controlledReadableByteStream);456 } else {457 ReadableByteStreamControllerCallPullIfNeeded(controller);458 }459}460function ReadableByteStreamControllerInvalidateBYOBRequest(controller: ReadableByteStreamController) {461 if (controller._byobRequest === null) {462 return;463 }464 controller._byobRequest._associatedReadableByteStreamController = undefined!;465 controller._byobRequest._view = null!;466 controller._byobRequest = null;467}468function ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller: ReadableByteStreamController) {469 assert(!controller._closeRequested);470 while (controller._pendingPullIntos.length > 0) {471 if (controller._queueTotalSize === 0) {472 return;473 }474 const pullIntoDescriptor = controller._pendingPullIntos.peek();475 if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {476 ReadableByteStreamControllerShiftPendingPullInto(controller);477 ReadableByteStreamControllerCommitPullIntoDescriptor(478 controller._controlledReadableByteStream,479 pullIntoDescriptor480 );481 }482 }483}484export function ReadableByteStreamControllerPullInto<T extends ArrayBufferView>(485 controller: ReadableByteStreamController,486 view: T,487 readIntoRequest: ReadIntoRequest<T>488): void {489 const stream = controller._controlledReadableByteStream;490 let elementSize = 1;491 if (view.constructor !== DataView) {492 elementSize = (view.constructor as ArrayBufferViewConstructor<T>).BYTES_PER_ELEMENT;493 }494 const ctor = view.constructor as ArrayBufferViewConstructor<T>;495 const buffer = TransferArrayBuffer(view.buffer);496 const pullIntoDescriptor: BYOBPullIntoDescriptor<T> = {497 buffer,498 byteOffset: view.byteOffset,499 byteLength: view.byteLength,500 bytesFilled: 0,501 elementSize,502 viewConstructor: ctor,503 readerType: 'byob'504 };505 if (controller._pendingPullIntos.length > 0) {506 controller._pendingPullIntos.push(pullIntoDescriptor);507 // No ReadableByteStreamControllerCallPullIfNeeded() call since:508 // - No change happens on desiredSize509 // - The source has already been notified of that there's at least 1 pending read(view)510 ReadableStreamAddReadIntoRequest(stream, readIntoRequest);511 return;512 }513 if (stream._state === 'closed') {514 const emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0);515 readIntoRequest._closeSteps(emptyView);516 return;517 }518 if (controller._queueTotalSize > 0) {519 if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {520 const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor<T>(pullIntoDescriptor);521 ReadableByteStreamControllerHandleQueueDrain(controller);522 readIntoRequest._chunkSteps(filledView);523 return;524 }525 if (controller._closeRequested) {526 const e = new TypeError('Insufficient bytes to fill elements in the given buffer');527 ReadableByteStreamControllerError(controller, e);528 readIntoRequest._errorSteps(e);529 return;530 }531 }532 controller._pendingPullIntos.push(pullIntoDescriptor);533 ReadableStreamAddReadIntoRequest<T>(stream, readIntoRequest);534 ReadableByteStreamControllerCallPullIfNeeded(controller);535}536function ReadableByteStreamControllerRespondInClosedState(controller: ReadableByteStreamController,537 firstDescriptor: PullIntoDescriptor) {538 firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer);539 assert(firstDescriptor.bytesFilled === 0);540 const stream = controller._controlledReadableByteStream;541 if (ReadableStreamHasBYOBReader(stream)) {542 while (ReadableStreamGetNumReadIntoRequests(stream) > 0) {543 const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller);544 ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor);545 }546 }547}548function ReadableByteStreamControllerRespondInReadableState(controller: ReadableByteStreamController,549 bytesWritten: number,550 pullIntoDescriptor: PullIntoDescriptor) {551 if (pullIntoDescriptor.bytesFilled + bytesWritten > pullIntoDescriptor.byteLength) {552 throw new RangeError('bytesWritten out of range');553 }554 ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor);555 if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.elementSize) {556 // TODO: Figure out whether we should detach the buffer or not here.557 return;558 }559 ReadableByteStreamControllerShiftPendingPullInto(controller);560 const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize;561 if (remainderSize > 0) {562 const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;563 const remainder = pullIntoDescriptor.buffer.slice(end - remainderSize, end);564 ReadableByteStreamControllerEnqueueChunkToQueue(controller, remainder, 0, remainder.byteLength);565 }566 pullIntoDescriptor.buffer = TransferArrayBuffer(pullIntoDescriptor.buffer);567 pullIntoDescriptor.bytesFilled -= remainderSize;568 ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor);569 ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);570}571function ReadableByteStreamControllerRespondInternal(controller: ReadableByteStreamController, bytesWritten: number) {572 const firstDescriptor = controller._pendingPullIntos.peek();573 const stream = controller._controlledReadableByteStream;574 if (stream._state === 'closed') {575 if (bytesWritten !== 0) {576 throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream');577 }578 ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor);579 } else {580 assert(stream._state === 'readable');581 ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor);582 }583 ReadableByteStreamControllerCallPullIfNeeded(controller);584}585function ReadableByteStreamControllerShiftPendingPullInto(controller: ReadableByteStreamController): PullIntoDescriptor {586 const descriptor = controller._pendingPullIntos.shift()!;587 ReadableByteStreamControllerInvalidateBYOBRequest(controller);588 return descriptor;589}590function ReadableByteStreamControllerShouldCallPull(controller: ReadableByteStreamController): boolean {591 const stream = controller._controlledReadableByteStream;592 if (stream._state !== 'readable') {593 return false;594 }595 if (controller._closeRequested) {596 return false;597 }598 if (!controller._started) {599 return false;600 }601 if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {602 return true;603 }604 if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) {605 return true;606 }607 const desiredSize = ReadableByteStreamControllerGetDesiredSize(controller);608 assert(desiredSize !== null);609 if (desiredSize! > 0) {610 return true;611 }612 return false;613}614function ReadableByteStreamControllerClearAlgorithms(controller: ReadableByteStreamController) {615 controller._pullAlgorithm = undefined!;616 controller._cancelAlgorithm = undefined!;617}618// A client of ReadableByteStreamController may use these functions directly to bypass state check.619function ReadableByteStreamControllerClose(controller: ReadableByteStreamController) {620 const stream = controller._controlledReadableByteStream;621 if (controller._closeRequested || stream._state !== 'readable') {622 return;623 }624 if (controller._queueTotalSize > 0) {625 controller._closeRequested = true;626 return;627 }628 if (controller._pendingPullIntos.length > 0) {629 const firstPendingPullInto = controller._pendingPullIntos.peek();630 if (firstPendingPullInto.bytesFilled > 0) {631 const e = new TypeError('Insufficient bytes to fill elements in the given buffer');632 ReadableByteStreamControllerError(controller, e);633 throw e;634 }635 }636 ReadableByteStreamControllerClearAlgorithms(controller);637 ReadableStreamClose(stream);638}639function ReadableByteStreamControllerEnqueue(controller: ReadableByteStreamController, chunk: ArrayBufferView) {640 const stream = controller._controlledReadableByteStream;641 if (controller._closeRequested || stream._state !== 'readable') {642 return;643 }644 const buffer = chunk.buffer;645 const byteOffset = chunk.byteOffset;646 const byteLength = chunk.byteLength;647 const transferredBuffer = TransferArrayBuffer(buffer);648 if (ReadableStreamHasDefaultReader(stream)) {649 if (ReadableStreamGetNumReadRequests(stream) === 0) {650 ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);651 } else {652 assert(controller._queue.length === 0);653 const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength);654 ReadableStreamFulfillReadRequest(stream, transferredView, false);655 }656 } else if (ReadableStreamHasBYOBReader(stream)) {657 // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully.658 ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);659 ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);660 } else {661 assert(!IsReadableStreamLocked(stream));662 ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);663 }664 ReadableByteStreamControllerCallPullIfNeeded(controller);665}666function ReadableByteStreamControllerError(controller: ReadableByteStreamController, e: any) {667 const stream = controller._controlledReadableByteStream;668 if (stream._state !== 'readable') {669 return;670 }671 ReadableByteStreamControllerClearPendingPullIntos(controller);672 ResetQueue(controller);673 ReadableByteStreamControllerClearAlgorithms(controller);674 ReadableStreamError(stream, e);675}676function ReadableByteStreamControllerGetDesiredSize(controller: ReadableByteStreamController): number | null {677 const stream = controller._controlledReadableByteStream;678 const state = stream._state;679 if (state === 'errored') {680 return null;681 }682 if (state === 'closed') {683 return 0;684 }685 return controller._strategyHWM - controller._queueTotalSize;686}687function ReadableByteStreamControllerRespond(controller: ReadableByteStreamController, bytesWritten: number) {688 bytesWritten = Number(bytesWritten);689 if (!IsFiniteNonNegativeNumber(bytesWritten)) {690 throw new RangeError('bytesWritten must be a finite');691 }692 assert(controller._pendingPullIntos.length > 0);693 ReadableByteStreamControllerRespondInternal(controller, bytesWritten);694}695function ReadableByteStreamControllerRespondWithNewView(controller: ReadableByteStreamController,696 view: ArrayBufferView) {697 assert(controller._pendingPullIntos.length > 0);698 const firstDescriptor = controller._pendingPullIntos.peek();699 if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) {700 throw new RangeError('The region specified by view does not match byobRequest');701 }702 if (firstDescriptor.byteLength !== view.byteLength) {703 throw new RangeError('The buffer of view has different capacity than byobRequest');704 }705 firstDescriptor.buffer = view.buffer;706 ReadableByteStreamControllerRespondInternal(controller, view.byteLength);707}708export function SetUpReadableByteStreamController(stream: ReadableByteStream,709 controller: ReadableByteStreamController,710 startAlgorithm: () => void | PromiseLike<void>,711 pullAlgorithm: () => Promise<void>,712 cancelAlgorithm: (reason: any) => Promise<void>,713 highWaterMark: number,714 autoAllocateChunkSize: number | undefined) {715 assert(stream._readableStreamController === undefined);716 if (autoAllocateChunkSize !== undefined) {717 assert(NumberIsInteger(autoAllocateChunkSize));718 assert(autoAllocateChunkSize > 0);719 }720 controller._controlledReadableByteStream = stream;721 controller._pullAgain = false;722 controller._pulling = false;723 controller._byobRequest = null;724 // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.725 controller._queue = controller._queueTotalSize = undefined!;726 ResetQueue(controller);727 controller._closeRequested = false;728 controller._started = false;729 controller._strategyHWM = highWaterMark;730 controller._pullAlgorithm = pullAlgorithm;731 controller._cancelAlgorithm = cancelAlgorithm;732 controller._autoAllocateChunkSize = autoAllocateChunkSize;733 controller._pendingPullIntos = new SimpleQueue();734 stream._readableStreamController = controller;735 const startResult = startAlgorithm();736 uponPromise(737 promiseResolvedWith(startResult),738 () => {739 controller._started = true;740 assert(!controller._pulling);741 assert(!controller._pullAgain);742 ReadableByteStreamControllerCallPullIfNeeded(controller);743 },744 r => {745 ReadableByteStreamControllerError(controller, r);746 }747 );748}749export function SetUpReadableByteStreamControllerFromUnderlyingSource(750 stream: ReadableByteStream,751 underlyingByteSource: ValidatedUnderlyingByteSource,752 highWaterMark: number753) {754 const controller: ReadableByteStreamController = Object.create(ReadableByteStreamController.prototype);755 let startAlgorithm: () => void | PromiseLike<void> = () => undefined;756 let pullAlgorithm: () => Promise<void> = () => promiseResolvedWith(undefined);757 let cancelAlgorithm: (reason: any) => Promise<void> = () => promiseResolvedWith(undefined);758 if (underlyingByteSource.start !== undefined) {759 startAlgorithm = () => underlyingByteSource.start!(controller);760 }761 if (underlyingByteSource.pull !== undefined) {762 pullAlgorithm = () => underlyingByteSource.pull!(controller);763 }764 if (underlyingByteSource.cancel !== undefined) {765 cancelAlgorithm = reason => underlyingByteSource.cancel!(reason);766 }767 const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize;768 SetUpReadableByteStreamController(769 stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize770 );771}772function SetUpReadableStreamBYOBRequest(request: ReadableStreamBYOBRequest,773 controller: ReadableByteStreamController,774 view: ArrayBufferView) {775 assert(IsReadableByteStreamController(controller));776 assert(typeof view === 'object');777 assert(ArrayBuffer.isView(view));778 assert(!IsDetachedBuffer(view.buffer));779 request._associatedReadableByteStreamController = controller;780 request._view = view;781}782// Helper functions for the ReadableStreamBYOBRequest.783function byobRequestBrandCheckException(name: string): TypeError {784 return new TypeError(785 `ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`);786}787// Helper functions for the ReadableByteStreamController.788function byteStreamControllerBrandCheckException(name: string): TypeError {789 return new TypeError(790 `ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`);...
Using AI Code Generation
1var test = async_test('Testing byteStreamControllerBrandCheckException method of wpt/resources/testharness.js');2test.step(function()3{4 var byteStreamControllerBrandCheckException = new ReadableStream({5 start(controller) {6 assert_throws(new TypeError(), function() {7 controller.enqueue("a");8 });9 test.done();10 }11 });12 byteStreamControllerBrandCheckException.getReader();13});14function byteStreamControllerBrandCheckException() {15 var rs = new ReadableStream({16 start(controller) {17 assert_throws(new TypeError(), function() {18 controller.enqueue("a");19 });20 done();21 }22 });23 rs.getReader();24}25test(function() {26 var rs = new ReadableStream({27 start(controller) {28 assert_throws(new TypeError(), function() {29 controller.enqueue("a");30 });31 done();32 }33 });34 rs.getReader();35});36promise_test(function() {37 var rs = new ReadableStream({38 start(controller) {39 assert_throws(new TypeError(), function() {40 controller.enqueue("a");41 });42 done();43 }44 });45 return rs.getReader().closed;46});47async_test(function(t) {48 var rs = new ReadableStream({49 start(controller) {50 assert_throws(new TypeError(), function() {51 controller.enqueue("a");52 });53 done();54 }55 });56 rs.getReader().closed.then(t.step_func(function() {57 t.done();58 }));59});60promise_test(function() {61 var rs = new ReadableStream({62 start(controller) {63 assert_throws(new TypeError(), function() {64 controller.enqueue("
Using AI Code Generation
1const test = async () => {2 const { ReadableStream, CountQueuingStrategy } = new WebAssembly.Instance(3 await WebAssembly.instantiateStreaming(fetch("wpt.wasm"), {}),4 {}5 ).exports;6 const stream = new ReadableStream({7 start(controller) {8 controller.enqueue(new Uint8Array([0, 1, 2]));9 },10 });11 const reader = stream.getReader();12 const result = await reader.read();13 const view = new Uint8Array(result.value);14 console.log(view);15};16test();17if (controller[byteStreamControllerBrandCheckException] !== undefined) {18 throw new TypeError();19 }20Error: WebAssembly.instantiateStreaming(): Wasm code generation disallowed by embedder
Using AI Code Generation
1var byteStreamControllerBrandCheckException = wpt.byteStreamControllerBrandCheckException;2var rs = new ReadableStream({3 pull: function(controller) {4 controller.enqueue(1);5 }6});7var reader = rs.getReader();8reader.read().then(function(result) {9 assert_equals(result.value, 1);10 assert_false(result.done);11 var controller = reader.releaseLock();12 assert_throws(byteStreamControllerBrandCheckException, function() {13 controller.enqueue(2);14 });15 return reader.read();16}).then(function(result) {17 assert_equals(result.value, 2);18 assert_false(result.done);19 return reader.read();20}).then(function(result) {21 assert_true(result.done);22}, function(e) {23 assert_unreached(e);24});25test(function() {26 var rs = new ReadableStream({27 pull: function(controller) {28 controller.enqueue(new Uint8Array(1));29 }30 });31 var reader = rs.getReader();32 reader.read().then(function(result) {33 assert_equals(result.value.byteLength, 1);34 assert_false(result.done);35 var controller = reader.releaseLock();36 assert_throws(byteStreamControllerBrandCheckException, function() {37 controller.enqueue(new Uint8Array(1));38 });39 return reader.read();40 }).then(function(result) {41 assert_equals(result.value.byteLength, 1);42 assert_false(result.done);43 return reader.read();44 }).then(function(result) {45 assert_true(result.done);46 }, function(e) {47 assert_unreached(e);48 });49}, 'ReadableStream with byte source: byte stream controller\'s brand check on enqueue()');50test(function() {51 var rs = new ReadableStream({52 pull: function(controller) {53 controller.enqueue(new Uint8Array(1));54 }55 });56 var reader = rs.getReader();57 reader.read().then(function(result) {58 assert_equals(result.value.byteLength, 1);59 assert_false(result.done);60 var controller = reader.releaseLock();61 assert_throws(byteStreamControllerBrandCheckException, function() {
Using AI Code Generation
1test(function() {2 assert_throws(new TypeError(), () => new ByteStreamController({type: "bytes"}));3}, "ByteStreamController constructor should throw when called with a ReadableStream");4function byteStreamControllerBrandCheckException() {5 return new TypeError();6}7function assert_throws(expected, func, description) {8 if (typeof expected === "function") {9 return assert_throws_js(expected, func, description);10 }11 if (typeof expected === "string") {12 return assert_throws_dom(expected, func, description);13 }14 if (typeof expected === "object" && expected !== null) {15 if (expected.name === "TypeError" && expected.message === "ByteStreamController constructor should throw when called with a ReadableStream") {16 return assert_throws_dom("TypeError", func, description);17 }18 }19 throw new Error("assert_throws: invalid expected argument: " + expected);20}21function assert_throws_dom(expected, func, description) {22 if (typeof expected !== "string") {23 throw new Error("assert_throws_dom: invalid expected argument: " + expected);24 }25 var e = assert_throws_js(DOMException, func, description);26 assert_equals(e.name, expected, description);27 return e;28}29function assert_throws_js(expected, func, description) {30 if (typeof expected !== "function") {31 throw new Error("assert_throws_js: invalid expected argument: " + expected);32 }33 var e;34 var message;35 try {36 func();37 } catch (ex) {38 e = ex;39 }40 if (e === undefined) {41 message = "function did not throw an exception";42 } else if (e instanceof expected) {43 return e;44 } else {45 message = "threw " + e + ", expected " + expected.name;46 }47 if (description !== undefined) {48 message = description + ": " + message;49 }50 assert_unreached(message);51}52function assert_unreached(message) {53 assert_true(false, message);54}
Using AI Code Generation
1'use strict';2const byteStreamControllerBrandCheckException = (obj, message) => {3 assert_throws(new TypeError(), () => {4 obj.enqueue('a');5 }, message);6};7test(() => {8 const rs = new ReadableStream({9 start(c) {10 byteStreamControllerBrandCheckException(c, 'controller');11 }12 });13}, 'ReadableStream with byte source: brand check on controller in start method');14test(() => {15 const rs = new ReadableStream({16 pull(c) {17 byteStreamControllerBrandCheckException(c, 'controller');18 }19 });20}, 'ReadableStream with byte source: brand check on controller in pull method');21test(() => {22 const rs = new ReadableStream({23 cancel(c) {24 byteStreamControllerBrandCheckException(c, 'controller');25 }26 });27 rs.cancel();28}, 'ReadableStream with byte source: brand check on controller in cancel method');29test(() => {30 const rs = new ReadableStream({31 start(c) {32 byteStreamControllerBrandCheckException(c.byobRequest, 'byobRequest');33 }34 });35}, 'ReadableStream with byte source: brand check on byobRequest in start method');36test(() => {37 const rs = new ReadableStream({38 pull(c) {39 byteStreamControllerBrandCheckException(c.byobRequest, 'byobRequest');40 }41 });42}, 'ReadableStream with byte source: brand check on byobRequest in pull method');43test(() => {44 const rs = new ReadableStream({45 cancel(c) {46 byteStreamControllerBrandCheckException(c.byobRequest, 'byobRequest');47 }48 });49 rs.cancel();50}, 'ReadableStream with byte source: brand check on byobRequest in cancel method');51test(() => {52 const rs = new ReadableStream({53 start(c) {54 byteStreamControllerBrandCheckException(c.desiredSize, 'desiredSize');55 }56 });57}, 'ReadableStream with byte source: brand check on desiredSize in start method');58test(() => {59 const rs = new ReadableStream({60 pull(c) {61 byteStreamControllerBrandCheckException(c.desiredSize, 'desiredSize');62 }63 });64}, 'ReadableStream with byte source: brand check on desiredSize in pull method');65test(() => {
Using AI Code Generation
1import { byteStreamControllerBrandCheckException } from './resources/test-utils.js';2const controller = new ReadableStream().getReader().read().controller;3byteStreamControllerBrandCheckException(controller);4export function byteStreamControllerBrandCheckException(controller) {5 assert_throws_js(TypeError, () => {6 controller.byobRequest;7 }, 'controller.byobRequest should throw a TypeError exception');8}9export function byteStreamControllerBrandCheckException(controller) {10 assert_throws_js(TypeError, () => {11 controller.byobRequest;12 }, 'controller.byobRequest should throw a TypeError exception');13}14 > };15> interface ByteStreamController {16> + readonly attribute BYOBRequest? byobRequest; 17 > };18> interface ReadableStream {19> + readonly attribute ByteStreamController? controller;
Using AI Code Generation
1var byteStreamControllerBrandCheckException = wpt.byteStreamControllerBrandCheckException;2var byteStreamControllerBrandCheck = wpt.byteStreamControllerBrandCheck;3try {4 byteStreamControllerBrandCheckException(1);5} catch (e) {6 console.log("Exception thrown: " + e);7}8var byteStreamController = new ByteStreamController();9try {10 byteStreamControllerBrandCheckException(byteStreamController);11} catch (e) {12 console.log("Exception thrown: " + e);13}14var byteStreamController = new ByteStreamController();15try {16 byteStreamControllerBrandCheck(byteStreamController);17} catch (e) {18 console.log("Exception thrown: " + e);19}20var byteStreamController = new ByteStreamController();21try {22 console.log(byteStreamControllerBrandCheck(byteStreamController));23} catch (e) {24 console.log("Exception thrown: " + e);25}26var byteStreamController = new ByteStreamController();27try {28 console.log(byteStreamControllerBrandCheck(1));29} catch (e) {30 console.log("Exception thrown: " + e);31}32var byteStreamController = new ByteStreamController();33try {34 console.log(byteStreamControllerBrandCheck("abc"));35} catch (e) {36 console.log("Exception thrown: " + e);37}38var byteStreamController = new ByteStreamController();39try {40 console.log(byteStreamControllerBrandCheck({}));41} catch (e) {42 console.log("Exception thrown: " + e);43}
Using AI Code Generation
1var rs = new ReadableStream({2 start(controller) {3 controller.enqueue(new ArrayBuffer(1));4 }5});6rs.getReader().read().then(({value, done}) => {7 assert_false(done);8 assert_equals(value.byteLength, 1);9});
Using AI Code Generation
1var ReadableStreamBYOBRequest = function (controller) {2 if (!IsReadableByteStreamController(controller)) {3 throw byteStreamControllerBrandCheckException("ReadableStreamBYOBRequest");4 }5 this._associatedReadableByteStreamController = controller;6};7var rs = new ReadableStreamBYOBRequest();
Using AI Code Generation
1import { byteStreamControllerBrandCheckException } from './wpt/resources/testharness.js';2test(() => {3 assert_throws(new RangeError(), () => byteStreamControllerBrandCheckException(undefined));4}, 'ByteStreamControllerBrandCheckException should throw a RangeError when ByteStreamController is passed as undefined');5export function byteStreamControllerBrandCheckException(controller) {6 if (controller === undefined) {7 throw new RangeError();8 }9}10exports.byteStreamControllerBrandCheckException = function(controller) {11 if (controller === undefined) {12 throw new RangeError();13 }14}
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!