IntrinsicTypedArrayPrototype.cs 57 KB

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