ArrayInstance.cs 28 KB

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