Repository navigation
Expand file tree
/
Copy pathJSCollectionExtensions.cs
More file actions
1099 lines (936 loc) · 36.8 KB
/
Copy pathJSCollectionExtensions.cs
File metadata and controls
1099 lines (936 loc) · 36.8 KB
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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
namespace Microsoft.JavaScript.NodeApi.Interop;
public static class JSCollectionExtensions
{
/// <summary>
/// Creates an async enumerable adapter for a JS async-iterable object, without copying.
/// </summary>
/// <remarks>
/// This method must be called from the JS thread. The returned enumerable object
/// is thread-safe and may be accessed from threads other than the JS thread
/// (though accessing from the JS thread is more efficient).
/// </remarks>
public static IAsyncEnumerable<T> AsAsyncEnumerable<T>(
this JSAsyncIterable iterable, JSValue.To<T> fromJS)
=> ((JSValue)iterable).IsNullOrUndefined() ? null! :
new JSAsyncIterableEnumerable<T>((JSValue)iterable, fromJS);
/// <summary>
/// Creates an enumerable adapter for a JS iterable object, without copying.
/// </summary>
/// <remarks>
/// This method must be called from the JS thread. The returned enumerable object
/// is thread-safe and may be accessed from threads other than the JS thread
/// (though accessing from the JS thread is more efficient).
/// </remarks>
public static IEnumerable<T> AsEnumerable<T>(this JSIterable iterable, JSValue.To<T> fromJS)
=> ((JSValue)iterable).IsNullOrUndefined() ? null! :
new JSIterableEnumerable<T>((JSValue)iterable, fromJS);
/// <summary>
/// Creates an enumerable adapter for a JS Array object, without copying.
/// </summary>
/// <remarks>
/// This method must be called from the JS thread. The returned enumerable object
/// is thread-safe and may be accessed from threads other than the JS thread
/// (though accessing from the JS thread is more efficient).
/// </remarks>
public static IEnumerable<T> AsEnumerable<T>(this JSArray array, JSValue.To<T> fromJS)
=> ((JSValue)array).IsNullOrUndefined() ? null! :
new JSIterableEnumerable<T>((JSValue)array, fromJS);
/// <summary>
/// Creates a read-only collection adapter for a JS Array object, without copying.
/// </summary>
/// <remarks>
/// This method must be called from the JS thread. The returned collection object
/// is thread-safe and may be accessed from threads other than the JS thread
/// (though accessing from the JS thread is more efficient).
/// </remarks>
public static IReadOnlyCollection<T> AsReadOnlyCollection<T>(
this JSArray array, JSValue.To<T> fromJS)
=> ((JSValue)array).IsNullOrUndefined() ? null! :
new JSArrayReadOnlyCollection<T>((JSValue)array, fromJS);
/// <summary>
/// Creates a collection adapter for a JS Array object, without copying.
/// </summary>
/// <remarks>
/// This method must be called from the JS thread. The returned collection object
/// is thread-safe and may be accessed from threads other than the JS thread
/// (though accessing from the JS thread is more efficient).
/// </remarks>
public static ICollection<T> AsCollection<T>(
this JSArray array, JSValue.To<T> fromJS, JSValue.From<T> toJS)
=> ((JSValue)array).IsNullOrUndefined() ? null! :
new JSArrayCollection<T>((JSValue)array, fromJS, toJS);
/// <summary>
/// Creates a read-only list adapter for a JS Array object, without copying.
/// </summary>
/// <remarks>
/// This method must be called from the JS thread. The returned list object
/// is thread-safe and may be accessed from threads other than the JS thread
/// (though accessing from the JS thread is more efficient).
/// </remarks>
public static IReadOnlyList<T> AsReadOnlyList<T>(this JSArray array, JSValue.To<T> fromJS)
=> ((JSValue)array).IsNullOrUndefined() ? null! :
new JSArrayReadOnlyList<T>((JSValue)array, fromJS);
/// <summary>
/// Creates a list adapter for a JS Array object, without copying.
/// </summary>
/// <remarks>
/// This method must be called from the JS thread. The returned list object
/// is thread-safe and may be accessed from threads other than the JS thread
/// (though accessing from the JS thread is more efficient).
/// </remarks>
public static IList<T> AsList<T>(this JSArray array, JSValue.To<T> fromJS, JSValue.From<T> toJS)
=> ((JSValue)array).IsNullOrUndefined() ? null! :
new JSArrayList<T>((JSValue)array, fromJS, toJS);
/// <summary>
/// Creates an enumerable adapter for a JS Set object, without copying.
/// </summary>
/// <remarks>
/// This method must be called from the JS thread. The returned enumerable object
/// is thread-safe and may be accessed from threads other than the JS thread
/// (though accessing from the JS thread is more efficient).
/// </remarks>
public static IEnumerable<T> AsEnumerable<T>(this JSSet set, JSValue.To<T> fromJS)
=> ((JSValue)set).IsNullOrUndefined() ? null! :
new JSIterableEnumerable<T>((JSValue)set, fromJS);
/// <summary>
/// Creates a read-only collection adapter for a JS Set object, without copying.
/// </summary>
/// <remarks>
/// This method must be called from the JS thread. The returned collection object
/// is thread-safe and may be accessed from threads other than the JS thread
/// (though accessing from the JS thread is more efficient).
/// </remarks>
public static IReadOnlyCollection<T> AsReadOnlyCollection<T>(this JSSet set, JSValue.To<T> fromJS)
=> ((JSValue)set).IsNullOrUndefined() ? null! :
new JSSetReadOnlyCollection<T>((JSValue)set, fromJS);
/// <summary>
/// Creates a collection adapter for a JS Set object, without copying.
/// </summary>
/// <remarks>
/// This method must be called from the JS thread. The returned collection object
/// is thread-safe and may be accessed from threads other than the JS thread
/// (though accessing from the JS thread is more efficient).
/// </remarks>
public static ICollection<T> AsCollection<T>(this JSSet set, JSValue.To<T> fromJS, JSValue.From<T> toJS)
=> ((JSValue)set).IsNullOrUndefined() ? null! :
new JSSetCollection<T>((JSValue)set, fromJS, toJS);
#if READONLY_SET
/// <summary>
/// Creates a read-only set adapter for a JS Set object, without copying.
/// </summary>
/// <remarks>
/// This method must be called from the JS thread. The returned set object
/// is thread-safe and may be accessed from threads other than the JS thread
/// (though accessing from the JS thread is more efficient).
/// </remarks>
public static IReadOnlySet<T> AsReadOnlySet<T>(this JSSet set, JSValue.To<T> fromJS, JSValue.From<T> toJS)
=> ((JSValue)set).IsNullOrUndefined() ? null! :
new JSSetReadOnlySet<T>((JSValue)set, fromJS, toJS);
#endif
/// <summary>
/// Creates a set adapter for a JS Set object, without copying.
/// </summary>
/// <remarks>
/// This method must be called from the JS thread. The returned set object
/// is thread-safe and may be accessed from threads other than the JS thread
/// (though accessing from the JS thread is more efficient).
/// </remarks>
public static ISet<T> AsSet<T>(this JSSet set, JSValue.To<T> fromJS, JSValue.From<T> toJS)
=> ((JSValue)set).IsNullOrUndefined() ? null! :
new JSSetSet<T>((JSValue)set, fromJS, toJS);
/// <summary>
/// Creates a read-only dictionary adapter for a JS Map object, without copying.
/// </summary>
/// <remarks>
/// This method must be called from the JS thread. The returned dictionary object
/// is thread-safe and may be accessed from threads other than the JS thread
/// (though accessing from the JS thread is more efficient).
/// </remarks>
public static IReadOnlyDictionary<TKey, TValue> AsReadOnlyDictionary<TKey, TValue>(
this JSMap map,
JSValue.To<TKey> keyFromJS,
JSValue.To<TValue> valueFromJS,
JSValue.From<TKey> keyToJS)
=> ((JSValue)map).IsNullOrUndefined() ? null! :
new JSMapReadOnlyDictionary<TKey, TValue>((JSValue)map, keyFromJS, valueFromJS, keyToJS);
/// <summary>
/// Creates a dictionary adapter for a JS Map object, without copying.
/// </summary>
/// <remarks>
/// This method must be called from the JS thread. The returned dictionary object
/// is thread-safe and may be accessed from threads other than the JS thread
/// (though accessing from the JS thread is more efficient).
/// </remarks>
public static IDictionary<TKey, TValue> AsDictionary<TKey, TValue>(
this JSMap map,
JSValue.To<TKey> keyFromJS,
JSValue.To<TValue> valueFromJS,
JSValue.From<TKey> keyToJS,
JSValue.From<TValue> valueToJS)
=> ((JSValue)map).IsNullOrUndefined() ? null! :
new JSMapDictionary<TKey, TValue>((JSValue)map, keyFromJS, valueFromJS, keyToJS, valueToJS);
/// <summary>
/// Creates a read-only dictionary adapter for properties of a JS object, without copying.
/// </summary>
/// <remarks>
/// This method must be called from the JS thread. The returned dictionary object
/// is thread-safe and may be accessed from threads other than the JS thread
/// (though accessing from the JS thread is more efficient).
/// </remarks>
public static IReadOnlyDictionary<string, TValue> AsReadOnlyDictionary<TValue>(
this JSObject obj,
JSValue.To<TValue> valueFromJS)
=> ((JSValue)obj).IsNullOrUndefined() ? null! :
new JSObjectReadOnlyDictionary<TValue>((JSValue)obj, valueFromJS);
/// <summary>
/// Creates a dictionary adapter for properties of a JS object, without copying.
/// </summary>
/// <remarks>
/// This method must be called from the JS thread. The returned dictionary object
/// is thread-safe and may be accessed from threads other than the JS thread
/// (though accessing from the JS thread is more efficient).
/// </remarks>
public static IDictionary<string, TValue> AsDictionary<TValue>(
this JSObject obj,
JSValue.To<TValue> valueFromJS,
JSValue.From<TValue> valueToJS)
=> ((JSValue)obj).IsNullOrUndefined() ? null! :
new JSObjectDictionary<TValue>((JSValue)obj, valueFromJS, valueToJS);
}
internal sealed class JSAsyncIterableEnumerator<T> : IAsyncEnumerator<T>, IDisposable
{
private readonly JSValue.To<T> _fromJS;
private readonly JSReference _iteratorReference;
private readonly CancellationToken _cancellation;
private JSReference? _currentReference;
internal JSAsyncIterableEnumerator(
JSValue iterable,
JSValue.To<T> fromJS,
CancellationToken cancellation)
{
_fromJS = fromJS;
_iteratorReference = new JSReference(iterable.CallMethod(JSSymbol.AsyncIterator));
_cancellation = cancellation;
_currentReference = null;
}
public async ValueTask<bool> MoveNextAsync()
{
return await _iteratorReference.Run(async (iterator) =>
{
_currentReference?.Dispose();
JSPromise nextPromise = (JSPromise)iterator.CallMethod("next");
JSValue nextResult = await nextPromise.AsTask(_cancellation);
JSValue done = nextResult["done"];
if (done.IsBoolean() && (bool)done)
{
_currentReference = null;
return false;
}
else
{
// Save a reference to the next result object rather than the value, because if
// the value is a primitive type then it's not possible to directly reference it.
_currentReference = new JSReference(nextResult);
return true;
}
});
}
public T Current => _currentReference != null
? _currentReference.Run((result) => _fromJS(result["value"]))
: throw new InvalidOperationException("Invalid enumerator state");
public void Dispose()
{
_currentReference?.Dispose();
_iteratorReference.Dispose();
}
ValueTask IAsyncDisposable.DisposeAsync()
{
_currentReference?.Dispose();
_iteratorReference.Dispose();
return default;
}
}
internal sealed class JSIterableEnumerator<T> :
IEnumerator<T>,
System.Collections.IEnumerator,
IDisposable
{
private readonly JSReference _iterableReference;
private readonly JSValue.To<T> _fromJS;
private JSReference _iteratorReference;
private JSReference? _currentReference;
internal JSIterableEnumerator(JSValue iterable, JSValue.To<T> fromJS)
{
_iterableReference = new JSReference(iterable);
_fromJS = fromJS;
_iteratorReference = new JSReference(iterable.CallMethod(JSSymbol.Iterator));
_currentReference = null;
}
public bool MoveNext()
{
return _iteratorReference.Run((iterator) =>
{
_currentReference?.Dispose();
JSValue nextResult = iterator.CallMethod("next");
JSValue done = nextResult["done"];
if (done.IsBoolean() && (bool)done)
{
_currentReference = null;
return false;
}
else
{
// Save a reference to the next result object rather than the value, because if
// the value is a primitive type then it's not possible to directly reference it.
_currentReference = new JSReference(nextResult);
return true;
}
});
}
public T Current => _currentReference != null
? _currentReference.Run((result) => _fromJS(result["value"])) :
throw new InvalidOperationException("Invalid enumerator state");
object? System.Collections.IEnumerator.Current => Current;
void System.Collections.IEnumerator.Reset()
{
_iterableReference.Run((iterable) =>
{
_currentReference?.Dispose();
_currentReference = null;
_iteratorReference.Dispose();
_iteratorReference = new JSReference(iterable.CallMethod(JSSymbol.Iterator));
});
}
public void Dispose()
{
_currentReference?.Dispose();
_iteratorReference.Dispose();
_iterableReference.Dispose();
}
}
internal sealed class JSAsyncIterableEnumerable<T> :
IAsyncEnumerable<T>,
IEquatable<JSValue>,
IAsyncDisposable,
IDisposable
{
private readonly JSReference _iterableReference;
private readonly JSValue.To<T> _fromJS;
internal JSAsyncIterableEnumerable(JSValue iterable, JSValue.To<T> fromJS)
{
_iterableReference = new JSReference(iterable);
_fromJS = fromJS;
}
bool IEquatable<JSValue>.Equals(JSValue other)
=> _iterableReference.Run((iterable) => iterable.Equals(other));
public IAsyncEnumerator<T> GetAsyncEnumerator(CancellationToken cancellation)
{
return _iterableReference.Run(
(iterable) => new JSAsyncIterableEnumerator<T>(iterable, _fromJS, cancellation));
}
public void Dispose()
{
_iterableReference.Dispose();
}
ValueTask IAsyncDisposable.DisposeAsync()
{
_iterableReference.Dispose();
return default;
}
}
internal class JSIterableEnumerable<T> : IEnumerable<T>, IEquatable<JSValue>, IDisposable
{
internal JSIterableEnumerable(JSValue iterable, JSValue.To<T> fromJS)
{
_iterableReference = new JSReference(iterable);
FromJS = fromJS;
}
private readonly JSReference _iterableReference;
internal JSValue Value => _iterableReference.GetValue();
protected void Run(Action<JSValue> action) => _iterableReference.Run(action);
protected TResult Run<TResult>(Func<JSValue, TResult> action) => _iterableReference.Run(action);
protected JSValue.To<T> FromJS { get; }
bool IEquatable<JSValue>.Equals(JSValue other) => Run((iterable) => iterable.Equals(other));
public IEnumerator<T> GetEnumerator()
=> Run((iterable) => new JSIterableEnumerator<T>(iterable, FromJS));
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
=> GetEnumerator();
public void Dispose()
{
// Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method
Dispose(disposing: true);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
_iterableReference.Dispose();
}
}
}
internal class JSIterableCollection<T>
: JSIterableEnumerable<T>, ICollection<T>, IReadOnlyCollection<T>
{
private readonly Func<int> _getCount;
internal JSIterableCollection(
JSValue iterable,
JSValue.To<T> fromJS,
Func<int> getCount) : base(iterable, fromJS)
{
_getCount = getCount;
}
public int Count => _getCount();
public bool IsReadOnly => true;
public bool Contains(T item)
{
return Run((iterable) =>
{
JSValue iterator = iterable.CallMethod(JSSymbol.Iterator);
while (true)
{
JSValue nextResult = iterator.CallMethod("next");
JSValue done = nextResult["done"];
if (done.IsBoolean() && (bool)done)
{
return false;
}
JSValue value = nextResult["value"];
if (value.Equals(item))
{
return true;
}
}
});
}
public void CopyTo(T[] array, int arrayIndex) => throw new NotSupportedException();
public void Add(T item) => throw new NotSupportedException();
public void Clear() => throw new NotSupportedException();
public bool Remove(T item) => throw new NotSupportedException();
}
internal class JSArrayReadOnlyCollection<T> : JSIterableEnumerable<T>, IReadOnlyCollection<T>
{
internal JSArrayReadOnlyCollection(JSValue array, JSValue.To<T> fromJS) : base(array, fromJS)
{
}
public int Count => Run((collection) => collection.GetArrayLength());
}
internal class JSArrayCollection<T> : JSArrayReadOnlyCollection<T>, ICollection<T>
{
internal JSArrayCollection(JSValue array, JSValue.To<T> fromJS, JSValue.From<T> toJS)
: base(array, fromJS)
{
ToJS = toJS;
}
protected JSValue.From<T> ToJS { get; }
public bool IsReadOnly => false;
public void Add(T item) => Run((array) => array.CallMethod("push", ToJS(item)));
public void Clear() => Run((array) => array.CallMethod("splice", 0, Count));
public bool Contains(T item)
=> Run((array) => (bool)array.CallMethod("includes", ToJS(item)));
public void CopyTo(T[] array, int arrayIndex)
{
Run((jsArray) =>
{
int i = arrayIndex;
JSValue iterator = jsArray.CallMethod(JSSymbol.Iterator);
while (true)
{
JSValue nextResult = iterator.CallMethod("next");
JSValue done = nextResult["done"];
if (done.IsBoolean() && (bool)done)
{
break;
}
JSValue value = nextResult["value"];
array[i++] = FromJS(value);
}
});
}
public bool Remove(T item)
{
return Run((array) =>
{
int index = (int)array.CallMethod("indexOf", ToJS(item));
if (index < 0)
{
return false;
}
array.CallMethod("splice", index, 1);
return true;
});
}
}
internal class JSArrayReadOnlyList<T> : JSArrayReadOnlyCollection<T>, IReadOnlyList<T>
{
internal JSArrayReadOnlyList(JSValue array, JSValue.To<T> fromJS) : base(array, fromJS)
{
}
public T this[int index] => Run((list) => FromJS(list.GetElement(index)));
}
internal class JSArrayList<T> : JSArrayCollection<T>, IList<T>
{
internal JSArrayList(JSValue array, JSValue.To<T> fromJS, JSValue.From<T> toJS)
: base(array, fromJS, toJS)
{
}
public T this[int index]
{
get => Run((array) => FromJS(array.GetElement(index)));
set => Run((array) => array.SetElement(index, ToJS(value)));
}
public int IndexOf(T item) => Run((array) => (int)array.CallMethod("indexOf", ToJS(item)));
public void Insert(int index, T item)
=> Run((array) => array.CallMethod("splice", index, 0, ToJS(item)));
public void RemoveAt(int index) => Run((array) => array.CallMethod("splice", index, 1));
}
internal class JSSetReadOnlyCollection<T> : JSIterableEnumerable<T>, IReadOnlyCollection<T>
{
internal JSSetReadOnlyCollection(JSValue value, JSValue.To<T> fromJS) : base(value, fromJS)
{
}
public int Count => Run((@set) => (int)@set["size"]);
}
internal class JSSetCollection<T> : JSSetReadOnlyCollection<T>, ICollection<T>
{
internal JSSetCollection(JSValue value, JSValue.To<T> fromJS, JSValue.From<T> toJS)
: base(value, fromJS)
{
ToJS = toJS;
}
protected JSValue.From<T> ToJS { get; }
bool ICollection<T>.IsReadOnly => false;
public void Add(T item) => Run((@set) => @set.CallMethod("add", ToJS(item)));
public void Clear() => Run((@set) => @set.CallMethod("clear"));
public bool Contains(T item) => Run((@set) => (bool)@set.CallMethod("has", ToJS(item)));
public void CopyTo(T[] array, int arrayIndex)
{
Run((@set) =>
{
int i = arrayIndex;
JSValue iterator = @set.CallMethod(JSSymbol.Iterator);
while (true)
{
JSValue nextResult = iterator.CallMethod("next");
JSValue done = nextResult["done"];
if (done.IsBoolean() && (bool)done)
{
break;
}
JSValue value = nextResult["value"];
array[i++] = FromJS(value);
}
});
}
public bool Remove(T item) => Run((@set) => (bool)@set.CallMethod("delete", ToJS(item)));
}
#if READONLY_SET
internal class JSSetReadOnlySet<T> : JSSetReadOnlyCollection<T>, IReadOnlySet<T>
{
internal JSSetReadOnlySet(JSValue value, JSValue.To<T> fromJS, JSValue.From<T> toJS)
: base(value, fromJS)
{
ToJS = toJS;
}
protected JSValue.From<T> ToJS { get; }
public bool Contains(T item) => Run((@set) => (bool)@set.CallMethod("has", ToJS(item)));
public bool IsProperSubsetOf(IEnumerable<T> other) => throw new NotImplementedException();
public bool IsProperSupersetOf(IEnumerable<T> other) => throw new NotImplementedException();
public bool IsSubsetOf(IEnumerable<T> other) => throw new NotImplementedException();
public bool IsSupersetOf(IEnumerable<T> other) => throw new NotImplementedException();
public bool Overlaps(IEnumerable<T> other) => throw new NotImplementedException();
public bool SetEquals(IEnumerable<T> other) => throw new NotImplementedException();
}
#endif
internal class JSSetSet<T> : JSSetCollection<T>, ISet<T>
{
internal JSSetSet(JSValue value, JSValue.To<T> fromJS, JSValue.From<T> toJS)
: base(value, fromJS, toJS)
{
}
public void ExceptWith(IEnumerable<T> other) => throw new NotImplementedException();
public void IntersectWith(IEnumerable<T> other) => throw new NotImplementedException();
public bool IsProperSubsetOf(IEnumerable<T> other) => throw new NotImplementedException();
public bool IsProperSupersetOf(IEnumerable<T> other) => throw new NotImplementedException();
public bool IsSubsetOf(IEnumerable<T> other) => throw new NotImplementedException();
public bool IsSupersetOf(IEnumerable<T> other) => throw new NotImplementedException();
public bool Overlaps(IEnumerable<T> other) => throw new NotImplementedException();
public bool SetEquals(IEnumerable<T> other) => throw new NotImplementedException();
public void SymmetricExceptWith(IEnumerable<T> other) => throw new NotImplementedException();
public void UnionWith(IEnumerable<T> other) => throw new NotImplementedException();
public new bool Add(T item)
{
return Run((@set) =>
{
int sizeBeforeAdd = (int)@set["size"];
@set.CallMethod("add", ToJS(item));
int sizeAfterAdd = (int)@set["size"];
return sizeAfterAdd > sizeBeforeAdd;
});
}
}
internal class JSMapReadOnlyDictionary<TKey, TValue> :
IReadOnlyDictionary<TKey, TValue>,
IEquatable<JSValue>,
IDisposable
{
internal JSMapReadOnlyDictionary(
JSValue map,
JSValue.To<TKey> keyFromJS,
JSValue.To<TValue> valueFromJS,
JSValue.From<TKey> keyToJS)
{
_mapReference = new JSReference(map);
KeyFromJS = keyFromJS;
ValueFromJS = valueFromJS;
KeyToJS = keyToJS;
}
private readonly JSReference _mapReference;
protected void Run(Action<JSValue> action) => _mapReference.Run(action);
protected TResult Run<TResult>(Func<JSValue, TResult> action) => _mapReference.Run(action);
internal JSValue Value => _mapReference.GetValue();
bool IEquatable<JSValue>.Equals(JSValue other) => Run((map) => map.Equals(other));
protected JSValue.To<TKey> KeyFromJS { get; }
protected JSValue.To<TValue> ValueFromJS { get; }
protected JSValue.From<TKey> KeyToJS { get; }
public int Count => Run((map) => (int)map["size"]);
public IEnumerable<TKey> Keys
=> Run((map) => ((JSIterable)map["keys"]).AsEnumerable<TKey>(KeyFromJS));
public IEnumerable<TValue> Values
=> Run((map) => ((JSIterable)map["values"]).AsEnumerable<TValue>(ValueFromJS));
public TValue this[TKey key]
{
get => Run((map) =>
{
JSValue value = map.CallMethod("get", KeyToJS(key));
if (value.IsUndefined())
{
throw new KeyNotFoundException();
}
return ValueFromJS(value);
});
}
public bool ContainsKey(TKey key) => Run((map) => (bool)map.CallMethod("has", KeyToJS(key)));
#if NETFRAMEWORK || NETSTANDARD
public bool TryGetValue(TKey key, out TValue value)
#else
public bool TryGetValue(TKey key, [MaybeNullWhen(false)] out TValue value)
#endif
{
bool result;
(result, value) = Run((map) =>
{
JSValue jsValue = map.CallMethod("get", KeyToJS(key));
if (jsValue.IsUndefined())
{
return (false, default!);
}
return (true, ValueFromJS(jsValue));
});
return result;
}
public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()
{
return Run((map) => new JSIterableEnumerator<KeyValuePair<TKey, TValue>>(
map, (pair) => new KeyValuePair<TKey, TValue>(
KeyFromJS(pair[0]), ValueFromJS(pair[1]))));
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
=> GetEnumerator();
public void Dispose()
{
// Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method
Dispose(disposing: true);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
_mapReference.Dispose();
}
}
}
internal class JSMapDictionary<TKey, TValue> :
JSMapReadOnlyDictionary<TKey, TValue>,
IDictionary<TKey, TValue>
{
internal JSMapDictionary(
JSValue map,
JSValue.To<TKey> keyFromJS,
JSValue.To<TValue> valueFromJS,
JSValue.From<TKey> keyToJS,
JSValue.From<TValue> valueToJS)
: base(map, keyFromJS, valueFromJS, keyToJS)
{
ValueToJS = valueToJS;
}
public new TValue this[TKey key]
{
get => Run((map) =>
{
JSValue value = map.CallMethod("get", KeyToJS(key));
if (value.IsUndefined())
{
throw new KeyNotFoundException();
}
return ValueFromJS(value);
});
set => Run((map) =>
{
map.CallMethod("set", KeyToJS(key), ValueToJS(value));
});
}
protected JSValue.From<TValue> ValueToJS { get; }
private int GetCount() => Count;
public void Add(TKey key, TValue value)
{
if (ContainsKey(key))
{
throw new ArgumentException("An item with the same key already exists.");
}
this[key] = value;
}
public bool Remove(TKey key) => Run((map) => (bool)map.CallMethod("delete", KeyToJS(key)));
public void Clear() => Run((map) => map.CallMethod("clear"));
ICollection<TKey> IDictionary<TKey, TValue>.Keys
=> Run((map) => new JSIterableCollection<TKey>(
(JSIterable)map["keys"], KeyFromJS, GetCount));
ICollection<TValue> IDictionary<TKey, TValue>.Values
=> Run((map) => new JSIterableCollection<TValue>(
(JSIterable)map["values"], ValueFromJS, GetCount));
bool ICollection<KeyValuePair<TKey, TValue>>.IsReadOnly => false;
void ICollection<KeyValuePair<TKey, TValue>>.Add(KeyValuePair<TKey, TValue> item)
=> Add(item.Key, item.Value);
bool ICollection<KeyValuePair<TKey, TValue>>.Contains(KeyValuePair<TKey, TValue> item)
=> TryGetValue(item.Key, out TValue? value) &&
(item.Value?.Equals(value) ?? value == null);
void ICollection<KeyValuePair<TKey, TValue>>.CopyTo(
KeyValuePair<TKey, TValue>[] array, int arrayIndex)
{
Run((map) =>
{
int i = arrayIndex;
JSValue iterator = map.CallMethod(JSSymbol.Iterator);
while (true)
{
JSValue nextResult = iterator.CallMethod("next");
JSValue done = nextResult["done"];
if (done.IsBoolean() && (bool)done)
{
break;
}
JSValue pair = nextResult["value"];
array[i++] = new KeyValuePair<TKey, TValue>(
KeyFromJS(pair[0]), ValueFromJS(pair[1]));
}
});
}
bool ICollection<KeyValuePair<TKey, TValue>>.Remove(KeyValuePair<TKey, TValue> item)
{
return Run((map) =>
{
JSValue jsValue = map.CallMethod("get", KeyToJS(item.Key));
if (jsValue.IsUndefined())
{
return false;
}
TValue value = ValueFromJS(jsValue);
if (value?.Equals(item.Value) != true)
{
return false;
}
map.CallMethod("delete", KeyToJS(item.Key));
return true;
});
}
}
internal class JSObjectReadOnlyDictionary<TValue> :
IReadOnlyDictionary<string, TValue>,
IEquatable<JSValue>,
IDisposable
{
internal JSObjectReadOnlyDictionary(
JSValue obj,
JSValue.To<TValue> valueFromJS)
{
_objReference = new JSReference(obj);
ValueFromJS = valueFromJS;
}
private readonly JSReference _objReference;
protected void Run(Action<JSValue> action) => _objReference.Run(action);
protected TResult Run<TResult>(Func<JSValue, TResult> action) => _objReference.Run(action);
internal JSValue Value => _objReference.GetValue();
bool IEquatable<JSValue>.Equals(JSValue other) => Run((obj) => obj.Equals(other));
protected JSValue.To<TValue> ValueFromJS { get; }
public int Count
=> Run((obj) => (int)JSValue.Global["Object"].CallMethod("keys", obj)["length"]);
public IEnumerable<string> Keys
=> Run((obj) => ((JSIterable)JSValue.Global["Object"].CallMethod("keys", obj))
.AsEnumerable<string>((key) => (string)key));
public IEnumerable<TValue> Values
=> Run((obj) => ((JSIterable)JSValue.Global["Object"].CallMethod("values", obj))
.AsEnumerable<TValue>(ValueFromJS));
public TValue this[string key]
{
get => Run((obj) =>
{
JSValue jsValue = obj.GetProperty(key);
if (jsValue.IsUndefined())
{
throw new KeyNotFoundException();
}
return ValueFromJS(jsValue);
});
}
public bool ContainsKey(string key) => Run((obj) => (bool)obj.HasProperty(key));
#if NETFRAMEWORK || NETSTANDARD
public bool TryGetValue(string key, out TValue value)
#else
public bool TryGetValue(string key, [MaybeNullWhen(false)] out TValue value)
#endif
{
bool result;
(result, value) = Run((obj) =>
{
JSValue jsValue = obj.GetProperty(key);
if (jsValue.IsUndefined())
{
return (false, default!);
}
return (true, ValueFromJS(jsValue));
});
return result;
}
public IEnumerator<KeyValuePair<string, TValue>> GetEnumerator()
{
return Run((obj) => ((JSIterable)JSValue.Global["Object"].CallMethod("values", obj))
.AsEnumerable<KeyValuePair<string, TValue>>((pair) => new KeyValuePair<string, TValue>(
(string)pair[0], ValueFromJS(pair[1])))).GetEnumerator();
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
=> GetEnumerator();
public void Dispose()
{
// Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method
Dispose(disposing: true);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
_objReference.Dispose();
}
}
}
internal class JSObjectDictionary<TValue> :
JSObjectReadOnlyDictionary<TValue>,
IDictionary<string, TValue>
{
internal JSObjectDictionary(
JSValue map,
JSValue.To<TValue> valueFromJS,
JSValue.From<TValue> valueToJS)
: base(map, valueFromJS)
{
ValueToJS = valueToJS;
}
public new TValue this[string key]
{
get => Run((obj) =>
{
JSValue jsValue = obj.GetProperty(key);
if (jsValue.IsUndefined())
{
throw new KeyNotFoundException();
}
return ValueFromJS(jsValue);
});