IntrinsicTypedArrayPrototype.cs 57 KB

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