IntrinsicTypedArrayPrototype.cs 63 KB

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