PageRenderTime 73ms CodeModel.GetById 37ms RepoModel.GetById 0ms app.codeStats 0ms

/Languages/IronPython/IronPython/Runtime/List.cs

https://github.com/IronLanguages/main
C# | 1671 lines | 1239 code | 311 blank | 121 comment | 227 complexity | 55f7f6bfeb8dd795029cb3097fe16b73 MD5 | raw file
Possible License(s): MPL-2.0-no-copyleft-exception

Large files files are truncated, but you can click here to view the full file

  1. /* ****************************************************************************
  2. *
  3. * Copyright (c) Microsoft Corporation.
  4. *
  5. * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
  6. * copy of the license can be found in the License.html file at the root of this distribution. If
  7. * you cannot locate the Apache License, Version 2.0, please send an email to
  8. * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
  9. * by the terms of the Apache License, Version 2.0.
  10. *
  11. * You must not remove this notice, or any other, from this software.
  12. *
  13. *
  14. * ***************************************************************************/
  15. using System;
  16. using System.Collections;
  17. using System.Collections.Generic;
  18. using System.Diagnostics;
  19. using System.Runtime.InteropServices;
  20. using System.Text;
  21. using System.Threading;
  22. using Microsoft.Scripting;
  23. using Microsoft.Scripting.Generation;
  24. using Microsoft.Scripting.Runtime;
  25. using Microsoft.Scripting.Utils;
  26. using IronPython.Runtime.Exceptions;
  27. using IronPython.Runtime.Operations;
  28. using IronPython.Runtime.Types;
  29. #if FEATURE_NUMERICS
  30. using System.Numerics;
  31. #else
  32. using Microsoft.Scripting.Math;
  33. #endif
  34. using SpecialNameAttribute = System.Runtime.CompilerServices.SpecialNameAttribute;
  35. namespace IronPython.Runtime {
  36. [PythonType("list"), Serializable, System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
  37. [DebuggerTypeProxy(typeof(ObjectCollectionDebugProxy)), DebuggerDisplay("list, {Count} items")]
  38. public class List : IList, ICodeFormattable, IList<object>, IReversible, IStructuralEquatable, IStructuralComparable
  39. #if CLR2
  40. , IValueEquality
  41. #endif
  42. {
  43. private const int INITIAL_SIZE = 20;
  44. internal int _size;
  45. internal volatile object[] _data;
  46. public void __init__() {
  47. _data = new object[8];
  48. _size = 0;
  49. }
  50. public void __init__([NotNull] IEnumerable enumerable) {
  51. __init__();
  52. foreach (object o in enumerable) {
  53. AddNoLock(o);
  54. }
  55. }
  56. public void __init__([NotNull] ICollection sequence) {
  57. _data = new object[sequence.Count];
  58. int i = 0;
  59. foreach (object item in sequence) {
  60. _data[i++] = item;
  61. }
  62. _size = i;
  63. }
  64. public void __init__([NotNull] SetCollection sequence) {
  65. List list = sequence._items.GetItems();
  66. _size = list._size;
  67. _data = list._data;
  68. }
  69. public void __init__([NotNull] FrozenSetCollection sequence) {
  70. List list = sequence._items.GetItems();
  71. _size = list._size;
  72. _data = list._data;
  73. }
  74. public void __init__([NotNull] List sequence) {
  75. if (this == sequence) {
  76. // list.__init__(l, l) resets l
  77. _size = 0;
  78. return;
  79. }
  80. _data = new object[sequence._size];
  81. object[] data = sequence._data;
  82. for (int i = 0; i < _data.Length; i++) {
  83. _data[i] = data[i];
  84. }
  85. _size = _data.Length;
  86. }
  87. public void __init__([NotNull] string sequence) {
  88. _data = new object[sequence.Length];
  89. _size = sequence.Length;
  90. for (int i = 0; i < sequence.Length; i++) {
  91. _data[i] = ScriptingRuntimeHelpers.CharToString(sequence[i]);
  92. }
  93. }
  94. public void __init__(CodeContext context, object sequence) {
  95. try {
  96. object len;
  97. if (PythonTypeOps.TryInvokeUnaryOperator(context, sequence, "__len__", out len)) {
  98. int ilen = PythonContext.GetContext(context).ConvertToInt32(len);
  99. _data = new object[ilen];
  100. _size = 0;
  101. extend(sequence);
  102. } else {
  103. _data = new object[INITIAL_SIZE];
  104. _size = 0;
  105. extend(sequence);
  106. }
  107. } catch (MissingMemberException) {
  108. _data = new object[INITIAL_SIZE];
  109. _size = 0;
  110. extend(sequence);
  111. }
  112. }
  113. public static object __new__(CodeContext/*!*/ context, PythonType cls) {
  114. if (cls == TypeCache.List) {
  115. return new List();
  116. }
  117. return cls.CreateInstance(context);
  118. }
  119. public static object __new__(CodeContext/*!*/ context, PythonType cls, object arg) {
  120. return __new__(context, cls);
  121. }
  122. public static object __new__(CodeContext/*!*/ context, PythonType cls, params object[] args\u00F8) {
  123. return __new__(context, cls);
  124. }
  125. public static object __new__(CodeContext/*!*/ context, PythonType cls, [ParamDictionary]IDictionary<object, object> kwArgs\u00F8, params object[] args\u00F8) {
  126. return __new__(context, cls);
  127. }
  128. private List(IEnumerator e)
  129. : this(10) {
  130. while (e.MoveNext()) AddNoLock(e.Current);
  131. }
  132. internal List(int capacity) {
  133. if (capacity == 0) {
  134. _data = ArrayUtils.EmptyObjects;
  135. } else {
  136. _data = new object[capacity];
  137. }
  138. }
  139. private List(params object[] items) {
  140. _data = items;
  141. _size = _data.Length;
  142. }
  143. public List()
  144. : this(0) {
  145. }
  146. #if ALLOC_DEBUG
  147. private static int total, totalSize, cnt, growthCnt, growthSize;
  148. ~List() {
  149. total += _data.Length;
  150. totalSize += _size;
  151. cnt++;
  152. Console.Error.WriteLine("List: allocated {0} used {1} total wasted {2} - grand total wasted {3}", _data.Length, _size, total-totalSize, growthSize + total - totalSize);
  153. Console.Error.WriteLine(" Growing {0} {1} avg {2}", growthCnt, growthSize, growthSize / growthCnt);
  154. }
  155. #endif
  156. internal List(object sequence) {
  157. ICollection items = sequence as ICollection;
  158. object len;
  159. if (items != null) {
  160. _data = new object[items.Count];
  161. int i = 0;
  162. foreach (object item in items) {
  163. _data[i++] = item;
  164. }
  165. _size = i;
  166. } else if (PythonTypeOps.TryInvokeUnaryOperator(DefaultContext.Default,
  167. sequence,
  168. "__len__",
  169. out len)) {
  170. int ilen = Converter.ConvertToInt32(len);
  171. _data = new object[ilen];
  172. extend(sequence);
  173. } else {
  174. _data = new object[INITIAL_SIZE];
  175. extend(sequence);
  176. }
  177. }
  178. internal List(ICollection items)
  179. : this(items.Count) {
  180. int i = 0;
  181. foreach (object item in items) {
  182. _data[i++] = item;
  183. }
  184. _size = i;
  185. }
  186. /// <summary>
  187. /// Creates a new list with the data in the array and a size
  188. /// the same as the length of the array. The array is held
  189. /// onto and may be mutated in the future by the list.
  190. /// </summary>
  191. /// <param name="data">params array to use for lists storage</param>
  192. internal static List FromArrayNoCopy(params object[] data) {
  193. return new List(data);
  194. }
  195. internal object[] GetObjectArray() {
  196. lock (this) {
  197. return ArrayOps.CopyArray(_data, _size);
  198. }
  199. }
  200. #region binary operators
  201. public static List operator +([NotNull]List l1, [NotNull]List l2) {
  202. object[] ret;
  203. int size;
  204. lock (l1) {
  205. ret = ArrayOps.CopyArray(l1._data, GetAddSize(l1._size, l2._size));
  206. size = l1._size;
  207. }
  208. lock (l2) {
  209. if (l2._size + size > ret.Length) {
  210. ret = ArrayOps.CopyArray(ret, GetAddSize(size, l2._size));
  211. }
  212. Array.Copy(l2._data, 0, ret, size, l2._size);
  213. List lret = new List(ret);
  214. lret._size = size + l2._size;
  215. return lret;
  216. }
  217. }
  218. /// <summary>
  219. /// Gets a reasonable size for the addition of two arrays. We round
  220. /// to a power of two so that we usually have some extra space if
  221. /// the resulting array gets added to.
  222. /// </summary>
  223. private static int GetAddSize(int s1, int s2) {
  224. int length = s1 + s2;
  225. return GetNewSize(length);
  226. }
  227. private static int GetNewSize(int length) {
  228. if (length > 256) {
  229. return length + (128 - 1) & ~(128 - 1);
  230. }
  231. return length + (16 - 1) & ~(16 - 1);
  232. }
  233. public static List operator *([NotNull]List l, int count) {
  234. return MultiplyWorker(l, count);
  235. }
  236. public static List operator *(int count, List l) {
  237. return MultiplyWorker(l, count);
  238. }
  239. public static object operator *([NotNull]List self, [NotNull]Index count) {
  240. return PythonOps.MultiplySequence<List>(MultiplyWorker, self, count, true);
  241. }
  242. public static object operator *([NotNull]Index count, [NotNull]List self) {
  243. return PythonOps.MultiplySequence<List>(MultiplyWorker, self, count, false);
  244. }
  245. public static object operator *([NotNull]List self, object count) {
  246. int index;
  247. if (Converter.TryConvertToIndex(count, out index)) {
  248. return self * index;
  249. }
  250. throw PythonOps.TypeErrorForUnIndexableObject(count);
  251. }
  252. public static object operator *(object count, [NotNull]List self) {
  253. int index;
  254. if (Converter.TryConvertToIndex(count, out index)) {
  255. return index * self;
  256. }
  257. throw PythonOps.TypeErrorForUnIndexableObject(count);
  258. }
  259. private static List MultiplyWorker(List self, int count) {
  260. if (count <= 0) return PythonOps.MakeEmptyList(0);
  261. int n, newCount;
  262. object[] ret;
  263. lock (self) {
  264. n = self._size;
  265. //??? is this useful optimization
  266. //???if (n == 1) return new List(Array.ArrayList.Repeat(this[0], count));
  267. newCount = checked(n * count);
  268. ret = ArrayOps.CopyArray(self._data, newCount);
  269. }
  270. // this should be extremely fast for large count as it uses the same algoithim as efficient integer powers
  271. // ??? need to test to see how large count and n need to be for this to be fastest approach
  272. int block = n;
  273. int pos = n;
  274. while (pos < newCount) {
  275. Array.Copy(ret, 0, ret, pos, Math.Min(block, newCount - pos));
  276. pos += block;
  277. block *= 2;
  278. }
  279. return new List(ret);
  280. }
  281. #endregion
  282. public virtual int __len__() {
  283. return _size;
  284. }
  285. public virtual IEnumerator __iter__() {
  286. // return type is strongly typed to IEnumerator so that
  287. // we can call it w/o requiring an explicit conversion. If the
  288. // user overrides this we'll place a conversion in the wrapper
  289. // helper
  290. return new ListIterator(this);
  291. }
  292. public virtual IEnumerator __reversed__() {
  293. return new ListReverseIterator(this);
  294. }
  295. public virtual bool __contains__(object value) {
  296. return ContainsWorker(value);
  297. }
  298. internal bool ContainsWorker(object value) {
  299. bool lockTaken = false;
  300. try {
  301. MonitorUtils.Enter(this, ref lockTaken);
  302. for (int i = 0; i < _size; i++) {
  303. object thisIndex = _data[i];
  304. // release the lock while we may call user code...
  305. MonitorUtils.Exit(this, ref lockTaken);
  306. try {
  307. if (PythonOps.EqualRetBool(thisIndex, value))
  308. return true;
  309. } finally {
  310. MonitorUtils.Enter(this, ref lockTaken);
  311. }
  312. }
  313. } finally {
  314. if (lockTaken) {
  315. Monitor.Exit(this);
  316. }
  317. }
  318. return false;
  319. }
  320. #region ISequence Members
  321. internal void AddRange<T>(ICollection<T> otherList) {
  322. foreach (object o in otherList) append(o);
  323. }
  324. [SpecialName]
  325. public virtual object InPlaceAdd(object other) {
  326. if (!Object.ReferenceEquals(this, other)) {
  327. IEnumerator e = PythonOps.GetEnumerator(other);
  328. while (e.MoveNext()) {
  329. append(e.Current);
  330. }
  331. } else {
  332. InPlaceMultiply(2);
  333. }
  334. return this;
  335. }
  336. [SpecialName]
  337. public List InPlaceMultiply(int count) {
  338. lock (this) {
  339. int n = this._size;
  340. int newCount = checked(n * count);
  341. EnsureSize(newCount);
  342. int block = n;
  343. int pos = n;
  344. while (pos < newCount) {
  345. Array.Copy(_data, 0, _data, pos, Math.Min(block, newCount - pos));
  346. pos += block;
  347. block *= 2;
  348. }
  349. this._size = newCount;
  350. }
  351. return this;
  352. }
  353. [SpecialName]
  354. public object InPlaceMultiply(Index count) {
  355. return PythonOps.MultiplySequence<List>(InPlaceMultiplyWorker, this, count, true);
  356. }
  357. [SpecialName]
  358. public object InPlaceMultiply(object count) {
  359. int index;
  360. if (Converter.TryConvertToIndex(count, out index)) {
  361. return InPlaceMultiply(index);
  362. }
  363. throw PythonOps.TypeErrorForUnIndexableObject(count);
  364. }
  365. private static List InPlaceMultiplyWorker(List self, int count) {
  366. return self.InPlaceMultiply(count);
  367. }
  368. public virtual object __getslice__(int start, int stop) {
  369. lock (this) {
  370. Slice.FixSliceArguments(_size, ref start, ref stop);
  371. object[] ret = ArrayOps.GetSlice(_data, start, stop);
  372. return new List(ret);
  373. }
  374. }
  375. internal object[] GetSliceAsArray(int start, int stop) {
  376. if (start < 0) start = 0;
  377. if (stop > Count) stop = Count;
  378. lock (this) return ArrayOps.GetSlice(_data, start, stop);
  379. }
  380. public virtual void __setslice__(int start, int stop, object value) {
  381. Slice.FixSliceArguments(_size, ref start, ref stop);
  382. if (value is List) {
  383. SliceNoStep(start, stop, (List)value);
  384. } else {
  385. SliceNoStep(start, stop, value);
  386. }
  387. }
  388. public virtual void __delslice__(int start, int stop) {
  389. lock (this) {
  390. Slice.FixSliceArguments(_size, ref start, ref stop);
  391. if (start > stop) return;
  392. int i = start;
  393. for (int j = stop; j < _size; j++, i++) {
  394. _data[i] = _data[j];
  395. }
  396. _size -= stop - start;
  397. }
  398. }
  399. private static readonly object _boxedOne = ScriptingRuntimeHelpers.Int32ToObject(1);
  400. public virtual object this[Slice slice] {
  401. get {
  402. if (slice == null) throw PythonOps.TypeError("list indices must be integer or slice, not None");
  403. int start, stop, step;
  404. slice.indices(_size, out start, out stop, out step);
  405. if ((step > 0 && start >= stop) || (step < 0 && start <= stop)) return new List();
  406. if (step == 1) {
  407. object[] ret;
  408. lock (this) ret = ArrayOps.GetSlice(_data, start, stop);
  409. return new List(ret);
  410. } else {
  411. // start/stop/step could be near Int32.MaxValue, and simply addition could cause overflow
  412. int n = (int)(step > 0 ? (0L + stop - start + step - 1) / step : (0L + stop - start + step + 1) / step);
  413. object[] ret = new object[n];
  414. lock (this) {
  415. int ri = 0;
  416. for (int i = 0, index = start; i < n; i++, index += step) {
  417. ret[ri++] = _data[index];
  418. }
  419. }
  420. return new List(ret);
  421. }
  422. }
  423. set {
  424. if (slice == null) throw PythonOps.TypeError("list indices must be integer or slice, not None");
  425. if (slice.step != null && (!(slice.step is int) || !slice.step.Equals(_boxedOne))) {
  426. // try to assign back to self: make a copy first
  427. if (this == value) value = new List(value);
  428. if (ValueRequiresNoLocks(value)) {
  429. // we don't need to worry about lock ordering of accesses to the
  430. // RHS & ourselves. We can lock once and avoid repeatedly locking/unlocking
  431. // on each assign.
  432. lock (this) {
  433. slice.DoSliceAssign(this.SliceAssignNoLock, _size, value);
  434. }
  435. } else {
  436. slice.DoSliceAssign(this.SliceAssign, _size, value);
  437. }
  438. } else {
  439. int start, stop, step;
  440. slice.indices(_size, out start, out stop, out step);
  441. List lstVal = value as List;
  442. if (lstVal != null) {
  443. SliceNoStep(start, stop, lstVal);
  444. } else {
  445. SliceNoStep(start, stop, value);
  446. }
  447. }
  448. }
  449. }
  450. private static bool ValueRequiresNoLocks(object value) {
  451. return value is PythonTuple || value is Array || value is FrozenSetCollection;
  452. }
  453. private void SliceNoStep(int start, int stop, List other) {
  454. // We don't lock other here - instead we read it's object array
  455. // and size therefore having a stable view even if it resizes.
  456. // This means if we had a multithreaded app like:
  457. //
  458. // T1 T2 T3
  459. // l1[:] = [1] * 100 l1[:] = [2] * 100 l3[:] = l1[:]
  460. //
  461. // we can end up with both 1s and 2s in the array. This is the
  462. // same as if our set was implemented on top of get/set item where
  463. // we'd take and release the locks repeatedly.
  464. int otherSize = other._size;
  465. object[] otherData = other._data;
  466. lock (this) {
  467. if ((stop - start) == otherSize) {
  468. // we are simply replacing values, this is fast...
  469. for (int i = 0; i < otherSize; i++) {
  470. _data[i + start] = otherData[i];
  471. }
  472. } else {
  473. // we are resizing the array (either bigger or smaller), we
  474. // will copy the data array and replace it all at once.
  475. stop = Math.Max(stop, start);
  476. int newSize = _size - (stop - start) + otherSize;
  477. object[] newData = new object[GetNewSize(newSize)];
  478. for (int i = 0; i < start; i++) {
  479. newData[i] = _data[i];
  480. }
  481. for (int i = 0; i < otherSize; i++) {
  482. newData[i + start] = otherData[i];
  483. }
  484. int writeOffset = otherSize - (stop - start);
  485. for (int i = stop; i < _size; i++) {
  486. newData[i + writeOffset] = _data[i];
  487. }
  488. _size = newSize;
  489. _data = newData;
  490. }
  491. }
  492. }
  493. private void SliceNoStep(int start, int stop, object value) {
  494. // always copy from a List object, even if it's a copy of some user defined enumerator. This
  495. // makes it easy to hold the lock for the duration fo the copy.
  496. IList<object> other = value as IList<object> ?? new List(PythonOps.GetEnumerator(value));
  497. lock (this) {
  498. if ((stop - start) == other.Count) {
  499. // we are simply replacing values, this is fast...
  500. for (int i = 0; i < other.Count; i++) {
  501. _data[i + start] = other[i];
  502. }
  503. } else {
  504. // we are resizing the array (either bigger or smaller), we
  505. // will copy the data array and replace it all at once.
  506. stop = Math.Max(stop, start);
  507. int newSize = _size - (stop - start) + other.Count;
  508. object[] newData = new object[GetNewSize(newSize)];
  509. for (int i = 0; i < start; i++) {
  510. newData[i] = _data[i];
  511. }
  512. for (int i = 0; i < other.Count; i++) {
  513. newData[i + start] = other[i];
  514. }
  515. int writeOffset = other.Count - (stop - start);
  516. for (int i = stop; i < _size; i++) {
  517. newData[i + writeOffset] = _data[i];
  518. }
  519. _size = newSize;
  520. _data = newData;
  521. }
  522. }
  523. }
  524. private void SliceAssign(int index, object value) {
  525. this[index] = value;
  526. }
  527. private void SliceAssignNoLock(int index, object value) {
  528. _data[index] = value;
  529. }
  530. public virtual void __delitem__(int index) {
  531. lock (this) RawDelete(PythonOps.FixIndex(index, _size));
  532. }
  533. public virtual void __delitem__(object index) {
  534. __delitem__(Converter.ConvertToIndex(index));
  535. }
  536. public void __delitem__(Slice slice) {
  537. if (slice == null) throw PythonOps.TypeError("list indices must be integers or slices");
  538. lock (this) {
  539. int start, stop, step;
  540. // slice is sealed, indices can't be user code...
  541. slice.indices(_size, out start, out stop, out step);
  542. if (step > 0 && (start >= stop)) return;
  543. if (step < 0 && (start <= stop)) return;
  544. if (step == 1) {
  545. int i = start;
  546. for (int j = stop; j < _size; j++, i++) {
  547. _data[i] = _data[j];
  548. }
  549. _size -= stop - start;
  550. return;
  551. }
  552. if (step == -1) {
  553. int i = stop + 1;
  554. for (int j = start + 1; j < _size; j++, i++) {
  555. _data[i] = _data[j];
  556. }
  557. _size -= start - stop;
  558. return;
  559. }
  560. if (step < 0) {
  561. // find "start" we will skip in the 1,2,3,... order
  562. int i = start;
  563. while (i > stop) {
  564. i += step;
  565. }
  566. i -= step;
  567. // swap start/stop, make step positive
  568. stop = start + 1;
  569. start = i;
  570. step = -step;
  571. }
  572. int curr, skip, move;
  573. // skip: the next position we should skip
  574. // curr: the next position we should fill in data
  575. // move: the next position we will check
  576. curr = skip = move = start;
  577. while (curr < stop && move < stop) {
  578. if (move != skip) {
  579. _data[curr++] = _data[move];
  580. } else
  581. skip += step;
  582. move++;
  583. }
  584. while (stop < _size) {
  585. _data[curr++] = _data[stop++];
  586. }
  587. _size = curr;
  588. }
  589. }
  590. #endregion
  591. private void RawDelete(int index) {
  592. int len = _size - 1;
  593. _size = len;
  594. object[] tempData = _data;
  595. for (int i = index; i < len; i++) {
  596. tempData[i] = tempData[i + 1];
  597. }
  598. tempData[len] = null;
  599. }
  600. internal void EnsureSize(int needed) {
  601. if (_data.Length >= needed) return;
  602. if (_data.Length == 0) {
  603. // free growth, we wasted nothing
  604. _data = new object[4];
  605. return;
  606. }
  607. int newSize = Math.Max(_size * 3, 10);
  608. while (newSize < needed) newSize *= 2;
  609. #if ALLOC_DEBUG
  610. growthCnt++;
  611. growthSize += _size;
  612. Console.Error.WriteLine("Growing {3} {0} {1} avg {2}", growthCnt, growthSize, growthSize/growthCnt, newSize - _size);
  613. #endif
  614. _data = ArrayOps.CopyArray(_data, newSize);
  615. }
  616. public void append(object item) {
  617. lock (this) {
  618. AddNoLock(item);
  619. }
  620. }
  621. /// <summary>
  622. /// Non-thread safe adder, should only be used by internal callers that
  623. /// haven't yet exposed their list.
  624. /// </summary>
  625. internal void AddNoLock(object item) {
  626. EnsureSize(_size + 1);
  627. _data[_size] = item;
  628. _size += 1;
  629. }
  630. internal void AddNoLockNoDups(object item) {
  631. for (int i = 0; i < _size; i++) {
  632. if (PythonOps.EqualRetBool(_data[i], item)) {
  633. return;
  634. }
  635. }
  636. AddNoLock(item);
  637. }
  638. internal void AppendListNoLockNoDups(List list) {
  639. if (list != null) {
  640. foreach (object item in list) {
  641. AddNoLockNoDups(item);
  642. }
  643. }
  644. }
  645. public int count(object item) {
  646. bool lockTaken = false;
  647. try {
  648. MonitorUtils.Enter(this, ref lockTaken);
  649. int cnt = 0;
  650. for (int i = 0, len = _size; i < len; i++) {
  651. object val = _data[i];
  652. MonitorUtils.Exit(this, ref lockTaken);
  653. try {
  654. if (PythonOps.EqualRetBool(val, item)) cnt++;
  655. } finally {
  656. MonitorUtils.Enter(this, ref lockTaken);
  657. }
  658. }
  659. return cnt;
  660. } finally {
  661. if (lockTaken) {
  662. Monitor.Exit(this);
  663. }
  664. }
  665. }
  666. public void extend([NotNull]List/*!*/ seq) {
  667. using(new OrderedLocker(this, seq)) {
  668. // use the original count for if we're extending this w/ this
  669. int count = seq.Count;
  670. EnsureSize(Count + count);
  671. for (int i = 0; i < count; i++) {
  672. AddNoLock(seq[i]);
  673. }
  674. }
  675. }
  676. public void extend([NotNull]PythonTuple/*!*/ seq) {
  677. lock (this) {
  678. EnsureSize(Count + seq.Count);
  679. for (int i = 0; i < seq.Count; i++) {
  680. AddNoLock(seq[i]);
  681. }
  682. }
  683. }
  684. public void extend(object seq) {
  685. IEnumerator i = PythonOps.GetEnumerator(seq);
  686. if (seq == (object)this) {
  687. List other = new List(i);
  688. i = ((IEnumerable)other).GetEnumerator();
  689. }
  690. while (i.MoveNext()) append(i.Current);
  691. }
  692. public int index(object item) {
  693. return index(item, 0, _size);
  694. }
  695. public int index(object item, int start) {
  696. return index(item, start, _size);
  697. }
  698. public int index(object item, int start, int stop) {
  699. // CPython behavior for index is to only look at the
  700. // original items. If new items are added they
  701. // are ignored, but if items are removed they
  702. // aren't iterated. We therefore get a stable view
  703. // of our data, and then go with the minimum between
  704. // our starting size and ending size.
  705. object[] locData;
  706. int locSize;
  707. lock (this) {
  708. // get a stable view on size / data...
  709. locData = _data;
  710. locSize = _size;
  711. }
  712. start = PythonOps.FixSliceIndex(start, locSize);
  713. stop = PythonOps.FixSliceIndex(stop, locSize);
  714. for (int i = start; i < Math.Min(stop, Math.Min(locSize, _size)); i++) {
  715. if (PythonOps.EqualRetBool(locData[i], item)) return i;
  716. }
  717. throw PythonOps.ValueError("list.index(item): item not in list");
  718. }
  719. public int index(object item, object start) {
  720. return index(item, Converter.ConvertToIndex(start), _size);
  721. }
  722. public int index(object item, object start, object stop) {
  723. return index(item, Converter.ConvertToIndex(start), Converter.ConvertToIndex(stop));
  724. }
  725. public void insert(int index, object value) {
  726. if (index >= _size) {
  727. append(value);
  728. return;
  729. }
  730. lock (this) {
  731. index = PythonOps.FixSliceIndex(index, _size);
  732. EnsureSize(_size + 1);
  733. _size += 1;
  734. for (int i = _size - 1; i > index; i--) {
  735. _data[i] = _data[i - 1];
  736. }
  737. _data[index] = value;
  738. }
  739. }
  740. [PythonHidden]
  741. public void Insert(int index, object value) {
  742. insert(index, value);
  743. }
  744. public object pop() {
  745. if (this._size == 0) throw PythonOps.IndexError("pop off of empty list");
  746. lock (this) {
  747. this._size -= 1;
  748. return _data[this._size];
  749. }
  750. }
  751. public object pop(int index) {
  752. lock (this) {
  753. index = PythonOps.FixIndex(index, _size);
  754. if (_size == 0) throw PythonOps.IndexError("pop off of empty list");
  755. object ret = _data[index];
  756. _size -= 1;
  757. for (int i = index; i < _size; i++) {
  758. _data[i] = _data[i + 1];
  759. }
  760. return ret;
  761. }
  762. }
  763. public void remove(object value) {
  764. lock (this) RawDelete(index(value));
  765. }
  766. void IList.Remove(object value) {
  767. remove(value);
  768. }
  769. public void reverse() {
  770. lock (this) Array.Reverse(_data, 0, _size);
  771. }
  772. internal void reverse(int index, int count) {
  773. lock (this) Array.Reverse(_data, index, count);
  774. }
  775. public void sort(CodeContext/*!*/ context) {
  776. sort(context, null, null, false);
  777. }
  778. public void sort(CodeContext/*!*/ context, object cmp) {
  779. sort(context, cmp, null, false);
  780. }
  781. public void sort(CodeContext/*!*/ context, object cmp, object key) {
  782. sort(context, cmp, key, false);
  783. }
  784. public void sort(CodeContext/*!*/ context,
  785. [DefaultParameterValue(null)] object cmp,
  786. [DefaultParameterValue(null)] object key,
  787. [DefaultParameterValue(false)] bool reverse) {
  788. if (cmp != null) {
  789. PythonOps.Warn3k(context, "the cmp argument is not supported in 3.x");
  790. }
  791. // the empty list is already sorted
  792. if (_size != 0) {
  793. IComparer comparer = PythonContext.GetContext(context).GetComparer(
  794. cmp,
  795. GetComparisonType());
  796. DoSort(context, comparer, key, reverse, 0, _size);
  797. }
  798. }
  799. private Type GetComparisonType() {
  800. if (_size >= 4000) {
  801. // we're big, we can afford a custom comparison call site.
  802. return null;
  803. }
  804. if (_data.Length > 0) {
  805. // use the 1st index to determine the type - we're assuming lists are
  806. // homogeneous
  807. return CompilerHelpers.GetType(_data[0]);
  808. }
  809. return typeof(object);
  810. }
  811. internal void DoSort(CodeContext/*!*/ context, IComparer cmp, object key, bool reverse, int index, int count) {
  812. lock (this) {
  813. object[] sortData = _data;
  814. int sortSize = _size;
  815. try {
  816. // make the list appear empty for the duration of the sort...
  817. _data = ArrayUtils.EmptyObjects;
  818. _size = 0;
  819. if (key != null) {
  820. object[] keys = new object[sortSize];
  821. for (int i = 0; i < sortSize; i++) {
  822. Debug.Assert(_data.Length == 0);
  823. keys[i] = PythonCalls.Call(context, key, sortData[i]);
  824. if (_data.Length != 0) throw PythonOps.ValueError("list mutated while determing keys");
  825. }
  826. sortData = ListMergeSort(sortData, keys, cmp, index, count, reverse);
  827. } else {
  828. sortData = ListMergeSort(sortData, cmp, index, count, reverse);
  829. }
  830. } finally {
  831. // restore the list to it's old data & size (which is now supported appropriately)
  832. _data = sortData;
  833. _size = sortSize;
  834. }
  835. }
  836. }
  837. internal object[] ListMergeSort(object[] sortData, IComparer cmp, int index, int count, bool reverse) {
  838. return ListMergeSort(sortData, null, cmp, index, count, reverse);
  839. }
  840. internal object[] ListMergeSort(object[] sortData, object[] keys, IComparer cmp, int index, int count, bool reverse) {
  841. if (count - index < 2) return sortData; // 1 or less items, we're sorted, quit now...
  842. if (keys == null) keys = sortData;
  843. // list merge sort - stable sort w/ a minimum # of comparisons.
  844. int len = count - index;
  845. // prepare the two lists.
  846. int[] lists = new int[len + 2]; //0 and count + 1 are auxillary fields
  847. lists[0] = 1;
  848. lists[len + 1] = 2;
  849. for (int i = 1; i <= len - 2; i++) {
  850. lists[i] = -(i + 2);
  851. }
  852. lists[len - 1] = lists[len] = 0;
  853. // new pass
  854. for (; ; ) {
  855. // p & q traverse the lists during each pass.
  856. // s is usually the most most recently processed record of the current sublist
  857. // t points to the end of the previously output sublist
  858. int s = 0;
  859. int t = len + 1;
  860. int p = lists[s];
  861. int q = lists[t];
  862. if (q == 0) break; // we're done
  863. for (; ; ) {
  864. // Indexes into the array here are 1 based. 0 is a
  865. // virtual element and so is (len - 1) - they only exist in
  866. // the length array.
  867. if ((p < 1) || (q <= len && DoCompare(keys, cmp, p + index - 1, q + index - 1, reverse))) {
  868. // advance p
  869. if (lists[s] < 0) lists[s] = Math.Abs(p) * -1;
  870. else lists[s] = Math.Abs(p);
  871. s = p;
  872. p = lists[p];
  873. if (p > 0) continue;
  874. // complete the sublist
  875. lists[s] = q;
  876. s = t;
  877. do {
  878. t = q;
  879. q = lists[q];
  880. } while (q > 0);
  881. } else {
  882. // advance q
  883. if (lists[s] < 0) lists[s] = Math.Abs(q) * -1;
  884. else lists[s] = Math.Abs(q);
  885. s = q;
  886. q = lists[q];
  887. if (q > 0) continue;
  888. // Complete the sublist
  889. lists[s] = p;
  890. s = t;
  891. do {
  892. t = p;
  893. p = lists[p];
  894. } while (p > 0);
  895. }
  896. Debug.Assert(p <= 0);
  897. Debug.Assert(q <= 0);
  898. p *= -1;
  899. q *= -1;
  900. if (q == 0) {
  901. if (lists[s] < 0) lists[s] = Math.Abs(p) * -1;
  902. else lists[s] = Math.Abs(p);
  903. lists[t] = 0;
  904. // go back to new pass
  905. break;
  906. } // else keep going
  907. }
  908. }
  909. // use the resulting indices to
  910. // extract the order.
  911. object[] newData = new object[len];
  912. int start = lists[0];
  913. int outIndex = 0;
  914. while (start != 0) {
  915. newData[outIndex++] = sortData[start + index - 1];
  916. start = lists[start];
  917. }
  918. if (sortData.Length != count || index != 0) {
  919. for (int j = 0; j < count; j++) {
  920. sortData[j + index] = newData[j];
  921. }
  922. } else {
  923. sortData = newData;
  924. }
  925. return sortData;
  926. }
  927. /// <summary>
  928. /// Compares the two specified keys
  929. /// </summary>
  930. private bool DoCompare(object[] keys, IComparer cmp, int p, int q, bool reverse) {
  931. Debug.Assert(_data.Length == 0);
  932. int result = cmp.Compare(keys[p], keys[q]);
  933. bool ret = reverse ? (result >= 0) : (result <= 0);
  934. if (_data.Length != 0) throw PythonOps.ValueError("list mutated during sort");
  935. return ret;
  936. }
  937. internal int BinarySearch(int index, int count, object value, IComparer comparer) {
  938. lock (this) return Array.BinarySearch(_data, index, count, value, comparer);
  939. }
  940. internal bool EqualsWorker(List l, IEqualityComparer comparer) {
  941. using (new OrderedLocker(this, l)) {
  942. if (comparer == null) {
  943. return PythonOps.ArraysEqual(_data, _size, l._data, l._size);
  944. } else {
  945. return PythonOps.ArraysEqual(_data, _size, l._data, l._size, comparer);
  946. }
  947. }
  948. }
  949. internal int CompareToWorker(List l) {
  950. return CompareToWorker(l, null);
  951. }
  952. internal int CompareToWorker(List l, IComparer comparer) {
  953. using (new OrderedLocker(this, l)) {
  954. if (comparer == null) {
  955. return PythonOps.CompareArrays(_data, _size, l._data, l._size);
  956. } else {
  957. return PythonOps.CompareArrays(_data, _size, l._data, l._size, comparer);
  958. }
  959. }
  960. }
  961. internal bool FastSwap(int i, int j) {
  962. // ensure i <= j
  963. if (i > j) {
  964. int tmp = i;
  965. i = j;
  966. j = tmp;
  967. }
  968. // bounds checking
  969. if (i < 0 || j >= _size) {
  970. return false;
  971. } else if (i == j) {
  972. return true;
  973. }
  974. object temp = _data[i];
  975. _data[i] = _data[j];
  976. _data[j] = temp;
  977. return true;
  978. }
  979. #region IList Members
  980. bool IList.IsReadOnly {
  981. get { return false; }
  982. }
  983. public virtual object this[int index] {
  984. get {
  985. // no locks works here, we either return an
  986. // old item (as if we were called first) or return
  987. // a current item...
  988. // force reading the array first, _size can change after
  989. object[] data = GetData();
  990. return data[PythonOps.FixIndex(index, _size)];
  991. }
  992. set {
  993. // but we need a lock here incase we're assigning
  994. // while re-sizing.
  995. lock (this) _data[PythonOps.FixIndex(index, _size)] = value;
  996. }
  997. }
  998. public virtual object this[BigInteger index] {
  999. get {
  1000. return this[(int)index];
  1001. }
  1002. set {
  1003. this[(int)index] = value;
  1004. }
  1005. }
  1006. /// <summary>
  1007. /// Supports __index__ on arbitrary types, also prevents __float__
  1008. /// </summary>
  1009. public virtual object this[object index] {
  1010. get {
  1011. return this[Converter.ConvertToIndex(index)];
  1012. }
  1013. set {
  1014. this[Converter.ConvertToIndex(index)] = value;
  1015. }
  1016. }
  1017. [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
  1018. private object[] GetData() {
  1019. return _data;
  1020. }
  1021. [PythonHidden]
  1022. public void RemoveAt(int index) {
  1023. lock (this) RawDelete(index);
  1024. }
  1025. [PythonHidden]
  1026. public bool Contains(object value) {
  1027. return __contains__(value);
  1028. }
  1029. [PythonHidden]
  1030. public void Clear() {
  1031. lock (this) _size = 0;
  1032. }
  1033. [PythonHidden]
  1034. public int IndexOf(object value) {
  1035. // we get a stable view of the list, and if user code
  1036. // clears it then we'll stop iterating.
  1037. object[] locData;
  1038. int locSize;
  1039. lock (this) {
  1040. locData = _data;
  1041. locSize = _size;
  1042. }
  1043. for (int i = 0; i < Math.Min(locSize, _size); i++) {
  1044. if (PythonOps.EqualRetBool(locData[i], value)) return i;
  1045. }
  1046. return -1;
  1047. }
  1048. [PythonHidden]
  1049. public int Add(object value) {
  1050. lock (this) {
  1051. AddNoLock(value);
  1052. return _size - 1;
  1053. }
  1054. }
  1055. bool IList.IsFixedSize {
  1056. get { return false; }
  1057. }
  1058. #endregion
  1059. #region ICollection Members
  1060. bool ICollection.IsSynchronized {
  1061. get { return false; }
  1062. }
  1063. public int Count {
  1064. [PythonHidden]
  1065. get { return _size; }
  1066. }
  1067. [PythonHidden]
  1068. public void CopyTo(Array array, int index) {
  1069. Array.Copy(_data, 0, array, index, _size);
  1070. }
  1071. internal void CopyTo(Array array, int index, int arrayIndex, int count) {
  1072. Array.Copy(_data, index, array, arrayIndex, count);
  1073. }
  1074. object ICollection.SyncRoot {
  1075. get {
  1076. return this;
  1077. }
  1078. }
  1079. #endregion
  1080. #region IEnumerable Members
  1081. [PythonHidden]
  1082. public IEnumerator GetEnumerator() {
  1083. return __iter__();
  1084. }
  1085. #endregion
  1086. #region ICodeFormattable Members
  1087. public virtual string/*!*/ __repr__(CodeContext/*!*/ context) {
  1088. List<object> infinite = PythonOps.GetAndCheckInfinite(this);
  1089. if (infinite == null) {
  1090. return "[...]";
  1091. }
  1092. int index = infinite.Count;
  1093. infinite.Add(this);
  1094. try {
  1095. StringBuilder buf = new StringBuilder();
  1096. buf.Append("[");
  1097. for (int i = 0; i < _size; i++) {
  1098. if (i > 0) buf.Append(", ");
  1099. buf.Append(PythonOps.Repr(context, _data[i]));
  1100. }
  1101. buf.Append("]");
  1102. return buf.ToString();
  1103. } finally {
  1104. System.Diagnostics.Debug.Assert(index == infinite.Count - 1);
  1105. infinite.RemoveAt(index);
  1106. }
  1107. }
  1108. #endregion
  1109. #region IValueEquality Members
  1110. #if CLR2
  1111. int IValueEquality.GetValueHashCode() {
  1112. throw PythonOps.TypeError("list object is unhashable");
  1113. }
  1114. bool IValueEquality.ValueEquals(object other) {
  1115. if (Object.ReferenceEquals(this, other)) return true;
  1116. List l = other as List;
  1117. if (l == null || l.Count != Count) return false;
  1118. return Equals(l);
  1119. }
  1120. #endif
  1121. #endregion
  1122. #region IStructuralEquatable Members
  1123. public const object __hash__ = null;
  1124. int IStructuralEquatable.GetHashCode(IEqualityComparer comparer) {
  1125. if (CompareUtil.Check(this)) {
  1126. return 0;
  1127. }
  1128. int res;
  1129. CompareUtil.Push(this);
  1130. try {
  1131. res = ((IStructuralEquatable)new PythonTuple(this)).GetHashCode(comparer);
  1132. } finally {
  1133. CompareUtil.Pop(this);
  1134. }
  1135. return res;
  1136. }
  1137. bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer) {
  1138. if (Object.ReferenceEquals(this, other)) return true;
  1139. List l = other as List;
  1140. if (l == null || l.Count != Count) return false;
  1141. return Equals(l, comparer);
  1142. }
  1143. #endregion
  1144. #region ICollection<object> Members
  1145. void ICollection<object>.Add(object item) {
  1146. append(item);
  1147. }
  1148. public void CopyTo(object[] array, int arrayIndex) {
  1149. for (int i = 0; i < Count; i++) {
  1150. array[arrayIndex + i] = this[i];
  1151. }
  1152. }
  1153. bool ICollection<object>.IsReadOnly {
  1154. get { return ((IList)this).IsReadOnly; }
  1155. }
  1156. [PythonHidden]
  1157. public bool Remove(object item) {
  1158. if (this.__contains__(item)) {
  1159. this.remove(item);
  1160. return true;
  1161. }
  1162. return false;
  1163. }
  1164. #endregion
  1165. #region IEnumerable<object> Members
  1166. IEnumerator<object> IEnumerable<object>.GetEnumerator() {
  1167. return new IEnumeratorOfTWrapper<object>(((IEnumerable)this).GetEnumerator());
  1168. }
  1169. #endregion
  1170. private bool Equals(List other) {
  1171. return Equals(other, null);
  1172. }
  1173. private bool Equals(List other, IEqualityComparer comparer) {
  1174. CompareUtil.Push(this, other);
  1175. try {
  1176. return EqualsWorker(other, comparer);
  1177. } finally {
  1178. CompareUtil.Pop(this, other);
  1179. }
  1180. }
  1181. internal int CompareTo(List other) {
  1182. return CompareTo(other, null);
  1183. }
  1184. internal int CompareTo(List other, IComparer comparer) {
  1185. CompareUtil.Push(this, other);
  1186. try {
  1187. return CompareToWorker(other, comparer);
  1188. } finally {
  1189. CompareUtil.Pop(this, other);
  1190. }
  1191. }
  1192. #region Rich Comparison Members
  1193. [return: MaybeNotImplemented]
  1194. public static object operator > (List self, object other) {
  1195. List l = other as List;
  1196. if (l == null) return NotImplementedType.Value;
  1197. return self.CompareTo(l) > 0 ? ScriptingRuntimeHelpers.True : ScriptingRuntimeHelpers.False;
  1198. }
  1199. [return: MaybeNotImplemented]
  1200. public static object operator <(List self, object other) {
  1201. List l = other as List;
  1202. if (l == null) return NotImplementedType.Value;
  1203. return self.CompareTo(l) < 0 ? ScriptingRuntimeHelpers.True : ScriptingRuntimeHelpers.False;
  1204. }
  1205. [return: MaybeNotImplemented]
  1206. public static object operator >=(List self, object other) {
  1207. List l = other as List;
  1208. if (l == null) return NotImplementedType.Value;
  1209. return self.CompareTo(l) >= 0 ? ScriptingRuntimeHelpers.True : ScriptingRuntimeHelpers.False;
  1210. }
  1211. [return: MaybeNotImplemented]
  1212. public static object operator <=(List self, object other) {
  1213. List l = other as List;
  1214. if (l == null) return NotImplementedType.Value;
  1215. return self.CompareTo(l) <= 0 ? ScriptingRuntimeHelpers.True : ScriptingRuntimeHelpers.False;
  1216. }
  1217. #endregion
  1218. #region IStructuralComparable Members
  1219. int IStructuralComparable.CompareTo(object other, IComparer comparer) {
  1220. List l = other as List;
  1221. if (l == null) {
  1222. throw new ValueErrorException("expected List");
  1223. }
  1224. return CompareTo(l, comparer);
  1225. }
  1226. #endregion
  1227. }
  1228. [PythonType("listiterator")]
  1229. public sealed class ListIterator : IEnumerator, IEnumerable, IEnumerable<o

Large files files are truncated, but you can click here to view the full file