1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
|
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim:set ts=2 sw=2 sts=2 et cindent: */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "mozilla/dom/ReadableStream.h"
#include "ReadIntoRequest.h"
#include "ReadableStreamPipeTo.h"
#include "ReadableStreamTee.h"
#include "StreamUtils.h"
#include "TeeState.h"
#include "js/Array.h"
#include "js/Exception.h"
#include "js/PropertyAndElement.h"
#include "js/TypeDecls.h"
#include "js/Value.h"
#include "mozilla/AlreadyAddRefed.h"
#include "mozilla/Assertions.h"
#include "mozilla/Attributes.h"
#include "mozilla/CycleCollectedJSContext.h"
#include "mozilla/HoldDropJSObjects.h"
#include "mozilla/StaticPrefs_dom.h"
#include "mozilla/dom/BindingCallContext.h"
#include "mozilla/dom/ByteStreamHelpers.h"
#include "mozilla/dom/QueueWithSizes.h"
#include "mozilla/dom/QueuingStrategyBinding.h"
#include "mozilla/dom/ReadRequest.h"
#include "mozilla/dom/ReadableByteStreamController.h"
#include "mozilla/dom/ReadableStreamBYOBReader.h"
#include "mozilla/dom/ReadableStreamBinding.h"
#include "mozilla/dom/ReadableStreamController.h"
#include "mozilla/dom/ReadableStreamDefaultController.h"
#include "mozilla/dom/ReadableStreamDefaultReader.h"
#include "mozilla/dom/RootedDictionary.h"
#include "mozilla/dom/ScriptSettings.h"
#include "mozilla/dom/UnderlyingSourceBinding.h"
#include "mozilla/dom/UnderlyingSourceCallbackHelpers.h"
#include "mozilla/dom/WritableStream.h"
#include "mozilla/dom/WritableStreamDefaultWriter.h"
#include "nsCOMPtr.h"
#include "mozilla/dom/Promise-inl.h"
#include "nsIGlobalObject.h"
#include "nsISupports.h"
inline void ImplCycleCollectionTraverse(
nsCycleCollectionTraversalCallback& aCallback,
mozilla::Variant<mozilla::Nothing,
RefPtr<mozilla::dom::ReadableStreamDefaultReader>>&
aReader,
const char* aName, uint32_t aFlags = 0) {
if (aReader.is<RefPtr<mozilla::dom::ReadableStreamDefaultReader>>()) {
ImplCycleCollectionTraverse(
aCallback,
aReader.as<RefPtr<mozilla::dom::ReadableStreamDefaultReader>>(), aName,
aFlags);
}
}
inline void ImplCycleCollectionUnlink(
mozilla::Variant<mozilla::Nothing,
RefPtr<mozilla::dom::ReadableStreamDefaultReader>>&
aReader) {
aReader = AsVariant(mozilla::Nothing());
}
namespace mozilla::dom {
using namespace streams_abstract;
// Only needed for refcounted objects.
NS_IMPL_CYCLE_COLLECTION_WRAPPERCACHE_WITH_JS_MEMBERS(
ReadableStream, (mGlobal, mController, mReader), (mStoredError))
NS_IMPL_CYCLE_COLLECTING_ADDREF(ReadableStream)
NS_IMPL_CYCLE_COLLECTING_RELEASE(ReadableStream)
NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(ReadableStream)
NS_WRAPPERCACHE_INTERFACE_MAP_ENTRY
NS_INTERFACE_MAP_ENTRY(nsISupports)
NS_INTERFACE_MAP_END
ReadableStream::ReadableStream(nsIGlobalObject* aGlobal,
HoldDropJSObjectsCaller aHoldDropCaller)
: mGlobal(aGlobal), mReader(nullptr), mHoldDropCaller(aHoldDropCaller) {
if (mHoldDropCaller == HoldDropJSObjectsCaller::Implicit) {
mozilla::HoldJSObjects(this);
}
}
ReadableStream::ReadableStream(const GlobalObject& aGlobal,
HoldDropJSObjectsCaller aHoldDropCaller)
: mGlobal(do_QueryInterface(aGlobal.GetAsSupports())),
mReader(nullptr),
mHoldDropCaller(aHoldDropCaller) {
if (mHoldDropCaller == HoldDropJSObjectsCaller::Implicit) {
mozilla::HoldJSObjects(this);
}
}
ReadableStream::~ReadableStream() {
if (mHoldDropCaller == HoldDropJSObjectsCaller::Implicit) {
mozilla::DropJSObjects(this);
}
}
JSObject* ReadableStream::WrapObject(JSContext* aCx,
JS::Handle<JSObject*> aGivenProto) {
return ReadableStream_Binding::Wrap(aCx, this, aGivenProto);
}
ReadableStreamDefaultReader* ReadableStream::GetDefaultReader() {
return mReader->AsDefault();
}
void ReadableStream::SetReader(ReadableStreamGenericReader* aReader) {
mReader = aReader;
}
namespace streams_abstract {
// https://streams.spec.whatwg.org/#readable-stream-has-byob-reader
bool ReadableStreamHasBYOBReader(ReadableStream* aStream) {
// Step 1. Let reader be stream.[[reader]].
ReadableStreamGenericReader* reader = aStream->GetReader();
// Step 2. If reader is undefined, return false.
if (!reader) {
return false;
}
// Step 3. If reader implements ReadableStreamBYOBReader, return true.
// Step 4. Return false.
return reader->IsBYOB();
}
// https://streams.spec.whatwg.org/#readable-stream-has-default-reader
bool ReadableStreamHasDefaultReader(ReadableStream* aStream) {
// Step 1. Let reader be stream.[[reader]].
ReadableStreamGenericReader* reader = aStream->GetReader();
// Step 2. If reader is undefined, return false.
if (!reader) {
return false;
}
// Step 3. If reader implements ReadableStreamDefaultReader, return true.
// Step 4. Return false.
return reader->IsDefault();
}
} // namespace streams_abstract
// Streams Spec: 4.2.4: https://streams.spec.whatwg.org/#rs-prototype
/* static */
already_AddRefed<ReadableStream> ReadableStream::Constructor(
const GlobalObject& aGlobal,
const Optional<JS::Handle<JSObject*>>& aUnderlyingSource,
const QueuingStrategy& aStrategy, ErrorResult& aRv) {
// Step 1.
JS::Rooted<JSObject*> underlyingSourceObj(
aGlobal.Context(),
aUnderlyingSource.WasPassed() ? aUnderlyingSource.Value() : nullptr);
// Step 2.
RootedDictionary<UnderlyingSource> underlyingSourceDict(aGlobal.Context());
if (underlyingSourceObj) {
JS::Rooted<JS::Value> objValue(aGlobal.Context(),
JS::ObjectValue(*underlyingSourceObj));
dom::BindingCallContext callCx(aGlobal.Context(),
"ReadableStream.constructor");
aRv.MightThrowJSException();
if (!underlyingSourceDict.Init(callCx, objValue)) {
aRv.StealExceptionFromJSContext(aGlobal.Context());
return nullptr;
}
}
// Step 3.
RefPtr<ReadableStream> readableStream =
new ReadableStream(aGlobal, HoldDropJSObjectsCaller::Implicit);
// Step 4.
if (underlyingSourceDict.mType.WasPassed()) {
// Implicit assertion on above check.
MOZ_ASSERT(underlyingSourceDict.mType.Value() == ReadableStreamType::Bytes);
// Step 4.1
if (aStrategy.mSize.WasPassed()) {
aRv.ThrowRangeError("Implementation preserved member 'size'");
return nullptr;
}
// Step 4.2
double highWaterMark = ExtractHighWaterMark(aStrategy, 0, aRv);
if (aRv.Failed()) {
return nullptr;
}
// Step 4.3
SetUpReadableByteStreamControllerFromUnderlyingSource(
aGlobal.Context(), readableStream, underlyingSourceObj,
underlyingSourceDict, highWaterMark, aRv);
if (aRv.Failed()) {
return nullptr;
}
return readableStream.forget();
}
// Step 5.1 (implicit in above check)
// Step 5.2. Extract callback.
//
// Implementation Note: The specification demands that if the size doesn't
// exist, we instead would provide an algorithm that returns 1. Instead, we
// will teach callers that a missing callback should simply return 1, rather
// than gin up a fake callback here.
//
// This decision may need to be revisited if the default action ever diverges
// within the specification.
RefPtr<QueuingStrategySize> sizeAlgorithm =
aStrategy.mSize.WasPassed() ? &aStrategy.mSize.Value() : nullptr;
// Step 5.3
double highWaterMark = ExtractHighWaterMark(aStrategy, 1, aRv);
if (aRv.Failed()) {
return nullptr;
}
// Step 5.4.
SetupReadableStreamDefaultControllerFromUnderlyingSource(
aGlobal.Context(), readableStream, underlyingSourceObj,
underlyingSourceDict, highWaterMark, sizeAlgorithm, aRv);
if (aRv.Failed()) {
return nullptr;
}
return readableStream.forget();
}
// Dealing with const this ptr is a pain, so just re-implement.
// https://streams.spec.whatwg.org/#is-readable-stream-locked
bool ReadableStream::Locked() const {
// Step 1 + 2.
return mReader;
}
namespace streams_abstract {
// https://streams.spec.whatwg.org/#initialize-readable-stream
static void InitializeReadableStream(ReadableStream* aStream) {
// Step 1.
aStream->SetState(ReadableStream::ReaderState::Readable);
// Step 2.
aStream->SetReader(nullptr);
aStream->SetStoredError(JS::UndefinedHandleValue);
// Step 3.
aStream->SetDisturbed(false);
}
} // namespace streams_abstract
// https://streams.spec.whatwg.org/#create-readable-stream
MOZ_CAN_RUN_SCRIPT
already_AddRefed<ReadableStream> ReadableStream::CreateAbstract(
JSContext* aCx, nsIGlobalObject* aGlobal,
UnderlyingSourceAlgorithmsBase* aAlgorithms,
mozilla::Maybe<double> aHighWaterMark, QueuingStrategySize* aSizeAlgorithm,
ErrorResult& aRv) {
// Step 1. If highWaterMark was not passed, set it to 1.
double highWaterMark = aHighWaterMark.valueOr(1.0);
// Step 2. consumers of sizeAlgorithm
// handle null algorithms correctly.
// Step 3.
MOZ_ASSERT(IsNonNegativeNumber(highWaterMark));
// Step 4.
RefPtr<ReadableStream> stream =
new ReadableStream(aGlobal, HoldDropJSObjectsCaller::Implicit);
// Step 5.
InitializeReadableStream(stream);
// Step 6.
RefPtr<ReadableStreamDefaultController> controller =
new ReadableStreamDefaultController(aGlobal);
// Step 7.
SetUpReadableStreamDefaultController(aCx, stream, controller, aAlgorithms,
highWaterMark, aSizeAlgorithm, aRv);
// Step 8.
return stream.forget();
}
namespace streams_abstract {
// https://streams.spec.whatwg.org/#readable-stream-close
void ReadableStreamClose(JSContext* aCx, ReadableStream* aStream,
ErrorResult& aRv) {
// Step 1.
MOZ_ASSERT(aStream->State() == ReadableStream::ReaderState::Readable);
// Step 2.
aStream->SetState(ReadableStream::ReaderState::Closed);
// Step 3.
ReadableStreamGenericReader* reader = aStream->GetReader();
// Step 4.
if (!reader) {
return;
}
// Step 5.
reader->ClosedPromise()->MaybeResolveWithUndefined();
// Step 6.
if (reader->IsDefault()) {
// Step 6.1. Let readRequests be reader.[[readRequests]].
// Move LinkedList out of DefaultReader onto stack to avoid the potential
// for concurrent modification, which could invalidate the iterator.
//
// See https://bugs.chromium.org/p/chromium/issues/detail?id=1045874 as an
// example of the kind of issue that could occur.
LinkedList<RefPtr<ReadRequest>> readRequests =
std::move(reader->AsDefault()->ReadRequests());
// Step 6.2. Set reader.[[readRequests]] to an empty list.
// Note: The std::move already cleared this anyway.
reader->AsDefault()->ReadRequests().clear();
// Step 6.3. For each readRequest of readRequests,
// Drain the local list and destroy elements along the way.
while (RefPtr<ReadRequest> readRequest = readRequests.popFirst()) {
// Step 6.3.1. Perform readRequest’s close steps.
readRequest->CloseSteps(aCx, aRv);
if (aRv.Failed()) {
return;
}
}
}
}
// https://streams.spec.whatwg.org/#readable-stream-cancel
already_AddRefed<Promise> ReadableStreamCancel(JSContext* aCx,
ReadableStream* aStream,
JS::Handle<JS::Value> aError,
ErrorResult& aRv) {
// Step 1.
aStream->SetDisturbed(true);
// Step 2.
if (aStream->State() == ReadableStream::ReaderState::Closed) {
RefPtr<Promise> promise =
Promise::CreateInfallible(aStream->GetParentObject());
promise->MaybeResolveWithUndefined();
return promise.forget();
}
// Step 3.
if (aStream->State() == ReadableStream::ReaderState::Errored) {
JS::Rooted<JS::Value> storedError(aCx, aStream->StoredError());
return Promise::CreateRejected(aStream->GetParentObject(), storedError,
aRv);
}
// Step 4.
ReadableStreamClose(aCx, aStream, aRv);
if (aRv.Failed()) {
return nullptr;
}
// Step 5.
ReadableStreamGenericReader* reader = aStream->GetReader();
// Step 6.
if (reader && reader->IsBYOB()) {
// Step 6.1. Let readIntoRequests be reader.[[readIntoRequests]].
LinkedList<RefPtr<ReadIntoRequest>> readIntoRequests =
std::move(reader->AsBYOB()->ReadIntoRequests());
// Step 6.2. Set reader.[[readIntoRequests]] to an empty list.
// Note: The std::move already cleared this anyway.
reader->AsBYOB()->ReadIntoRequests().clear();
// Step 6.3. For each readIntoRequest of readIntoRequests,
while (RefPtr<ReadIntoRequest> readIntoRequest =
readIntoRequests.popFirst()) {
// Step 6.3.1.Perform readIntoRequest’s close steps, given undefined.
readIntoRequest->CloseSteps(aCx, JS::UndefinedHandleValue, aRv);
if (aRv.Failed()) {
return nullptr;
}
}
}
// Step 7.
RefPtr<ReadableStreamController> controller(aStream->Controller());
RefPtr<Promise> sourceCancelPromise =
controller->CancelSteps(aCx, aError, aRv);
if (aRv.Failed()) {
return nullptr;
}
// Step 8.
RefPtr<Promise> promise =
Promise::CreateInfallible(sourceCancelPromise->GetParentObject());
// ThenWithCycleCollectedArgs will carry promise, keeping it alive until the
// callback executes.
Result<RefPtr<Promise>, nsresult> returnResult =
sourceCancelPromise->ThenWithCycleCollectedArgs(
[](JSContext*, JS::Handle<JS::Value>, ErrorResult&,
RefPtr<Promise> newPromise) {
newPromise->MaybeResolveWithUndefined();
return newPromise.forget();
},
promise);
if (returnResult.isErr()) {
aRv.Throw(returnResult.unwrapErr());
return nullptr;
}
return returnResult.unwrap().forget();
}
} // namespace streams_abstract
// https://streams.spec.whatwg.org/#rs-cancel
already_AddRefed<Promise> ReadableStream::Cancel(JSContext* aCx,
JS::Handle<JS::Value> aReason,
ErrorResult& aRv) {
// Step 1. If ! IsReadableStreamLocked(this) is true,
// return a promise rejected with a TypeError exception.
if (Locked()) {
aRv.ThrowTypeError("Cannot cancel a stream locked by a reader.");
return nullptr;
}
// Step 2. Return ! ReadableStreamCancel(this, reason).
RefPtr<ReadableStream> thisRefPtr = this;
return ReadableStreamCancel(aCx, thisRefPtr, aReason, aRv);
}
namespace streams_abstract {
// https://streams.spec.whatwg.org/#acquire-readable-stream-reader
already_AddRefed<ReadableStreamDefaultReader>
AcquireReadableStreamDefaultReader(ReadableStream* aStream, ErrorResult& aRv) {
// Step 1.
RefPtr<ReadableStreamDefaultReader> reader =
new ReadableStreamDefaultReader(aStream->GetParentObject());
// Step 2.
SetUpReadableStreamDefaultReader(reader, aStream, aRv);
if (aRv.Failed()) {
return nullptr;
}
// Step 3.
return reader.forget();
}
} // namespace streams_abstract
// https://streams.spec.whatwg.org/#rs-get-reader
void ReadableStream::GetReader(const ReadableStreamGetReaderOptions& aOptions,
OwningReadableStreamReader& resultReader,
ErrorResult& aRv) {
// Step 1. If options["mode"] does not exist,
// return ? AcquireReadableStreamDefaultReader(this).
if (!aOptions.mMode.WasPassed()) {
RefPtr<ReadableStreamDefaultReader> defaultReader =
AcquireReadableStreamDefaultReader(this, aRv);
if (aRv.Failed()) {
return;
}
resultReader.SetAsReadableStreamDefaultReader() = defaultReader;
return;
}
// Step 2. Assert: options["mode"] is "byob".
MOZ_ASSERT(aOptions.mMode.Value() == ReadableStreamReaderMode::Byob);
// Step 3. Return ? AcquireReadableStreamBYOBReader(this).
RefPtr<ReadableStreamBYOBReader> byobReader =
AcquireReadableStreamBYOBReader(this, aRv);
if (aRv.Failed()) {
return;
}
resultReader.SetAsReadableStreamBYOBReader() = byobReader;
}
namespace streams_abstract {
// https://streams.spec.whatwg.org/#is-readable-stream-locked
bool IsReadableStreamLocked(ReadableStream* aStream) {
// Step 1 + 2.
return aStream->Locked();
}
} // namespace streams_abstract
// https://streams.spec.whatwg.org/#rs-pipe-through
MOZ_CAN_RUN_SCRIPT already_AddRefed<ReadableStream> ReadableStream::PipeThrough(
const ReadableWritablePair& aTransform, const StreamPipeOptions& aOptions,
ErrorResult& aRv) {
// Step 1: If ! IsReadableStreamLocked(this) is true, throw a TypeError
// exception.
if (IsReadableStreamLocked(this)) {
aRv.ThrowTypeError("Cannot pipe from a locked stream.");
return nullptr;
}
// Step 2: If ! IsWritableStreamLocked(transform["writable"]) is true, throw a
// TypeError exception.
if (IsWritableStreamLocked(aTransform.mWritable)) {
aRv.ThrowTypeError("Cannot pipe to a locked stream.");
return nullptr;
}
// Step 3: Let signal be options["signal"] if it exists, or undefined
// otherwise.
RefPtr<AbortSignal> signal =
aOptions.mSignal.WasPassed() ? &aOptions.mSignal.Value() : nullptr;
// Step 4: Let promise be ! ReadableStreamPipeTo(this, transform["writable"],
// options["preventClose"], options["preventAbort"], options["preventCancel"],
// signal).
RefPtr<WritableStream> writable = aTransform.mWritable;
RefPtr<Promise> promise = ReadableStreamPipeTo(
this, writable, aOptions.mPreventClose, aOptions.mPreventAbort,
aOptions.mPreventCancel, signal, aRv);
if (aRv.Failed()) {
return nullptr;
}
// Step 5: Set promise.[[PromiseIsHandled]] to true.
MOZ_ALWAYS_TRUE(promise->SetAnyPromiseIsHandled());
// Step 6: Return transform["readable"].
return do_AddRef(aTransform.mReadable.get());
};
namespace streams_abstract {
// https://streams.spec.whatwg.org/#readable-stream-get-num-read-requests
double ReadableStreamGetNumReadRequests(ReadableStream* aStream) {
// Step 1.
MOZ_ASSERT(ReadableStreamHasDefaultReader(aStream));
// Step 2.
return double(aStream->GetDefaultReader()->ReadRequests().length());
}
// https://streams.spec.whatwg.org/#readable-stream-error
void ReadableStreamError(JSContext* aCx, ReadableStream* aStream,
JS::Handle<JS::Value> aValue, ErrorResult& aRv) {
// Step 1.
MOZ_ASSERT(aStream->State() == ReadableStream::ReaderState::Readable);
// Step 2.
aStream->SetState(ReadableStream::ReaderState::Errored);
// Step 3.
aStream->SetStoredError(aValue);
// Step 4.
ReadableStreamGenericReader* reader = aStream->GetReader();
// Step 5.
if (!reader) {
return;
}
// Step 6.
reader->ClosedPromise()->MaybeReject(aValue);
// Step 7.
reader->ClosedPromise()->SetSettledPromiseIsHandled();
// Step 8.
if (reader->IsDefault()) {
// Step 8.1. Perform ! ReadableStreamDefaultReaderErrorReadRequests(reader,
// e).
RefPtr<ReadableStreamDefaultReader> defaultReader = reader->AsDefault();
ReadableStreamDefaultReaderErrorReadRequests(aCx, defaultReader, aValue,
aRv);
if (aRv.Failed()) {
return;
}
} else {
// Step 9. Otherwise,
// Step 9.1. Assert: reader implements ReadableStreamBYOBReader.
MOZ_ASSERT(reader->IsBYOB());
// Step 9.2. Perform ! ReadableStreamBYOBReaderErrorReadIntoRequests(reader,
// e).
RefPtr<ReadableStreamBYOBReader> byobReader = reader->AsBYOB();
ReadableStreamBYOBReaderErrorReadIntoRequests(aCx, byobReader, aValue, aRv);
if (aRv.Failed()) {
return;
}
}
}
// https://streams.spec.whatwg.org/#rs-default-controller-close
void ReadableStreamFulfillReadRequest(JSContext* aCx, ReadableStream* aStream,
JS::Handle<JS::Value> aChunk, bool aDone,
ErrorResult& aRv) {
// Step 1.
MOZ_ASSERT(ReadableStreamHasDefaultReader(aStream));
// Step 2.
ReadableStreamDefaultReader* reader = aStream->GetDefaultReader();
// Step 3.
MOZ_ASSERT(!reader->ReadRequests().isEmpty());
// Step 4+5.
RefPtr<ReadRequest> readRequest = reader->ReadRequests().popFirst();
// Step 6.
if (aDone) {
readRequest->CloseSteps(aCx, aRv);
if (aRv.Failed()) {
return;
}
}
// Step 7.
readRequest->ChunkSteps(aCx, aChunk, aRv);
}
// https://streams.spec.whatwg.org/#readable-stream-add-read-request
void ReadableStreamAddReadRequest(ReadableStream* aStream,
ReadRequest* aReadRequest) {
// Step 1.
MOZ_ASSERT(aStream->GetReader()->IsDefault());
// Step 2.
MOZ_ASSERT(aStream->State() == ReadableStream::ReaderState::Readable);
// Step 3.
aStream->GetDefaultReader()->ReadRequests().insertBack(aReadRequest);
}
} // namespace streams_abstract
// https://streams.spec.whatwg.org/#abstract-opdef-readablestreamdefaulttee
// Step 14, 15
MOZ_CAN_RUN_SCRIPT already_AddRefed<Promise>
ReadableStreamDefaultTeeSourceAlgorithms::CancelCallback(
JSContext* aCx, const Optional<JS::Handle<JS::Value>>& aReason,
ErrorResult& aRv) {
// Step 1.
mTeeState->SetCanceled(mBranch, true);
// Step 2.
mTeeState->SetReason(mBranch, aReason.Value());
// Step 3.
if (mTeeState->Canceled(OtherTeeBranch(mBranch))) {
// Step 3.1
JS::Rooted<JSObject*> compositeReason(aCx, JS::NewArrayObject(aCx, 2));
if (!compositeReason) {
aRv.StealExceptionFromJSContext(aCx);
return nullptr;
}
JS::Rooted<JS::Value> reason1(aCx, mTeeState->Reason1());
if (!JS_SetElement(aCx, compositeReason, 0, reason1)) {
aRv.StealExceptionFromJSContext(aCx);
return nullptr;
}
JS::Rooted<JS::Value> reason2(aCx, mTeeState->Reason2());
if (!JS_SetElement(aCx, compositeReason, 1, reason2)) {
aRv.StealExceptionFromJSContext(aCx);
return nullptr;
}
// Step 3.2
JS::Rooted<JS::Value> compositeReasonValue(
aCx, JS::ObjectValue(*compositeReason));
RefPtr<ReadableStream> stream(mTeeState->GetStream());
RefPtr<Promise> cancelResult =
ReadableStreamCancel(aCx, stream, compositeReasonValue, aRv);
if (aRv.Failed()) {
return nullptr;
}
// Step 3.3
mTeeState->CancelPromise()->MaybeResolve(cancelResult);
}
// Step 4.
return do_AddRef(mTeeState->CancelPromise());
}
// https://streams.spec.whatwg.org/#abstract-opdef-readablestreamdefaulttee
MOZ_CAN_RUN_SCRIPT
static void ReadableStreamDefaultTee(JSContext* aCx, ReadableStream* aStream,
bool aCloneForBranch2,
nsTArray<RefPtr<ReadableStream>>& aResult,
ErrorResult& aRv) {
// Step 1. Implicit.
// Step 2. Implicit.
// Steps 3-12 are contained in the construction of Tee State.
RefPtr<TeeState> teeState = TeeState::Create(aStream, aCloneForBranch2, aRv);
if (aRv.Failed()) {
return;
}
// Step 13 - 16
auto branch1Algorithms = MakeRefPtr<ReadableStreamDefaultTeeSourceAlgorithms>(
teeState, TeeBranch::Branch1);
auto branch2Algorithms = MakeRefPtr<ReadableStreamDefaultTeeSourceAlgorithms>(
teeState, TeeBranch::Branch2);
// Step 17.
nsCOMPtr<nsIGlobalObject> global(
do_AddRef(teeState->GetStream()->GetParentObject()));
teeState->SetBranch1(ReadableStream::CreateAbstract(
aCx, global, branch1Algorithms, mozilla::Nothing(), nullptr, aRv));
if (aRv.Failed()) {
return;
}
// Step 18.
teeState->SetBranch2(ReadableStream::CreateAbstract(
aCx, global, branch2Algorithms, mozilla::Nothing(), nullptr, aRv));
if (aRv.Failed()) {
return;
}
// Step 19.
teeState->GetReader()->ClosedPromise()->AddCallbacksWithCycleCollectedArgs(
[](JSContext* aCx, JS::Handle<JS::Value> aValue, ErrorResult& aRv,
TeeState* aTeeState) {},
[](JSContext* aCx, JS::Handle<JS::Value> aReason, ErrorResult& aRv,
TeeState* aTeeState) {
// Step 19.1.
ReadableStreamDefaultControllerError(
aCx, aTeeState->Branch1()->DefaultController(), aReason, aRv);
if (aRv.Failed()) {
return;
}
// Step 19.2
ReadableStreamDefaultControllerError(
aCx, aTeeState->Branch2()->DefaultController(), aReason, aRv);
if (aRv.Failed()) {
return;
}
// Step 19.3
if (!aTeeState->Canceled1() || !aTeeState->Canceled2()) {
aTeeState->CancelPromise()->MaybeResolveWithUndefined();
}
},
RefPtr(teeState));
// Step 20.
aResult.AppendElement(teeState->Branch1());
aResult.AppendElement(teeState->Branch2());
}
// https://streams.spec.whatwg.org/#rs-pipe-to
already_AddRefed<Promise> ReadableStream::PipeTo(
WritableStream& aDestination, const StreamPipeOptions& aOptions,
ErrorResult& aRv) {
// Step 1. If !IsReadableStreamLocked(this) is true, return a promise rejected
// with a TypeError exception.
if (IsReadableStreamLocked(this)) {
aRv.ThrowTypeError("Cannot pipe from a locked stream.");
return nullptr;
}
// Step 2. If !IsWritableStreamLocked(destination) is true, return a promise
// rejected with a TypeError exception.
if (IsWritableStreamLocked(&aDestination)) {
aRv.ThrowTypeError("Cannot pipe to a locked stream.");
return nullptr;
}
// Step 3. Let signal be options["signal"] if it exists, or undefined
// otherwise.
RefPtr<AbortSignal> signal =
aOptions.mSignal.WasPassed() ? &aOptions.mSignal.Value() : nullptr;
// Step 4. Return ! ReadableStreamPipeTo(this, destination,
// options["preventClose"], options["preventAbort"], options["preventCancel"],
// signal).
return ReadableStreamPipeTo(this, &aDestination, aOptions.mPreventClose,
aOptions.mPreventAbort, aOptions.mPreventCancel,
signal, aRv);
}
// https://streams.spec.whatwg.org/#readable-stream-tee
MOZ_CAN_RUN_SCRIPT
static void ReadableStreamTee(JSContext* aCx, ReadableStream* aStream,
bool aCloneForBranch2,
nsTArray<RefPtr<ReadableStream>>& aResult,
ErrorResult& aRv) {
// Step 1. Implicit.
// Step 2. Implicit.
// Step 3.
if (aStream->Controller()->IsByte()) {
ReadableByteStreamTee(aCx, aStream, aResult, aRv);
return;
}
// Step 4.
ReadableStreamDefaultTee(aCx, aStream, aCloneForBranch2, aResult, aRv);
}
void ReadableStream::Tee(JSContext* aCx,
nsTArray<RefPtr<ReadableStream>>& aResult,
ErrorResult& aRv) {
ReadableStreamTee(aCx, this, false, aResult, aRv);
}
void ReadableStream::IteratorData::Traverse(
nsCycleCollectionTraversalCallback& cb) {
ReadableStream::IteratorData* tmp = this;
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mReader);
}
void ReadableStream::IteratorData::Unlink() {
ReadableStream::IteratorData* tmp = this;
NS_IMPL_CYCLE_COLLECTION_UNLINK(mReader);
}
// https://streams.spec.whatwg.org/#rs-get-iterator
void ReadableStream::InitAsyncIteratorData(
IteratorData& aData, Iterator::IteratorType aType,
const ReadableStreamIteratorOptions& aOptions, ErrorResult& aRv) {
// Step 1. Let reader be ? AcquireReadableStreamDefaultReader(stream).
RefPtr<ReadableStreamDefaultReader> reader =
AcquireReadableStreamDefaultReader(this, aRv);
if (aRv.Failed()) {
return;
}
// Step 2. Set iterator’s reader to reader.
aData.mReader = reader;
// Step 3. Let preventCancel be args[0]["preventCancel"].
// Step 4. Set iterator’s prevent cancel to preventCancel.
aData.mPreventCancel = aOptions.mPreventCancel;
}
// https://streams.spec.whatwg.org/#rs-asynciterator-prototype-next
// Step 4.
struct IteratorReadRequest : public ReadRequest {
public:
NS_DECL_ISUPPORTS_INHERITED
NS_DECL_CYCLE_COLLECTION_CLASS_INHERITED(IteratorReadRequest, ReadRequest)
RefPtr<Promise> mPromise;
RefPtr<ReadableStreamDefaultReader> mReader;
explicit IteratorReadRequest(Promise* aPromise,
ReadableStreamDefaultReader* aReader)
: mPromise(aPromise), mReader(aReader) {}
// chunk steps, given chunk
void ChunkSteps(JSContext* aCx, JS::Handle<JS::Value> aChunk,
ErrorResult& aRv) override {
// Step 1. Resolve promise with chunk.
mPromise->MaybeResolve(aChunk);
}
// close steps
void CloseSteps(JSContext* aCx, ErrorResult& aRv) override {
// Step 1. Perform ! ReadableStreamDefaultReaderRelease(reader).
ReadableStreamDefaultReaderRelease(aCx, mReader, aRv);
if (aRv.Failed()) {
mPromise->MaybeRejectWithUndefined();
return;
}
// Step 2. Resolve promise with end of iteration.
iterator_utils::ResolvePromiseForFinished(mPromise);
}
// error steps, given e
void ErrorSteps(JSContext* aCx, JS::Handle<JS::Value> aError,
ErrorResult& aRv) override {
// Step 1. Perform ! ReadableStreamDefaultReaderRelease(reader).
ReadableStreamDefaultReaderRelease(aCx, mReader, aRv);
if (aRv.Failed()) {
mPromise->MaybeRejectWithUndefined();
return;
}
// Step 2. Reject promise with e.
mPromise->MaybeReject(aError);
}
protected:
virtual ~IteratorReadRequest() = default;
};
NS_IMPL_CYCLE_COLLECTION_INHERITED(IteratorReadRequest, ReadRequest, mPromise,
mReader)
NS_IMPL_ADDREF_INHERITED(IteratorReadRequest, ReadRequest)
NS_IMPL_RELEASE_INHERITED(IteratorReadRequest, ReadRequest)
NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(IteratorReadRequest)
NS_INTERFACE_MAP_END_INHERITING(ReadRequest)
// https://streams.spec.whatwg.org/#rs-asynciterator-prototype-next
already_AddRefed<Promise> ReadableStream::GetNextIterationResult(
Iterator* aIterator, ErrorResult& aRv) {
// Step 1. Let reader be iterator’s reader.
RefPtr<ReadableStreamDefaultReader> reader = aIterator->Data().mReader;
// Step 2. Assert: reader.[[stream]] is not undefined.
MOZ_ASSERT(reader->GetStream());
// Step 3. Let promise be a new promise.
RefPtr<Promise> promise = Promise::CreateInfallible(GetParentObject());
// Step 4. Let readRequest be a new read request with the following items:
RefPtr<ReadRequest> request = new IteratorReadRequest(promise, reader);
// Step 5. Perform ! ReadableStreamDefaultReaderRead(this, readRequest).
AutoJSAPI jsapi;
if (!jsapi.Init(mGlobal)) {
aRv.ThrowUnknownError("Internal error");
return nullptr;
}
ReadableStreamDefaultReaderRead(jsapi.cx(), reader, request, aRv);
if (aRv.Failed()) {
return nullptr;
}
// Step 6. Return promise.
return promise.forget();
}
// https://streams.spec.whatwg.org/#rs-asynciterator-prototype-return
already_AddRefed<Promise> ReadableStream::IteratorReturn(
JSContext* aCx, Iterator* aIterator, JS::Handle<JS::Value> aValue,
ErrorResult& aRv) {
// Step 1. Let reader be iterator’s reader.
RefPtr<ReadableStreamDefaultReader> reader = aIterator->Data().mReader;
// Step 2. Assert: reader.[[stream]] is not undefined.
MOZ_ASSERT(reader->GetStream());
// Step 3. Assert: reader.[[readRequests]] is empty, as the async iterator
// machinery guarantees that any previous calls to next() have settled before
// this is called.
MOZ_ASSERT(reader->ReadRequests().isEmpty());
// Step 4. If iterator’s prevent cancel is false:
if (!aIterator->Data().mPreventCancel) {
// Step 4.1. Let result be ! ReadableStreamReaderGenericCancel(reader, arg).
RefPtr<ReadableStream> stream(reader->GetStream());
RefPtr<Promise> result = ReadableStreamCancel(aCx, stream, aValue, aRv);
if (NS_WARN_IF(aRv.Failed())) {
return nullptr;
}
MOZ_DIAGNOSTIC_ASSERT(
reader->GetStream(),
"We shouldn't have a null stream here (bug 1821169).");
if (!reader->GetStream()) {
aRv.Throw(NS_ERROR_FAILURE);
return nullptr;
}
// Step 4.2. Perform ! ReadableStreamDefaultReaderRelease(reader).
ReadableStreamDefaultReaderRelease(aCx, reader, aRv);
if (NS_WARN_IF(aRv.Failed())) {
return nullptr;
}
// Step 4.3. Return result.
return result.forget();
}
// Step 5. Perform ! ReadableStreamDefaultReaderRelease(reader).
ReadableStreamDefaultReaderRelease(aCx, reader, aRv);
if (NS_WARN_IF(aRv.Failed())) {
return nullptr;
}
// Step 6. Return a promise resolved with undefined.
return Promise::CreateResolvedWithUndefined(GetParentObject(), aRv);
}
namespace streams_abstract {
// https://streams.spec.whatwg.org/#readable-stream-add-read-into-request
void ReadableStreamAddReadIntoRequest(ReadableStream* aStream,
ReadIntoRequest* aReadIntoRequest) {
// Step 1. Assert: stream.[[reader]] implements ReadableStreamBYOBReader.
MOZ_ASSERT(aStream->GetReader()->IsBYOB());
// Step 2. Assert: stream.[[state]] is "readable" or "closed".
MOZ_ASSERT(aStream->State() == ReadableStream::ReaderState::Readable ||
aStream->State() == ReadableStream::ReaderState::Closed);
// Step 3. Append readRequest to stream.[[reader]].[[readIntoRequests]].
aStream->GetReader()->AsBYOB()->ReadIntoRequests().insertBack(
aReadIntoRequest);
}
} // namespace streams_abstract
// https://streams.spec.whatwg.org/#abstract-opdef-createreadablebytestream
already_AddRefed<ReadableStream> ReadableStream::CreateByteAbstract(
JSContext* aCx, nsIGlobalObject* aGlobal,
UnderlyingSourceAlgorithmsBase* aAlgorithms, ErrorResult& aRv) {
// Step 1. Let stream be a new ReadableStream.
RefPtr<ReadableStream> stream =
new ReadableStream(aGlobal, HoldDropJSObjectsCaller::Implicit);
// Step 2. Perform ! InitializeReadableStream(stream).
InitializeReadableStream(stream);
// Step 3. Let controller be a new ReadableByteStreamController.
RefPtr<ReadableByteStreamController> controller =
new ReadableByteStreamController(aGlobal);
// Step 4. Perform ? SetUpReadableByteStreamController(stream, controller,
// startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, undefined).
SetUpReadableByteStreamController(aCx, stream, controller, aAlgorithms, 0,
mozilla::Nothing(), aRv);
if (aRv.Failed()) {
return nullptr;
}
// Return stream.
return stream.forget();
}
// https://streams.spec.whatwg.org/#readablestream-set-up
// (except this instead creates a new ReadableStream rather than accepting an
// existing instance)
// _BOUNDARY because `aAlgorithms->StartCallback` (called by
// SetUpReadableStreamDefaultController below) should not be able to run script
// in this case.
MOZ_CAN_RUN_SCRIPT_BOUNDARY already_AddRefed<ReadableStream>
ReadableStream::CreateNative(JSContext* aCx, nsIGlobalObject* aGlobal,
UnderlyingSourceAlgorithmsWrapper& aAlgorithms,
mozilla::Maybe<double> aHighWaterMark,
QueuingStrategySize* aSizeAlgorithm,
ErrorResult& aRv) {
// an optional number highWaterMark (default 1)
double highWaterMark = aHighWaterMark.valueOr(1);
// and if given, highWaterMark must be a non-negative, non-NaN number.
MOZ_ASSERT(IsNonNegativeNumber(highWaterMark));
// Step 1: Let startAlgorithm be an algorithm that returns undefined.
// Step 2: Let pullAlgorithmWrapper be an algorithm that runs these steps:
// Step 3: Let cancelAlgorithmWrapper be an algorithm that runs these steps:
// (Done by UnderlyingSourceAlgorithmsWrapper)
// Step 4: If sizeAlgorithm was not given, then set it to an algorithm that
// returns 1. (Callers will treat nullptr as such, see
// ReadableStream::Constructor for details)
// Step 5: Perform ! InitializeReadableStream(stream).
RefPtr<ReadableStream> stream =
new ReadableStream(aGlobal, HoldDropJSObjectsCaller::Implicit);
// Step 6: Let controller be a new ReadableStreamDefaultController.
auto controller = MakeRefPtr<ReadableStreamDefaultController>(aGlobal);
// Step 7: Perform ! SetUpReadableStreamDefaultController(stream, controller,
// startAlgorithm, pullAlgorithmWrapper, cancelAlgorithmWrapper,
// highWaterMark, sizeAlgorithm).
SetUpReadableStreamDefaultController(aCx, stream, controller, &aAlgorithms,
highWaterMark, aSizeAlgorithm, aRv);
if (aRv.Failed()) {
return nullptr;
}
return stream.forget();
}
// https://streams.spec.whatwg.org/#readablestream-set-up-with-byte-reading-support
// _BOUNDARY because `aAlgorithms->StartCallback` (called by
// SetUpReadableByteStreamController below) should not be able to run script in
// this case.
MOZ_CAN_RUN_SCRIPT_BOUNDARY void ReadableStream::SetUpByteNative(
JSContext* aCx, UnderlyingSourceAlgorithmsWrapper& aAlgorithms,
mozilla::Maybe<double> aHighWaterMark, ErrorResult& aRv) {
// an optional number highWaterMark (default 0)
double highWaterMark = aHighWaterMark.valueOr(0);
// and if given, highWaterMark must be a non-negative, non-NaN number.
MOZ_ASSERT(IsNonNegativeNumber(highWaterMark));
// Step 1: Let startAlgorithm be an algorithm that returns undefined.
// Step 2: Let pullAlgorithmWrapper be an algorithm that runs these steps:
// Step 3: Let cancelAlgorithmWrapper be an algorithm that runs these steps:
// (Done by UnderlyingSourceAlgorithmsWrapper)
// Step 4: Perform ! InitializeReadableStream(stream).
// (Covered by constructor)
// Step 5: Let controller be a new ReadableByteStreamController.
auto controller = MakeRefPtr<ReadableByteStreamController>(GetParentObject());
// Step 6: Perform ! SetUpReadableByteStreamController(stream, controller,
// startAlgorithm, pullAlgorithmWrapper, cancelAlgorithmWrapper,
// highWaterMark, undefined).
SetUpReadableByteStreamController(aCx, this, controller, &aAlgorithms,
highWaterMark, Nothing(), aRv);
}
already_AddRefed<ReadableStream> ReadableStream::CreateByteNative(
JSContext* aCx, nsIGlobalObject* aGlobal,
UnderlyingSourceAlgorithmsWrapper& aAlgorithms,
mozilla::Maybe<double> aHighWaterMark, ErrorResult& aRv) {
RefPtr<ReadableStream> stream =
new ReadableStream(aGlobal, HoldDropJSObjectsCaller::Implicit);
stream->SetUpByteNative(aCx, aAlgorithms, aHighWaterMark, aRv);
if (aRv.Failed()) {
return nullptr;
}
return stream.forget();
}
// https://streams.spec.whatwg.org/#readablestream-close
void ReadableStream::CloseNative(JSContext* aCx, ErrorResult& aRv) {
MOZ_ASSERT(mController->GetAlgorithms()->IsNative());
// Step 1: If stream.[[controller]] implements ReadableByteStreamController,
if (mController->IsByte()) {
RefPtr<ReadableByteStreamController> controller = mController->AsByte();
// Step 1.1: Perform !
// ReadableByteStreamControllerClose(stream.[[controller]]).
ReadableByteStreamControllerClose(aCx, controller, aRv);
if (aRv.Failed()) {
return;
}
// Step 1.2: If stream.[[controller]].[[pendingPullIntos]] is not empty,
// perform ! ReadableByteStreamControllerRespond(stream.[[controller]], 0).
if (!controller->PendingPullIntos().isEmpty()) {
ReadableByteStreamControllerRespond(aCx, controller, 0, aRv);
}
return;
}
// Step 2: Otherwise, perform !
// ReadableStreamDefaultControllerClose(stream.[[controller]]).
RefPtr<ReadableStreamDefaultController> controller = mController->AsDefault();
ReadableStreamDefaultControllerClose(aCx, controller, aRv);
}
// https://streams.spec.whatwg.org/#readablestream-error
void ReadableStream::ErrorNative(JSContext* aCx, JS::Handle<JS::Value> aError,
ErrorResult& aRv) {
// Step 1: If stream.[[controller]] implements ReadableByteStreamController,
// then perform ! ReadableByteStreamControllerError(stream.[[controller]], e).
if (mController->IsByte()) {
ReadableByteStreamControllerError(mController->AsByte(), aError, aRv);
return;
}
// Step 2: Otherwise, perform !
// ReadableStreamDefaultControllerError(stream.[[controller]], e).
ReadableStreamDefaultControllerError(aCx, mController->AsDefault(), aError,
aRv);
}
// https://streams.spec.whatwg.org/#readablestream-current-byob-request-view
static void CurrentBYOBRequestView(JSContext* aCx,
ReadableByteStreamController& aController,
JS::MutableHandle<JSObject*> aRetVal,
ErrorResult& aRv) {
// Step 1. Assert: stream.[[controller]] implements
// ReadableByteStreamController. (implicit)
// Step 2: Let byobRequest be !
// ReadableByteStreamControllerGetBYOBRequest(stream.[[controller]]).
RefPtr<ReadableStreamBYOBRequest> byobRequest =
ReadableByteStreamControllerGetBYOBRequest(aCx, &aController, aRv);
// Step 3: If byobRequest is null, then return null.
if (!byobRequest) {
aRetVal.set(nullptr);
return;
}
// Step 4: Return byobRequest.[[view]].
byobRequest->GetView(aCx, aRetVal);
}
static bool HasSameBufferView(JSContext* aCx, JS::Handle<JSObject*> aX,
JS::Handle<JSObject*> aY, ErrorResult& aRv) {
bool isShared;
JS::Rooted<JSObject*> viewedBufferX(
aCx, JS_GetArrayBufferViewBuffer(aCx, aX, &isShared));
if (!viewedBufferX) {
aRv.StealExceptionFromJSContext(aCx);
return false;
}
JS::Rooted<JSObject*> viewedBufferY(
aCx, JS_GetArrayBufferViewBuffer(aCx, aY, &isShared));
if (!viewedBufferY) {
aRv.StealExceptionFromJSContext(aCx);
return false;
}
return viewedBufferX == viewedBufferY;
}
// https://streams.spec.whatwg.org/#readablestream-enqueue
void ReadableStream::EnqueueNative(JSContext* aCx, JS::Handle<JS::Value> aChunk,
ErrorResult& aRv) {
MOZ_ASSERT(mController->GetAlgorithms()->IsNative());
// Step 1: If stream.[[controller]] implements
// ReadableStreamDefaultController,
if (mController->IsDefault()) {
// Step 1.1: Perform !
// ReadableStreamDefaultControllerEnqueue(stream.[[controller]], chunk).
RefPtr<ReadableStreamDefaultController> controller =
mController->AsDefault();
ReadableStreamDefaultControllerEnqueue(aCx, controller, aChunk, aRv);
return;
}
// Step 2.1: Assert: stream.[[controller]] implements
// ReadableByteStreamController.
MOZ_ASSERT(mController->IsByte());
RefPtr<ReadableByteStreamController> controller = mController->AsByte();
// Step 2.2: Assert: chunk is an ArrayBufferView.
MOZ_ASSERT(aChunk.isObject() &&
JS_IsArrayBufferViewObject(&aChunk.toObject()));
JS::Rooted<JSObject*> chunk(aCx, &aChunk.toObject());
// Step 3: Let byobView be the current BYOB request view for stream.
JS::Rooted<JSObject*> byobView(aCx);
CurrentBYOBRequestView(aCx, *controller, &byobView, aRv);
if (aRv.Failed()) {
return;
}
// Step 4: If byobView is non-null, and chunk.[[ViewedArrayBuffer]] is
// byobView.[[ViewedArrayBuffer]], then:
if (byobView && HasSameBufferView(aCx, chunk, byobView, aRv)) {
// Step 4.1: Assert: chunk.[[ByteOffset]] is byobView.[[ByteOffset]].
MOZ_ASSERT(JS_GetArrayBufferViewByteOffset(chunk) ==
JS_GetArrayBufferViewByteOffset(byobView));
// Step 4.2: Assert: chunk.[[ByteLength]] ≤ byobView.[[ByteLength]].
MOZ_ASSERT(JS_GetArrayBufferViewByteLength(chunk) ==
JS_GetArrayBufferViewByteLength(byobView));
// Step 4.3: Perform ?
// ReadableByteStreamControllerRespond(stream.[[controller]],
// chunk.[[ByteLength]]).
ReadableByteStreamControllerRespond(
aCx, controller, JS_GetArrayBufferViewByteLength(chunk), aRv);
return;
}
if (aRv.Failed()) {
return;
}
// Step 5: Otherwise, perform ?
// ReadableByteStreamControllerEnqueue(stream.[[controller]], chunk).
ReadableByteStreamControllerEnqueue(aCx, controller, chunk, aRv);
}
// https://streams.spec.whatwg.org/#readablestream-get-a-reader
// To get a reader for a ReadableStream stream, return ?
// AcquireReadableStreamDefaultReader(stream). The result will be a
// ReadableStreamDefaultReader.
already_AddRefed<mozilla::dom::ReadableStreamDefaultReader>
ReadableStream::GetReader(ErrorResult& aRv) {
return AcquireReadableStreamDefaultReader(this, aRv);
}
} // namespace mozilla::dom
|