2
0

IntrinsicTypedArrayPrototype.cs 57 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717
  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, 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. 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, JsValue[] arguments)
  245. {
  246. var taRecord = thisObject.ValidateTypedArray(_realm, ArrayBufferOrder.SeqCst);
  247. var o = taRecord.Object;
  248. var len = taRecord.TypedArrayLength;
  249. var target = arguments.At(0);
  250. var start = arguments.At(1);
  251. var end = arguments.At(2);
  252. var relativeTarget = TypeConverter.ToIntegerOrInfinity(target);
  253. long to;
  254. if (double.IsNegativeInfinity(relativeTarget))
  255. {
  256. to = 0;
  257. }
  258. else if (relativeTarget < 0)
  259. {
  260. to = (long) System.Math.Max(len + relativeTarget, 0);
  261. }
  262. else
  263. {
  264. to = (long) System.Math.Min(relativeTarget, len);
  265. }
  266. var relativeStart = TypeConverter.ToIntegerOrInfinity(start);
  267. long from;
  268. if (double.IsNegativeInfinity(relativeStart))
  269. {
  270. from = 0;
  271. }
  272. else if (relativeStart < 0)
  273. {
  274. from = (long) System.Math.Max(len + relativeStart, 0);
  275. }
  276. else
  277. {
  278. from = (long) System.Math.Min(relativeStart, len);
  279. }
  280. var relativeEnd = end.IsUndefined()
  281. ? len
  282. : TypeConverter.ToIntegerOrInfinity(end);
  283. long final;
  284. if (double.IsNegativeInfinity(relativeEnd))
  285. {
  286. final = 0;
  287. }
  288. else if (relativeEnd < 0)
  289. {
  290. final = (long) System.Math.Max(len + relativeEnd, 0);
  291. }
  292. else
  293. {
  294. final = (long) System.Math.Min(relativeEnd, len);
  295. }
  296. var count = System.Math.Min(final - from, len - to);
  297. if (count > 0)
  298. {
  299. var buffer = o._viewedArrayBuffer;
  300. buffer.AssertNotDetached();
  301. 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, JsValue[] 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, JsValue[] 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, JsValue[] 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, JsValue[] 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, new JsValue[] { 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, JsValue[] 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, JsValue[] arguments)
  486. {
  487. return DoFind(thisObject, arguments).Key;
  488. }
  489. private JsValue FindLast(JsValue thisObject, JsValue[] arguments)
  490. {
  491. return DoFind(thisObject, arguments, fromEnd: true).Value;
  492. }
  493. private JsValue FindLastIndex(JsValue thisObject, JsValue[] arguments)
  494. {
  495. return DoFind(thisObject, arguments, fromEnd: true).Key;
  496. }
  497. private KeyValuePair<JsValue, JsValue> DoFind(JsValue thisObject, JsValue[] 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, JsValue[] 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, JsValue[] 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, JsValue[] 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, JsValue[] 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, JsValue[] 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, JsValue[] 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, JsValue[] 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, new JsValue[] { 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, JsValue[] 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, JsValue[] 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, JsValue[] 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, JsValue[] 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, JsValue[] 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, JsValue[] 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 k;
  1034. if (double.IsNegativeInfinity(relativeStart))
  1035. {
  1036. k = 0;
  1037. }
  1038. else if (relativeStart < 0)
  1039. {
  1040. k = (int) System.Math.Max(len + relativeStart, 0);
  1041. }
  1042. else
  1043. {
  1044. k = (int) System.Math.Min(relativeStart, len);
  1045. }
  1046. var relativeEnd = end.IsUndefined()
  1047. ? len
  1048. : TypeConverter.ToIntegerOrInfinity(end);
  1049. long final;
  1050. if (double.IsNegativeInfinity(relativeEnd))
  1051. {
  1052. final = 0;
  1053. }
  1054. else if (relativeEnd < 0)
  1055. {
  1056. final = (long) System.Math.Max(len + relativeEnd, 0);
  1057. }
  1058. else
  1059. {
  1060. final = (long) System.Math.Min(relativeEnd, len);
  1061. }
  1062. var count = System.Math.Max(final - k, 0);
  1063. var a = _realm.Intrinsics.TypedArray.TypedArraySpeciesCreate(o, new JsValue[] { count });
  1064. if (count > 0)
  1065. {
  1066. o._viewedArrayBuffer.AssertNotDetached();
  1067. var srcType = o._arrayElementType;
  1068. var targetType = a._arrayElementType;
  1069. if (srcType != targetType)
  1070. {
  1071. var n = 0;
  1072. while (k < final)
  1073. {
  1074. var kValue = o[k];
  1075. a[n] = kValue;
  1076. k++;
  1077. n++;
  1078. }
  1079. }
  1080. else
  1081. {
  1082. var srcBuffer = o._viewedArrayBuffer;
  1083. var targetBuffer = a._viewedArrayBuffer;
  1084. var elementSize = srcType.GetElementSize();
  1085. var srcByteOffset = o._byteOffset;
  1086. var targetByteIndex = a._byteOffset;
  1087. var srcByteIndex = (int) k * elementSize + srcByteOffset;
  1088. var limit = targetByteIndex + count * elementSize;
  1089. while (targetByteIndex < limit)
  1090. {
  1091. var value = srcBuffer.GetValueFromBuffer(srcByteIndex, TypedArrayElementType.Uint8, true, ArrayBufferOrder.Unordered);
  1092. targetBuffer.SetValueInBuffer(targetByteIndex, TypedArrayElementType.Uint8, value, true, ArrayBufferOrder.Unordered);
  1093. srcByteIndex++;
  1094. targetByteIndex++;
  1095. }
  1096. }
  1097. }
  1098. return a;
  1099. }
  1100. /// <summary>
  1101. /// https://tc39.es/ecma262/#sec-%typedarray%.prototype.some
  1102. /// </summary>
  1103. private JsValue Some(JsValue thisObject, JsValue[] arguments)
  1104. {
  1105. var taRecord = thisObject.ValidateTypedArray(_realm, ArrayBufferOrder.SeqCst);
  1106. var o = taRecord.Object;
  1107. var len = taRecord.TypedArrayLength;
  1108. var callbackfn = GetCallable(arguments.At(0));
  1109. var thisArg = arguments.At(1);
  1110. var args = _engine._jsValueArrayPool.RentArray(3);
  1111. args[2] = o;
  1112. for (var k = 0; k < len; k++)
  1113. {
  1114. args[0] = o[k];
  1115. args[1] = k;
  1116. if (TypeConverter.ToBoolean(callbackfn.Call(thisArg, args)))
  1117. {
  1118. return JsBoolean.True;
  1119. }
  1120. }
  1121. _engine._jsValueArrayPool.ReturnArray(args);
  1122. return JsBoolean.False;
  1123. }
  1124. /// <summary>
  1125. /// https://tc39.es/ecma262/#sec-%typedarray%.prototype.sort
  1126. /// </summary>
  1127. private JsValue Sort(JsValue thisObject, JsValue[] arguments)
  1128. {
  1129. /*
  1130. * %TypedArray%.prototype.sort is a distinct function that, except as described below,
  1131. * implements the same requirements as those of Array.prototype.sort as defined in 23.1.3.27.
  1132. * The implementation of the %TypedArray%.prototype.sort specification may be optimized with the knowledge that the this value is
  1133. * an object that has a fixed length and whose integer-indexed properties are not sparse.
  1134. */
  1135. var taRecord = thisObject.ValidateTypedArray(_realm, ArrayBufferOrder.SeqCst);
  1136. var o = taRecord.Object;
  1137. var len = taRecord.TypedArrayLength;
  1138. var buffer = o._viewedArrayBuffer;
  1139. var compareFn = GetCompareFunction(arguments.At(0));
  1140. if (len <= 1)
  1141. {
  1142. return o;
  1143. }
  1144. var array = SortArray(buffer, compareFn, o);
  1145. for (var i = 0; i < (uint) array.Length; ++i)
  1146. {
  1147. o[i] = array[i];
  1148. }
  1149. return o;
  1150. }
  1151. /// <summary>
  1152. /// https://tc39.es/ecma262/#sec-%typedarray%.prototype.subarray
  1153. /// </summary>
  1154. private JsValue Subarray(JsValue thisObject, JsValue[] arguments)
  1155. {
  1156. var o = thisObject as JsTypedArray;
  1157. if (o is null)
  1158. {
  1159. ExceptionHelper.ThrowTypeError(_realm);
  1160. }
  1161. var start = arguments.At(0);
  1162. var end = arguments.At(1);
  1163. var buffer = o._viewedArrayBuffer;
  1164. var srcRecord = MakeTypedArrayWithBufferWitnessRecord(o, ArrayBufferOrder.SeqCst);
  1165. uint srcLength = 0;
  1166. if (!srcRecord.IsTypedArrayOutOfBounds)
  1167. {
  1168. srcLength = srcRecord.TypedArrayLength;
  1169. }
  1170. var relativeStart = TypeConverter.ToIntegerOrInfinity(start);
  1171. double startIndex;
  1172. if (double.IsNegativeInfinity(relativeStart))
  1173. {
  1174. startIndex = 0;
  1175. }
  1176. else if (relativeStart < 0)
  1177. {
  1178. startIndex = System.Math.Max(srcLength + relativeStart, 0);
  1179. }
  1180. else
  1181. {
  1182. startIndex = System.Math.Min(relativeStart, srcLength);
  1183. }
  1184. var elementSize = o._arrayElementType.GetElementSize();
  1185. var srcByteOffset = o._byteOffset;
  1186. var beginByteOffset = srcByteOffset + startIndex * elementSize;
  1187. JsValue[] argumentsList;
  1188. if (o._arrayLength == JsTypedArray.LengthAuto && end.IsUndefined())
  1189. {
  1190. argumentsList = [buffer, beginByteOffset];
  1191. }
  1192. else
  1193. {
  1194. double relativeEnd;
  1195. if (end.IsUndefined())
  1196. {
  1197. relativeEnd = srcLength;
  1198. }
  1199. else
  1200. {
  1201. relativeEnd = TypeConverter.ToIntegerOrInfinity(end);
  1202. }
  1203. double endIndex;
  1204. if (double.IsNegativeInfinity(relativeEnd))
  1205. {
  1206. endIndex = 0;
  1207. }
  1208. else if (relativeEnd < 0)
  1209. {
  1210. endIndex = System.Math.Max(srcLength + relativeEnd, 0);
  1211. }
  1212. else
  1213. {
  1214. endIndex = System.Math.Min(relativeEnd, srcLength);
  1215. }
  1216. var newLength = System.Math.Max(endIndex - startIndex, 0);
  1217. argumentsList = [buffer, beginByteOffset, newLength];
  1218. }
  1219. return _realm.Intrinsics.TypedArray.TypedArraySpeciesCreate(o, argumentsList);
  1220. }
  1221. /// <summary>
  1222. /// https://tc39.es/ecma262/#sec-%typedarray%.prototype.tolocalestring
  1223. /// </summary>
  1224. private JsValue ToLocaleString(JsValue thisObject, JsValue[] arguments)
  1225. {
  1226. /*
  1227. * %TypedArray%.prototype.toLocaleString is a distinct function that implements the same algorithm as Array.prototype.toLocaleString
  1228. * as defined in 23.1.3.29 except that the this value's [[ArrayLength]] internal slot is accessed in place of performing
  1229. * a [[Get]] of "length". The implementation of the algorithm may be optimized with the knowledge that the this value is an object
  1230. * that has a fixed length and whose integer-indexed properties are not sparse. However, such optimization must not introduce
  1231. * any observable changes in the specified behaviour of the algorithm.
  1232. */
  1233. var taRecord = thisObject.ValidateTypedArray(_realm, ArrayBufferOrder.SeqCst);
  1234. var array = taRecord.Object;
  1235. var len = taRecord.TypedArrayLength;
  1236. const string separator = ",";
  1237. if (len == 0)
  1238. {
  1239. return JsString.Empty;
  1240. }
  1241. JsValue r;
  1242. if (!array.TryGetValue(0, out var firstElement) || firstElement.IsNull() || firstElement.IsUndefined())
  1243. {
  1244. r = JsString.Empty;
  1245. }
  1246. else
  1247. {
  1248. var elementObj = TypeConverter.ToObject(_realm, firstElement);
  1249. var func = elementObj.Get("toLocaleString") as ICallable;
  1250. if (func is null)
  1251. {
  1252. ExceptionHelper.ThrowTypeError(_realm);
  1253. }
  1254. r = func.Call(elementObj, Arguments.Empty);
  1255. }
  1256. for (var k = 1; k < len; k++)
  1257. {
  1258. var s = r + separator;
  1259. var elementObj = TypeConverter.ToObject(_realm, array[k]);
  1260. var func = elementObj.Get("toLocaleString") as ICallable;
  1261. if (func is null)
  1262. {
  1263. ExceptionHelper.ThrowTypeError(_realm);
  1264. }
  1265. r = func.Call(elementObj, Arguments.Empty);
  1266. r = s + r;
  1267. }
  1268. return r;
  1269. }
  1270. /// <summary>
  1271. /// https://tc39.es/ecma262/#sec-%typedarray%.prototype.values
  1272. /// </summary>
  1273. private JsValue Values(JsValue thisObject, JsValue[] arguments)
  1274. {
  1275. var taRecord = thisObject.ValidateTypedArray(_realm, ArrayBufferOrder.SeqCst);
  1276. var o = taRecord.Object;
  1277. return _realm.Intrinsics.ArrayIteratorPrototype.Construct(o, ArrayIteratorType.Value);
  1278. }
  1279. /// <summary>
  1280. /// https://tc39.es/ecma262/#sec-get-%typedarray%.prototype-@@tostringtag
  1281. /// </summary>
  1282. private static JsValue ToStringTag(JsValue thisObject, JsValue[] arguments)
  1283. {
  1284. if (thisObject is not JsTypedArray o)
  1285. {
  1286. return Undefined;
  1287. }
  1288. return o._arrayElementType.GetTypedArrayName();
  1289. }
  1290. private JsValue ToReversed(JsValue thisObject, JsValue[] arguments)
  1291. {
  1292. var taRecord = thisObject.ValidateTypedArray(_realm, ArrayBufferOrder.SeqCst);
  1293. var o = taRecord.Object;
  1294. var len = taRecord.TypedArrayLength;
  1295. var a = TypedArrayCreateSameType(o, new [] { JsNumber.Create(len) });
  1296. uint k = 0;
  1297. while (k < len)
  1298. {
  1299. var from = len - k - 1;
  1300. a[k++] = o.Get(from);
  1301. }
  1302. return a;
  1303. }
  1304. private JsValue ToSorted(JsValue thisObject, JsValue[] arguments)
  1305. {
  1306. var taRecord = thisObject.ValidateTypedArray(_realm, ArrayBufferOrder.SeqCst);
  1307. var o = taRecord.Object;
  1308. var len = taRecord.TypedArrayLength;
  1309. var compareFn = GetCompareFunction(arguments.At(0));
  1310. var buffer = o._viewedArrayBuffer;
  1311. var a = TypedArrayCreateSameType(o, new [] { JsNumber.Create(len) });
  1312. var array = SortArray(buffer, compareFn, o);
  1313. for (var i = 0; (uint) i < (uint) array.Length; ++i)
  1314. {
  1315. a[i] = array[i];
  1316. }
  1317. return a;
  1318. }
  1319. private ObjectInstance With(JsValue thisObject, JsValue[] arguments)
  1320. {
  1321. var taRecord = thisObject.ValidateTypedArray(_realm, ArrayBufferOrder.SeqCst);
  1322. var o = taRecord.Object;
  1323. var len = taRecord.TypedArrayLength;
  1324. var value = arguments.At(1);
  1325. var relativeIndex = TypeConverter.ToIntegerOrInfinity(arguments.At(0));
  1326. long actualIndex;
  1327. if (relativeIndex >= 0)
  1328. {
  1329. actualIndex = (long) relativeIndex;
  1330. }
  1331. else
  1332. {
  1333. actualIndex = (long) (len + relativeIndex);
  1334. }
  1335. value = o._contentType == TypedArrayContentType.BigInt
  1336. ? TypeConverter.ToJsBigInt(value)
  1337. : TypeConverter.ToJsNumber(value);
  1338. if (!o.IsValidIntegerIndex(actualIndex))
  1339. {
  1340. ExceptionHelper.ThrowRangeError(_realm, "Invalid start index");
  1341. }
  1342. var a = TypedArrayCreateSameType(o, new [] { JsNumber.Create(len) });
  1343. var k = 0;
  1344. while (k < len)
  1345. {
  1346. a[k] = k == (int) actualIndex ? value : o.Get(k);
  1347. k++;
  1348. }
  1349. return a;
  1350. }
  1351. private JsTypedArray TypedArrayCreateSameType(JsTypedArray exemplar, JsValue[] argumentList)
  1352. {
  1353. var constructor = exemplar._arrayElementType.GetConstructor(_realm.Intrinsics);
  1354. var result = IntrinsicTypedArrayConstructor.TypedArrayCreate(_realm, constructor, argumentList);
  1355. return result;
  1356. }
  1357. private ICallable? GetCompareFunction(JsValue compareArg)
  1358. {
  1359. ICallable? compareFn = null;
  1360. if (!compareArg.IsUndefined())
  1361. {
  1362. if (compareArg is not ICallable callable)
  1363. {
  1364. ExceptionHelper.ThrowTypeError(_realm, "The comparison function must be either a function or undefined");
  1365. return null;
  1366. }
  1367. compareFn = callable;
  1368. }
  1369. return compareFn;
  1370. }
  1371. private static JsValue[] SortArray(JsArrayBuffer buffer, ICallable? compareFn, JsTypedArray obj)
  1372. {
  1373. var comparer = TypedArrayComparer.WithFunction(buffer, compareFn);
  1374. var operations = ArrayOperations.For(obj, forWrite: false);
  1375. try
  1376. {
  1377. return operations.OrderBy(x => x, comparer).ToArray();
  1378. }
  1379. catch (InvalidOperationException e)
  1380. {
  1381. throw e.InnerException ?? e;
  1382. }
  1383. }
  1384. private sealed class TypedArrayComparer : IComparer<JsValue>
  1385. {
  1386. public static TypedArrayComparer WithFunction(JsArrayBuffer buffer, ICallable? compare)
  1387. {
  1388. return new TypedArrayComparer(buffer, compare);
  1389. }
  1390. private readonly JsArrayBuffer _buffer;
  1391. private readonly ICallable? _compare;
  1392. private readonly JsValue[] _comparableArray = new JsValue[2];
  1393. private TypedArrayComparer(JsArrayBuffer buffer, ICallable? compare)
  1394. {
  1395. _buffer = buffer;
  1396. _compare = compare;
  1397. }
  1398. public int Compare(JsValue? x, JsValue? y)
  1399. {
  1400. if (x is null && y is null)
  1401. {
  1402. return 0;
  1403. }
  1404. if (x is not null && y is null)
  1405. {
  1406. return 1;
  1407. }
  1408. if (x is null)
  1409. {
  1410. return -1;
  1411. }
  1412. if (y is null)
  1413. {
  1414. return 1;
  1415. }
  1416. if (_compare is not null)
  1417. {
  1418. _comparableArray[0] = x;
  1419. _comparableArray[1] = y;
  1420. var v = TypeConverter.ToNumber(_compare.Call(Undefined, _comparableArray));
  1421. if (double.IsNaN(v))
  1422. {
  1423. return 0;
  1424. }
  1425. return (int) v;
  1426. }
  1427. if (x.Type == Types.BigInt || y.Type == Types.BigInt)
  1428. {
  1429. var xBigInt = TypeConverter.ToBigInt(x);
  1430. var yBigInt = TypeConverter.ToBigInt(y);
  1431. return xBigInt.CompareTo(yBigInt);
  1432. }
  1433. var xValue = x.AsNumber();
  1434. var yValue = y.AsNumber();
  1435. if (double.IsNaN(xValue) && double.IsNaN(yValue))
  1436. {
  1437. return 0;
  1438. }
  1439. if (double.IsNaN(xValue))
  1440. {
  1441. return 1;
  1442. }
  1443. if (double.IsNaN(yValue))
  1444. {
  1445. return -1;
  1446. }
  1447. if (xValue < yValue)
  1448. {
  1449. return -1;
  1450. }
  1451. if (xValue > yValue)
  1452. {
  1453. return 1;
  1454. }
  1455. if (NumberInstance.IsNegativeZero(xValue) && yValue == 0)
  1456. {
  1457. return -1;
  1458. }
  1459. if (xValue == 0 && NumberInstance.IsNegativeZero(yValue))
  1460. {
  1461. return 1;
  1462. }
  1463. return 0;
  1464. }
  1465. }
  1466. }