IntrinsicTypedArrayPrototype.cs 59 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680
  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 ClrFunctionInstance? _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 ClrFunctionInstance(Engine, "at", At, 1, PropertyFlag.Configurable), PropertyFlags),
  38. ["buffer"] = new GetSetPropertyDescriptor(new ClrFunctionInstance(_engine, "get buffer", Buffer, 0, LengthFlags), Undefined, PropertyFlag.Configurable),
  39. ["byteLength"] = new GetSetPropertyDescriptor(new ClrFunctionInstance(_engine, "get byteLength", ByteLength, 0, LengthFlags), Undefined, PropertyFlag.Configurable),
  40. ["byteOffset"] = new GetSetPropertyDescriptor(new ClrFunctionInstance(Engine, "get byteOffset", ByteOffset, 0, LengthFlags), Undefined, PropertyFlag.Configurable),
  41. ["constructor"] = new(_constructor, PropertyFlag.NonEnumerable),
  42. ["copyWithin"] = new(new ClrFunctionInstance(Engine, "copyWithin", CopyWithin, 2, PropertyFlag.Configurable), PropertyFlags),
  43. ["entries"] = new(new ClrFunctionInstance(Engine, "entries", Entries, 0, PropertyFlag.Configurable), PropertyFlags),
  44. ["every"] = new(new ClrFunctionInstance(Engine, "every", Every, 1, PropertyFlag.Configurable), PropertyFlags),
  45. ["fill"] = new(new ClrFunctionInstance(Engine, "fill", Fill, 1, PropertyFlag.Configurable), PropertyFlags),
  46. ["filter"] = new(new ClrFunctionInstance(Engine, "filter", Filter, 1, PropertyFlag.Configurable), PropertyFlags),
  47. ["find"] = new(new ClrFunctionInstance(Engine, "find", Find, 1, PropertyFlag.Configurable), PropertyFlags),
  48. ["findIndex"] = new(new ClrFunctionInstance(Engine, "findIndex", FindIndex, 1, PropertyFlag.Configurable), PropertyFlags),
  49. ["findLast"] = new(new ClrFunctionInstance(Engine, "findLast", FindLast, 1, PropertyFlag.Configurable), PropertyFlags),
  50. ["findLastIndex"] = new(new ClrFunctionInstance(Engine, "findLastIndex", FindLastIndex, 1, PropertyFlag.Configurable), PropertyFlags),
  51. ["forEach"] = new(new ClrFunctionInstance(Engine, "forEach", ForEach, 1, PropertyFlag.Configurable), PropertyFlags),
  52. ["includes"] = new(new ClrFunctionInstance(Engine, "includes", Includes, 1, PropertyFlag.Configurable), PropertyFlags),
  53. ["indexOf"] = new(new ClrFunctionInstance(Engine, "indexOf", IndexOf, 1, PropertyFlag.Configurable), PropertyFlags),
  54. ["join"] = new(new ClrFunctionInstance(Engine, "join", Join, 1, PropertyFlag.Configurable), PropertyFlags),
  55. ["keys"] = new(new ClrFunctionInstance(Engine, "keys", Keys, 0, PropertyFlag.Configurable), PropertyFlags),
  56. ["lastIndexOf"] = new(new ClrFunctionInstance(Engine, "lastIndexOf", LastIndexOf, 1, PropertyFlag.Configurable), PropertyFlags),
  57. ["length"] = new GetSetPropertyDescriptor(new ClrFunctionInstance(Engine, "get length", GetLength, 0, LengthFlags), Undefined, PropertyFlag.Configurable),
  58. ["map"] = new(new ClrFunctionInstance(Engine, "map", Map, 1, PropertyFlag.Configurable), PropertyFlags),
  59. ["reduce"] = new(new ClrFunctionInstance(Engine, "reduce", Reduce, 1, PropertyFlag.Configurable), PropertyFlags),
  60. ["reduceRight"] = new(new ClrFunctionInstance(Engine, "reduceRight", ReduceRight, 1, PropertyFlag.Configurable), PropertyFlags),
  61. ["reverse"] = new(new ClrFunctionInstance(Engine, "reverse", Reverse, 0, PropertyFlag.Configurable), PropertyFlags),
  62. ["set"] = new(new ClrFunctionInstance(Engine, "set", Set, 1, PropertyFlag.Configurable), PropertyFlags),
  63. ["slice"] = new(new ClrFunctionInstance(Engine, "slice", Slice, 2, PropertyFlag.Configurable), PropertyFlags),
  64. ["some"] = new(new ClrFunctionInstance(Engine, "some", Some, 1, PropertyFlag.Configurable), PropertyFlags),
  65. ["sort"] = new(new ClrFunctionInstance(Engine, "sort", Sort, 1, PropertyFlag.Configurable), PropertyFlags),
  66. ["subarray"] = new(new ClrFunctionInstance(Engine, "subarray", Subarray, 2, PropertyFlag.Configurable), PropertyFlags),
  67. ["toLocaleString"] = new(new ClrFunctionInstance(Engine, "toLocaleString", ToLocaleString, 0, PropertyFlag.Configurable), PropertyFlags),
  68. ["toReversed"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "toReversed", ToReversed, 0, PropertyFlag.Configurable), PropertyFlags),
  69. ["toSorted"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "toSorted", ToSorted, 1, PropertyFlag.Configurable), PropertyFlags),
  70. ["toString"] = new(new ClrFunctionInstance(Engine, "toLocaleString", _realm.Intrinsics.Array.PrototypeObject.ToString, 0, PropertyFlag.Configurable), PropertyFlags),
  71. ["values"] = new(new ClrFunctionInstance(Engine, "values", Values, 0, PropertyFlag.Configurable), PropertyFlags),
  72. ["with"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "with", With, 2, PropertyFlag.Configurable), PropertyFlags),
  73. };
  74. SetProperties(properties);
  75. _originalIteratorFunction = new ClrFunctionInstance(Engine, "iterator", Values, 1);
  76. var symbols = new SymbolDictionary(2)
  77. {
  78. [GlobalSymbolRegistry.Iterator] = new(_originalIteratorFunction, PropertyFlags),
  79. [GlobalSymbolRegistry.ToStringTag] = new GetSetPropertyDescriptor(new ClrFunctionInstance(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. bool same;
  908. if (srcBuffer.IsSharedArrayBuffer && targetBuffer.IsSharedArrayBuffer)
  909. {
  910. // a. If srcBuffer.[[ArrayBufferData]] and targetBuffer.[[ArrayBufferData]] are the same Shared Data Block values, let same be true; else let same be false.
  911. ExceptionHelper.ThrowNotImplementedException("SharedBuffer not implemented");
  912. same = false;
  913. }
  914. else
  915. {
  916. same = SameValue(srcBuffer, targetBuffer);
  917. }
  918. int srcByteIndex;
  919. if (same)
  920. {
  921. var srcByteLength = srcRecord.TypedArrayByteLength;
  922. srcBuffer = srcBuffer.CloneArrayBuffer(_realm.Intrinsics.ArrayBuffer, srcByteOffset, srcByteLength);
  923. // %ArrayBuffer% is used to clone srcBuffer because is it known to not have any observable side-effects.
  924. srcByteIndex = 0;
  925. }
  926. else
  927. {
  928. srcByteIndex = srcByteOffset;
  929. }
  930. var targetByteIndex = (int) (targetOffset * targetElementSize + targetByteOffset);
  931. var limit = targetByteIndex + targetElementSize * srcLength;
  932. if (srcType == targetType)
  933. {
  934. // 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.
  935. while (targetByteIndex < limit)
  936. {
  937. var value = srcBuffer.GetValueFromBuffer(srcByteIndex, TypedArrayElementType.Uint8, isTypedArray: true, ArrayBufferOrder.Unordered);
  938. targetBuffer.SetValueInBuffer(targetByteIndex, TypedArrayElementType.Uint8, value, isTypedArray: true, ArrayBufferOrder.Unordered);
  939. srcByteIndex += 1;
  940. targetByteIndex += 1;
  941. }
  942. }
  943. else
  944. {
  945. while (targetByteIndex < limit)
  946. {
  947. var value = srcBuffer.GetValueFromBuffer(srcByteIndex, srcType, isTypedArray: true, ArrayBufferOrder.Unordered);
  948. targetBuffer.SetValueInBuffer(targetByteIndex, targetType, value, isTypedArray: true, ArrayBufferOrder.Unordered);
  949. srcByteIndex += srcElementSize;
  950. targetByteIndex += targetElementSize;
  951. }
  952. }
  953. }
  954. /// <summary>
  955. /// https://tc39.es/ecma262/#sec-settypedarrayfromarraylike
  956. /// </summary>
  957. private void SetTypedArrayFromArrayLike(JsTypedArray target, int targetOffset, JsValue source)
  958. {
  959. var targetBuffer = target._viewedArrayBuffer;
  960. targetBuffer.AssertNotDetached();
  961. var targetLength = target._arrayLength;
  962. var src = ArrayOperations.For(TypeConverter.ToObject(_realm, source));
  963. var srcLength = src.GetLength();
  964. if (double.IsNegativeInfinity(targetOffset))
  965. {
  966. ExceptionHelper.ThrowRangeError(_realm, "Invalid target offset");
  967. }
  968. if (srcLength + targetOffset > targetLength)
  969. {
  970. ExceptionHelper.ThrowRangeError(_realm, "Invalid target offset");
  971. }
  972. var k = 0;
  973. while (k < srcLength)
  974. {
  975. var jsValue = src.Get((ulong) k);
  976. target.IntegerIndexedElementSet(targetOffset + k, jsValue);
  977. k++;
  978. }
  979. }
  980. /// <summary>
  981. /// https://tc39.es/proposal-relative-indexing-method/#sec-%typedarray.prototype%-additions
  982. /// </summary>
  983. private JsValue At(JsValue thisObject, JsValue[] arguments)
  984. {
  985. var start = arguments.At(0);
  986. var taRecord = thisObject.ValidateTypedArray(_realm, ArrayBufferOrder.SeqCst);
  987. var o = taRecord.Object;
  988. var len = taRecord.TypedArrayLength;
  989. var relativeStart = TypeConverter.ToInteger(start);
  990. int k;
  991. if (relativeStart < 0)
  992. {
  993. k = (int) (len + relativeStart);
  994. }
  995. else
  996. {
  997. k = (int) relativeStart;
  998. }
  999. if (k < 0 || k >= len)
  1000. {
  1001. return Undefined;
  1002. }
  1003. return o.Get(k);
  1004. }
  1005. /// <summary>
  1006. /// https://tc39.es/ecma262/#sec-%typedarray%.prototype.slice
  1007. /// </summary>
  1008. private JsValue Slice(JsValue thisObject, JsValue[] arguments)
  1009. {
  1010. var start = arguments.At(0);
  1011. var end = arguments.At(1);
  1012. var taRecord = thisObject.ValidateTypedArray(_realm, ArrayBufferOrder.SeqCst);
  1013. var o = taRecord.Object;
  1014. var len = taRecord.TypedArrayLength;
  1015. var relativeStart = TypeConverter.ToIntegerOrInfinity(start);
  1016. int k;
  1017. if (double.IsNegativeInfinity(relativeStart))
  1018. {
  1019. k = 0;
  1020. }
  1021. else if (relativeStart < 0)
  1022. {
  1023. k = (int) System.Math.Max(len + relativeStart, 0);
  1024. }
  1025. else
  1026. {
  1027. k = (int) System.Math.Min(relativeStart, len);
  1028. }
  1029. var relativeEnd = end.IsUndefined()
  1030. ? len
  1031. : TypeConverter.ToIntegerOrInfinity(end);
  1032. long final;
  1033. if (double.IsNegativeInfinity(relativeEnd))
  1034. {
  1035. final = 0;
  1036. }
  1037. else if (relativeEnd < 0)
  1038. {
  1039. final = (long) System.Math.Max(len + relativeEnd, 0);
  1040. }
  1041. else
  1042. {
  1043. final = (long) System.Math.Min(relativeEnd, len);
  1044. }
  1045. var count = System.Math.Max(final - k, 0);
  1046. var a = _realm.Intrinsics.TypedArray.TypedArraySpeciesCreate(o, new JsValue[] { count });
  1047. if (count > 0)
  1048. {
  1049. o._viewedArrayBuffer.AssertNotDetached();
  1050. var srcType = o._arrayElementType;
  1051. var targetType = a._arrayElementType;
  1052. if (srcType != targetType)
  1053. {
  1054. var n = 0;
  1055. while (k < final)
  1056. {
  1057. var kValue = o[k];
  1058. a[n] = kValue;
  1059. k++;
  1060. n++;
  1061. }
  1062. }
  1063. else
  1064. {
  1065. var srcBuffer = o._viewedArrayBuffer;
  1066. var targetBuffer = a._viewedArrayBuffer;
  1067. var elementSize = srcType.GetElementSize();
  1068. var srcByteOffset = o._byteOffset;
  1069. var targetByteIndex = a._byteOffset;
  1070. var srcByteIndex = (int) k * elementSize + srcByteOffset;
  1071. var limit = targetByteIndex + count * elementSize;
  1072. while (targetByteIndex < limit)
  1073. {
  1074. var value = srcBuffer.GetValueFromBuffer(srcByteIndex, TypedArrayElementType.Uint8, true, ArrayBufferOrder.Unordered);
  1075. targetBuffer.SetValueInBuffer(targetByteIndex, TypedArrayElementType.Uint8, value, true, ArrayBufferOrder.Unordered);
  1076. srcByteIndex++;
  1077. targetByteIndex++;
  1078. }
  1079. }
  1080. }
  1081. return a;
  1082. }
  1083. /// <summary>
  1084. /// https://tc39.es/ecma262/#sec-%typedarray%.prototype.some
  1085. /// </summary>
  1086. private JsValue Some(JsValue thisObject, JsValue[] arguments)
  1087. {
  1088. var taRecord = thisObject.ValidateTypedArray(_realm, ArrayBufferOrder.SeqCst);
  1089. var o = taRecord.Object;
  1090. var len = taRecord.TypedArrayLength;
  1091. var callbackfn = GetCallable(arguments.At(0));
  1092. var thisArg = arguments.At(1);
  1093. var args = _engine._jsValueArrayPool.RentArray(3);
  1094. args[2] = o;
  1095. for (var k = 0; k < len; k++)
  1096. {
  1097. args[0] = o[k];
  1098. args[1] = k;
  1099. if (TypeConverter.ToBoolean(callbackfn.Call(thisArg, args)))
  1100. {
  1101. return JsBoolean.True;
  1102. }
  1103. }
  1104. _engine._jsValueArrayPool.ReturnArray(args);
  1105. return JsBoolean.False;
  1106. }
  1107. /// <summary>
  1108. /// https://tc39.es/ecma262/#sec-%typedarray%.prototype.sort
  1109. /// </summary>
  1110. private JsValue Sort(JsValue thisObject, JsValue[] arguments)
  1111. {
  1112. /*
  1113. * %TypedArray%.prototype.sort is a distinct function that, except as described below,
  1114. * implements the same requirements as those of Array.prototype.sort as defined in 23.1.3.27.
  1115. * The implementation of the %TypedArray%.prototype.sort specification may be optimized with the knowledge that the this value is
  1116. * an object that has a fixed length and whose integer-indexed properties are not sparse.
  1117. */
  1118. var taRecord = thisObject.ValidateTypedArray(_realm, ArrayBufferOrder.SeqCst);
  1119. var o = taRecord.Object;
  1120. var len = taRecord.TypedArrayLength;
  1121. var buffer = o._viewedArrayBuffer;
  1122. var compareFn = GetCompareFunction(arguments.At(0));
  1123. if (len <= 1)
  1124. {
  1125. return o;
  1126. }
  1127. var array = SortArray(buffer, compareFn, o);
  1128. for (var i = 0; i < (uint) array.Length; ++i)
  1129. {
  1130. o[i] = array[i];
  1131. }
  1132. return o;
  1133. }
  1134. /// <summary>
  1135. /// https://tc39.es/ecma262/#sec-%typedarray%.prototype.subarray
  1136. /// </summary>
  1137. private JsValue Subarray(JsValue thisObject, JsValue[] arguments)
  1138. {
  1139. var o = thisObject as JsTypedArray;
  1140. if (o is null)
  1141. {
  1142. ExceptionHelper.ThrowTypeError(_realm);
  1143. }
  1144. var begin = arguments.At(0);
  1145. var end = arguments.At(1);
  1146. var buffer = o._viewedArrayBuffer;
  1147. var srcLength = o.Length;
  1148. var relativeBegin = TypeConverter.ToIntegerOrInfinity(begin);
  1149. double beginIndex;
  1150. if (double.IsNegativeInfinity(relativeBegin))
  1151. {
  1152. beginIndex = 0;
  1153. }
  1154. else if (relativeBegin < 0)
  1155. {
  1156. beginIndex = System.Math.Max(srcLength + relativeBegin, 0);
  1157. }
  1158. else
  1159. {
  1160. beginIndex = System.Math.Min(relativeBegin, srcLength);
  1161. }
  1162. double relativeEnd;
  1163. if (end.IsUndefined())
  1164. {
  1165. relativeEnd = srcLength;
  1166. }
  1167. else
  1168. {
  1169. relativeEnd = TypeConverter.ToIntegerOrInfinity(end);
  1170. }
  1171. double endIndex;
  1172. if (double.IsNegativeInfinity(relativeEnd))
  1173. {
  1174. endIndex = 0;
  1175. }
  1176. else if (relativeEnd < 0)
  1177. {
  1178. endIndex = System.Math.Max(srcLength + relativeEnd, 0);
  1179. }
  1180. else
  1181. {
  1182. endIndex = System.Math.Min(relativeEnd, srcLength);
  1183. }
  1184. var newLength = System.Math.Max(endIndex - beginIndex, 0);
  1185. var elementSize = o._arrayElementType.GetElementSize();
  1186. var srcByteOffset = o._byteOffset;
  1187. var beginByteOffset = srcByteOffset + beginIndex * elementSize;
  1188. var argumentsList = new JsValue[] { buffer, beginByteOffset, newLength };
  1189. return _realm.Intrinsics.TypedArray.TypedArraySpeciesCreate(o, argumentsList);
  1190. }
  1191. /// <summary>
  1192. /// https://tc39.es/ecma262/#sec-%typedarray%.prototype.tolocalestring
  1193. /// </summary>
  1194. private JsValue ToLocaleString(JsValue thisObject, JsValue[] arguments)
  1195. {
  1196. /*
  1197. * %TypedArray%.prototype.toLocaleString is a distinct function that implements the same algorithm as Array.prototype.toLocaleString
  1198. * as defined in 23.1.3.29 except that the this value's [[ArrayLength]] internal slot is accessed in place of performing
  1199. * a [[Get]] of "length". The implementation of the algorithm may be optimized with the knowledge that the this value is an object
  1200. * that has a fixed length and whose integer-indexed properties are not sparse. However, such optimization must not introduce
  1201. * any observable changes in the specified behaviour of the algorithm.
  1202. */
  1203. var taRecord = thisObject.ValidateTypedArray(_realm, ArrayBufferOrder.SeqCst);
  1204. var array = taRecord.Object;
  1205. var len = taRecord.TypedArrayLength;
  1206. const string separator = ",";
  1207. if (len == 0)
  1208. {
  1209. return JsString.Empty;
  1210. }
  1211. JsValue r;
  1212. if (!array.TryGetValue(0, out var firstElement) || firstElement.IsNull() || firstElement.IsUndefined())
  1213. {
  1214. r = JsString.Empty;
  1215. }
  1216. else
  1217. {
  1218. var elementObj = TypeConverter.ToObject(_realm, firstElement);
  1219. var func = elementObj.Get("toLocaleString") as ICallable;
  1220. if (func is null)
  1221. {
  1222. ExceptionHelper.ThrowTypeError(_realm);
  1223. }
  1224. r = func.Call(elementObj, Arguments.Empty);
  1225. }
  1226. for (var k = 1; k < len; k++)
  1227. {
  1228. var s = r + separator;
  1229. var elementObj = TypeConverter.ToObject(_realm, array[k]);
  1230. var func = elementObj.Get("toLocaleString") as ICallable;
  1231. if (func is null)
  1232. {
  1233. ExceptionHelper.ThrowTypeError(_realm);
  1234. }
  1235. r = func.Call(elementObj, Arguments.Empty);
  1236. r = s + r;
  1237. }
  1238. return r;
  1239. }
  1240. /// <summary>
  1241. /// https://tc39.es/ecma262/#sec-%typedarray%.prototype.values
  1242. /// </summary>
  1243. private JsValue Values(JsValue thisObject, JsValue[] arguments)
  1244. {
  1245. var taRecord = thisObject.ValidateTypedArray(_realm, ArrayBufferOrder.SeqCst);
  1246. var o = taRecord.Object;
  1247. return _realm.Intrinsics.ArrayIteratorPrototype.Construct(o, ArrayIteratorType.Value);
  1248. }
  1249. /// <summary>
  1250. /// https://tc39.es/ecma262/#sec-get-%typedarray%.prototype-@@tostringtag
  1251. /// </summary>
  1252. private static JsValue ToStringTag(JsValue thisObject, JsValue[] arguments)
  1253. {
  1254. if (thisObject is not JsTypedArray o)
  1255. {
  1256. return Undefined;
  1257. }
  1258. return o._arrayElementType.GetTypedArrayName();
  1259. }
  1260. private JsValue ToReversed(JsValue thisObject, JsValue[] arguments)
  1261. {
  1262. var taRecord = thisObject.ValidateTypedArray(_realm, ArrayBufferOrder.SeqCst);
  1263. var o = taRecord.Object;
  1264. var len = taRecord.TypedArrayLength;
  1265. var a = TypedArrayCreateSameType(o, new [] { JsNumber.Create(len) });
  1266. uint k = 0;
  1267. while (k < len)
  1268. {
  1269. var from = len - k - 1;
  1270. a[k++] = o.Get(from);
  1271. }
  1272. return a;
  1273. }
  1274. private JsValue ToSorted(JsValue thisObject, JsValue[] arguments)
  1275. {
  1276. var taRecord = thisObject.ValidateTypedArray(_realm, ArrayBufferOrder.SeqCst);
  1277. var o = taRecord.Object;
  1278. var len = taRecord.TypedArrayLength;
  1279. var compareFn = GetCompareFunction(arguments.At(0));
  1280. var buffer = o._viewedArrayBuffer;
  1281. var a = TypedArrayCreateSameType(o, new [] { JsNumber.Create(len) });
  1282. var array = SortArray(buffer, compareFn, o);
  1283. for (var i = 0; (uint) i < (uint) array.Length; ++i)
  1284. {
  1285. a[i] = array[i];
  1286. }
  1287. return a;
  1288. }
  1289. private ObjectInstance With(JsValue thisObject, JsValue[] arguments)
  1290. {
  1291. var taRecord = thisObject.ValidateTypedArray(_realm, ArrayBufferOrder.SeqCst);
  1292. var o = taRecord.Object;
  1293. var len = taRecord.TypedArrayLength;
  1294. var value = arguments.At(1);
  1295. var relativeIndex = TypeConverter.ToIntegerOrInfinity(arguments.At(0));
  1296. long actualIndex;
  1297. if (relativeIndex >= 0)
  1298. {
  1299. actualIndex = (long) relativeIndex;
  1300. }
  1301. else
  1302. {
  1303. actualIndex = (long) (len + relativeIndex);
  1304. }
  1305. value = o._contentType == TypedArrayContentType.BigInt
  1306. ? TypeConverter.ToJsBigInt(value)
  1307. : TypeConverter.ToJsNumber(value);
  1308. if (!o.IsValidIntegerIndex(actualIndex))
  1309. {
  1310. ExceptionHelper.ThrowRangeError(_realm, "Invalid start index");
  1311. }
  1312. var a = TypedArrayCreateSameType(o, new [] { JsNumber.Create(len) });
  1313. var k = 0;
  1314. while (k < len)
  1315. {
  1316. a[k] = k == (int) actualIndex ? value : o.Get(k);
  1317. k++;
  1318. }
  1319. return a;
  1320. }
  1321. private JsTypedArray TypedArrayCreateSameType(JsTypedArray exemplar, JsValue[] argumentList)
  1322. {
  1323. var constructor = exemplar._arrayElementType.GetConstructor(_realm.Intrinsics);
  1324. var result = IntrinsicTypedArrayConstructor.TypedArrayCreate(_realm, constructor, argumentList);
  1325. return result;
  1326. }
  1327. private ICallable? GetCompareFunction(JsValue compareArg)
  1328. {
  1329. ICallable? compareFn = null;
  1330. if (!compareArg.IsUndefined())
  1331. {
  1332. if (compareArg is not ICallable callable)
  1333. {
  1334. ExceptionHelper.ThrowTypeError(_realm, "The comparison function must be either a function or undefined");
  1335. return null;
  1336. }
  1337. compareFn = callable;
  1338. }
  1339. return compareFn;
  1340. }
  1341. private static JsValue[] SortArray(JsArrayBuffer buffer, ICallable? compareFn, JsTypedArray obj)
  1342. {
  1343. var comparer = TypedArrayComparer.WithFunction(buffer, compareFn);
  1344. var operations = ArrayOperations.For(obj);
  1345. try
  1346. {
  1347. return operations.OrderBy(x => x, comparer).ToArray();
  1348. }
  1349. catch (InvalidOperationException e)
  1350. {
  1351. throw e.InnerException ?? e;
  1352. }
  1353. }
  1354. private sealed class TypedArrayComparer : IComparer<JsValue>
  1355. {
  1356. public static TypedArrayComparer WithFunction(JsArrayBuffer buffer, ICallable? compare)
  1357. {
  1358. return new TypedArrayComparer(buffer, compare);
  1359. }
  1360. private readonly JsArrayBuffer _buffer;
  1361. private readonly ICallable? _compare;
  1362. private readonly JsValue[] _comparableArray = new JsValue[2];
  1363. private TypedArrayComparer(JsArrayBuffer buffer, ICallable? compare)
  1364. {
  1365. _buffer = buffer;
  1366. _compare = compare;
  1367. }
  1368. public int Compare(JsValue? x, JsValue? y)
  1369. {
  1370. if (x is null && y is null)
  1371. {
  1372. return 0;
  1373. }
  1374. if (x is not null && y is null)
  1375. {
  1376. return 1;
  1377. }
  1378. if (x is null)
  1379. {
  1380. return -1;
  1381. }
  1382. if (y is null)
  1383. {
  1384. return 1;
  1385. }
  1386. if (_compare is not null)
  1387. {
  1388. _comparableArray[0] = x;
  1389. _comparableArray[1] = y;
  1390. var v = TypeConverter.ToNumber(_compare.Call(Undefined, _comparableArray));
  1391. if (double.IsNaN(v))
  1392. {
  1393. return 0;
  1394. }
  1395. return (int) v;
  1396. }
  1397. if (x.Type == Types.BigInt || y.Type == Types.BigInt)
  1398. {
  1399. var xBigInt = TypeConverter.ToBigInt(x);
  1400. var yBigInt = TypeConverter.ToBigInt(y);
  1401. return xBigInt.CompareTo(yBigInt);
  1402. }
  1403. var xValue = x.AsNumber();
  1404. var yValue = y.AsNumber();
  1405. if (double.IsNaN(xValue) && double.IsNaN(yValue))
  1406. {
  1407. return 0;
  1408. }
  1409. if (double.IsNaN(xValue))
  1410. {
  1411. return 1;
  1412. }
  1413. if (double.IsNaN(yValue))
  1414. {
  1415. return -1;
  1416. }
  1417. if (xValue < yValue)
  1418. {
  1419. return -1;
  1420. }
  1421. if (xValue > yValue)
  1422. {
  1423. return 1;
  1424. }
  1425. if (NumberInstance.IsNegativeZero(xValue) && yValue == 0)
  1426. {
  1427. return -1;
  1428. }
  1429. if (xValue == 0 && NumberInstance.IsNegativeZero(yValue))
  1430. {
  1431. return 1;
  1432. }
  1433. return 0;
  1434. }
  1435. }
  1436. }
  1437. }