IntrinsicTypedArrayPrototype.cs 62 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687
  1. #pragma warning disable CA1859 // Use concrete types when possible for improved performance -- most of prototype methods return JsValue
  2. using System.Linq;
  3. using System.Text;
  4. using Jint.Collections;
  5. using Jint.Native.Array;
  6. using Jint.Native.ArrayBuffer;
  7. using Jint.Native.Iterator;
  8. using Jint.Native.Number;
  9. using Jint.Native.Object;
  10. using Jint.Native.Symbol;
  11. using Jint.Runtime;
  12. using Jint.Runtime.Descriptors;
  13. using Jint.Runtime.Descriptors.Specialized;
  14. using Jint.Runtime.Interop;
  15. namespace Jint.Native.TypedArray
  16. {
  17. /// <summary>
  18. /// https://tc39.es/ecma262/#sec-properties-of-the-%typedarrayprototype%-object
  19. /// </summary>
  20. internal sealed class IntrinsicTypedArrayPrototype : Prototype
  21. {
  22. private readonly IntrinsicTypedArrayConstructor _constructor;
  23. private ClrFunction? _originalIteratorFunction;
  24. internal IntrinsicTypedArrayPrototype(
  25. Engine engine,
  26. ObjectInstance objectPrototype,
  27. IntrinsicTypedArrayConstructor constructor) : base(engine, engine.Realm)
  28. {
  29. _prototype = objectPrototype;
  30. _constructor = constructor;
  31. }
  32. protected override void Initialize()
  33. {
  34. const PropertyFlag LengthFlags = PropertyFlag.Configurable;
  35. const PropertyFlag PropertyFlags = PropertyFlag.Writable | PropertyFlag.Configurable;
  36. var properties = new PropertyDictionary(36, false)
  37. {
  38. ["at"] = new LazyPropertyDescriptor<IntrinsicTypedArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "at", prototype.At, 1, PropertyFlag.Configurable), PropertyFlags),
  39. ["buffer"] = new GetSetPropertyDescriptor(new ClrFunction(_engine, "get buffer", Buffer, 0, LengthFlags), Undefined, PropertyFlag.Configurable),
  40. ["byteLength"] = new GetSetPropertyDescriptor(new ClrFunction(_engine, "get byteLength", ByteLength, 0, LengthFlags), Undefined, PropertyFlag.Configurable),
  41. ["byteOffset"] = new GetSetPropertyDescriptor(new ClrFunction(_engine, "get byteOffset", ByteOffset, 0, LengthFlags), Undefined, PropertyFlag.Configurable),
  42. ["constructor"] = new(_constructor, PropertyFlag.NonEnumerable),
  43. ["copyWithin"] = new LazyPropertyDescriptor<IntrinsicTypedArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "copyWithin", prototype.CopyWithin, 2, PropertyFlag.Configurable), PropertyFlags),
  44. ["entries"] = new LazyPropertyDescriptor<IntrinsicTypedArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "entries", prototype.Entries, 0, PropertyFlag.Configurable), PropertyFlags),
  45. ["every"] = new LazyPropertyDescriptor<IntrinsicTypedArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "every", prototype.Every, 1, PropertyFlag.Configurable), PropertyFlags),
  46. ["fill"] = new LazyPropertyDescriptor<IntrinsicTypedArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "fill", prototype.Fill, 1, PropertyFlag.Configurable), PropertyFlags),
  47. ["filter"] = new LazyPropertyDescriptor<IntrinsicTypedArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "filter", prototype.Filter, 1, PropertyFlag.Configurable), PropertyFlags),
  48. ["find"] = new LazyPropertyDescriptor<IntrinsicTypedArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "find", prototype.Find, 1, PropertyFlag.Configurable), PropertyFlags),
  49. ["findIndex"] = new LazyPropertyDescriptor<IntrinsicTypedArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "findIndex",prototype. FindIndex, 1, PropertyFlag.Configurable), PropertyFlags),
  50. ["findLast"] = new LazyPropertyDescriptor<IntrinsicTypedArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "findLast", prototype.FindLast, 1, PropertyFlag.Configurable), PropertyFlags),
  51. ["findLastIndex"] = new LazyPropertyDescriptor<IntrinsicTypedArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "findLastIndex", prototype.FindLastIndex, 1, PropertyFlag.Configurable), PropertyFlags),
  52. ["forEach"] = new LazyPropertyDescriptor<IntrinsicTypedArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "forEach", prototype.ForEach, 1, PropertyFlag.Configurable), PropertyFlags),
  53. ["includes"] = new LazyPropertyDescriptor<IntrinsicTypedArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "includes", prototype.Includes, 1, PropertyFlag.Configurable), PropertyFlags),
  54. ["indexOf"] = new LazyPropertyDescriptor<IntrinsicTypedArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "indexOf", prototype.IndexOf, 1, PropertyFlag.Configurable), PropertyFlags),
  55. ["join"] = new LazyPropertyDescriptor<IntrinsicTypedArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "join", prototype.Join, 1, PropertyFlag.Configurable), PropertyFlags),
  56. ["keys"] = new LazyPropertyDescriptor<IntrinsicTypedArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "keys", prototype.Keys, 0, PropertyFlag.Configurable), PropertyFlags),
  57. ["lastIndexOf"] = new LazyPropertyDescriptor<IntrinsicTypedArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "lastIndexOf", prototype.LastIndexOf, 1, PropertyFlag.Configurable), PropertyFlags),
  58. ["length"] = new GetSetPropertyDescriptor(new ClrFunction(_engine, "get length", GetLength, 0, LengthFlags), Undefined, PropertyFlag.Configurable),
  59. ["map"] = new LazyPropertyDescriptor<IntrinsicTypedArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "map", prototype.Map, 1, PropertyFlag.Configurable), PropertyFlags),
  60. ["reduce"] = new LazyPropertyDescriptor<IntrinsicTypedArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "reduce", prototype.Reduce, 1, PropertyFlag.Configurable), PropertyFlags),
  61. ["reduceRight"] = new LazyPropertyDescriptor<IntrinsicTypedArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "reduceRight", prototype.ReduceRight, 1, PropertyFlag.Configurable), PropertyFlags),
  62. ["reverse"] = new LazyPropertyDescriptor<IntrinsicTypedArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "reverse", prototype.Reverse, 0, PropertyFlag.Configurable), PropertyFlags),
  63. ["set"] = new LazyPropertyDescriptor<IntrinsicTypedArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "set", prototype.Set, 1, PropertyFlag.Configurable), PropertyFlags),
  64. ["slice"] = new LazyPropertyDescriptor<IntrinsicTypedArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "slice", prototype.Slice, 2, PropertyFlag.Configurable), PropertyFlags),
  65. ["some"] = new LazyPropertyDescriptor<IntrinsicTypedArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "some", prototype.Some, 1, PropertyFlag.Configurable), PropertyFlags),
  66. ["sort"] = new LazyPropertyDescriptor<IntrinsicTypedArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "sort", prototype.Sort, 1, PropertyFlag.Configurable), PropertyFlags),
  67. ["subarray"] = new LazyPropertyDescriptor<IntrinsicTypedArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "subarray", prototype.Subarray, 2, PropertyFlag.Configurable), PropertyFlags),
  68. ["toLocaleString"] = new LazyPropertyDescriptor<IntrinsicTypedArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "toLocaleString", prototype.ToLocaleString, 0, PropertyFlag.Configurable), PropertyFlags),
  69. ["toReversed"] = new LazyPropertyDescriptor<IntrinsicTypedArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "toReversed", prototype.ToReversed, 0, PropertyFlag.Configurable), PropertyFlags),
  70. ["toSorted"] = new LazyPropertyDescriptor<IntrinsicTypedArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "toSorted", prototype.ToSorted, 1, PropertyFlag.Configurable), PropertyFlags),
  71. ["toString"] = new LazyPropertyDescriptor<IntrinsicTypedArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "toLocaleString", prototype._realm.Intrinsics.Array.PrototypeObject.ToString, 0, PropertyFlag.Configurable), PropertyFlags),
  72. ["values"] = new LazyPropertyDescriptor<IntrinsicTypedArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "values", prototype.Values, 0, PropertyFlag.Configurable), PropertyFlags),
  73. ["with"] = new LazyPropertyDescriptor<IntrinsicTypedArrayPrototype>(this, static prototype => new ClrFunction(prototype._engine, "with", prototype.With, 2, PropertyFlag.Configurable), PropertyFlags),
  74. };
  75. SetProperties(properties);
  76. _originalIteratorFunction = new ClrFunction(_engine, "iterator", Values, 1);
  77. var symbols = new SymbolDictionary(2)
  78. {
  79. [GlobalSymbolRegistry.Iterator] = new(_originalIteratorFunction, PropertyFlags),
  80. [GlobalSymbolRegistry.ToStringTag] = new GetSetPropertyDescriptor(new ClrFunction(_engine, "get [Symbol.toStringTag]", ToStringTag, 0, PropertyFlag.Configurable), Undefined, PropertyFlag.Configurable)
  81. };
  82. SetSymbols(symbols);
  83. }
  84. /// <summary>
  85. /// https://tc39.es/ecma262/#sec-get-%typedarray%.prototype.buffer
  86. /// </summary>
  87. private JsValue Buffer(JsValue thisObject, JsValue[] arguments)
  88. {
  89. var o = thisObject as JsTypedArray;
  90. if (o is null)
  91. {
  92. ExceptionHelper.ThrowTypeError(_realm);
  93. }
  94. return o._viewedArrayBuffer;
  95. }
  96. /// <summary>
  97. /// https://tc39.es/ecma262/#sec-get-%typedarray%.prototype.bytelength
  98. /// </summary>
  99. private JsValue ByteLength(JsValue thisObject, JsValue[] arguments)
  100. {
  101. var o = thisObject as JsTypedArray;
  102. if (o is null)
  103. {
  104. ExceptionHelper.ThrowTypeError(_realm);
  105. }
  106. var taRecord = MakeTypedArrayWithBufferWitnessRecord(o, ArrayBufferOrder.SeqCst);
  107. return JsNumber.Create(taRecord.TypedArrayByteLength);
  108. }
  109. /// <summary>
  110. /// https://tc39.es/ecma262/#sec-get-%typedarray%.prototype.byteoffset
  111. /// </summary>
  112. private JsValue ByteOffset(JsValue thisObject, JsValue[] arguments)
  113. {
  114. var o = thisObject as JsTypedArray;
  115. if (o is null)
  116. {
  117. ExceptionHelper.ThrowTypeError(_realm);
  118. }
  119. var taRecord = MakeTypedArrayWithBufferWitnessRecord(o, ArrayBufferOrder.SeqCst);
  120. if (taRecord.IsTypedArrayOutOfBounds)
  121. {
  122. return JsNumber.PositiveZero;
  123. }
  124. return JsNumber.Create(o._byteOffset);
  125. }
  126. /// <summary>
  127. /// https://tc39.es/ecma262/#sec-get-%typedarray%.prototype.length
  128. /// </summary>
  129. private JsValue GetLength(JsValue thisObject, JsValue[] arguments)
  130. {
  131. var o = thisObject as JsTypedArray;
  132. if (o is null)
  133. {
  134. ExceptionHelper.ThrowTypeError(_realm);
  135. }
  136. var taRecord = MakeTypedArrayWithBufferWitnessRecord(o, ArrayBufferOrder.SeqCst);
  137. if (taRecord.IsTypedArrayOutOfBounds)
  138. {
  139. return JsNumber.PositiveZero;
  140. }
  141. return JsNumber.Create(taRecord.TypedArrayLength);
  142. }
  143. internal readonly record struct TypedArrayWithBufferWitnessRecord(JsTypedArray Object, int CachedBufferByteLength)
  144. {
  145. /// <summary>
  146. /// https://tc39.es/ecma262/#sec-istypedarrayoutofbounds
  147. /// </summary>
  148. public bool IsTypedArrayOutOfBounds
  149. {
  150. get
  151. {
  152. var o = Object;
  153. var bufferByteLength = CachedBufferByteLength;
  154. if (bufferByteLength == -1)
  155. {
  156. return true;
  157. }
  158. var byteOffsetStart = o._byteOffset;
  159. long byteOffsetEnd;
  160. if (o._arrayLength == JsTypedArray.LengthAuto)
  161. {
  162. byteOffsetEnd = bufferByteLength;
  163. }
  164. else
  165. {
  166. var elementSize = o._arrayElementType.GetElementSize();
  167. byteOffsetEnd = byteOffsetStart + o._arrayLength * elementSize;
  168. }
  169. if (byteOffsetStart > bufferByteLength || byteOffsetEnd > bufferByteLength)
  170. {
  171. return true;
  172. }
  173. return false;
  174. }
  175. }
  176. /// <summary>
  177. /// https://tc39.es/ecma262/#sec-typedarraylength
  178. /// </summary>
  179. public uint TypedArrayLength
  180. {
  181. get
  182. {
  183. var o = Object;
  184. if (o._arrayLength != JsTypedArray.LengthAuto)
  185. {
  186. return o._arrayLength;
  187. }
  188. var byteOffset = o._byteOffset;
  189. var elementSize = o._arrayElementType.GetElementSize();
  190. var byteLength = (double) CachedBufferByteLength;
  191. return (uint) System.Math.Floor((byteLength - byteOffset) / elementSize);
  192. }
  193. }
  194. /// <summary>
  195. /// https://tc39.es/ecma262/#sec-typedarraybytelength
  196. /// </summary>
  197. public uint TypedArrayByteLength
  198. {
  199. get
  200. {
  201. if (IsTypedArrayOutOfBounds)
  202. {
  203. return 0;
  204. }
  205. var length = TypedArrayLength;
  206. if (length == 0)
  207. {
  208. return 0;
  209. }
  210. var o = Object;
  211. if (o._byteLength != JsTypedArray.LengthAuto)
  212. {
  213. return o._byteLength;
  214. }
  215. return length * o._arrayElementType.GetElementSize();
  216. }
  217. }
  218. }
  219. internal static TypedArrayWithBufferWitnessRecord MakeTypedArrayWithBufferWitnessRecord(JsTypedArray obj, ArrayBufferOrder order)
  220. {
  221. var buffer = obj._viewedArrayBuffer;
  222. var byteLength = buffer.IsDetachedBuffer
  223. ? -1
  224. : ArrayBufferByteLength(buffer, order);
  225. return new TypedArrayWithBufferWitnessRecord(obj, byteLength);
  226. }
  227. /// <summary>
  228. /// https://tc39.es/ecma262/#sec-arraybufferbytelength
  229. /// </summary>
  230. internal static int ArrayBufferByteLength(JsArrayBuffer arrayBuffer, ArrayBufferOrder order)
  231. {
  232. if (arrayBuffer.IsSharedArrayBuffer && arrayBuffer.ArrayBufferByteLength > 0)
  233. {
  234. // a. Let bufferByteLengthBlock be arrayBuffer.[[ArrayBufferByteLengthData]].
  235. // b. Let rawLength be GetRawBytesFromSharedBlock(bufferByteLengthBlock, 0, BIGUINT64, true, order).
  236. // c. Let isLittleEndian be the value of the [[LittleEndian]] field of the surrounding agent's Agent Record.
  237. // d. Return ℝ(RawBytesToNumeric(BIGUINT64, rawLength, isLittleEndian)).
  238. }
  239. return arrayBuffer.ArrayBufferByteLength;
  240. }
  241. /// <summary>
  242. /// https://tc39.es/ecma262/#sec-%typedarray%.prototype.copywithin
  243. /// </summary>
  244. private JsValue CopyWithin(JsValue thisObject, JsValue[] arguments)
  245. {
  246. var taRecord = thisObject.ValidateTypedArray(_realm, ArrayBufferOrder.SeqCst);
  247. var o = taRecord.Object;
  248. var len = taRecord.TypedArrayLength;
  249. var target = arguments.At(0);
  250. var start = arguments.At(1);
  251. var end = arguments.At(2);
  252. var relativeTarget = TypeConverter.ToIntegerOrInfinity(target);
  253. long to;
  254. if (double.IsNegativeInfinity(relativeTarget))
  255. {
  256. to = 0;
  257. }
  258. else if (relativeTarget < 0)
  259. {
  260. to = (long) System.Math.Max(len + relativeTarget, 0);
  261. }
  262. else
  263. {
  264. to = (long) System.Math.Min(relativeTarget, len);
  265. }
  266. var relativeStart = TypeConverter.ToIntegerOrInfinity(start);
  267. long from;
  268. if (double.IsNegativeInfinity(relativeStart))
  269. {
  270. from = 0;
  271. }
  272. else if (relativeStart < 0)
  273. {
  274. from = (long) System.Math.Max(len + relativeStart, 0);
  275. }
  276. else
  277. {
  278. from = (long) System.Math.Min(relativeStart, len);
  279. }
  280. var relativeEnd = end.IsUndefined()
  281. ? len
  282. : TypeConverter.ToIntegerOrInfinity(end);
  283. long final;
  284. if (double.IsNegativeInfinity(relativeEnd))
  285. {
  286. final = 0;
  287. }
  288. else if (relativeEnd < 0)
  289. {
  290. final = (long) System.Math.Max(len + relativeEnd, 0);
  291. }
  292. else
  293. {
  294. final = (long) System.Math.Min(relativeEnd, len);
  295. }
  296. var count = System.Math.Min(final - from, len - to);
  297. if (count > 0)
  298. {
  299. var buffer = o._viewedArrayBuffer;
  300. buffer.AssertNotDetached();
  301. var elementSize = o._arrayElementType.GetElementSize();
  302. var byteOffset = o._byteOffset;
  303. var toByteIndex = to * elementSize + byteOffset;
  304. var fromByteIndex = from * elementSize + byteOffset;
  305. var countBytes = count * elementSize;
  306. int direction;
  307. if (fromByteIndex < toByteIndex && toByteIndex < fromByteIndex + countBytes)
  308. {
  309. direction = -1;
  310. fromByteIndex = fromByteIndex + countBytes - 1;
  311. toByteIndex = toByteIndex + countBytes - 1;
  312. }
  313. else
  314. {
  315. direction = 1;
  316. }
  317. while (countBytes > 0)
  318. {
  319. var value = buffer.GetValueFromBuffer((int) fromByteIndex, TypedArrayElementType.Uint8, true, ArrayBufferOrder.Unordered);
  320. buffer.SetValueInBuffer((int) toByteIndex, TypedArrayElementType.Uint8, value, true, ArrayBufferOrder.Unordered);
  321. fromByteIndex += direction;
  322. toByteIndex += direction;
  323. countBytes--;
  324. }
  325. }
  326. return o;
  327. }
  328. /// <summary>
  329. /// https://tc39.es/ecma262/#sec-%typedarray%.prototype.entries
  330. /// </summary>
  331. private JsValue Entries(JsValue thisObject, JsValue[] arguments)
  332. {
  333. var taRecord = thisObject.ValidateTypedArray(_realm, ArrayBufferOrder.SeqCst);
  334. var o = taRecord.Object;
  335. return _realm.Intrinsics.ArrayIteratorPrototype.Construct(o, ArrayIteratorType.KeyAndValue);
  336. }
  337. /// <summary>
  338. /// https://tc39.es/ecma262/#sec-%typedarray%.prototype.every
  339. /// </summary>
  340. private JsValue Every(JsValue thisObject, JsValue[] arguments)
  341. {
  342. var taRecord = thisObject.ValidateTypedArray(_realm, ArrayBufferOrder.SeqCst);
  343. var o = taRecord.Object;
  344. var len = taRecord.TypedArrayLength;
  345. if (len == 0)
  346. {
  347. return JsBoolean.True;
  348. }
  349. var predicate = GetCallable(arguments.At(0));
  350. var thisArg = arguments.At(1);
  351. var args = _engine._jsValueArrayPool.RentArray(3);
  352. args[2] = o;
  353. for (var k = 0; k < len; k++)
  354. {
  355. args[0] = o[k];
  356. args[1] = k;
  357. if (!TypeConverter.ToBoolean(predicate.Call(thisArg, args)))
  358. {
  359. return JsBoolean.False;
  360. }
  361. }
  362. _engine._jsValueArrayPool.ReturnArray(args);
  363. return JsBoolean.True;
  364. }
  365. /// <summary>
  366. /// https://tc39.es/ecma262/#sec-%typedarray%.prototype.fill
  367. /// </summary>
  368. private JsValue Fill(JsValue thisObject, JsValue[] arguments)
  369. {
  370. var taRecord = thisObject.ValidateTypedArray(_realm, ArrayBufferOrder.SeqCst);
  371. var o = taRecord.Object;
  372. var len = taRecord.TypedArrayLength;
  373. var jsValue = arguments.At(0);
  374. var start = arguments.At(1);
  375. var end = arguments.At(2);
  376. JsValue value;
  377. if (o._contentType == TypedArrayContentType.BigInt)
  378. {
  379. value = JsBigInt.Create(jsValue.ToBigInteger(_engine));
  380. }
  381. else
  382. {
  383. value = JsNumber.Create(jsValue);
  384. }
  385. int k;
  386. var relativeStart = TypeConverter.ToIntegerOrInfinity(start);
  387. if (double.IsNegativeInfinity(relativeStart))
  388. {
  389. k = 0;
  390. }
  391. else if (relativeStart < 0)
  392. {
  393. k = (int) System.Math.Max(len + relativeStart, 0);
  394. }
  395. else
  396. {
  397. k = (int) System.Math.Min(relativeStart, len);
  398. }
  399. uint final;
  400. var relativeEnd = end.IsUndefined() ? len : TypeConverter.ToIntegerOrInfinity(end);
  401. if (double.IsNegativeInfinity(relativeEnd))
  402. {
  403. final = 0;
  404. }
  405. else if (relativeEnd < 0)
  406. {
  407. final = (uint) System.Math.Max(len + relativeEnd, 0);
  408. }
  409. else
  410. {
  411. final = (uint) System.Math.Min(relativeEnd, len);
  412. }
  413. o._viewedArrayBuffer.AssertNotDetached();
  414. for (var i = k; i < final; ++i)
  415. {
  416. o[i] = value;
  417. }
  418. return thisObject;
  419. }
  420. /// <summary>
  421. /// https://tc39.es/ecma262/#sec-%typedarray%.prototype.filter
  422. /// </summary>
  423. private JsValue Filter(JsValue thisObject, JsValue[] arguments)
  424. {
  425. var callbackfn = GetCallable(arguments.At(0));
  426. var thisArg = arguments.At(1);
  427. var taRecord = thisObject.ValidateTypedArray(_realm, ArrayBufferOrder.SeqCst);
  428. var o = taRecord.Object;
  429. var len = taRecord.TypedArrayLength;
  430. var kept = new List<JsValue>();
  431. var captured = 0;
  432. var args = _engine._jsValueArrayPool.RentArray(3);
  433. args[2] = o;
  434. for (var k = 0; k < len; k++)
  435. {
  436. var kValue = o[k];
  437. args[0] = kValue;
  438. args[1] = k;
  439. var selected = callbackfn.Call(thisArg, args);
  440. if (TypeConverter.ToBoolean(selected))
  441. {
  442. kept.Add(kValue);
  443. captured++;
  444. }
  445. }
  446. _engine._jsValueArrayPool.ReturnArray(args);
  447. var a = _realm.Intrinsics.TypedArray.TypedArraySpeciesCreate(o, new JsValue[] { captured });
  448. for (var n = 0; n < captured; ++n)
  449. {
  450. a[n] = kept[n];
  451. }
  452. return a;
  453. }
  454. /// <summary>
  455. /// https://tc39.es/ecma262/#sec-%typedarray%.prototype.find
  456. /// </summary>
  457. private JsValue Find(JsValue thisObject, JsValue[] arguments)
  458. {
  459. return DoFind(thisObject, arguments).Value;
  460. }
  461. /// <summary>
  462. /// https://tc39.es/ecma262/#sec-%typedarray%.prototype.findindex
  463. /// </summary>
  464. private JsValue FindIndex(JsValue thisObject, JsValue[] arguments)
  465. {
  466. return DoFind(thisObject, arguments).Key;
  467. }
  468. private JsValue FindLast(JsValue thisObject, JsValue[] arguments)
  469. {
  470. return DoFind(thisObject, arguments, fromEnd: true).Value;
  471. }
  472. private JsValue FindLastIndex(JsValue thisObject, JsValue[] arguments)
  473. {
  474. return DoFind(thisObject, arguments, fromEnd: true).Key;
  475. }
  476. private KeyValuePair<JsValue, JsValue> DoFind(JsValue thisObject, JsValue[] arguments, bool fromEnd = false)
  477. {
  478. var taRecord = thisObject.ValidateTypedArray(_realm, ArrayBufferOrder.SeqCst);
  479. var o = taRecord.Object;
  480. var len = taRecord.TypedArrayLength;
  481. var predicate = GetCallable(arguments.At(0));
  482. var thisArg = arguments.At(1);
  483. if (len == 0)
  484. {
  485. return new KeyValuePair<JsValue, JsValue>(JsNumber.IntegerNegativeOne, Undefined);
  486. }
  487. var args = _engine._jsValueArrayPool.RentArray(3);
  488. args[2] = o;
  489. if (!fromEnd)
  490. {
  491. for (var k = 0; k < len; k++)
  492. {
  493. var kNumber = JsNumber.Create(k);
  494. var kValue = o[k];
  495. args[0] = kValue;
  496. args[1] = kNumber;
  497. if (TypeConverter.ToBoolean(predicate.Call(thisArg, args)))
  498. {
  499. return new KeyValuePair<JsValue, JsValue>(kNumber, kValue);
  500. }
  501. }
  502. }
  503. else
  504. {
  505. for (var k = (int) (len - 1); k >= 0; k--)
  506. {
  507. var kNumber = JsNumber.Create(k);
  508. var kValue = o[k];
  509. args[0] = kValue;
  510. args[1] = kNumber;
  511. if (TypeConverter.ToBoolean(predicate.Call(thisArg, args)))
  512. {
  513. return new KeyValuePair<JsValue, JsValue>(kNumber, kValue);
  514. }
  515. }
  516. }
  517. return new KeyValuePair<JsValue, JsValue>(JsNumber.IntegerNegativeOne, Undefined);
  518. }
  519. /// <summary>
  520. /// https://tc39.es/ecma262/#sec-%typedarray%.prototype.foreach
  521. /// </summary>
  522. private JsValue ForEach(JsValue thisObject, JsValue[] arguments)
  523. {
  524. var callbackfn = GetCallable(arguments.At(0));
  525. var thisArg = arguments.At(1);
  526. var taRecord = thisObject.ValidateTypedArray(_realm, ArrayBufferOrder.SeqCst);
  527. var o = taRecord.Object;
  528. var len = taRecord.TypedArrayLength;
  529. var args = _engine._jsValueArrayPool.RentArray(3);
  530. args[2] = o;
  531. for (var k = 0; k < len; k++)
  532. {
  533. var kValue = o[k];
  534. args[0] = kValue;
  535. args[1] = k;
  536. callbackfn.Call(thisArg, args);
  537. }
  538. _engine._jsValueArrayPool.ReturnArray(args);
  539. return Undefined;
  540. }
  541. /// <summary>
  542. /// https://tc39.es/ecma262/#sec-%typedarray%.prototype.includes
  543. /// </summary>
  544. private JsValue Includes(JsValue thisObject, JsValue[] arguments)
  545. {
  546. var taRecord = thisObject.ValidateTypedArray(_realm, ArrayBufferOrder.SeqCst);
  547. var o = taRecord.Object;
  548. var len = taRecord.TypedArrayLength;
  549. if (len == 0)
  550. {
  551. return false;
  552. }
  553. var searchElement = arguments.At(0);
  554. var fromIndex = arguments.At(1, 0);
  555. var n = TypeConverter.ToIntegerOrInfinity(fromIndex);
  556. if (double.IsPositiveInfinity(n))
  557. {
  558. return JsBoolean.False;
  559. }
  560. else if (double.IsNegativeInfinity(n))
  561. {
  562. n = 0;
  563. }
  564. long k;
  565. if (n >= 0)
  566. {
  567. k = (long) n;
  568. }
  569. else
  570. {
  571. k = (long) (len + n);
  572. if (k < 0)
  573. {
  574. k = 0;
  575. }
  576. }
  577. while (k < len)
  578. {
  579. var value = o[(int) k];
  580. if (SameValueZeroComparer.Equals(value, searchElement))
  581. {
  582. return JsBoolean.True;
  583. }
  584. k++;
  585. }
  586. return JsBoolean.False;
  587. }
  588. /// <summary>
  589. /// https://tc39.es/ecma262/#sec-%typedarray%.prototype.indexof
  590. /// </summary>
  591. private JsValue IndexOf(JsValue thisObject, JsValue[] arguments)
  592. {
  593. var searchElement = arguments.At(0);
  594. var fromIndex = arguments.At(1);
  595. var taRecord = thisObject.ValidateTypedArray(_realm, ArrayBufferOrder.SeqCst);
  596. var o = taRecord.Object;
  597. var len = taRecord.TypedArrayLength;
  598. if (len == 0)
  599. {
  600. return JsNumber.IntegerNegativeOne;
  601. }
  602. var n = TypeConverter.ToIntegerOrInfinity(fromIndex);
  603. if (double.IsPositiveInfinity(n))
  604. {
  605. return JsNumber.IntegerNegativeOne;
  606. }
  607. else if (double.IsNegativeInfinity(n))
  608. {
  609. n = 0;
  610. }
  611. long k;
  612. if (n >= 0)
  613. {
  614. k = (long) n;
  615. }
  616. else
  617. {
  618. k = (long) (len + n);
  619. if (k < 0)
  620. {
  621. k = 0;
  622. }
  623. }
  624. for (; k < len; k++)
  625. {
  626. var kPresent = o.HasProperty(k);
  627. if (kPresent)
  628. {
  629. var elementK = o[(int) k];
  630. if (elementK == searchElement)
  631. {
  632. return k;
  633. }
  634. }
  635. }
  636. return JsNumber.IntegerNegativeOne;
  637. }
  638. /// <summary>
  639. /// https://tc39.es/ecma262/#sec-%typedarray%.prototype.join
  640. /// </summary>
  641. private JsValue Join(JsValue thisObject, JsValue[] arguments)
  642. {
  643. var separator = arguments.At(0);
  644. var taRecord = thisObject.ValidateTypedArray(_realm, ArrayBufferOrder.SeqCst);
  645. var o = taRecord.Object;
  646. var len = taRecord.TypedArrayLength;
  647. var sep = TypeConverter.ToString(separator.IsUndefined() ? JsString.CommaString : separator);
  648. // as per the spec, this has to be called after ToString(separator)
  649. if (len == 0)
  650. {
  651. return JsString.Empty;
  652. }
  653. static string StringFromJsValue(JsValue value)
  654. {
  655. return value.IsUndefined()
  656. ? ""
  657. : TypeConverter.ToString(value);
  658. }
  659. var s = StringFromJsValue(o[0]);
  660. if (len == 1)
  661. {
  662. return s;
  663. }
  664. using var result = new ValueStringBuilder();
  665. result.Append(s);
  666. for (var k = 1; k < len; k++)
  667. {
  668. result.Append(sep);
  669. result.Append(StringFromJsValue(o[k]));
  670. }
  671. return result.ToString();
  672. }
  673. /// <summary>
  674. /// https://tc39.es/ecma262/#sec-%typedarray%.prototype.keys
  675. /// </summary>
  676. private JsValue Keys(JsValue thisObject, JsValue[] arguments)
  677. {
  678. var taRecord = thisObject.ValidateTypedArray(_realm, ArrayBufferOrder.SeqCst);
  679. var o = taRecord.Object;
  680. return _realm.Intrinsics.ArrayIteratorPrototype.Construct(o, ArrayIteratorType.Key);
  681. }
  682. /// <summary>
  683. /// https://tc39.es/ecma262/#sec-%typedarray%.prototype.lastindexof
  684. /// </summary>
  685. private JsValue LastIndexOf(JsValue thisObject, JsValue[] arguments)
  686. {
  687. var searchElement = arguments.At(0);
  688. var taRecord = thisObject.ValidateTypedArray(_realm, ArrayBufferOrder.SeqCst);
  689. var o = taRecord.Object;
  690. var len = taRecord.TypedArrayLength;
  691. if (len == 0)
  692. {
  693. return JsNumber.IntegerNegativeOne;
  694. }
  695. var fromIndex = arguments.At(1, len - 1);
  696. var n = TypeConverter.ToIntegerOrInfinity(fromIndex);
  697. if (double.IsNegativeInfinity(n))
  698. {
  699. return JsNumber.IntegerNegativeOne;
  700. }
  701. long k;
  702. if (n >= 0)
  703. {
  704. k = (long) System.Math.Min(n, len - 1);
  705. }
  706. else
  707. {
  708. k = (long) (len + n);
  709. }
  710. for (; k >= 0; k--)
  711. {
  712. var kPresent = o.HasProperty(k);
  713. if (kPresent)
  714. {
  715. var elementK = o[(int) k];
  716. if (elementK == searchElement)
  717. {
  718. return k;
  719. }
  720. }
  721. }
  722. return JsNumber.IntegerNegativeOne;
  723. }
  724. /// <summary>
  725. /// https://tc39.es/ecma262/#sec-%typedarray%.prototype.map
  726. /// </summary>
  727. private ObjectInstance Map(JsValue thisObject, JsValue[] arguments)
  728. {
  729. var taRecord = thisObject.ValidateTypedArray(_realm, ArrayBufferOrder.SeqCst);
  730. var o = taRecord.Object;
  731. var len = taRecord.TypedArrayLength;
  732. var thisArg = arguments.At(1);
  733. var callable = GetCallable(arguments.At(0));
  734. var a = _realm.Intrinsics.TypedArray.TypedArraySpeciesCreate(o, new JsValue[] { len });
  735. var args = _engine._jsValueArrayPool.RentArray(3);
  736. args[2] = o;
  737. for (var k = 0; k < len; k++)
  738. {
  739. args[0] = o[k];
  740. args[1] = k;
  741. var mappedValue = callable.Call(thisArg, args);
  742. a[k] = mappedValue;
  743. }
  744. _engine._jsValueArrayPool.ReturnArray(args);
  745. return a;
  746. }
  747. /// <summary>
  748. /// https://tc39.es/ecma262/#sec-%typedarray%.prototype.reduce
  749. /// </summary>
  750. private JsValue Reduce(JsValue thisObject, JsValue[] arguments)
  751. {
  752. var callbackfn = GetCallable(arguments.At(0));
  753. var initialValue = arguments.At(1);
  754. var taRecord = thisObject.ValidateTypedArray(_realm, ArrayBufferOrder.SeqCst);
  755. var o = taRecord.Object;
  756. var len = taRecord.TypedArrayLength;
  757. if (len == 0 && arguments.Length < 2)
  758. {
  759. ExceptionHelper.ThrowTypeError(_realm);
  760. }
  761. var k = 0;
  762. var accumulator = Undefined;
  763. if (!initialValue.IsUndefined())
  764. {
  765. accumulator = initialValue;
  766. }
  767. else
  768. {
  769. accumulator = o[k];
  770. k++;
  771. }
  772. var args = _engine._jsValueArrayPool.RentArray(4);
  773. args[3] = o;
  774. while (k < len)
  775. {
  776. var kValue = o[k];
  777. args[0] = accumulator;
  778. args[1] = kValue;
  779. args[2] = k;
  780. accumulator = callbackfn.Call(Undefined, args);
  781. k++;
  782. }
  783. _engine._jsValueArrayPool.ReturnArray(args);
  784. return accumulator;
  785. }
  786. /// <summary>
  787. /// https://tc39.es/ecma262/#sec-%typedarray%.prototype.reduceright
  788. /// </summary>
  789. private JsValue ReduceRight(JsValue thisObject, JsValue[] arguments)
  790. {
  791. var callbackfn = GetCallable(arguments.At(0));
  792. var initialValue = arguments.At(1);
  793. var taRecord = thisObject.ValidateTypedArray(_realm, ArrayBufferOrder.SeqCst);
  794. var o = taRecord.Object;
  795. var len = taRecord.TypedArrayLength;
  796. if (len == 0 && arguments.Length < 2)
  797. {
  798. ExceptionHelper.ThrowTypeError(_realm);
  799. }
  800. var k = (long) len - 1;
  801. JsValue accumulator;
  802. if (arguments.Length > 1)
  803. {
  804. accumulator = initialValue;
  805. }
  806. else
  807. {
  808. accumulator = o[k];
  809. k--;
  810. }
  811. var jsValues = _engine._jsValueArrayPool.RentArray(4);
  812. jsValues[3] = o;
  813. for (; k >= 0; k--)
  814. {
  815. jsValues[0] = accumulator;
  816. jsValues[1] = o[(int) k];
  817. jsValues[2] = k;
  818. accumulator = callbackfn.Call(Undefined, jsValues);
  819. }
  820. _engine._jsValueArrayPool.ReturnArray(jsValues);
  821. return accumulator;
  822. }
  823. /// <summary>
  824. /// https://tc39.es/ecma262/#sec-%typedarray%.prototype.reverse
  825. /// </summary>
  826. private ObjectInstance Reverse(JsValue thisObject, JsValue[] arguments)
  827. {
  828. var taRecord = thisObject.ValidateTypedArray(_realm, ArrayBufferOrder.SeqCst);
  829. var o = taRecord.Object;
  830. var len = taRecord.TypedArrayLength;
  831. var middle = (int) System.Math.Floor(len / 2.0);
  832. var lower = 0;
  833. while (lower != middle)
  834. {
  835. var upper = len - lower - 1;
  836. var lowerValue = o[lower];
  837. var upperValue = o[upper];
  838. o[lower] = upperValue;
  839. o[upper] = lowerValue;
  840. lower++;
  841. }
  842. return o;
  843. }
  844. /// <summary>
  845. /// https://tc39.es/ecma262/#sec-%typedarray%.prototype.set
  846. /// </summary>
  847. private JsValue Set(JsValue thisObject, JsValue[] arguments)
  848. {
  849. var target = thisObject as JsTypedArray;
  850. if (target is null)
  851. {
  852. ExceptionHelper.ThrowTypeError(_realm);
  853. }
  854. var source = arguments.At(0);
  855. var offset = arguments.At(1);
  856. var targetOffset = TypeConverter.ToIntegerOrInfinity(offset);
  857. if (targetOffset < 0)
  858. {
  859. ExceptionHelper.ThrowRangeError(_realm, "Invalid offset");
  860. }
  861. if (source is JsTypedArray typedArrayInstance)
  862. {
  863. SetTypedArrayFromTypedArray(target, targetOffset, typedArrayInstance);
  864. }
  865. else
  866. {
  867. SetTypedArrayFromArrayLike(target, (int) targetOffset, source);
  868. }
  869. return Undefined;
  870. }
  871. /// <summary>
  872. /// https://tc39.es/ecma262/#sec-settypedarrayfromtypedarray
  873. /// </summary>
  874. private void SetTypedArrayFromTypedArray(JsTypedArray target, double targetOffset, JsTypedArray source)
  875. {
  876. var targetBuffer = target._viewedArrayBuffer;
  877. var targetRecord = MakeTypedArrayWithBufferWitnessRecord(target, ArrayBufferOrder.SeqCst);
  878. if (targetRecord.IsTypedArrayOutOfBounds)
  879. {
  880. ExceptionHelper.ThrowTypeError(_realm);
  881. }
  882. var targetLength = targetRecord.TypedArrayLength;
  883. var srcBuffer = source._viewedArrayBuffer;
  884. var srcRecord = MakeTypedArrayWithBufferWitnessRecord(source, ArrayBufferOrder.SeqCst);
  885. if (srcRecord.IsTypedArrayOutOfBounds)
  886. {
  887. ExceptionHelper.ThrowTypeError(_realm);
  888. }
  889. var targetType = target._arrayElementType;
  890. var targetElementSize = targetType.GetElementSize();
  891. var targetByteOffset = target._byteOffset;
  892. var srcType = source._arrayElementType;
  893. var srcElementSize = srcType.GetElementSize();
  894. var srcLength = srcRecord.TypedArrayLength;
  895. var srcByteOffset = source._byteOffset;
  896. if (double.IsNegativeInfinity(targetOffset))
  897. {
  898. ExceptionHelper.ThrowRangeError(_realm, "Invalid target offset");
  899. }
  900. if (srcLength + targetOffset > targetLength)
  901. {
  902. ExceptionHelper.ThrowRangeError(_realm, "Invalid target offset");
  903. }
  904. if (target._contentType != source._contentType)
  905. {
  906. ExceptionHelper.ThrowTypeError(_realm, "Content type mismatch");
  907. }
  908. var same = SameValue(srcBuffer, targetBuffer);
  909. int srcByteIndex;
  910. if (same)
  911. {
  912. var srcByteLength = srcRecord.TypedArrayByteLength;
  913. srcBuffer = srcBuffer.CloneArrayBuffer(_realm.Intrinsics.ArrayBuffer, srcByteOffset, srcByteLength);
  914. // %ArrayBuffer% is used to clone srcBuffer because is it known to not have any observable side-effects.
  915. srcByteIndex = 0;
  916. }
  917. else
  918. {
  919. srcByteIndex = srcByteOffset;
  920. }
  921. var targetByteIndex = (int) (targetOffset * targetElementSize + targetByteOffset);
  922. var limit = targetByteIndex + targetElementSize * srcLength;
  923. if (srcType == targetType)
  924. {
  925. // NOTE: If srcType and targetType are the same, the transfer must be performed in a manner that preserves the bit-level encoding of the source data.
  926. while (targetByteIndex < limit)
  927. {
  928. var value = srcBuffer.GetValueFromBuffer(srcByteIndex, TypedArrayElementType.Uint8, isTypedArray: true, ArrayBufferOrder.Unordered);
  929. targetBuffer.SetValueInBuffer(targetByteIndex, TypedArrayElementType.Uint8, value, isTypedArray: true, ArrayBufferOrder.Unordered);
  930. srcByteIndex += 1;
  931. targetByteIndex += 1;
  932. }
  933. }
  934. else
  935. {
  936. while (targetByteIndex < limit)
  937. {
  938. var value = srcBuffer.GetValueFromBuffer(srcByteIndex, srcType, isTypedArray: true, ArrayBufferOrder.Unordered);
  939. targetBuffer.SetValueInBuffer(targetByteIndex, targetType, value, isTypedArray: true, ArrayBufferOrder.Unordered);
  940. srcByteIndex += srcElementSize;
  941. targetByteIndex += targetElementSize;
  942. }
  943. }
  944. }
  945. /// <summary>
  946. /// https://tc39.es/ecma262/#sec-settypedarrayfromarraylike
  947. /// </summary>
  948. private void SetTypedArrayFromArrayLike(JsTypedArray target, int targetOffset, JsValue source)
  949. {
  950. var targetBuffer = target._viewedArrayBuffer;
  951. targetBuffer.AssertNotDetached();
  952. var targetLength = target._arrayLength;
  953. var src = ArrayOperations.For(_realm, source, forWrite: false);
  954. var srcLength = src.GetLength();
  955. if (double.IsNegativeInfinity(targetOffset))
  956. {
  957. ExceptionHelper.ThrowRangeError(_realm, "Invalid target offset");
  958. }
  959. if (srcLength + targetOffset > targetLength)
  960. {
  961. ExceptionHelper.ThrowRangeError(_realm, "Invalid target offset");
  962. }
  963. var k = 0;
  964. while (k < srcLength)
  965. {
  966. var jsValue = src.Get((ulong) k);
  967. target.IntegerIndexedElementSet(targetOffset + k, jsValue);
  968. k++;
  969. }
  970. }
  971. /// <summary>
  972. /// https://tc39.es/proposal-relative-indexing-method/#sec-%typedarray.prototype%-additions
  973. /// </summary>
  974. private JsValue At(JsValue thisObject, JsValue[] arguments)
  975. {
  976. var start = arguments.At(0);
  977. var taRecord = thisObject.ValidateTypedArray(_realm, ArrayBufferOrder.SeqCst);
  978. var o = taRecord.Object;
  979. var len = taRecord.TypedArrayLength;
  980. var relativeStart = TypeConverter.ToInteger(start);
  981. int k;
  982. if (relativeStart < 0)
  983. {
  984. k = (int) (len + relativeStart);
  985. }
  986. else
  987. {
  988. k = (int) relativeStart;
  989. }
  990. if (k < 0 || k >= len)
  991. {
  992. return Undefined;
  993. }
  994. return o.Get(k);
  995. }
  996. /// <summary>
  997. /// https://tc39.es/ecma262/#sec-%typedarray%.prototype.slice
  998. /// </summary>
  999. private JsValue Slice(JsValue thisObject, JsValue[] arguments)
  1000. {
  1001. var start = arguments.At(0);
  1002. var end = arguments.At(1);
  1003. var taRecord = thisObject.ValidateTypedArray(_realm, ArrayBufferOrder.SeqCst);
  1004. var o = taRecord.Object;
  1005. var len = taRecord.TypedArrayLength;
  1006. var relativeStart = TypeConverter.ToIntegerOrInfinity(start);
  1007. int k;
  1008. if (double.IsNegativeInfinity(relativeStart))
  1009. {
  1010. k = 0;
  1011. }
  1012. else if (relativeStart < 0)
  1013. {
  1014. k = (int) System.Math.Max(len + relativeStart, 0);
  1015. }
  1016. else
  1017. {
  1018. k = (int) System.Math.Min(relativeStart, len);
  1019. }
  1020. var relativeEnd = end.IsUndefined()
  1021. ? len
  1022. : TypeConverter.ToIntegerOrInfinity(end);
  1023. long final;
  1024. if (double.IsNegativeInfinity(relativeEnd))
  1025. {
  1026. final = 0;
  1027. }
  1028. else if (relativeEnd < 0)
  1029. {
  1030. final = (long) System.Math.Max(len + relativeEnd, 0);
  1031. }
  1032. else
  1033. {
  1034. final = (long) System.Math.Min(relativeEnd, len);
  1035. }
  1036. var count = System.Math.Max(final - k, 0);
  1037. var a = _realm.Intrinsics.TypedArray.TypedArraySpeciesCreate(o, new JsValue[] { count });
  1038. if (count > 0)
  1039. {
  1040. o._viewedArrayBuffer.AssertNotDetached();
  1041. var srcType = o._arrayElementType;
  1042. var targetType = a._arrayElementType;
  1043. if (srcType != targetType)
  1044. {
  1045. var n = 0;
  1046. while (k < final)
  1047. {
  1048. var kValue = o[k];
  1049. a[n] = kValue;
  1050. k++;
  1051. n++;
  1052. }
  1053. }
  1054. else
  1055. {
  1056. var srcBuffer = o._viewedArrayBuffer;
  1057. var targetBuffer = a._viewedArrayBuffer;
  1058. var elementSize = srcType.GetElementSize();
  1059. var srcByteOffset = o._byteOffset;
  1060. var targetByteIndex = a._byteOffset;
  1061. var srcByteIndex = (int) k * elementSize + srcByteOffset;
  1062. var limit = targetByteIndex + count * elementSize;
  1063. while (targetByteIndex < limit)
  1064. {
  1065. var value = srcBuffer.GetValueFromBuffer(srcByteIndex, TypedArrayElementType.Uint8, true, ArrayBufferOrder.Unordered);
  1066. targetBuffer.SetValueInBuffer(targetByteIndex, TypedArrayElementType.Uint8, value, true, ArrayBufferOrder.Unordered);
  1067. srcByteIndex++;
  1068. targetByteIndex++;
  1069. }
  1070. }
  1071. }
  1072. return a;
  1073. }
  1074. /// <summary>
  1075. /// https://tc39.es/ecma262/#sec-%typedarray%.prototype.some
  1076. /// </summary>
  1077. private JsValue Some(JsValue thisObject, JsValue[] arguments)
  1078. {
  1079. var taRecord = thisObject.ValidateTypedArray(_realm, ArrayBufferOrder.SeqCst);
  1080. var o = taRecord.Object;
  1081. var len = taRecord.TypedArrayLength;
  1082. var callbackfn = GetCallable(arguments.At(0));
  1083. var thisArg = arguments.At(1);
  1084. var args = _engine._jsValueArrayPool.RentArray(3);
  1085. args[2] = o;
  1086. for (var k = 0; k < len; k++)
  1087. {
  1088. args[0] = o[k];
  1089. args[1] = k;
  1090. if (TypeConverter.ToBoolean(callbackfn.Call(thisArg, args)))
  1091. {
  1092. return JsBoolean.True;
  1093. }
  1094. }
  1095. _engine._jsValueArrayPool.ReturnArray(args);
  1096. return JsBoolean.False;
  1097. }
  1098. /// <summary>
  1099. /// https://tc39.es/ecma262/#sec-%typedarray%.prototype.sort
  1100. /// </summary>
  1101. private JsValue Sort(JsValue thisObject, JsValue[] arguments)
  1102. {
  1103. /*
  1104. * %TypedArray%.prototype.sort is a distinct function that, except as described below,
  1105. * implements the same requirements as those of Array.prototype.sort as defined in 23.1.3.27.
  1106. * The implementation of the %TypedArray%.prototype.sort specification may be optimized with the knowledge that the this value is
  1107. * an object that has a fixed length and whose integer-indexed properties are not sparse.
  1108. */
  1109. var taRecord = thisObject.ValidateTypedArray(_realm, ArrayBufferOrder.SeqCst);
  1110. var o = taRecord.Object;
  1111. var len = taRecord.TypedArrayLength;
  1112. var buffer = o._viewedArrayBuffer;
  1113. var compareFn = GetCompareFunction(arguments.At(0));
  1114. if (len <= 1)
  1115. {
  1116. return o;
  1117. }
  1118. var array = SortArray(buffer, compareFn, o);
  1119. for (var i = 0; i < (uint) array.Length; ++i)
  1120. {
  1121. o[i] = array[i];
  1122. }
  1123. return o;
  1124. }
  1125. /// <summary>
  1126. /// https://tc39.es/ecma262/#sec-%typedarray%.prototype.subarray
  1127. /// </summary>
  1128. private JsValue Subarray(JsValue thisObject, JsValue[] arguments)
  1129. {
  1130. var o = thisObject as JsTypedArray;
  1131. if (o is null)
  1132. {
  1133. ExceptionHelper.ThrowTypeError(_realm);
  1134. }
  1135. var start = arguments.At(0);
  1136. var end = arguments.At(1);
  1137. var buffer = o._viewedArrayBuffer;
  1138. var srcRecord = MakeTypedArrayWithBufferWitnessRecord(o, ArrayBufferOrder.SeqCst);
  1139. uint srcLength = 0;
  1140. if (!srcRecord.IsTypedArrayOutOfBounds)
  1141. {
  1142. srcLength = srcRecord.TypedArrayLength;
  1143. }
  1144. var relativeStart = TypeConverter.ToIntegerOrInfinity(start);
  1145. double startIndex;
  1146. if (double.IsNegativeInfinity(relativeStart))
  1147. {
  1148. startIndex = 0;
  1149. }
  1150. else if (relativeStart < 0)
  1151. {
  1152. startIndex = System.Math.Max(srcLength + relativeStart, 0);
  1153. }
  1154. else
  1155. {
  1156. startIndex = System.Math.Min(relativeStart, srcLength);
  1157. }
  1158. var elementSize = o._arrayElementType.GetElementSize();
  1159. var srcByteOffset = o._byteOffset;
  1160. var beginByteOffset = srcByteOffset + startIndex * elementSize;
  1161. JsValue[] argumentsList;
  1162. if (o._arrayLength == JsTypedArray.LengthAuto && end.IsUndefined())
  1163. {
  1164. argumentsList = [buffer, beginByteOffset];
  1165. }
  1166. else
  1167. {
  1168. double relativeEnd;
  1169. if (end.IsUndefined())
  1170. {
  1171. relativeEnd = srcLength;
  1172. }
  1173. else
  1174. {
  1175. relativeEnd = TypeConverter.ToIntegerOrInfinity(end);
  1176. }
  1177. double endIndex;
  1178. if (double.IsNegativeInfinity(relativeEnd))
  1179. {
  1180. endIndex = 0;
  1181. }
  1182. else if (relativeEnd < 0)
  1183. {
  1184. endIndex = System.Math.Max(srcLength + relativeEnd, 0);
  1185. }
  1186. else
  1187. {
  1188. endIndex = System.Math.Min(relativeEnd, srcLength);
  1189. }
  1190. var newLength = System.Math.Max(endIndex - startIndex, 0);
  1191. argumentsList = [buffer, beginByteOffset, newLength];
  1192. }
  1193. return _realm.Intrinsics.TypedArray.TypedArraySpeciesCreate(o, argumentsList);
  1194. }
  1195. /// <summary>
  1196. /// https://tc39.es/ecma262/#sec-%typedarray%.prototype.tolocalestring
  1197. /// </summary>
  1198. private JsValue ToLocaleString(JsValue thisObject, JsValue[] arguments)
  1199. {
  1200. /*
  1201. * %TypedArray%.prototype.toLocaleString is a distinct function that implements the same algorithm as Array.prototype.toLocaleString
  1202. * as defined in 23.1.3.29 except that the this value's [[ArrayLength]] internal slot is accessed in place of performing
  1203. * a [[Get]] of "length". The implementation of the algorithm may be optimized with the knowledge that the this value is an object
  1204. * that has a fixed length and whose integer-indexed properties are not sparse. However, such optimization must not introduce
  1205. * any observable changes in the specified behaviour of the algorithm.
  1206. */
  1207. var taRecord = thisObject.ValidateTypedArray(_realm, ArrayBufferOrder.SeqCst);
  1208. var array = taRecord.Object;
  1209. var len = taRecord.TypedArrayLength;
  1210. const string separator = ",";
  1211. if (len == 0)
  1212. {
  1213. return JsString.Empty;
  1214. }
  1215. JsValue r;
  1216. if (!array.TryGetValue(0, out var firstElement) || firstElement.IsNull() || firstElement.IsUndefined())
  1217. {
  1218. r = JsString.Empty;
  1219. }
  1220. else
  1221. {
  1222. var elementObj = TypeConverter.ToObject(_realm, firstElement);
  1223. var func = elementObj.Get("toLocaleString") as ICallable;
  1224. if (func is null)
  1225. {
  1226. ExceptionHelper.ThrowTypeError(_realm);
  1227. }
  1228. r = func.Call(elementObj, Arguments.Empty);
  1229. }
  1230. for (var k = 1; k < len; k++)
  1231. {
  1232. var s = r + separator;
  1233. var elementObj = TypeConverter.ToObject(_realm, array[k]);
  1234. var func = elementObj.Get("toLocaleString") as ICallable;
  1235. if (func is null)
  1236. {
  1237. ExceptionHelper.ThrowTypeError(_realm);
  1238. }
  1239. r = func.Call(elementObj, Arguments.Empty);
  1240. r = s + r;
  1241. }
  1242. return r;
  1243. }
  1244. /// <summary>
  1245. /// https://tc39.es/ecma262/#sec-%typedarray%.prototype.values
  1246. /// </summary>
  1247. private JsValue Values(JsValue thisObject, JsValue[] arguments)
  1248. {
  1249. var taRecord = thisObject.ValidateTypedArray(_realm, ArrayBufferOrder.SeqCst);
  1250. var o = taRecord.Object;
  1251. return _realm.Intrinsics.ArrayIteratorPrototype.Construct(o, ArrayIteratorType.Value);
  1252. }
  1253. /// <summary>
  1254. /// https://tc39.es/ecma262/#sec-get-%typedarray%.prototype-@@tostringtag
  1255. /// </summary>
  1256. private static JsValue ToStringTag(JsValue thisObject, JsValue[] arguments)
  1257. {
  1258. if (thisObject is not JsTypedArray o)
  1259. {
  1260. return Undefined;
  1261. }
  1262. return o._arrayElementType.GetTypedArrayName();
  1263. }
  1264. private JsValue ToReversed(JsValue thisObject, JsValue[] arguments)
  1265. {
  1266. var taRecord = thisObject.ValidateTypedArray(_realm, ArrayBufferOrder.SeqCst);
  1267. var o = taRecord.Object;
  1268. var len = taRecord.TypedArrayLength;
  1269. var a = TypedArrayCreateSameType(o, new [] { JsNumber.Create(len) });
  1270. uint k = 0;
  1271. while (k < len)
  1272. {
  1273. var from = len - k - 1;
  1274. a[k++] = o.Get(from);
  1275. }
  1276. return a;
  1277. }
  1278. private JsValue ToSorted(JsValue thisObject, JsValue[] arguments)
  1279. {
  1280. var taRecord = thisObject.ValidateTypedArray(_realm, ArrayBufferOrder.SeqCst);
  1281. var o = taRecord.Object;
  1282. var len = taRecord.TypedArrayLength;
  1283. var compareFn = GetCompareFunction(arguments.At(0));
  1284. var buffer = o._viewedArrayBuffer;
  1285. var a = TypedArrayCreateSameType(o, new [] { JsNumber.Create(len) });
  1286. var array = SortArray(buffer, compareFn, o);
  1287. for (var i = 0; (uint) i < (uint) array.Length; ++i)
  1288. {
  1289. a[i] = array[i];
  1290. }
  1291. return a;
  1292. }
  1293. private ObjectInstance With(JsValue thisObject, JsValue[] arguments)
  1294. {
  1295. var taRecord = thisObject.ValidateTypedArray(_realm, ArrayBufferOrder.SeqCst);
  1296. var o = taRecord.Object;
  1297. var len = taRecord.TypedArrayLength;
  1298. var value = arguments.At(1);
  1299. var relativeIndex = TypeConverter.ToIntegerOrInfinity(arguments.At(0));
  1300. long actualIndex;
  1301. if (relativeIndex >= 0)
  1302. {
  1303. actualIndex = (long) relativeIndex;
  1304. }
  1305. else
  1306. {
  1307. actualIndex = (long) (len + relativeIndex);
  1308. }
  1309. value = o._contentType == TypedArrayContentType.BigInt
  1310. ? TypeConverter.ToJsBigInt(value)
  1311. : TypeConverter.ToJsNumber(value);
  1312. if (!o.IsValidIntegerIndex(actualIndex))
  1313. {
  1314. ExceptionHelper.ThrowRangeError(_realm, "Invalid start index");
  1315. }
  1316. var a = TypedArrayCreateSameType(o, new [] { JsNumber.Create(len) });
  1317. var k = 0;
  1318. while (k < len)
  1319. {
  1320. a[k] = k == (int) actualIndex ? value : o.Get(k);
  1321. k++;
  1322. }
  1323. return a;
  1324. }
  1325. private JsTypedArray TypedArrayCreateSameType(JsTypedArray exemplar, JsValue[] argumentList)
  1326. {
  1327. var constructor = exemplar._arrayElementType.GetConstructor(_realm.Intrinsics);
  1328. var result = IntrinsicTypedArrayConstructor.TypedArrayCreate(_realm, constructor, argumentList);
  1329. return result;
  1330. }
  1331. private ICallable? GetCompareFunction(JsValue compareArg)
  1332. {
  1333. ICallable? compareFn = null;
  1334. if (!compareArg.IsUndefined())
  1335. {
  1336. if (compareArg is not ICallable callable)
  1337. {
  1338. ExceptionHelper.ThrowTypeError(_realm, "The comparison function must be either a function or undefined");
  1339. return null;
  1340. }
  1341. compareFn = callable;
  1342. }
  1343. return compareFn;
  1344. }
  1345. private static JsValue[] SortArray(JsArrayBuffer buffer, ICallable? compareFn, JsTypedArray obj)
  1346. {
  1347. var comparer = TypedArrayComparer.WithFunction(buffer, compareFn);
  1348. var operations = ArrayOperations.For(obj, forWrite: false);
  1349. try
  1350. {
  1351. return operations.OrderBy(x => x, comparer).ToArray();
  1352. }
  1353. catch (InvalidOperationException e)
  1354. {
  1355. throw e.InnerException ?? e;
  1356. }
  1357. }
  1358. private sealed class TypedArrayComparer : IComparer<JsValue>
  1359. {
  1360. public static TypedArrayComparer WithFunction(JsArrayBuffer buffer, ICallable? compare)
  1361. {
  1362. return new TypedArrayComparer(buffer, compare);
  1363. }
  1364. private readonly JsArrayBuffer _buffer;
  1365. private readonly ICallable? _compare;
  1366. private readonly JsValue[] _comparableArray = new JsValue[2];
  1367. private TypedArrayComparer(JsArrayBuffer buffer, ICallable? compare)
  1368. {
  1369. _buffer = buffer;
  1370. _compare = compare;
  1371. }
  1372. public int Compare(JsValue? x, JsValue? y)
  1373. {
  1374. if (x is null && y is null)
  1375. {
  1376. return 0;
  1377. }
  1378. if (x is not null && y is null)
  1379. {
  1380. return 1;
  1381. }
  1382. if (x is null)
  1383. {
  1384. return -1;
  1385. }
  1386. if (y is null)
  1387. {
  1388. return 1;
  1389. }
  1390. if (_compare is not null)
  1391. {
  1392. _comparableArray[0] = x;
  1393. _comparableArray[1] = y;
  1394. var v = TypeConverter.ToNumber(_compare.Call(Undefined, _comparableArray));
  1395. if (double.IsNaN(v))
  1396. {
  1397. return 0;
  1398. }
  1399. return (int) v;
  1400. }
  1401. if (x.Type == Types.BigInt || y.Type == Types.BigInt)
  1402. {
  1403. var xBigInt = TypeConverter.ToBigInt(x);
  1404. var yBigInt = TypeConverter.ToBigInt(y);
  1405. return xBigInt.CompareTo(yBigInt);
  1406. }
  1407. var xValue = x.AsNumber();
  1408. var yValue = y.AsNumber();
  1409. if (double.IsNaN(xValue) && double.IsNaN(yValue))
  1410. {
  1411. return 0;
  1412. }
  1413. if (double.IsNaN(xValue))
  1414. {
  1415. return 1;
  1416. }
  1417. if (double.IsNaN(yValue))
  1418. {
  1419. return -1;
  1420. }
  1421. if (xValue < yValue)
  1422. {
  1423. return -1;
  1424. }
  1425. if (xValue > yValue)
  1426. {
  1427. return 1;
  1428. }
  1429. if (NumberInstance.IsNegativeZero(xValue) && yValue == 0)
  1430. {
  1431. return -1;
  1432. }
  1433. if (xValue == 0 && NumberInstance.IsNegativeZero(yValue))
  1434. {
  1435. return 1;
  1436. }
  1437. return 0;
  1438. }
  1439. }
  1440. }
  1441. }