ArrayInstance.cs 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using System.Runtime.CompilerServices;
  4. using Jint.Native.Object;
  5. using Jint.Native.Symbol;
  6. using Jint.Runtime;
  7. using Jint.Runtime.Descriptors;
  8. namespace Jint.Native.Array
  9. {
  10. public class ArrayInstance : ObjectInstance, IEnumerable<JsValue>
  11. {
  12. internal PropertyDescriptor _length;
  13. private const int MaxDenseArrayLength = 10_000_000;
  14. // we have dense and sparse, we usually can start with dense and fall back to sparse when necessary
  15. internal PropertyDescriptor[] _dense;
  16. private Dictionary<uint, PropertyDescriptor> _sparse;
  17. public ArrayInstance(Engine engine, uint capacity = 0) : base(engine, ObjectClass.Array)
  18. {
  19. if (capacity > engine.Options.Constraints.MaxArraySize)
  20. {
  21. ThrowMaximumArraySizeReachedException(engine, capacity);
  22. }
  23. if (capacity < MaxDenseArrayLength)
  24. {
  25. _dense = capacity > 0 ? new PropertyDescriptor[capacity] : System.Array.Empty<PropertyDescriptor>();
  26. }
  27. else
  28. {
  29. _sparse = new Dictionary<uint, PropertyDescriptor>((int) (capacity <= 1024 ? capacity : 1024));
  30. }
  31. }
  32. /// <summary>
  33. /// Possibility to construct valid array fast, requires that supplied array does not have holes.
  34. /// </summary>
  35. public ArrayInstance(Engine engine, PropertyDescriptor[] items) : base(engine, ObjectClass.Array)
  36. {
  37. int length = 0;
  38. if (items == null || items.Length == 0)
  39. {
  40. _dense = System.Array.Empty<PropertyDescriptor>();
  41. length = 0;
  42. }
  43. else
  44. {
  45. _dense = items;
  46. length = items.Length;
  47. }
  48. _length = new PropertyDescriptor(length, PropertyFlag.OnlyWritable);
  49. }
  50. public ArrayInstance(Engine engine, Dictionary<uint, PropertyDescriptor> items) : base(engine, ObjectClass.Array)
  51. {
  52. _sparse = items;
  53. var length = items?.Count ?? 0;
  54. _length = new PropertyDescriptor(length, PropertyFlag.OnlyWritable);
  55. }
  56. public override bool IsArrayLike => true;
  57. public override bool IsArray() => true;
  58. internal override bool HasOriginalIterator
  59. => ReferenceEquals(Get(GlobalSymbolRegistry.Iterator), _engine.Realm.Intrinsics.Array.PrototypeObject._originalIteratorFunction);
  60. public override bool DefineOwnProperty(JsValue property, PropertyDescriptor desc)
  61. {
  62. if (property == CommonProperties.Length)
  63. {
  64. var value = desc.Value;
  65. if (ReferenceEquals(value, null))
  66. {
  67. return base.DefineOwnProperty(CommonProperties.Length, desc);
  68. }
  69. var newLenDesc = new PropertyDescriptor(desc);
  70. uint newLen = TypeConverter.ToUint32(value);
  71. if (newLen != TypeConverter.ToNumber(value))
  72. {
  73. ExceptionHelper.ThrowRangeError(_engine.Realm);
  74. }
  75. var oldLenDesc = _length;
  76. var oldLen = (uint) TypeConverter.ToNumber(oldLenDesc.Value);
  77. newLenDesc.Value = newLen;
  78. if (newLen >= oldLen)
  79. {
  80. return base.DefineOwnProperty(CommonProperties.Length, newLenDesc);
  81. }
  82. if (!oldLenDesc.Writable)
  83. {
  84. return false;
  85. }
  86. bool newWritable;
  87. if (!newLenDesc.WritableSet || newLenDesc.Writable)
  88. {
  89. newWritable = true;
  90. }
  91. else
  92. {
  93. newWritable = false;
  94. newLenDesc.Writable = true;
  95. }
  96. var succeeded = base.DefineOwnProperty(CommonProperties.Length, newLenDesc);
  97. if (!succeeded)
  98. {
  99. return false;
  100. }
  101. var count = _dense?.Length ?? _sparse.Count;
  102. if (count < oldLen - newLen)
  103. {
  104. if (_dense != null)
  105. {
  106. for (uint keyIndex = 0; keyIndex < _dense.Length; ++keyIndex)
  107. {
  108. if (_dense[keyIndex] == null)
  109. {
  110. continue;
  111. }
  112. // is it the index of the array
  113. if (keyIndex >= newLen && keyIndex < oldLen)
  114. {
  115. var deleteSucceeded = Delete(keyIndex);
  116. if (!deleteSucceeded)
  117. {
  118. newLenDesc.Value = keyIndex + 1;
  119. if (!newWritable)
  120. {
  121. newLenDesc.Writable = false;
  122. }
  123. base.DefineOwnProperty(CommonProperties.Length, newLenDesc);
  124. return false;
  125. }
  126. }
  127. }
  128. }
  129. else
  130. {
  131. // in the case of sparse arrays, treat each concrete element instead of
  132. // iterating over all indexes
  133. var keys = new List<uint>(_sparse.Keys);
  134. var keysCount = keys.Count;
  135. for (var i = 0; i < keysCount; i++)
  136. {
  137. var keyIndex = keys[i];
  138. // is it the index of the array
  139. if (keyIndex >= newLen && keyIndex < oldLen)
  140. {
  141. var deleteSucceeded = Delete(TypeConverter.ToString(keyIndex));
  142. if (!deleteSucceeded)
  143. {
  144. newLenDesc.Value = JsNumber.Create(keyIndex + 1);
  145. if (!newWritable)
  146. {
  147. newLenDesc.Writable = false;
  148. }
  149. base.DefineOwnProperty(CommonProperties.Length, newLenDesc);
  150. return false;
  151. }
  152. }
  153. }
  154. }
  155. }
  156. else
  157. {
  158. while (newLen < oldLen)
  159. {
  160. // algorithm as per the spec
  161. oldLen--;
  162. var deleteSucceeded = Delete(oldLen);
  163. if (!deleteSucceeded)
  164. {
  165. newLenDesc.Value = oldLen + 1;
  166. if (!newWritable)
  167. {
  168. newLenDesc.Writable = false;
  169. }
  170. base.DefineOwnProperty(CommonProperties.Length, newLenDesc);
  171. return false;
  172. }
  173. }
  174. }
  175. if (!newWritable)
  176. {
  177. base.DefineOwnProperty(CommonProperties.Length, new PropertyDescriptor(value: null, PropertyFlag.WritableSet));
  178. }
  179. return true;
  180. }
  181. if (IsArrayIndex(property, out var index))
  182. {
  183. return DefineOwnProperty(index, desc);
  184. }
  185. return base.DefineOwnProperty(property, desc);
  186. }
  187. private bool DefineOwnProperty(uint index, PropertyDescriptor desc)
  188. {
  189. var oldLenDesc = _length;
  190. var oldLen = (uint) TypeConverter.ToNumber(oldLenDesc.Value);
  191. if (index >= oldLen && !oldLenDesc.Writable)
  192. {
  193. return false;
  194. }
  195. var succeeded = base.DefineOwnProperty(index, desc);
  196. if (!succeeded)
  197. {
  198. return false;
  199. }
  200. if (index >= oldLen)
  201. {
  202. oldLenDesc.Value = index + 1;
  203. base.DefineOwnProperty(CommonProperties.Length, oldLenDesc);
  204. }
  205. return true;
  206. }
  207. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  208. internal uint GetLength()
  209. {
  210. if (_length is null)
  211. {
  212. return 0;
  213. }
  214. return (uint) ((JsNumber) _length._value)._value;
  215. }
  216. protected override void AddProperty(JsValue property, PropertyDescriptor descriptor)
  217. {
  218. if (property == CommonProperties.Length)
  219. {
  220. _length = descriptor;
  221. return;
  222. }
  223. base.AddProperty(property, descriptor);
  224. }
  225. protected override bool TryGetProperty(JsValue property, out PropertyDescriptor descriptor)
  226. {
  227. if (property == CommonProperties.Length)
  228. {
  229. descriptor = _length;
  230. return _length != null;
  231. }
  232. return base.TryGetProperty(property, out descriptor);
  233. }
  234. public override List<JsValue> GetOwnPropertyKeys(Types types = Types.None | Types.String | Types.Symbol)
  235. {
  236. if ((types & Types.String) == 0)
  237. {
  238. return base.GetOwnPropertyKeys(types);
  239. }
  240. var properties = new List<JsValue>(_dense?.Length ?? 0 + 1);
  241. if (_dense != null)
  242. {
  243. var length = System.Math.Min(_dense.Length, GetLength());
  244. for (var i = 0; i < length; i++)
  245. {
  246. if (_dense[i] != null)
  247. {
  248. properties.Add(JsString.Create(i));
  249. }
  250. }
  251. }
  252. else
  253. {
  254. foreach (var entry in _sparse)
  255. {
  256. properties.Add(JsString.Create(entry.Key));
  257. }
  258. }
  259. if (_length != null)
  260. {
  261. properties.Add(CommonProperties.Length);
  262. }
  263. properties.AddRange(base.GetOwnPropertyKeys(types));
  264. return properties;
  265. }
  266. public override IEnumerable<KeyValuePair<JsValue, PropertyDescriptor>> GetOwnProperties()
  267. {
  268. if (_dense != null)
  269. {
  270. var length = System.Math.Min(_dense.Length, GetLength());
  271. for (var i = 0; i < length; i++)
  272. {
  273. if (_dense[i] != null)
  274. {
  275. yield return new KeyValuePair<JsValue, PropertyDescriptor>(TypeConverter.ToString(i), _dense[i]);
  276. }
  277. }
  278. }
  279. else
  280. {
  281. foreach (var entry in _sparse)
  282. {
  283. yield return new KeyValuePair<JsValue, PropertyDescriptor>(TypeConverter.ToString(entry.Key), entry.Value);
  284. }
  285. }
  286. if (_length != null)
  287. {
  288. yield return new KeyValuePair<JsValue, PropertyDescriptor>(CommonProperties.Length, _length);
  289. }
  290. foreach (var entry in base.GetOwnProperties())
  291. {
  292. yield return entry;
  293. }
  294. }
  295. public override PropertyDescriptor GetOwnProperty(JsValue property)
  296. {
  297. if (property == CommonProperties.Length)
  298. {
  299. return _length ?? PropertyDescriptor.Undefined;
  300. }
  301. if (IsArrayIndex(property, out var index))
  302. {
  303. if (TryGetDescriptor(index, out var result))
  304. {
  305. return result;
  306. }
  307. return PropertyDescriptor.Undefined;
  308. }
  309. return base.GetOwnProperty(property);
  310. }
  311. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  312. private PropertyDescriptor GetOwnProperty(uint index)
  313. {
  314. return TryGetDescriptor(index, out var result)
  315. ? result
  316. : PropertyDescriptor.Undefined;
  317. }
  318. internal JsValue Get(uint index)
  319. {
  320. var prop = GetOwnProperty(index);
  321. if (prop == PropertyDescriptor.Undefined)
  322. {
  323. prop = Prototype?.GetProperty(JsString.Create(index)) ?? PropertyDescriptor.Undefined;
  324. }
  325. return UnwrapJsValue(prop);
  326. }
  327. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  328. private PropertyDescriptor GetProperty(uint index)
  329. {
  330. var prop = GetOwnProperty(index);
  331. if (prop != PropertyDescriptor.Undefined)
  332. {
  333. return prop;
  334. }
  335. return Prototype?.GetProperty(JsString.Create(index)) ?? PropertyDescriptor.Undefined;
  336. }
  337. protected internal override void SetOwnProperty(JsValue property, PropertyDescriptor desc)
  338. {
  339. if (IsArrayIndex(property, out var index))
  340. {
  341. WriteArrayValue(index, desc);
  342. }
  343. else if (property == CommonProperties.Length)
  344. {
  345. _length = desc;
  346. }
  347. else
  348. {
  349. base.SetOwnProperty(property, desc);
  350. }
  351. }
  352. public override bool HasOwnProperty(JsValue p)
  353. {
  354. if (IsArrayIndex(p, out var index))
  355. {
  356. return index < GetLength()
  357. && (_sparse == null || _sparse.ContainsKey(index))
  358. && (_dense == null || (index < (uint) _dense.Length && _dense[index] != null));
  359. }
  360. if (p == CommonProperties.Length)
  361. {
  362. return _length != null;
  363. }
  364. return base.HasOwnProperty(p);
  365. }
  366. public override void RemoveOwnProperty(JsValue p)
  367. {
  368. if (IsArrayIndex(p, out var index))
  369. {
  370. Delete(index);
  371. }
  372. if (p == CommonProperties.Length)
  373. {
  374. _length = null;
  375. }
  376. base.RemoveOwnProperty(p);
  377. }
  378. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  379. private static bool IsArrayIndex(JsValue p, out uint index)
  380. {
  381. if (p is JsNumber number)
  382. {
  383. var value = number._value;
  384. var intValue = (uint) value;
  385. index = intValue;
  386. return value == intValue && intValue != uint.MaxValue;
  387. }
  388. index = ParseArrayIndex(p.ToString());
  389. return index != uint.MaxValue;
  390. // 15.4 - Use an optimized version of the specification
  391. // return TypeConverter.ToString(index) == TypeConverter.ToString(p) && index != uint.MaxValue;
  392. }
  393. private static uint ParseArrayIndex(string p)
  394. {
  395. if (p.Length == 0)
  396. {
  397. return uint.MaxValue;
  398. }
  399. int d = p[0] - '0';
  400. if (d < 0 || d > 9)
  401. {
  402. return uint.MaxValue;
  403. }
  404. if (d == 0 && p.Length > 1)
  405. {
  406. // If p is a number that start with '0' and is not '0' then
  407. // its ToString representation can't be the same a p. This is
  408. // not a valid array index. '01' !== ToString(ToUInt32('01'))
  409. // http://www.ecma-international.org/ecma-262/5.1/#sec-15.4
  410. return uint.MaxValue;
  411. }
  412. if (p.Length > 1)
  413. {
  414. return StringAsIndex(d, p);
  415. }
  416. return (uint) d;
  417. }
  418. private static uint StringAsIndex(int d, string p)
  419. {
  420. ulong result = (uint) d;
  421. for (int i = 1; i < p.Length; i++)
  422. {
  423. d = p[i] - '0';
  424. if (d < 0 || d > 9)
  425. {
  426. return uint.MaxValue;
  427. }
  428. result = result * 10 + (uint) d;
  429. if (result >= uint.MaxValue)
  430. {
  431. return uint.MaxValue;
  432. }
  433. }
  434. return (uint) result;
  435. }
  436. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  437. internal void SetIndexValue(uint index, JsValue value, bool updateLength)
  438. {
  439. if (updateLength)
  440. {
  441. var length = GetLength();
  442. if (index >= length)
  443. {
  444. SetLength(index + 1);
  445. }
  446. }
  447. WriteArrayValue(index, new PropertyDescriptor(value, PropertyFlag.ConfigurableEnumerableWritable));
  448. }
  449. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  450. internal void SetLength(uint length)
  451. {
  452. _length.Value = length;
  453. }
  454. internal uint GetSmallestIndex()
  455. {
  456. if (_dense != null)
  457. {
  458. return 0;
  459. }
  460. uint smallest = 0;
  461. // only try to help if collection reasonable small
  462. if (_sparse.Count > 0 && _sparse.Count < 100 && !_sparse.ContainsKey(0))
  463. {
  464. smallest = uint.MaxValue;
  465. foreach (var key in _sparse.Keys)
  466. {
  467. smallest = System.Math.Min(key, smallest);
  468. }
  469. }
  470. return smallest;
  471. }
  472. public bool TryGetValue(uint index, out JsValue value)
  473. {
  474. value = Undefined;
  475. if (!TryGetDescriptor(index, out var desc))
  476. {
  477. desc = GetProperty(JsString.Create(index));
  478. }
  479. return desc.TryGetValue(this, out value);
  480. }
  481. internal bool DeletePropertyOrThrow(uint index)
  482. {
  483. if (!Delete(index))
  484. {
  485. ExceptionHelper.ThrowTypeError(_engine.Realm);
  486. }
  487. return true;
  488. }
  489. internal bool Delete(uint index)
  490. {
  491. var desc = GetOwnProperty(index);
  492. if (desc == PropertyDescriptor.Undefined)
  493. {
  494. return true;
  495. }
  496. if (desc.Configurable)
  497. {
  498. DeleteAt(index);
  499. return true;
  500. }
  501. return false;
  502. }
  503. internal bool DeleteAt(uint index)
  504. {
  505. var temp = _dense;
  506. if (temp != null)
  507. {
  508. if (index < (uint) temp.Length)
  509. {
  510. temp[index] = null;
  511. return true;
  512. }
  513. }
  514. else
  515. {
  516. return _sparse.Remove(index);
  517. }
  518. return false;
  519. }
  520. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  521. private bool TryGetDescriptor(uint index, out PropertyDescriptor descriptor)
  522. {
  523. var temp = _dense;
  524. if (temp != null)
  525. {
  526. descriptor = null;
  527. if (index < (uint) temp.Length)
  528. {
  529. descriptor = temp[index];
  530. }
  531. return descriptor != null;
  532. }
  533. return _sparse.TryGetValue(index, out descriptor);
  534. }
  535. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  536. internal void WriteArrayValue(uint index, PropertyDescriptor desc)
  537. {
  538. // calculate eagerly so we know if we outgrow
  539. var newSize = _dense != null && index >= (uint) _dense.Length
  540. ? System.Math.Max(index, System.Math.Max(_dense.Length, 2)) * 2
  541. : 0;
  542. bool canUseDense = _dense != null
  543. && index < MaxDenseArrayLength
  544. && newSize < MaxDenseArrayLength
  545. && index < _dense.Length + 50; // looks sparse
  546. if (canUseDense)
  547. {
  548. if (index >= (uint) _dense.Length)
  549. {
  550. EnsureCapacity((uint) newSize);
  551. }
  552. _dense[index] = desc;
  553. }
  554. else
  555. {
  556. if (_dense != null)
  557. {
  558. ConvertToSparse();
  559. }
  560. _sparse[index] = desc;
  561. }
  562. }
  563. private void ConvertToSparse()
  564. {
  565. _sparse = new Dictionary<uint, PropertyDescriptor>(_dense.Length <= 1024 ? _dense.Length : 0);
  566. // need to move data
  567. for (uint i = 0; i < (uint) _dense.Length; ++i)
  568. {
  569. if (_dense[i] != null)
  570. {
  571. _sparse[i] = _dense[i];
  572. }
  573. }
  574. _dense = null;
  575. }
  576. internal void EnsureCapacity(uint capacity)
  577. {
  578. if (capacity > MaxDenseArrayLength || _dense is null || capacity <= (uint) _dense.Length)
  579. {
  580. return;
  581. }
  582. if (capacity > _engine.Options.Constraints.MaxArraySize)
  583. {
  584. ThrowMaximumArraySizeReachedException(_engine, capacity);
  585. }
  586. // need to grow
  587. var newArray = new PropertyDescriptor[capacity];
  588. System.Array.Copy(_dense, newArray, _dense.Length);
  589. _dense = newArray;
  590. }
  591. public IEnumerator<JsValue> GetEnumerator()
  592. {
  593. var length = GetLength();
  594. for (uint i = 0; i < length; i++)
  595. {
  596. TryGetValue(i, out var outValue);
  597. yield return outValue;
  598. }
  599. }
  600. IEnumerator IEnumerable.GetEnumerator()
  601. {
  602. return GetEnumerator();
  603. }
  604. internal uint Push(JsValue[] arguments)
  605. {
  606. var initialLength = GetLength();
  607. var newLength = initialLength + arguments.Length;
  608. // if we see that we are bringing more than normal growth algorithm handles, ensure capacity eagerly
  609. if (_dense != null
  610. && initialLength != 0
  611. && arguments.Length > initialLength * 2
  612. && newLength <= MaxDenseArrayLength)
  613. {
  614. EnsureCapacity((uint) newLength);
  615. }
  616. var canUseDirectIndexSet = _dense != null && newLength <= _dense.Length;
  617. double n = initialLength;
  618. foreach (var argument in arguments)
  619. {
  620. var desc = new PropertyDescriptor(argument, PropertyFlag.ConfigurableEnumerableWritable);
  621. if (canUseDirectIndexSet)
  622. {
  623. _dense[(uint) n] = desc;
  624. }
  625. else
  626. {
  627. WriteValueSlow(n, desc);
  628. }
  629. n++;
  630. }
  631. // check if we can set length fast without breaking ECMA specification
  632. if (n < uint.MaxValue && CanSetLength())
  633. {
  634. _length.Value = (uint) n;
  635. }
  636. else
  637. {
  638. if (!Set(CommonProperties.Length, newLength))
  639. {
  640. ExceptionHelper.ThrowTypeError(_engine.Realm);
  641. }
  642. }
  643. return (uint) n;
  644. }
  645. private bool CanSetLength()
  646. {
  647. if (!_length.IsAccessorDescriptor())
  648. {
  649. return _length.Writable;
  650. }
  651. var set = _length.Set;
  652. return set is not null && !set.IsUndefined();
  653. }
  654. [MethodImpl(MethodImplOptions.NoInlining)]
  655. private void WriteValueSlow(double n, PropertyDescriptor desc)
  656. {
  657. if (n < uint.MaxValue)
  658. {
  659. WriteArrayValue((uint) n, desc);
  660. }
  661. else
  662. {
  663. DefinePropertyOrThrow((uint) n, desc);
  664. }
  665. }
  666. internal ArrayInstance Map(JsValue[] arguments)
  667. {
  668. var callbackfn = arguments.At(0);
  669. var thisArg = arguments.At(1);
  670. var len = GetLength();
  671. var callable = GetCallable(callbackfn);
  672. var a = Engine.Realm.Intrinsics.Array.ArrayCreate(len);
  673. var args = _engine._jsValueArrayPool.RentArray(3);
  674. args[2] = this;
  675. for (uint k = 0; k < len; k++)
  676. {
  677. if (TryGetValue(k, out var kvalue))
  678. {
  679. args[0] = kvalue;
  680. args[1] = k;
  681. var mappedValue = callable.Call(thisArg, args);
  682. var desc = new PropertyDescriptor(mappedValue, PropertyFlag.ConfigurableEnumerableWritable);
  683. if (a._dense != null && k < (uint) a._dense.Length)
  684. {
  685. a._dense[k] = desc;
  686. }
  687. else
  688. {
  689. a.WriteArrayValue(k, desc);
  690. }
  691. }
  692. }
  693. _engine._jsValueArrayPool.ReturnArray(args);
  694. return a;
  695. }
  696. /// <inheritdoc />
  697. internal override bool FindWithCallback(
  698. JsValue[] arguments,
  699. out uint index,
  700. out JsValue value,
  701. bool visitUnassigned,
  702. bool fromEnd = false)
  703. {
  704. var thisArg = arguments.At(1);
  705. var callbackfn = arguments.At(0);
  706. var callable = GetCallable(callbackfn);
  707. var len = GetLength();
  708. if (len == 0)
  709. {
  710. index = 0;
  711. value = Undefined;
  712. return false;
  713. }
  714. var args = _engine._jsValueArrayPool.RentArray(3);
  715. args[2] = this;
  716. if (!fromEnd)
  717. {
  718. for (uint k = 0; k < len; k++)
  719. {
  720. if (TryGetValue(k, out var kvalue) || visitUnassigned)
  721. {
  722. args[0] = kvalue;
  723. args[1] = k;
  724. var testResult = callable.Call(thisArg, args);
  725. if (TypeConverter.ToBoolean(testResult))
  726. {
  727. index = k;
  728. value = kvalue;
  729. return true;
  730. }
  731. }
  732. }
  733. }
  734. else
  735. {
  736. for (long k = len - 1; k >= 0; k--)
  737. {
  738. var idx = (uint) k;
  739. if (TryGetValue(idx, out var kvalue) || visitUnassigned)
  740. {
  741. args[0] = kvalue;
  742. args[1] = idx;
  743. var testResult = callable.Call(thisArg, args);
  744. if (TypeConverter.ToBoolean(testResult))
  745. {
  746. index = idx;
  747. value = kvalue;
  748. return true;
  749. }
  750. }
  751. }
  752. }
  753. _engine._jsValueArrayPool.ReturnArray(args);
  754. index = 0;
  755. value = Undefined;
  756. return false;
  757. }
  758. public override uint Length => GetLength();
  759. internal override bool IsIntegerIndexedArray => true;
  760. public JsValue this[uint index]
  761. {
  762. get
  763. {
  764. TryGetValue(index, out var kValue);
  765. return kValue;
  766. }
  767. }
  768. /// <summary>
  769. /// Fast path for concatenating sane-sized arrays, we assume size has been calculated.
  770. /// </summary>
  771. internal void CopyValues(ArrayInstance source, uint sourceStartIndex, uint targetStartIndex, uint length)
  772. {
  773. if (length == 0)
  774. {
  775. return;
  776. }
  777. var sourceDense = source._dense;
  778. if (sourceDense is not null)
  779. {
  780. EnsureCapacity((uint) sourceDense.LongLength);
  781. }
  782. var dense = _dense;
  783. if (dense != null && sourceDense != null
  784. && (uint) dense.Length >= targetStartIndex + length
  785. && dense[targetStartIndex] is null)
  786. {
  787. uint j = 0;
  788. for (uint i = sourceStartIndex; i < sourceStartIndex + length; ++i, j++)
  789. {
  790. var sourcePropertyDescriptor = i < (uint) sourceDense.Length && sourceDense[i] != null
  791. ? sourceDense[i]
  792. : source.GetProperty(i);
  793. dense[targetStartIndex + j] = sourcePropertyDescriptor?._value is not null
  794. ? new PropertyDescriptor(sourcePropertyDescriptor._value, PropertyFlag.ConfigurableEnumerableWritable)
  795. : null;
  796. }
  797. }
  798. else
  799. {
  800. // slower version
  801. for (uint k = sourceStartIndex; k < length; k++)
  802. {
  803. if (source.TryGetValue(k, out var subElement))
  804. {
  805. SetIndexValue(targetStartIndex, subElement, updateLength: false);
  806. }
  807. targetStartIndex++;
  808. }
  809. }
  810. }
  811. public override string ToString()
  812. {
  813. // debugger can make things hard when evaluates computed values
  814. return "(" + (_length?._value.AsNumber() ?? 0) + ")[]";
  815. }
  816. private static void ThrowMaximumArraySizeReachedException(Engine engine, uint capacity)
  817. {
  818. ExceptionHelper.ThrowMemoryLimitExceededException(
  819. $"The array size {capacity} is larger than maximum allowed ({engine.Options.Constraints.MaxArraySize})"
  820. );
  821. }
  822. }
  823. }