IntrinsicTypedArrayPrototype.cs 59 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686
  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 start = arguments.At(0);
  1135. var end = arguments.At(1);
  1136. var buffer = o._viewedArrayBuffer;
  1137. var srcRecord = MakeTypedArrayWithBufferWitnessRecord(o, ArrayBufferOrder.SeqCst);
  1138. uint srcLength = 0;
  1139. if (!srcRecord.IsTypedArrayOutOfBounds)
  1140. {
  1141. srcLength = srcRecord.TypedArrayLength;
  1142. }
  1143. var relativeStart = TypeConverter.ToIntegerOrInfinity(start);
  1144. double startIndex;
  1145. if (double.IsNegativeInfinity(relativeStart))
  1146. {
  1147. startIndex = 0;
  1148. }
  1149. else if (relativeStart < 0)
  1150. {
  1151. startIndex = System.Math.Max(srcLength + relativeStart, 0);
  1152. }
  1153. else
  1154. {
  1155. startIndex = System.Math.Min(relativeStart, srcLength);
  1156. }
  1157. var elementSize = o._arrayElementType.GetElementSize();
  1158. var srcByteOffset = o._byteOffset;
  1159. var beginByteOffset = srcByteOffset + startIndex * elementSize;
  1160. JsValue[] argumentsList;
  1161. if (o._arrayLength == JsTypedArray.LengthAuto && end.IsUndefined())
  1162. {
  1163. argumentsList = [buffer, beginByteOffset];
  1164. }
  1165. else
  1166. {
  1167. double relativeEnd;
  1168. if (end.IsUndefined())
  1169. {
  1170. relativeEnd = srcLength;
  1171. }
  1172. else
  1173. {
  1174. relativeEnd = TypeConverter.ToIntegerOrInfinity(end);
  1175. }
  1176. double endIndex;
  1177. if (double.IsNegativeInfinity(relativeEnd))
  1178. {
  1179. endIndex = 0;
  1180. }
  1181. else if (relativeEnd < 0)
  1182. {
  1183. endIndex = System.Math.Max(srcLength + relativeEnd, 0);
  1184. }
  1185. else
  1186. {
  1187. endIndex = System.Math.Min(relativeEnd, srcLength);
  1188. }
  1189. var newLength = System.Math.Max(endIndex - startIndex, 0);
  1190. argumentsList = [buffer, beginByteOffset, newLength];
  1191. }
  1192. return _realm.Intrinsics.TypedArray.TypedArraySpeciesCreate(o, argumentsList);
  1193. }
  1194. /// <summary>
  1195. /// https://tc39.es/ecma262/#sec-%typedarray%.prototype.tolocalestring
  1196. /// </summary>
  1197. private JsValue ToLocaleString(JsValue thisObject, JsValue[] arguments)
  1198. {
  1199. /*
  1200. * %TypedArray%.prototype.toLocaleString is a distinct function that implements the same algorithm as Array.prototype.toLocaleString
  1201. * as defined in 23.1.3.29 except that the this value's [[ArrayLength]] internal slot is accessed in place of performing
  1202. * a [[Get]] of "length". The implementation of the algorithm may be optimized with the knowledge that the this value is an object
  1203. * that has a fixed length and whose integer-indexed properties are not sparse. However, such optimization must not introduce
  1204. * any observable changes in the specified behaviour of the algorithm.
  1205. */
  1206. var taRecord = thisObject.ValidateTypedArray(_realm, ArrayBufferOrder.SeqCst);
  1207. var array = taRecord.Object;
  1208. var len = taRecord.TypedArrayLength;
  1209. const string separator = ",";
  1210. if (len == 0)
  1211. {
  1212. return JsString.Empty;
  1213. }
  1214. JsValue r;
  1215. if (!array.TryGetValue(0, out var firstElement) || firstElement.IsNull() || firstElement.IsUndefined())
  1216. {
  1217. r = JsString.Empty;
  1218. }
  1219. else
  1220. {
  1221. var elementObj = TypeConverter.ToObject(_realm, firstElement);
  1222. var func = elementObj.Get("toLocaleString") as ICallable;
  1223. if (func is null)
  1224. {
  1225. ExceptionHelper.ThrowTypeError(_realm);
  1226. }
  1227. r = func.Call(elementObj, Arguments.Empty);
  1228. }
  1229. for (var k = 1; k < len; k++)
  1230. {
  1231. var s = r + separator;
  1232. var elementObj = TypeConverter.ToObject(_realm, array[k]);
  1233. var func = elementObj.Get("toLocaleString") as ICallable;
  1234. if (func is null)
  1235. {
  1236. ExceptionHelper.ThrowTypeError(_realm);
  1237. }
  1238. r = func.Call(elementObj, Arguments.Empty);
  1239. r = s + r;
  1240. }
  1241. return r;
  1242. }
  1243. /// <summary>
  1244. /// https://tc39.es/ecma262/#sec-%typedarray%.prototype.values
  1245. /// </summary>
  1246. private JsValue Values(JsValue thisObject, JsValue[] arguments)
  1247. {
  1248. var taRecord = thisObject.ValidateTypedArray(_realm, ArrayBufferOrder.SeqCst);
  1249. var o = taRecord.Object;
  1250. return _realm.Intrinsics.ArrayIteratorPrototype.Construct(o, ArrayIteratorType.Value);
  1251. }
  1252. /// <summary>
  1253. /// https://tc39.es/ecma262/#sec-get-%typedarray%.prototype-@@tostringtag
  1254. /// </summary>
  1255. private static JsValue ToStringTag(JsValue thisObject, JsValue[] arguments)
  1256. {
  1257. if (thisObject is not JsTypedArray o)
  1258. {
  1259. return Undefined;
  1260. }
  1261. return o._arrayElementType.GetTypedArrayName();
  1262. }
  1263. private JsValue ToReversed(JsValue thisObject, JsValue[] arguments)
  1264. {
  1265. var taRecord = thisObject.ValidateTypedArray(_realm, ArrayBufferOrder.SeqCst);
  1266. var o = taRecord.Object;
  1267. var len = taRecord.TypedArrayLength;
  1268. var a = TypedArrayCreateSameType(o, new [] { JsNumber.Create(len) });
  1269. uint k = 0;
  1270. while (k < len)
  1271. {
  1272. var from = len - k - 1;
  1273. a[k++] = o.Get(from);
  1274. }
  1275. return a;
  1276. }
  1277. private JsValue ToSorted(JsValue thisObject, JsValue[] arguments)
  1278. {
  1279. var taRecord = thisObject.ValidateTypedArray(_realm, ArrayBufferOrder.SeqCst);
  1280. var o = taRecord.Object;
  1281. var len = taRecord.TypedArrayLength;
  1282. var compareFn = GetCompareFunction(arguments.At(0));
  1283. var buffer = o._viewedArrayBuffer;
  1284. var a = TypedArrayCreateSameType(o, new [] { JsNumber.Create(len) });
  1285. var array = SortArray(buffer, compareFn, o);
  1286. for (var i = 0; (uint) i < (uint) array.Length; ++i)
  1287. {
  1288. a[i] = array[i];
  1289. }
  1290. return a;
  1291. }
  1292. private ObjectInstance With(JsValue thisObject, JsValue[] arguments)
  1293. {
  1294. var taRecord = thisObject.ValidateTypedArray(_realm, ArrayBufferOrder.SeqCst);
  1295. var o = taRecord.Object;
  1296. var len = taRecord.TypedArrayLength;
  1297. var value = arguments.At(1);
  1298. var relativeIndex = TypeConverter.ToIntegerOrInfinity(arguments.At(0));
  1299. long actualIndex;
  1300. if (relativeIndex >= 0)
  1301. {
  1302. actualIndex = (long) relativeIndex;
  1303. }
  1304. else
  1305. {
  1306. actualIndex = (long) (len + relativeIndex);
  1307. }
  1308. value = o._contentType == TypedArrayContentType.BigInt
  1309. ? TypeConverter.ToJsBigInt(value)
  1310. : TypeConverter.ToJsNumber(value);
  1311. if (!o.IsValidIntegerIndex(actualIndex))
  1312. {
  1313. ExceptionHelper.ThrowRangeError(_realm, "Invalid start index");
  1314. }
  1315. var a = TypedArrayCreateSameType(o, new [] { JsNumber.Create(len) });
  1316. var k = 0;
  1317. while (k < len)
  1318. {
  1319. a[k] = k == (int) actualIndex ? value : o.Get(k);
  1320. k++;
  1321. }
  1322. return a;
  1323. }
  1324. private JsTypedArray TypedArrayCreateSameType(JsTypedArray exemplar, JsValue[] argumentList)
  1325. {
  1326. var constructor = exemplar._arrayElementType.GetConstructor(_realm.Intrinsics);
  1327. var result = IntrinsicTypedArrayConstructor.TypedArrayCreate(_realm, constructor, argumentList);
  1328. return result;
  1329. }
  1330. private ICallable? GetCompareFunction(JsValue compareArg)
  1331. {
  1332. ICallable? compareFn = null;
  1333. if (!compareArg.IsUndefined())
  1334. {
  1335. if (compareArg is not ICallable callable)
  1336. {
  1337. ExceptionHelper.ThrowTypeError(_realm, "The comparison function must be either a function or undefined");
  1338. return null;
  1339. }
  1340. compareFn = callable;
  1341. }
  1342. return compareFn;
  1343. }
  1344. private static JsValue[] SortArray(JsArrayBuffer buffer, ICallable? compareFn, JsTypedArray obj)
  1345. {
  1346. var comparer = TypedArrayComparer.WithFunction(buffer, compareFn);
  1347. var operations = ArrayOperations.For(obj, forWrite: false);
  1348. try
  1349. {
  1350. return operations.OrderBy(x => x, comparer).ToArray();
  1351. }
  1352. catch (InvalidOperationException e)
  1353. {
  1354. throw e.InnerException ?? e;
  1355. }
  1356. }
  1357. private sealed class TypedArrayComparer : IComparer<JsValue>
  1358. {
  1359. public static TypedArrayComparer WithFunction(JsArrayBuffer buffer, ICallable? compare)
  1360. {
  1361. return new TypedArrayComparer(buffer, compare);
  1362. }
  1363. private readonly JsArrayBuffer _buffer;
  1364. private readonly ICallable? _compare;
  1365. private readonly JsValue[] _comparableArray = new JsValue[2];
  1366. private TypedArrayComparer(JsArrayBuffer buffer, ICallable? compare)
  1367. {
  1368. _buffer = buffer;
  1369. _compare = compare;
  1370. }
  1371. public int Compare(JsValue? x, JsValue? y)
  1372. {
  1373. if (x is null && y is null)
  1374. {
  1375. return 0;
  1376. }
  1377. if (x is not null && y is null)
  1378. {
  1379. return 1;
  1380. }
  1381. if (x is null)
  1382. {
  1383. return -1;
  1384. }
  1385. if (y is null)
  1386. {
  1387. return 1;
  1388. }
  1389. if (_compare is not null)
  1390. {
  1391. _comparableArray[0] = x;
  1392. _comparableArray[1] = y;
  1393. var v = TypeConverter.ToNumber(_compare.Call(Undefined, _comparableArray));
  1394. if (double.IsNaN(v))
  1395. {
  1396. return 0;
  1397. }
  1398. return (int) v;
  1399. }
  1400. if (x.Type == Types.BigInt || y.Type == Types.BigInt)
  1401. {
  1402. var xBigInt = TypeConverter.ToBigInt(x);
  1403. var yBigInt = TypeConverter.ToBigInt(y);
  1404. return xBigInt.CompareTo(yBigInt);
  1405. }
  1406. var xValue = x.AsNumber();
  1407. var yValue = y.AsNumber();
  1408. if (double.IsNaN(xValue) && double.IsNaN(yValue))
  1409. {
  1410. return 0;
  1411. }
  1412. if (double.IsNaN(xValue))
  1413. {
  1414. return 1;
  1415. }
  1416. if (double.IsNaN(yValue))
  1417. {
  1418. return -1;
  1419. }
  1420. if (xValue < yValue)
  1421. {
  1422. return -1;
  1423. }
  1424. if (xValue > yValue)
  1425. {
  1426. return 1;
  1427. }
  1428. if (NumberInstance.IsNegativeZero(xValue) && yValue == 0)
  1429. {
  1430. return -1;
  1431. }
  1432. if (xValue == 0 && NumberInstance.IsNegativeZero(yValue))
  1433. {
  1434. return 1;
  1435. }
  1436. return 0;
  1437. }
  1438. }
  1439. }
  1440. }