IntrinsicTypedArrayPrototype.cs 58 KB

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