How to use ReadableByteStreamControllerConvertPullIntoDescriptor method in wpt

Best JavaScript code snippet using wpt

byte-stream-controller.ts

Source:byte-stream-controller.ts Github

copy

Full Screen

1import assert from '../../stub/assert';2import { SimpleQueue } from '../simple-queue';3import { ResetQueue } from '../abstract-ops/queue-with-sizes';4import {5 ReadableStreamAddReadRequest,6 ReadableStreamFulfillReadRequest,7 ReadableStreamGetNumReadRequests,8 ReadableStreamHasDefaultReader,9 ReadRequest10} from './default-reader';11import {12 ReadableStreamAddReadIntoRequest,13 ReadableStreamFulfillReadIntoRequest,14 ReadableStreamGetNumReadIntoRequests,15 ReadableStreamHasBYOBReader,16 ReadIntoRequest17} from './byob-reader';18import NumberIsInteger from '../../stub/number-isinteger';19import {20 IsReadableStreamLocked,21 ReadableByteStream,22 ReadableStreamClose,23 ReadableStreamError24} from '../readable-stream';25import { ValidatedUnderlyingByteSource } from './underlying-source';26import { typeIsObject } from '../helpers/miscellaneous';27import { CopyDataBlockBytes, IsDetachedBuffer, TransferArrayBuffer } from '../abstract-ops/ecmascript';28import { CancelSteps, PullSteps } from '../abstract-ops/internal-methods';29import { IsFiniteNonNegativeNumber } from '../abstract-ops/miscellaneous';30import { promiseResolvedWith, uponPromise } from '../helpers/webidl';31import { assertRequiredArgument, convertUnsignedLongLongWithEnforceRange } from '../validators/basic';32/**33 * A pull-into request in a {@link ReadableByteStreamController}.34 *35 * @public36 */37export class ReadableStreamBYOBRequest {38 /** @internal */39 _associatedReadableByteStreamController!: ReadableByteStreamController;40 /** @internal */41 _view!: ArrayBufferView | null;42 private constructor() {43 throw new TypeError('Illegal constructor');44 }45 /**46 * Returns the view for writing in to, or `null` if the BYOB request has already been responded to.47 */48 get view(): ArrayBufferView | null {49 if (!IsReadableStreamBYOBRequest(this)) {50 throw byobRequestBrandCheckException('view');51 }52 return this._view;53 }54 /**55 * Indicates to the associated readable byte stream that `bytesWritten` bytes were written into56 * {@link ReadableStreamBYOBRequest.view | view}, causing the result be surfaced to the consumer.57 *58 * After this method is called, {@link ReadableStreamBYOBRequest.view | view} will be transferred and no longer59 * modifiable.60 */61 respond(bytesWritten: number): void;62 respond(bytesWritten: number | undefined): void {63 if (!IsReadableStreamBYOBRequest(this)) {64 throw byobRequestBrandCheckException('respond');65 }66 assertRequiredArgument(bytesWritten, 1, 'respond');67 bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter');68 if (this._associatedReadableByteStreamController === undefined) {69 throw new TypeError('This BYOB request has been invalidated');70 }71 if (IsDetachedBuffer(this._view!.buffer)) {72 throw new TypeError(`The BYOB request's buffer has been detached and so cannot be used as a response`);73 }74 assert(this._view!.byteLength > 0);75 assert(this._view!.buffer.byteLength > 0);76 ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten);77 }78 /**79 * Indicates to the associated readable byte stream that instead of writing into80 * {@link ReadableStreamBYOBRequest.view | view}, the underlying byte source is providing a new `ArrayBufferView`,81 * which will be given to the consumer of the readable byte stream.82 *83 * After this method is called, `view` will be transferred and no longer modifiable.84 */85 respondWithNewView(view: ArrayBufferView): void;86 respondWithNewView(view: ArrayBufferView | undefined): void {87 if (!IsReadableStreamBYOBRequest(this)) {88 throw byobRequestBrandCheckException('respondWithNewView');89 }90 assertRequiredArgument(view, 1, 'respondWithNewView');91 if (!ArrayBuffer.isView(view)) {92 throw new TypeError('You can only respond with array buffer views');93 }94 if (view.byteLength === 0) {95 throw new TypeError('chunk must have non-zero byteLength');96 }97 if (view.buffer.byteLength === 0) {98 throw new TypeError(`chunk's buffer must have non-zero byteLength`);99 }100 if (this._associatedReadableByteStreamController === undefined) {101 throw new TypeError('This BYOB request has been invalidated');102 }103 ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view);104 }105}106Object.defineProperties(ReadableStreamBYOBRequest.prototype, {107 respond: { enumerable: true },108 respondWithNewView: { enumerable: true },109 view: { enumerable: true }110});111if (typeof Symbol.toStringTag === 'symbol') {112 Object.defineProperty(ReadableStreamBYOBRequest.prototype, Symbol.toStringTag, {113 value: 'ReadableStreamBYOBRequest',114 configurable: true115 });116}117interface ArrayBufferViewConstructor<T extends ArrayBufferView = ArrayBufferView> {118 new(buffer: ArrayBufferLike, byteOffset: number, length?: number): T;119 readonly prototype: T;120 readonly BYTES_PER_ELEMENT: number;121}122interface ByteQueueElement {123 buffer: ArrayBufferLike;124 byteOffset: number;125 byteLength: number;126}127type PullIntoDescriptor<T extends ArrayBufferView = ArrayBufferView> =128 DefaultPullIntoDescriptor129 | BYOBPullIntoDescriptor;130interface DefaultPullIntoDescriptor {131 buffer: ArrayBufferLike;132 byteOffset: number;133 byteLength: number;134 bytesFilled: number;135 elementSize: number;136 viewConstructor: ArrayBufferViewConstructor<Uint8Array>;137 readerType: 'default';138}139interface BYOBPullIntoDescriptor<T extends ArrayBufferView = ArrayBufferView> {140 buffer: ArrayBufferLike;141 byteOffset: number;142 byteLength: number;143 bytesFilled: number;144 elementSize: number;145 viewConstructor: ArrayBufferViewConstructor<T>;146 readerType: 'byob';147}148/**149 * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue.150 *151 * @public152 */153export class ReadableByteStreamController {154 /** @internal */155 _controlledReadableByteStream!: ReadableByteStream;156 /** @internal */157 _queue!: SimpleQueue<ByteQueueElement>;158 /** @internal */159 _queueTotalSize!: number;160 /** @internal */161 _started!: boolean;162 /** @internal */163 _closeRequested!: boolean;164 /** @internal */165 _pullAgain!: boolean;166 /** @internal */167 _pulling !: boolean;168 /** @internal */169 _strategyHWM!: number;170 /** @internal */171 _pullAlgorithm!: () => Promise<void>;172 /** @internal */173 _cancelAlgorithm!: (reason: any) => Promise<void>;174 /** @internal */175 _autoAllocateChunkSize: number | undefined;176 /** @internal */177 _byobRequest: ReadableStreamBYOBRequest | null;178 /** @internal */179 _pendingPullIntos!: SimpleQueue<PullIntoDescriptor>;180 private constructor() {181 throw new TypeError('Illegal constructor');182 }183 /**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`);...

Full Screen

Full Screen

readable_byte_stream_controller.ts

Source:readable_byte_stream_controller.ts Github

copy

Full Screen

...231 if (stream.state === "closed") {232 Assert(pullIntoDescriptor.bytesFilled === 0);233 done = true;234 }235 const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(236 pullIntoDescriptor237 );238 if (pullIntoDescriptor.readerType === "default") {239 ReadableStreamFulfillReadRequest(stream, filledView, done);240 } else {241 Assert(pullIntoDescriptor.readerType === "byob");242 ReadableStreamFulfillReadIntoRequest(stream, filledView, done);243 }244}245export function ReadableByteStreamControllerConvertPullIntoDescriptor(246 pullIntoDescriptor: PullIntoDescriptor247) {248 const { bytesFilled, elementSize } = pullIntoDescriptor;249 Assert(bytesFilled <= pullIntoDescriptor.byteLength);250 Assert(bytesFilled % pullIntoDescriptor.elementSize === 0);251 return new pullIntoDescriptor.ctor(252 pullIntoDescriptor.buffer,253 pullIntoDescriptor.byteOffset,254 bytesFilled / elementSize255 );256}257export function ReadableByteStreamControllerEnqueue(258 controller: ReadableByteStreamController,259 chunk: ArrayBufferView260) {261 const stream = controller.controlledReadableByteStream;262 Assert(controller.closeRequested === false);263 Assert(stream.state === "readable");264 const { buffer } = chunk;265 const { byteOffset, byteLength } = chunk;266 const transferredBuffer = TransferArrayBuffer(buffer);267 if (ReadableStreamHasDefaultReader(stream)) {268 if (ReadableStreamGetNumReadRequests(stream) === 0) {269 ReadableByteStreamControllerEnqueueChunkToQueue(270 controller,271 transferredBuffer,272 byteOffset,273 byteLength274 );275 } else {276 Assert(controller.queue.length === 0, "l=0");277 const transferredView = new Uint8Array(278 transferredBuffer,279 byteOffset,280 byteLength281 );282 ReadableStreamFulfillReadRequest(stream, transferredView, false);283 }284 } else if (ReadableStreamHasBYOBReader(stream)) {285 ReadableByteStreamControllerEnqueueChunkToQueue(286 controller,287 transferredBuffer,288 byteOffset,289 byteLength290 );291 ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(292 controller293 );294 } else {295 Assert(296 IsReadableStreamLocked(stream) === false,297 "stream should not be locked"298 );299 ReadableByteStreamControllerEnqueueChunkToQueue(300 controller,301 transferredBuffer,302 byteOffset,303 byteLength304 );305 }306 ReadableByteStreamControllerCallPullIfNeeded(controller);307}308export function ReadableByteStreamControllerEnqueueChunkToQueue(309 controller: ReadableByteStreamController,310 buffer: ArrayBuffer,311 byteOffset: number,312 byteLength: number313) {314 controller.queue.push({315 buffer,316 byteOffset,317 byteLength318 });319 controller.queueTotalSize += byteLength;320}321export function ReadableByteStreamControllerError(322 controller: ReadableByteStreamController,323 e324) {325 const stream = controller.controlledReadableByteStream;326 if (stream.state !== "readable") {327 return;328 }329 ReadableByteStreamControllerClearPendingPullIntos(controller);330 ResetQueue(controller);331 ReadableByteStreamControllerClearAlgorithms(controller);332 ReadableStreamError(controller.controlledReadableByteStream, e);333}334export function ReadableByteStreamControllerFillHeadPullIntoDescriptor(335 controller: ReadableByteStreamController,336 size: number,337 pullIntoDescriptor: PullIntoDescriptor338) {339 Assert(340 controller.pendingPullIntos.length === 0 ||341 controller.pendingPullIntos[0] === pullIntoDescriptor342 );343 ReadableByteStreamControllerInvalidateBYOBRequest(controller);344 pullIntoDescriptor.bytesFilled += size;345}346export function ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(347 controller: ReadableByteStreamController,348 pullIntoDescriptor: PullIntoDescriptor349): boolean {350 const { elementSize } = pullIntoDescriptor;351 const currentAlignedBytes =352 pullIntoDescriptor.bytesFilled -353 (pullIntoDescriptor.bytesFilled % elementSize);354 const maxBytesToCopy = Math.min(355 controller.queueTotalSize,356 pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled357 );358 const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy;359 const maxAlignedBytes = maxBytesFilled - (maxBytesFilled % elementSize);360 let totalBytesToCopyRemaining = maxBytesToCopy;361 let ready = false;362 if (maxAlignedBytes > currentAlignedBytes) {363 totalBytesToCopyRemaining =364 maxAlignedBytes - pullIntoDescriptor.bytesFilled;365 ready = true;366 }367 const { queue } = controller;368 while (totalBytesToCopyRemaining > 0) {369 const headOfQueue = queue[0];370 const bytesToCopy = Math.min(371 totalBytesToCopyRemaining,372 headOfQueue.byteLength373 );374 const destStart =375 pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;376 const srcView = new Uint8Array(377 headOfQueue.buffer,378 headOfQueue.byteOffset,379 headOfQueue.byteLength380 );381 const destView = new Uint8Array(382 pullIntoDescriptor.buffer,383 destStart,384 bytesToCopy385 );386 for (let i = 0; i < bytesToCopy; i++) {387 destView[i] = srcView[i];388 }389 if (headOfQueue.byteLength === bytesToCopy) {390 queue.shift();391 } else {392 headOfQueue.byteOffset += bytesToCopy;393 headOfQueue.byteLength -= bytesToCopy;394 }395 controller.queueTotalSize -= bytesToCopy;396 ReadableByteStreamControllerFillHeadPullIntoDescriptor(397 controller,398 bytesToCopy,399 pullIntoDescriptor400 );401 totalBytesToCopyRemaining -= bytesToCopy;402 }403 if (ready === false) {404 Assert(controller.queueTotalSize === 0);405 Assert(pullIntoDescriptor.bytesFilled > 0);406 Assert(pullIntoDescriptor.bytesFilled < pullIntoDescriptor.elementSize);407 }408 return ready;409}410export function ReadableByteStreamControllerGetDesiredSize(411 controller: ReadableByteStreamController412): number | null {413 const stream = controller.controlledReadableByteStream;414 const { state } = stream;415 if (state === "errored") {416 return null;417 }418 if (state === "closed") {419 return 0;420 }421 return controller.strategyHWM - controller.queueTotalSize;422}423export function ReadableByteStreamControllerHandleQueueDrain(424 controller: ReadableByteStreamController425) {426 Assert(controller.controlledReadableByteStream.state === "readable");427 if (controller.queueTotalSize === 0 && controller.closeRequested) {428 ReadableByteStreamControllerClearAlgorithms(controller);429 ReadableStreamClose(controller.controlledReadableByteStream);430 } else {431 ReadableByteStreamControllerCallPullIfNeeded(controller);432 }433}434export function ReadableByteStreamControllerInvalidateBYOBRequest(435 controller: ReadableByteStreamController436) {437 if (controller._byobRequest === void 0) {438 return;439 }440 controller._byobRequest.associatedReadableByteStreamController = void 0;441 controller._byobRequest._view = void 0;442 controller._byobRequest = void 0;443}444export function ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(445 controller: ReadableByteStreamController446) {447 Assert(controller.closeRequested === false);448 while (controller.pendingPullIntos.length > 0) {449 if (controller.queueTotalSize === 0) {450 return;451 }452 const pullIntoDescriptor = controller.pendingPullIntos[0];453 if (454 ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(455 controller,456 pullIntoDescriptor457 ) === true458 ) {459 ReadableByteStreamControllerShiftPendingPullInto(controller);460 ReadableByteStreamControllerCommitPullIntoDescriptor(461 controller.controlledReadableByteStream,462 pullIntoDescriptor463 );464 }465 }466}467const TypedArraySizeMap = {468 Int8Array: [1, Int8Array],469 Uint8Array: [1, Uint8Array],470 Uint8ClampedArray: [1, Uint8ClampedArray],471 Int16Array: [2, Int16Array],472 Uint16Array: [2, Uint16Array],473 Int32Array: [4, Int32Array],474 Uint32Array: [4, Uint32Array],475 Float32Array: [4, Float32Array],476 Float64Array: [8, Float64Array]477};478export function ReadableByteStreamControllerPullInto(479 controller: ReadableByteStreamController,480 view: ArrayBufferView,481 forAuthorCode?: boolean482): Promise<any> {483 const stream = controller.controlledReadableByteStream;484 let elementSize = 1;485 let ctor = DataView;486 const ctorName = view.constructor.name;487 if (TypedArraySizeMap[ctorName]) {488 [elementSize, ctor] = TypedArraySizeMap[ctorName];489 }490 const { byteOffset, byteLength } = view;491 const buffer = TransferArrayBuffer(view.buffer);492 const pullIntoDescriptor: PullIntoDescriptor = {493 buffer,494 byteOffset,495 byteLength,496 bytesFilled: 0,497 elementSize,498 ctor,499 readerType: "byob"500 };501 if (controller.pendingPullIntos.length > 0) {502 controller.pendingPullIntos.push(pullIntoDescriptor);503 return ReadableStreamAddReadIntoRequest(stream, forAuthorCode);504 }505 if (stream.state === "closed") {506 const emptyView = new ctor(507 pullIntoDescriptor.buffer,508 pullIntoDescriptor.byteOffset,509 0510 );511 return Promise.resolve(512 ReadableStreamCreateReadResult(emptyView, true, forAuthorCode)513 );514 }515 if (controller.queueTotalSize > 0) {516 if (517 ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(518 controller,519 pullIntoDescriptor520 )521 ) {522 const filedView = ReadableByteStreamControllerConvertPullIntoDescriptor(523 pullIntoDescriptor524 );525 ReadableByteStreamControllerHandleQueueDrain(controller);526 return Promise.resolve(527 ReadableStreamCreateReadResult(filedView, false, forAuthorCode)528 );529 }530 if (controller.closeRequested) {531 const e = new TypeError();532 ReadableByteStreamControllerError(controller, e);533 return Promise.reject(e);534 }535 }536 controller.pendingPullIntos.push(pullIntoDescriptor);...

Full Screen

Full Screen

ReadableByteStreamInternals.js

Source:ReadableByteStreamInternals.js Github

copy

Full Screen

1/*2 * Copyright (C) 2016 Canon Inc. All rights reserved.3 *4 * Redistribution and use in source and binary forms, with or without5 * modification, are permitted provided that the following conditions6 * are met:7 * 1. Redistributions of source code must retain the above copyright8 * notice, this list of conditions and the following disclaimer.9 * 2. Redistributions in binary form must reproduce the above copyright10 * notice, this list of conditions and the following disclaimer in the11 * documentation and/or other materials provided with the distribution.12 *13 * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY14 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE15 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR16 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR17 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,18 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,19 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR20 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY21 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT22 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE23 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.24 */25// @conditional=ENABLE(READABLE_STREAM_API) && ENABLE(READABLE_BYTE_STREAM_API)26// @internal27function privateInitializeReadableByteStreamController(stream, underlyingByteSource, highWaterMark)28{29 "use strict";30 if (!@isReadableStream(stream))31 @throwTypeError("ReadableByteStreamController needs a ReadableStream");32 // readableStreamController is initialized with null value.33 if (stream.@readableStreamController !== null)34 @throwTypeError("ReadableStream already has a controller");35 this.@controlledReadableStream = stream;36 this.@underlyingByteSource = underlyingByteSource;37 this.@pullAgain = false;38 this.@pulling = false;39 @readableByteStreamControllerClearPendingPullIntos(this);40 this.@queue = [];41 this.@totalQueuedBytes = 0;42 this.@started = false;43 this.@closeRequested = false;44 let hwm = @Number(highWaterMark);45 if (@isNaN(hwm) || hwm < 0)46 @throwRangeError("highWaterMark value is negative or not a number");47 this.@strategyHWM = hwm;48 let autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize;49 if (autoAllocateChunkSize !== @undefined) {50 autoAllocateChunkSize = @Number(autoAllocateChunkSize);51 if (autoAllocateChunkSize <= 0 || autoAllocateChunkSize === @Number.POSITIVE_INFINITY || autoAllocateChunkSize === @Number.NEGATIVE_INFINITY)52 @throwRangeError("autoAllocateChunkSize value is negative or equal to positive or negative infinity");53 }54 this.@autoAllocateChunkSize = autoAllocateChunkSize;55 this.@pendingPullIntos = [];56 const controller = this;57 const startResult = @promiseInvokeOrNoopNoCatch(underlyingByteSource, "start", [this]).@then(() => {58 controller.@started = true;59 @assert(!controller.@pulling);60 @assert(!controller.@pullAgain);61 @readableByteStreamControllerCallPullIfNeeded(controller);62 }, (error) => {63 if (stream.@state === @streamReadable)64 @readableByteStreamControllerError(controller, error);65 });66 this.@cancel = @readableByteStreamControllerCancel;67 this.@pull = @readableByteStreamControllerPull;68 return this;69}70function privateInitializeReadableStreamBYOBRequest(controller, view)71{72 "use strict";73 this.@associatedReadableByteStreamController = controller;74 this.@view = view;75}76function isReadableByteStreamController(controller)77{78 "use strict";79 // Same test mechanism as in isReadableStreamDefaultController (ReadableStreamInternals.js).80 // See corresponding function for explanations.81 return @isObject(controller) && !!controller.@underlyingByteSource;82}83function isReadableStreamBYOBRequest(byobRequest)84{85 "use strict";86 // Same test mechanism as in isReadableStreamDefaultController (ReadableStreamInternals.js).87 // See corresponding function for explanations.88 return @isObject(byobRequest) && !!byobRequest.@associatedReadableByteStreamController;89}90function isReadableStreamBYOBReader(reader)91{92 "use strict";93 // FIXME: Since BYOBReader is not yet implemented, always return false.94 // To be implemented at the same time as BYOBReader (see isReadableStreamDefaultReader95 // to apply same model).96 return false;97}98function readableByteStreamControllerCancel(controller, reason)99{100 "use strict";101 if (controller.@pendingPullIntos.length > 0)102 controller.@pendingPullIntos[0].bytesFilled = 0;103 controller.@queue = [];104 controller.@totalQueuedBytes = 0;105 return @promiseInvokeOrNoop(controller.@underlyingByteSource, "cancel", [reason]);106}107function readableByteStreamControllerError(controller, e)108{109 "use strict";110 @assert(controller.@controlledReadableStream.@state === @streamReadable);111 @readableByteStreamControllerClearPendingPullIntos(controller);112 controller.@queue = [];113 @readableStreamError(controller.@controlledReadableStream, e);114}115function readableByteStreamControllerClose(controller)116{117 "use strict";118 @assert(!controller.@closeRequested);119 @assert(controller.@controlledReadableStream.@state === @streamReadable);120 if (controller.@totalQueuedBytes > 0) {121 controller.@closeRequested = true;122 return;123 }124 if (controller.@pendingPullIntos.length > 0) {125 if (controller.@pendingPullIntos[0].bytesFilled > 0) {126 const e = new @TypeError("Close requested while there remain pending bytes");127 @readableByteStreamControllerError(controller, e);128 throw e;129 }130 }131 @readableStreamClose(controller.@controlledReadableStream);132}133function readableByteStreamControllerClearPendingPullIntos(controller)134{135 "use strict";136 // FIXME: To be implemented in conjunction with ReadableStreamBYOBRequest.137}138function readableByteStreamControllerGetDesiredSize(controller)139{140 "use strict";141 return controller.@strategyHWM - controller.@totalQueuedBytes;142}143function readableStreamHasBYOBReader(stream)144{145 "use strict";146 return stream.@reader !== @undefined && @isReadableStreamBYOBReader(stream.@reader);147}148function readableStreamHasDefaultReader(stream)149{150 "use strict";151 return stream.@reader !== @undefined && @isReadableStreamDefaultReader(stream.@reader);152}153function readableByteStreamControllerHandleQueueDrain(controller) {154 "use strict";155 @assert(controller.@controlledReadableStream.@state === @streamReadable);156 if (!controller.@totalQueuedBytes && controller.@closeRequested)157 @readableStreamClose(controller.@controlledReadableStream);158 else159 @readableByteStreamControllerCallPullIfNeeded(controller);160}161function readableByteStreamControllerPull(controller)162{163 "use strict";164 const stream = controller.@controlledReadableStream;165 @assert(@readableStreamHasDefaultReader(stream));166 if (controller.@totalQueuedBytes > 0) {167 @assert(stream.@reader.@readRequests.length === 0);168 const entry = controller.@queue.@shift();169 controller.@totalQueuedBytes -= entry.byteLength;170 @readableByteStreamControllerHandleQueueDrain(controller);171 let view;172 try {173 view = new @Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength);174 } catch (error) {175 return @Promise.@reject(error);176 }177 return @Promise.@resolve({value: view, done: false});178 }179 if (controller.@autoAllocateChunkSize !== @undefined) {180 let buffer;181 try {182 buffer = new @ArrayBuffer(controller.@autoAllocateChunkSize);183 } catch (error) {184 return @Promise.@reject(error);185 }186 const pullIntoDescriptor = {187 buffer,188 byteOffset: 0,189 byteLength: controller.@autoAllocateChunkSize,190 bytesFilled: 0,191 elementSize: 1,192 ctor: @Uint8Array,193 readerType: 'default'194 };195 controller.@pendingPullIntos.@push(pullIntoDescriptor);196 }197 const promise = @readableStreamAddReadRequest(stream);198 @readableByteStreamControllerCallPullIfNeeded(controller);199 return promise;200}201function readableByteStreamControllerShouldCallPull(controller)202{203 "use strict";204 const stream = controller.@controlledReadableStream;205 if (stream.@state !== @streamReadable)206 return false;207 if (controller.@closeRequested)208 return false;209 if (!controller.@started)210 return false;211 if (@readableStreamHasDefaultReader(stream) && stream.@reader.@readRequests.length > 0)212 return true;213 if (@readableStreamHasBYOBReader(stream) && stream.@reader.@readIntoRequests.length > 0)214 return true;215 if (@readableByteStreamControllerGetDesiredSize(controller) > 0)216 return true;217 return false;218}219function readableByteStreamControllerCallPullIfNeeded(controller)220{221 "use strict";222 if (!@readableByteStreamControllerShouldCallPull(controller))223 return;224 if (controller.@pulling) {225 controller.@pullAgain = true;226 return;227 }228 @assert(!controller.@pullAgain);229 controller.@pulling = true;230 @promiseInvokeOrNoop(controller.@underlyingByteSource, "pull", [controller]).@then(() => {231 controller.@pulling = false;232 if (controller.@pullAgain) {233 controller.@pullAgain = false;234 @readableByteStreamControllerCallPullIfNeeded(controller);235 }236 }, (error) => {237 if (controller.@controlledReadableStream.@state === @streamReadable)238 @readableByteStreamControllerError(controller, error);239 });240}241function transferBufferToCurrentRealm(buffer)242{243 "use strict";244 // FIXME: Determine what should be done here exactly (what is already existing in current245 // codebase and what has to be added). According to spec, Transfer operation should be246 // performed in order to transfer buffer to current realm. For the moment, simply return247 // received buffer.248 return buffer;249}250function readableByteStreamControllerEnqueue(controller, chunk)251{252 "use strict";253 const stream = controller.@controlledReadableStream;254 @assert(!controller.@closeRequested);255 @assert(stream.@state === @streamReadable);256 const buffer = chunk.buffer;257 const byteOffset = chunk.byteOffset;258 const byteLength = chunk.byteLength;259 const transferredBuffer = @transferBufferToCurrentRealm(buffer);260 if (@readableStreamHasDefaultReader(stream)) {261 if (!stream.@reader.@readRequests.length)262 @readableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);263 else {264 @assert(!controller.@queue.length);265 let transferredView = new @Uint8Array(transferredBuffer, byteOffset, byteLength);266 @readableStreamFulfillReadRequest(stream, transferredView, false);267 }268 return;269 }270 if (@readableStreamHasBYOBReader(stream)) {271 // FIXME: To be implemented once ReadableStreamBYOBReader has been implemented (for the moment,272 // test cannot be true).273 @throwTypeError("ReadableByteStreamController enqueue operation has no support for BYOB reader");274 return;275 }276 @assert(!@isReadableStreamLocked(stream));277 @readableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);278}279function readableByteStreamControllerEnqueueChunkToQueue(controller, buffer, byteOffset, byteLength)280{281 "use strict";282 controller.@queue.@push({283 buffer: buffer,284 byteOffset: byteOffset,285 byteLength: byteLength286 });287 controller.@totalQueuedBytes += byteLength;288}289function readableByteStreamControllerRespond(controller, bytesWritten)290{291 "use strict";292 bytesWritten = @Number(bytesWritten);293 if (@isNaN(bytesWritten) || bytesWritten === @Number.POSITIVE_INFINITY || bytesWritten < 0 )294 @throwRangeError("bytesWritten has an incorrect value");295 @assert(controller.@pendingPullIntos.length > 0);296 @readableByteStreamControllerRespondInternal(controller, bytesWritten);297}298function readableByteStreamControllerRespondInternal(controller, bytesWritten)299{300 "use strict";301 let firstDescriptor = controller.@pendingPullIntos[0];302 let stream = controller.@controlledReadableStream;303 if (stream.@state === @streamClosed) {304 if (bytesWritten !== 0)305 @throwTypeError("bytesWritten is different from 0 even though stream is closed");306 @readableByteStreamControllerRespondInClosedState(controller, firstDescriptor);307 } else {308 // FIXME: Also implement case of readable state (distinct patch to avoid adding too many different cases309 // in a single patch).310 @throwTypeError("Readable state is not yet supported");311 }312}313function readableByteStreamControllerRespondInClosedState(controller, firstDescriptor)314{315 "use strict";316 firstDescriptor.buffer = @transferBufferToCurrentRealm(firstDescriptor.buffer);317 @assert(firstDescriptor.bytesFilled === 0);318 // FIXME: Spec does not describe below test. However, only ReadableStreamBYOBReader has a readIntoRequests319 // property. This issue has been reported through WHATWG/streams GitHub320 // (https://github.com/whatwg/streams/issues/686), but no solution has been provided for the moment.321 // Therefore, below test is added as a temporary fix.322 if (!@isReadableStreamBYOBReader(controller.@reader))323 return;324 while (controller.@reader.@readIntoRequests.length > 0) {325 let pullIntoDescriptor = @readableByteStreamControllerShiftPendingPullInto(controller);326 @readableByteStreamControllerCommitPullIntoDescriptor(controller.@controlledReadableStream, pullIntoDescriptor);327 }328}329function readableByteStreamControllerShiftPendingPullInto(controller)330{331 "use strict";332 let descriptor = controller.@pendingPullIntos.@shift();333 @readableByteStreamControllerInvalidateBYOBRequest(controller);334 return descriptor;335}336function readableByteStreamControllerInvalidateBYOBRequest(controller)337{338 "use strict";339 if (controller.@byobRequest === @undefined)340 return;341 controller.@byobRequest.@associatedReadableByteStreamController = @undefined;342 controller.@byobRequest.@view = @undefined;343 controller.@byobRequest = @undefined;344}345function readableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor)346{347 "use strict";348 @assert(stream.@state !== @streamErrored);349 let done = false;350 if (stream.@state === @streamClosed) {351 @assert(!pullIntoDescriptor.bytesFilled);352 done = true;353 }354 let filledView = @readableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);355 if (pullIntoDescriptor.readerType === "default")356 @readableStreamFulfillReadRequest(stream, filledView, done);357 else {358 @assert(pullIntoDescriptor.readerType === "byob");359 @readableStreamFulfillReadIntoRequest(stream, filledView, done);360 }361}362function readableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor)363{364 "use strict";365 @assert(pullIntoDescriptor.bytesFilled <= pullIntoDescriptor.bytesLength);366 @assert(pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize === 0);367 return new pullIntoDescriptor.ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, pullIntoDescriptor.bytesFilled / pullIntoDescriptor.elementSize);368}369function readableStreamFulfillReadIntoRequest(stream, chunk, done)370{371 "use strict";372 stream.@reader.@readIntoRequests.@shift().@resolve.@call(@undefined, {value: chunk, done: done});...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const { ReadableStream, ReadableByteStreamController } = require('stream/web');2const { ReadableStreamBYOBReader } = require('stream/web');3const { ReadableStreamBYOBRequest } = require('stream/web');4const { ReadableByteStreamControllerConvertPullIntoDescriptor } = require('stream/web');5const { ReadableByteStreamControllerEnqueue } = require('stream/web');6const { ReadableByteStreamControllerClose } = require('stream/web');7const { ReadableByteStreamControllerError } = require('stream/web');8const { ReadableStreamDefaultReader } = require('stream/web');9const { ReadableStreamDefaultController } = require('stream/web');10const { ReadableStreamDefaultControllerClose } = require('stream/web');11const { ReadableStreamDefaultControllerEnqueue } = require('stream/web');12const { ReadableStreamDefaultControllerError } = require('stream/web');13const { ReadableStreamBYOBReaderReadResult } = require('stream/web');14const { ReadableStreamDefaultReaderReadResult } = require('stream/web');15const { ReadableStreamDefaultControllerErrorIfNeeded } = require('stream/web');16const { ReadableStreamDefaultControllerCanCloseOrEnqueue } = require('stream/web');17const { ReadableStreamDefaultControllerHasBackpressure } = require('stream/web');18const { ReadableStreamDefaultControllerGetDesiredSize } = require('stream/web');19const { ReadableStreamTee } = require('stream/web');20const { ReadableStreamCancel } = require('stream/web');21const { ReadableStreamClose } = require('stream/web');22const { ReadableStreamCreateReadResult } = require('stream/web');23const { ReadableStreamError } = require('stream/web');24const { ReadableStreamFulfillReadRequest } = require('stream/web');25const { ReadableStreamGetNumReadRequests } = require('stream/web');26const { ReadableStreamHasDefaultReader } = require('stream/web');27const { ReadableStreamHasBYOBReader } = require('stream/web');28const { ReadableStreamGetNumReadIntoRequests } = require('stream/web');29const { ReadableStreamGetNumReadRequests } = require('stream/web');30const { ReadableStreamTeeBranch1 } = require('stream/web');31const { ReadableStreamTeeBranch2 } = require('stream/web');32const { Read

Full Screen

Using AI Code Generation

copy

Full Screen

1var pullIntoDescriptor = {buffer: new ArrayBuffer(4), byteOffset: 0, bytesFilled: 0, elementSize: 1, ctor: Uint8Array, type: "uint8"};2var controller = {byobRequest: undefined, desiredSize: 1, closeRequested: false, queue: [], queueTotalSize: 0, started: false};3ReadableByteStreamControllerConvertPullIntoDescriptor(controller, pullIntoDescriptor);4var controller = {byobRequest: undefined, desiredSize: 1, closeRequested: false, queue: [], queueTotalSize: 0, started: false};5var pullIntoDescriptor = {buffer: new ArrayBuffer(4), byteOffset: 0, bytesFilled: 0, elementSize: 1, ctor: Uint8Array, type: "uint8"};6var bytesWritten = 1;7ReadableByteStreamControllerRespond(controller, pullIntoDescriptor, bytesWritten);8var controller = {byobRequest: undefined, desiredSize: 1, closeRequested: false, queue: [], queueTotalSize: 0, started: false};9var view = new Uint8Array(new ArrayBuffer(4));10ReadableByteStreamControllerRespondWithNewView(controller, view);11var reader = new ReadableStreamBYOBReader();12var view = new Uint8Array(new ArrayBuffer(4));13var readPromise = ReadableStreamBYOBReaderRead(reader, view);14var byobRequest = {view: new Uint8Array(new ArrayBuffer(4))};15var bytesWritten = 1;16ReadableStreamBYOBRequestRespond(byobRequest, bytesWritten);17var byobRequest = {view: new Uint8Array(new ArrayBuffer(4))};18var view = new Uint8Array(new ArrayBuffer(

Full Screen

Using AI Code Generation

copy

Full Screen

1var rs = new ReadableStream({2 pull: function(c) {3 var desc = {4 buffer: new ArrayBuffer(1),5 };6 var result = ReadableByteStreamControllerConvertPullIntoDescriptor(c, desc);7 assert_equals(result, undefined);8 assert_equals(desc.buffer.constructor, ArrayBuffer);9 assert_equals(desc.byteOffset, 0);10 assert_equals(desc.bytesFilled, 0);11 assert_equals(desc.byteLength, 1);12 assert_equals(desc.elementSize, 1);13 assert_equals(desc.ctor, Uint8Array);14 assert_equals(desc.readerType, 'default');15 c.enqueue(new Uint8Array([1]));16 }17});18var reader = rs.getReader();19var result = reader.read();20result.then(function(r) {21 assert_equals(r.value.constructor, Uint8Array);22 assert_equals(r.value[0], 1);23 assert_equals(r.done, false);24});25var rs = new ReadableStream({26 pull: function(c) {27 c.enqueue(new Uint8Array([1]));28 }29});30var reader = rs.getReader();31var result = reader.read(new Uint8Array(1));32result.then(function(r) {33 assert_equals(r.value.constructor, Uint8Array);34 assert_equals(r.value[0], 1);35 assert_equals(r.done, false);36});37var rs = new ReadableStream({38 pull: function(c) {39 c.enqueue(new Uint8Array([1]));40 }41});42var reader = rs.getReader();43var result = reader.read('a');44result.then(function(r) {45 assert_equals(r.value.constructor, Uint8Array);46 assert_equals(r.value[0],

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run wpt automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful