PageRenderTime 50ms CodeModel.GetById 14ms RepoModel.GetById 1ms app.codeStats 0ms

/mcs/class/Mono.C5/C5/linkedlists/LinkedList.cs

https://bitbucket.org/danipen/mono
C# | 3919 lines | 2791 code | 357 blank | 771 comment | 695 complexity | 6d21a466f36b04d570234993d218f167 MD5 | raw file
Possible License(s): Unlicense, Apache-2.0, LGPL-2.0, MPL-2.0-no-copyleft-exception, CC-BY-SA-3.0, GPL-2.0

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

  1. /*
  2. Copyright (c) 2003-2006 Niels Kokholm and Peter Sestoft
  3. Permission is hereby granted, free of charge, to any person obtaining a copy
  4. of this software and associated documentation files (the "Software"), to deal
  5. in the Software without restriction, including without limitation the rights
  6. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  7. copies of the Software, and to permit persons to whom the Software is
  8. furnished to do so, subject to the following conditions:
  9. The above copyright notice and this permission notice shall be included in
  10. all copies or substantial portions of the Software.
  11. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  12. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  13. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  14. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  15. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  16. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  17. SOFTWARE.
  18. */
  19. #define HASHINDEXnot
  20. using System;
  21. using System.Diagnostics;
  22. using SCG = System.Collections.Generic;
  23. namespace C5
  24. {
  25. /// <summary>
  26. /// A list collection class based on a doubly linked list data structure.
  27. /// </summary>
  28. [Serializable]
  29. public class LinkedList<T> : SequencedBase<T>, IList<T>, SCG.IList<T>
  30. #if HASHINDEX
  31. #else
  32. , IStack<T>, IQueue<T>
  33. #endif
  34. {
  35. #region Fields
  36. /// <summary>
  37. /// IExtensible.Add(T) always does AddLast(T), fIFO determines
  38. /// if T Remove() does RemoveFirst() or RemoveLast()
  39. /// </summary>
  40. bool fIFO = true;
  41. #region Events
  42. /// <summary>
  43. ///
  44. /// </summary>
  45. /// <value></value>
  46. public override EventTypeEnum ListenableEvents { get { return underlying == null ? EventTypeEnum.All : EventTypeEnum.None; } }
  47. #endregion
  48. //Invariant: startsentinel != null && endsentinel != null
  49. //If size==0: startsentinel.next == endsentinel && endsentinel.prev == startsentinel
  50. //Else: startsentinel.next == First && endsentinel.prev == Last)
  51. /// <summary>
  52. /// Node to the left of first node
  53. /// </summary>
  54. Node startsentinel;
  55. /// <summary>
  56. /// Node to the right of last node
  57. /// </summary>
  58. Node endsentinel;
  59. /// <summary>
  60. /// Offset of this view in underlying list
  61. /// </summary>
  62. #if HASHINDEX
  63. int? offset;
  64. #else
  65. int offset;
  66. #endif
  67. /// <summary>
  68. /// underlying list of this view (or null for the underlying list)
  69. /// </summary>
  70. LinkedList<T> underlying;
  71. //Note: all views will have the same views list since all view objects are created by MemberwiseClone()
  72. WeakViewList<LinkedList<T>> views;
  73. WeakViewList<LinkedList<T>>.Node myWeakReference;
  74. /// <summary>
  75. /// Has this list or view not been invalidated by some operation (by someone calling Dispose())
  76. /// </summary>
  77. bool isValid = true;
  78. #if HASHINDEX
  79. HashDictionary<T, Node> dict;
  80. /// <summary>
  81. /// Number of taggroups
  82. /// </summary>
  83. int taggroups;
  84. /// <summary>
  85. ///
  86. /// </summary>
  87. /// <value></value>
  88. int Taggroups
  89. {
  90. get { return underlying == null ? taggroups : underlying.taggroups; }
  91. set { if (underlying == null) taggroups = value; else underlying.taggroups = value; }
  92. }
  93. #endif
  94. #endregion
  95. #region Util
  96. bool equals(T i1, T i2) { return itemequalityComparer.Equals(i1, i2); }
  97. #region Check utilities
  98. /// <summary>
  99. /// Check if it is valid to perform updates and increment stamp of
  100. /// underlying if this is a view.
  101. /// <para>This method should be called in every public modifying
  102. /// methods before any modifications are performed.
  103. /// </para>
  104. /// </summary>
  105. /// <exception cref="InvalidOperationException"> if check fails.</exception>
  106. protected override void updatecheck()
  107. {
  108. validitycheck();
  109. base.updatecheck();
  110. if (underlying != null)
  111. underlying.stamp++;
  112. }
  113. /// <summary>
  114. /// Check if we are a view that the underlyinglist has only been updated through us.
  115. /// <br/>
  116. /// This method should be called from enumerators etc to guard against
  117. /// modification of the base collection.
  118. /// </summary>
  119. /// <exception cref="InvalidOperationException"> if check fails.</exception>
  120. void validitycheck()
  121. {
  122. if (!isValid)
  123. throw new ViewDisposedException();
  124. }
  125. /// <summary>
  126. /// Check that the list has not been updated since a particular time.
  127. /// </summary>
  128. /// <param name="stamp">The stamp indicating the time.</param>
  129. /// <exception cref="CollectionModifiedException"> if check fails.</exception>
  130. protected override void modifycheck(int stamp)
  131. {
  132. validitycheck();
  133. if ((underlying != null ? underlying.stamp : this.stamp) != stamp)
  134. throw new CollectionModifiedException();
  135. }
  136. #endregion
  137. #region Searching
  138. bool contains(T item, out Node node)
  139. {
  140. #if HASHINDEX
  141. if (dict.Find(item, out node))
  142. return insideview(node);
  143. #else
  144. //TODO: search from both ends? Or search from the end selected by FIFO?
  145. node = startsentinel.next;
  146. while (node != endsentinel)
  147. {
  148. if (equals(item, node.item))
  149. return true;
  150. node = node.next;
  151. }
  152. #endif
  153. return false;
  154. }
  155. /// <summary>
  156. /// Search forwards from a node for a node with a particular item.
  157. /// </summary>
  158. /// <param name="item">The item to look for</param>
  159. /// <param name="node">On input, the node to start at. If item was found, the node found on output.</param>
  160. /// <param name="index">If node was found, the value will be the number of links followed higher than
  161. /// the value on input. If item was not found, the value on output is undefined.</param>
  162. /// <returns>True if node was found.</returns>
  163. bool find(T item, ref Node node, ref int index)
  164. {
  165. while (node != endsentinel)
  166. {
  167. //if (item.Equals(node.item))
  168. if (itemequalityComparer.Equals(item, node.item))
  169. return true;
  170. index++;
  171. node = node.next;
  172. }
  173. return false;
  174. }
  175. bool dnif(T item, ref Node node, ref int index)
  176. {
  177. while (node != startsentinel)
  178. {
  179. //if (item.Equals(node.item))
  180. if (itemequalityComparer.Equals(item, node.item))
  181. return true;
  182. index--;
  183. node = node.prev;
  184. }
  185. return false;
  186. }
  187. #if HASHINDEX
  188. bool insideview(Node node)
  189. {
  190. if (underlying == null)
  191. return true;
  192. return (startsentinel.precedes(node) && node.precedes(endsentinel));
  193. }
  194. #endif
  195. #endregion
  196. #region Indexing
  197. /// <summary>
  198. /// Return the node at position pos
  199. /// </summary>
  200. /// <param name="pos"></param>
  201. /// <returns></returns>
  202. Node get(int pos)
  203. {
  204. if (pos < 0 || pos >= size)
  205. throw new IndexOutOfRangeException();
  206. else if (pos < size / 2)
  207. { // Closer to front
  208. Node node = startsentinel;
  209. for (int i = 0; i <= pos; i++)
  210. node = node.next;
  211. return node;
  212. }
  213. else
  214. { // Closer to end
  215. Node node = endsentinel;
  216. for (int i = size; i > pos; i--)
  217. node = node.prev;
  218. return node;
  219. }
  220. }
  221. /// <summary>
  222. /// Find the distance from pos to the set given by positions. Return the
  223. /// signed distance as return value and as an out parameter, the
  224. /// array index of the nearest position. This is used for up to length 5 of
  225. /// positions, and we do not assume it is sorted.
  226. /// </summary>
  227. /// <param name="pos"></param>
  228. /// <param name="positions"></param>
  229. /// <param name="nearest"></param>
  230. /// <returns></returns>
  231. int dist(int pos, out int nearest, int[] positions)
  232. {
  233. nearest = -1;
  234. int bestdist = int.MaxValue;
  235. int signeddist = bestdist;
  236. for (int i = 0; i < positions.Length; i++)
  237. {
  238. int thisdist = positions[i] - pos;
  239. if (thisdist >= 0 && thisdist < bestdist) { nearest = i; bestdist = thisdist; signeddist = thisdist; }
  240. if (thisdist < 0 && -thisdist < bestdist) { nearest = i; bestdist = -thisdist; signeddist = thisdist; }
  241. }
  242. return signeddist;
  243. }
  244. /// <summary>
  245. /// Find the node at position pos, given known positions of several nodes.
  246. /// </summary>
  247. /// <param name="pos"></param>
  248. /// <param name="positions"></param>
  249. /// <param name="nodes"></param>
  250. /// <returns></returns>
  251. Node get(int pos, int[] positions, Node[] nodes)
  252. {
  253. int nearest;
  254. int delta = dist(pos, out nearest, positions);
  255. Node node = nodes[nearest];
  256. if (delta > 0)
  257. for (int i = 0; i < delta; i++)
  258. node = node.prev;
  259. else
  260. for (int i = 0; i > delta; i--)
  261. node = node.next;
  262. return node;
  263. }
  264. /// <summary>
  265. /// Get nodes at positions p1 and p2, given nodes at several positions.
  266. /// </summary>
  267. /// <param name="p1"></param>
  268. /// <param name="p2"></param>
  269. /// <param name="n1"></param>
  270. /// <param name="n2"></param>
  271. /// <param name="positions"></param>
  272. /// <param name="nodes"></param>
  273. void getPair(int p1, int p2, out Node n1, out Node n2, int[] positions, Node[] nodes)
  274. {
  275. int nearest1, nearest2;
  276. int delta1 = dist(p1, out nearest1, positions), d1 = delta1 < 0 ? -delta1 : delta1;
  277. int delta2 = dist(p2, out nearest2, positions), d2 = delta2 < 0 ? -delta2 : delta2;
  278. if (d1 < d2)
  279. {
  280. n1 = get(p1, positions, nodes);
  281. n2 = get(p2, new int[] { positions[nearest2], p1 }, new Node[] { nodes[nearest2], n1 });
  282. }
  283. else
  284. {
  285. n2 = get(p2, positions, nodes);
  286. n1 = get(p1, new int[] { positions[nearest1], p2 }, new Node[] { nodes[nearest1], n2 });
  287. }
  288. }
  289. #endregion
  290. #region Insertion
  291. #if HASHINDEX
  292. void insert(int index, Node succ, T item)
  293. {
  294. Node newnode = new Node(item);
  295. if (dict.FindOrAdd(item, ref newnode))
  296. throw new DuplicateNotAllowedException("Item already in indexed list");
  297. insertNode(true, succ, newnode);
  298. }
  299. /// <summary>
  300. /// Insert a Node before another one. Unchecked version.
  301. /// </summary>
  302. /// <param name="succ">The successor to be</param>
  303. /// <param name="newnode">Node to insert</param>
  304. /// <param name="updateViews">update overlapping view in this call</param>
  305. void insertNode(bool updateViews, Node succ, Node newnode)
  306. {
  307. newnode.next = succ;
  308. Node pred = newnode.prev = succ.prev;
  309. succ.prev.next = newnode;
  310. succ.prev = newnode;
  311. size++;
  312. if (underlying != null)
  313. underlying.size++;
  314. settag(newnode);
  315. if (updateViews)
  316. fixViewsAfterInsert(succ, pred, 1, 0);
  317. }
  318. #else
  319. /// <summary>
  320. ///
  321. /// </summary>
  322. /// <param name="index">The index in this view</param>
  323. /// <param name="succ"></param>
  324. /// <param name="item"></param>
  325. /// <returns></returns>
  326. Node insert(int index, Node succ, T item)
  327. {
  328. Node newnode = new Node(item, succ.prev, succ);
  329. succ.prev.next = newnode;
  330. succ.prev = newnode;
  331. size++;
  332. if (underlying != null)
  333. underlying.size++;
  334. fixViewsAfterInsert(succ, newnode.prev, 1, Offset + index);
  335. return newnode;
  336. }
  337. #endif
  338. #endregion
  339. #region Removal
  340. T remove(Node node, int index)
  341. {
  342. fixViewsBeforeSingleRemove(node, Offset + index);
  343. node.prev.next = node.next;
  344. node.next.prev = node.prev;
  345. size--;
  346. if (underlying != null)
  347. underlying.size--;
  348. #if HASHINDEX
  349. removefromtaggroup(node);
  350. #endif
  351. return node.item;
  352. }
  353. #if HASHINDEX
  354. private bool dictremove(T item, out Node node)
  355. {
  356. if (underlying == null)
  357. {
  358. if (!dict.Remove(item, out node))
  359. return false;
  360. }
  361. else
  362. {
  363. //We cannot avoid calling dict twice - have to intersperse the listorder test!
  364. if (!contains(item, out node))
  365. return false;
  366. dict.Remove(item);
  367. }
  368. return true;
  369. }
  370. #endif
  371. #endregion
  372. #region fixView utilities
  373. /// <summary>
  374. ///
  375. /// </summary>
  376. /// <param name="added">The actual number of inserted nodes</param>
  377. /// <param name="pred">The predecessor of the inserted nodes</param>
  378. /// <param name="succ">The successor of the added nodes</param>
  379. /// <param name="realInsertionIndex"></param>
  380. void fixViewsAfterInsert(Node succ, Node pred, int added, int realInsertionIndex)
  381. {
  382. if (views != null)
  383. foreach (LinkedList<T> view in views)
  384. {
  385. if (view != this)
  386. {
  387. #if HASHINDEX
  388. if (pred.precedes(view.startsentinel) || (view.startsentinel == pred && view.size > 0))
  389. view.offset += added;
  390. if (view.startsentinel.precedes(pred) && succ.precedes(view.endsentinel))
  391. view.size += added;
  392. if (view.startsentinel == pred && view.size > 0)
  393. view.startsentinel = succ.prev;
  394. if (view.endsentinel == succ)
  395. view.endsentinel = pred.next;
  396. #else
  397. if (view.Offset == realInsertionIndex && view.size > 0)
  398. view.startsentinel = succ.prev;
  399. if (view.Offset + view.size == realInsertionIndex)
  400. view.endsentinel = pred.next;
  401. if (view.Offset < realInsertionIndex && view.Offset + view.size > realInsertionIndex)
  402. view.size += added;
  403. if (view.Offset > realInsertionIndex || (view.Offset == realInsertionIndex && view.size > 0))
  404. view.offset += added;
  405. #endif
  406. }
  407. }
  408. }
  409. void fixViewsBeforeSingleRemove(Node node, int realRemovalIndex)
  410. {
  411. if (views != null)
  412. foreach (LinkedList<T> view in views)
  413. {
  414. if (view != this)
  415. {
  416. #if HASHINDEX
  417. if (view.startsentinel.precedes(node) && node.precedes(view.endsentinel))
  418. view.size--;
  419. if (!view.startsentinel.precedes(node))
  420. view.offset--;
  421. if (view.startsentinel == node)
  422. view.startsentinel = node.prev;
  423. if (view.endsentinel == node)
  424. view.endsentinel = node.next;
  425. #else
  426. if (view.offset - 1 == realRemovalIndex)
  427. view.startsentinel = node.prev;
  428. if (view.offset + view.size == realRemovalIndex)
  429. view.endsentinel = node.next;
  430. if (view.offset <= realRemovalIndex && view.offset + view.size > realRemovalIndex)
  431. view.size--;
  432. if (view.offset > realRemovalIndex)
  433. view.offset--;
  434. #endif
  435. }
  436. }
  437. }
  438. #if HASHINDEX
  439. #else
  440. void fixViewsBeforeRemove(int start, int count, Node first, Node last)
  441. {
  442. int clearend = start + count - 1;
  443. if (views != null)
  444. foreach (LinkedList<T> view in views)
  445. {
  446. if (view == this)
  447. continue;
  448. int viewoffset = view.Offset, viewend = viewoffset + view.size - 1;
  449. //sentinels
  450. if (start < viewoffset && viewoffset - 1 <= clearend)
  451. view.startsentinel = first.prev;
  452. if (start <= viewend + 1 && viewend < clearend)
  453. view.endsentinel = last.next;
  454. //offsets and sizes
  455. if (start < viewoffset)
  456. {
  457. if (clearend < viewoffset)
  458. view.offset = viewoffset - count;
  459. else
  460. {
  461. view.offset = start;
  462. view.size = clearend < viewend ? viewend - clearend : 0;
  463. }
  464. }
  465. else if (start <= viewend)
  466. view.size = clearend <= viewend ? view.size - count : start - viewoffset;
  467. }
  468. }
  469. #endif
  470. /// <summary>
  471. ///
  472. /// </summary>
  473. /// <param name="otherView"></param>
  474. /// <returns>The position of View(otherOffset, otherSize) wrt. this view</returns>
  475. MutualViewPosition viewPosition(LinkedList<T> otherView)
  476. {
  477. #if HASHINDEX
  478. Node otherstartsentinel = otherView.startsentinel, otherendsentinel = otherView.endsentinel,
  479. first = startsentinel.next, last = endsentinel.prev,
  480. otherfirst = otherstartsentinel.next, otherlast = otherendsentinel.prev;
  481. if (last.precedes(otherfirst) || otherlast.precedes(first))
  482. return MutualViewPosition.NonOverlapping;
  483. if (size == 0 || (otherstartsentinel.precedes(first) && last.precedes(otherendsentinel)))
  484. return MutualViewPosition.Contains;
  485. if (otherView.size == 0 || (startsentinel.precedes(otherfirst) && otherlast.precedes(endsentinel)))
  486. return MutualViewPosition.ContainedIn;
  487. return MutualViewPosition.Overlapping;
  488. #else
  489. int end = offset + size, otherOffset = otherView.offset, otherSize = otherView.size, otherEnd = otherOffset + otherSize;
  490. if (otherOffset >= end || otherEnd <= offset)
  491. return MutualViewPosition.NonOverlapping;
  492. if (size == 0 || (otherOffset <= offset && end <= otherEnd))
  493. return MutualViewPosition.Contains;
  494. if (otherSize == 0 || (offset <= otherOffset && otherEnd <= end))
  495. return MutualViewPosition.ContainedIn;
  496. return MutualViewPosition.Overlapping;
  497. #endif
  498. }
  499. void disposeOverlappingViews(bool reverse)
  500. {
  501. if (views != null)
  502. {
  503. foreach (LinkedList<T> view in views)
  504. {
  505. if (view != this)
  506. {
  507. switch (viewPosition(view))
  508. {
  509. case MutualViewPosition.ContainedIn:
  510. if (reverse)
  511. { }
  512. else
  513. view.Dispose();
  514. break;
  515. case MutualViewPosition.Overlapping:
  516. view.Dispose();
  517. break;
  518. case MutualViewPosition.Contains:
  519. case MutualViewPosition.NonOverlapping:
  520. break;
  521. }
  522. }
  523. }
  524. }
  525. }
  526. #endregion
  527. #endregion
  528. #region Constructors
  529. /// <summary>
  530. /// Create a linked list with en external item equalityComparer
  531. /// </summary>
  532. /// <param name="itemequalityComparer">The external equalityComparer</param>
  533. public LinkedList(SCG.IEqualityComparer<T> itemequalityComparer)
  534. : base(itemequalityComparer)
  535. {
  536. offset = 0;
  537. size = stamp = 0;
  538. startsentinel = new Node(default(T));
  539. endsentinel = new Node(default(T));
  540. startsentinel.next = endsentinel;
  541. endsentinel.prev = startsentinel;
  542. #if HASHINDEX
  543. //It is important that the sentinels are different:
  544. startsentinel.taggroup = new TagGroup();
  545. startsentinel.taggroup.tag = int.MinValue;
  546. startsentinel.taggroup.count = 0;
  547. endsentinel.taggroup = new TagGroup();
  548. endsentinel.taggroup.tag = int.MaxValue;
  549. endsentinel.taggroup.count = 0;
  550. dict = new HashDictionary<T, Node>(itemequalityComparer);
  551. #endif
  552. }
  553. /// <summary>
  554. /// Create a linked list with the natural item equalityComparer
  555. /// </summary>
  556. public LinkedList() : this(EqualityComparer<T>.Default) { }
  557. #endregion
  558. #region Node nested class
  559. /// <summary>
  560. /// An individual cell in the linked list
  561. /// </summary>
  562. [Serializable]
  563. class Node
  564. {
  565. public Node prev;
  566. public Node next;
  567. public T item;
  568. #region Tag support
  569. #if HASHINDEX
  570. internal int tag;
  571. internal TagGroup taggroup;
  572. internal bool precedes(Node that)
  573. {
  574. //Debug.Assert(taggroup != null, "taggroup field null");
  575. //Debug.Assert(that.taggroup != null, "that.taggroup field null");
  576. int t1 = taggroup.tag;
  577. int t2 = that.taggroup.tag;
  578. return t1 < t2 ? true : t1 > t2 ? false : tag < that.tag;
  579. }
  580. #endif
  581. #endregion
  582. [Tested]
  583. internal Node(T item) { this.item = item; }
  584. [Tested]
  585. internal Node(T item, Node prev, Node next)
  586. {
  587. this.item = item; this.prev = prev; this.next = next;
  588. }
  589. public override string ToString()
  590. {
  591. #if HASHINDEX
  592. return String.Format("Node: (item={0}, tag={1})", item, tag);
  593. #else
  594. return String.Format("Node(item={0})", item);
  595. #endif
  596. }
  597. }
  598. #endregion
  599. #region Taggroup nested class and tag maintenance utilities
  600. #if HASHINDEX
  601. /// <summary>
  602. /// A group of nodes with the same high tag. Purpose is to be
  603. /// able to tell the sequence order of two nodes without having to scan through
  604. /// the list.
  605. /// </summary>
  606. [Serializable]
  607. class TagGroup
  608. {
  609. internal int tag, count;
  610. internal Node first, last;
  611. /// <summary>
  612. /// Pretty print a tag group
  613. /// </summary>
  614. /// <returns>Formatted tag group</returns>
  615. public override string ToString()
  616. { return String.Format("TagGroup(tag={0}, cnt={1}, fst={2}, lst={3})", tag, count, first, last); }
  617. }
  618. //Constants for tag maintenance
  619. const int wordsize = 32;
  620. const int lobits = 3;
  621. const int hibits = lobits + 1;
  622. const int losize = 1 << lobits;
  623. const int hisize = 1 << hibits;
  624. const int logwordsize = 5;
  625. TagGroup gettaggroup(Node pred, Node succ, out int lowbound, out int highbound)
  626. {
  627. TagGroup predgroup = pred.taggroup, succgroup = succ.taggroup;
  628. if (predgroup == succgroup)
  629. {
  630. lowbound = pred.tag + 1;
  631. highbound = succ.tag - 1;
  632. return predgroup;
  633. }
  634. else if (predgroup.first != null)
  635. {
  636. lowbound = pred.tag + 1;
  637. highbound = int.MaxValue;
  638. return predgroup;
  639. }
  640. else if (succgroup.first != null)
  641. {
  642. lowbound = int.MinValue;
  643. highbound = succ.tag - 1;
  644. return succgroup;
  645. }
  646. else
  647. {
  648. lowbound = int.MinValue;
  649. highbound = int.MaxValue;
  650. return new TagGroup();
  651. }
  652. }
  653. /// <summary>
  654. /// Put a tag on a node (already inserted in the list). Split taggroups and renumber as
  655. /// necessary.
  656. /// </summary>
  657. /// <param name="node">The node to tag</param>
  658. void settag(Node node)
  659. {
  660. Node pred = node.prev, succ = node.next;
  661. TagGroup predgroup = pred.taggroup, succgroup = succ.taggroup;
  662. if (predgroup == succgroup)
  663. {
  664. node.taggroup = predgroup;
  665. predgroup.count++;
  666. if (pred.tag + 1 == succ.tag)
  667. splittaggroup(predgroup);
  668. else
  669. node.tag = (pred.tag + 1) / 2 + (succ.tag - 1) / 2;
  670. }
  671. else if (predgroup.first != null)
  672. {
  673. node.taggroup = predgroup;
  674. predgroup.last = node;
  675. predgroup.count++;
  676. if (pred.tag == int.MaxValue)
  677. splittaggroup(predgroup);
  678. else
  679. node.tag = pred.tag / 2 + int.MaxValue / 2 + 1;
  680. }
  681. else if (succgroup.first != null)
  682. {
  683. node.taggroup = succgroup;
  684. succgroup.first = node;
  685. succgroup.count++;
  686. if (succ.tag == int.MinValue)
  687. splittaggroup(node.taggroup);
  688. else
  689. node.tag = int.MinValue / 2 + (succ.tag - 1) / 2;
  690. }
  691. else
  692. {
  693. Debug.Assert(Taggroups == 0);
  694. TagGroup newgroup = new TagGroup();
  695. Taggroups = 1;
  696. node.taggroup = newgroup;
  697. newgroup.first = newgroup.last = node;
  698. newgroup.count = 1;
  699. return;
  700. }
  701. }
  702. /// <summary>
  703. /// Remove a node from its taggroup.
  704. /// <br/> When this is called, node must already have been removed from the underlying list
  705. /// </summary>
  706. /// <param name="node">The node to remove</param>
  707. void removefromtaggroup(Node node)
  708. {
  709. TagGroup taggroup = node.taggroup;
  710. if (--taggroup.count == 0)
  711. {
  712. Taggroups--;
  713. return;
  714. }
  715. if (node == taggroup.first)
  716. taggroup.first = node.next;
  717. if (node == taggroup.last)
  718. taggroup.last = node.prev;
  719. //node.taggroup = null;
  720. if (taggroup.count != losize || Taggroups == 1)
  721. return;
  722. TagGroup otg;
  723. // bug20070911:
  724. Node neighbor;
  725. if ((neighbor = taggroup.first.prev) != startsentinel
  726. && (otg = neighbor.taggroup).count <= losize)
  727. taggroup.first = otg.first;
  728. else if ((neighbor = taggroup.last.next) != endsentinel
  729. && (otg = neighbor.taggroup).count <= losize)
  730. taggroup.last = otg.last;
  731. else
  732. return;
  733. Node n = otg.first;
  734. for (int i = 0, length = otg.count; i < length; i++)
  735. {
  736. n.taggroup = taggroup;
  737. n = n.next;
  738. }
  739. taggroup.count += otg.count;
  740. Taggroups--;
  741. n = taggroup.first;
  742. const int ofs = wordsize - hibits;
  743. for (int i = 0, count = taggroup.count; i < count; i++)
  744. {
  745. n.tag = (i - losize) << ofs; //(i-8)<<28
  746. n = n.next;
  747. }
  748. }
  749. /// <summary>
  750. /// Split a tag group to make rom for more tags.
  751. /// </summary>
  752. /// <param name="taggroup">The tag group</param>
  753. void splittaggroup(TagGroup taggroup)
  754. {
  755. Node n = taggroup.first;
  756. int ptgt = taggroup.first.prev.taggroup.tag;
  757. int ntgt = taggroup.last.next.taggroup.tag;
  758. Debug.Assert(ptgt + 1 <= ntgt - 1);
  759. int ofs = wordsize - hibits;
  760. int newtgs = (taggroup.count - 1) / hisize;
  761. int tgtdelta = (int)((ntgt + 0.0 - ptgt) / (newtgs + 2)), tgtag = ptgt;
  762. tgtdelta = tgtdelta == 0 ? 1 : tgtdelta;
  763. for (int j = 0; j < newtgs; j++)
  764. {
  765. TagGroup newtaggroup = new TagGroup();
  766. newtaggroup.tag = (tgtag = tgtag >= ntgt - tgtdelta ? ntgt : tgtag + tgtdelta);
  767. newtaggroup.first = n;
  768. newtaggroup.count = hisize;
  769. for (int i = 0; i < hisize; i++)
  770. {
  771. n.taggroup = newtaggroup;
  772. n.tag = (i - losize) << ofs; //(i-8)<<28
  773. n = n.next;
  774. }
  775. newtaggroup.last = n.prev;
  776. }
  777. int rest = taggroup.count - hisize * newtgs;
  778. taggroup.first = n;
  779. taggroup.count = rest;
  780. taggroup.tag = (tgtag = tgtag >= ntgt - tgtdelta ? ntgt : tgtag + tgtdelta); ofs--;
  781. for (int i = 0; i < rest; i++)
  782. {
  783. n.tag = (i - hisize) << ofs; //(i-16)<<27
  784. n = n.next;
  785. }
  786. taggroup.last = n.prev;
  787. Taggroups += newtgs;
  788. if (tgtag == ntgt)
  789. redistributetaggroups(taggroup);
  790. }
  791. private void redistributetaggroups(TagGroup taggroup)
  792. {
  793. TagGroup pred = taggroup, succ = taggroup, tmp;
  794. double limit = 1, bigt = Math.Pow(Taggroups, 1.0 / 30);//?????
  795. int bits = 1, count = 1, lowmask = 0, himask = 0, target = 0;
  796. do
  797. {
  798. bits++;
  799. lowmask = (1 << bits) - 1;
  800. himask = ~lowmask;
  801. target = taggroup.tag & himask;
  802. while ((tmp = pred.first.prev.taggroup).first != null && (tmp.tag & himask) == target)
  803. { count++; pred = tmp; }
  804. while ((tmp = succ.last.next.taggroup).last != null && (tmp.tag & himask) == target)
  805. { count++; succ = tmp; }
  806. limit *= bigt;
  807. } while (count > limit);
  808. //redistibute tags
  809. int lob = pred.first.prev.taggroup.tag, upb = succ.last.next.taggroup.tag;
  810. int delta = upb / (count + 1) - lob / (count + 1);
  811. Debug.Assert(delta > 0);
  812. for (int i = 0; i < count; i++)
  813. {
  814. pred.tag = lob + (i + 1) * delta;
  815. pred = pred.last.next.taggroup;
  816. }
  817. }
  818. #endif
  819. #endregion
  820. #region Position, PositionComparer and ViewHandler nested types
  821. class PositionComparer : SCG.IComparer<Position>
  822. {
  823. static PositionComparer _default;
  824. PositionComparer() { }
  825. public static PositionComparer Default { get { return _default ?? (_default = new PositionComparer()); } }
  826. public int Compare(Position a, Position b)
  827. {
  828. #if HASHINDEX
  829. return a.Endpoint == b.Endpoint ? 0 : a.Endpoint.precedes(b.Endpoint) ? -1 : 1;
  830. #else
  831. return a.Index.CompareTo(b.Index);
  832. #endif
  833. }
  834. }
  835. /// <summary>
  836. /// During RemoveAll, we need to cache the original endpoint indices of views
  837. /// </summary>
  838. struct Position
  839. {
  840. public readonly LinkedList<T> View;
  841. public bool Left;
  842. #if HASHINDEX
  843. public readonly Node Endpoint;
  844. #else
  845. public readonly int Index;
  846. #endif
  847. public Position(LinkedList<T> view, bool left)
  848. {
  849. View = view;
  850. Left = left;
  851. #if HASHINDEX
  852. Endpoint = left ? view.startsentinel.next : view.endsentinel.prev;
  853. #else
  854. Index = left ? view.Offset : view.Offset + view.size - 1;
  855. #endif
  856. }
  857. #if HASHINDEX
  858. public Position(Node node, int foo) { this.Endpoint = node; View = null; Left = false; }
  859. #else
  860. public Position(int index) { this.Index = index; View = null; Left = false; }
  861. #endif
  862. }
  863. //TODO: merge the two implementations using Position values as arguments
  864. /// <summary>
  865. /// Handle the update of (other) views during a multi-remove operation.
  866. /// </summary>
  867. struct ViewHandler
  868. {
  869. ArrayList<Position> leftEnds;
  870. ArrayList<Position> rightEnds;
  871. int leftEndIndex, rightEndIndex, leftEndIndex2, rightEndIndex2;
  872. internal readonly int viewCount;
  873. internal ViewHandler(LinkedList<T> list)
  874. {
  875. leftEndIndex = rightEndIndex = leftEndIndex2 = rightEndIndex2 = viewCount = 0;
  876. leftEnds = rightEnds = null;
  877. if (list.views != null)
  878. foreach (LinkedList<T> v in list.views)
  879. if (v != list)
  880. {
  881. if (leftEnds == null)
  882. {
  883. leftEnds = new ArrayList<Position>();
  884. rightEnds = new ArrayList<Position>();
  885. }
  886. leftEnds.Add(new Position(v, true));
  887. rightEnds.Add(new Position(v, false));
  888. }
  889. if (leftEnds == null)
  890. return;
  891. viewCount = leftEnds.Count;
  892. leftEnds.Sort(PositionComparer.Default);
  893. rightEnds.Sort(PositionComparer.Default);
  894. }
  895. #if HASHINDEX
  896. internal void skipEndpoints(int removed, Node n)
  897. {
  898. if (viewCount > 0)
  899. {
  900. Position endpoint;
  901. while (leftEndIndex < viewCount && ((endpoint = leftEnds[leftEndIndex]).Endpoint.prev.precedes(n)))
  902. {
  903. LinkedList<T> view = endpoint.View;
  904. view.offset = view.offset - removed;//TODO: extract offset.Value?
  905. view.size += removed;
  906. leftEndIndex++;
  907. }
  908. while (rightEndIndex < viewCount && (endpoint = rightEnds[rightEndIndex]).Endpoint.precedes(n))
  909. {
  910. LinkedList<T> view = endpoint.View;
  911. view.size -= removed;
  912. rightEndIndex++;
  913. }
  914. }
  915. if (viewCount > 0)
  916. {
  917. Position endpoint;
  918. while (leftEndIndex2 < viewCount && (endpoint = leftEnds[leftEndIndex2]).Endpoint.prev.precedes(n))
  919. leftEndIndex2++;
  920. while (rightEndIndex2 < viewCount && (endpoint = rightEnds[rightEndIndex2]).Endpoint.next.precedes(n))
  921. rightEndIndex2++;
  922. }
  923. }
  924. /// <summary>
  925. /// To be called with n pointing to the right of each node to be removed in a stretch.
  926. /// And at the endsentinel.
  927. ///
  928. /// Update offset of a view whose left endpoint (has not already been handled and) is n or precedes n.
  929. /// I.e. startsentinel precedes n.
  930. /// Also update the size as a prelude to handling the right endpoint.
  931. ///
  932. /// Update size of a view not already handled and whose right endpoint precedes n.
  933. /// </summary>
  934. /// <param name="removed">The number of nodes left of n to be removed</param>
  935. /// <param name="n"></param>
  936. internal void updateViewSizesAndCounts(int removed, Node n)
  937. {
  938. if (viewCount > 0)
  939. {
  940. Position endpoint;
  941. while (leftEndIndex < viewCount && ((endpoint = leftEnds[leftEndIndex]).Endpoint.prev.precedes(n)))
  942. {
  943. LinkedList<T> view = endpoint.View;
  944. view.offset = view.offset - removed; //TODO: fix use of offset
  945. view.size += removed;
  946. leftEndIndex++;
  947. }
  948. while (rightEndIndex < viewCount && (endpoint = rightEnds[rightEndIndex]).Endpoint.precedes(n))
  949. {
  950. LinkedList<T> view = endpoint.View;
  951. view.size -= removed;
  952. rightEndIndex++;
  953. }
  954. }
  955. }
  956. /// <summary>
  957. /// To be called with n being the first not-to-be-removed node after a (stretch of) node(s) to be removed.
  958. ///
  959. /// It will update the startsentinel of views (that have not been handled before and)
  960. /// whose startsentinel precedes n, i.e. is to be deleted.
  961. ///
  962. /// It will update the endsentinel of views (...) whose endsentinel precedes n, i.e. is to be deleted.
  963. ///
  964. /// PROBLEM: DOESNT WORK AS ORIGINALLY ADVERTISED. WE MUST DO THIS BEFORE WE ACTUALLY REMOVE THE NODES. WHEN THE
  965. /// NODES HAVE BEEN REMOVED, THE precedes METHOD WILL NOT WORK!
  966. /// </summary>
  967. /// <param name="n"></param>
  968. /// <param name="newstart"></param>
  969. /// <param name="newend"></param>
  970. internal void updateSentinels(Node n, Node newstart, Node newend)
  971. {
  972. if (viewCount > 0)
  973. {
  974. Position endpoint;
  975. while (leftEndIndex2 < viewCount && (endpoint = leftEnds[leftEndIndex2]).Endpoint.prev.precedes(n))
  976. {
  977. LinkedList<T> view = endpoint.View;
  978. view.startsentinel = newstart;
  979. leftEndIndex2++;
  980. }
  981. while (rightEndIndex2 < viewCount && (endpoint = rightEnds[rightEndIndex2]).Endpoint.next.precedes(n))
  982. {
  983. LinkedList<T> view = endpoint.View;
  984. view.endsentinel = newend;
  985. rightEndIndex2++;
  986. }
  987. }
  988. }
  989. #else
  990. /// <summary>
  991. /// This is to be called with realindex pointing to the first node to be removed after a (stretch of) node that was not removed
  992. /// </summary>
  993. /// <param name="removed"></param>
  994. /// <param name="realindex"></param>
  995. internal void skipEndpoints(int removed, int realindex)
  996. {
  997. if (viewCount > 0)
  998. {
  999. Position endpoint;
  1000. while (leftEndIndex < viewCount && (endpoint = leftEnds[leftEndIndex]).Index <= realindex)
  1001. {
  1002. LinkedList<T> view = endpoint.View;
  1003. view.offset = view.offset - removed;
  1004. view.size += removed;
  1005. leftEndIndex++;
  1006. }
  1007. while (rightEndIndex < viewCount && (endpoint = rightEnds[rightEndIndex]).Index < realindex)
  1008. {
  1009. LinkedList<T> view = endpoint.View;
  1010. view.size -= removed;
  1011. rightEndIndex++;
  1012. }
  1013. }
  1014. if (viewCount > 0)
  1015. {
  1016. Position endpoint;
  1017. while (leftEndIndex2 < viewCount && (endpoint = leftEnds[leftEndIndex2]).Index <= realindex)
  1018. leftEndIndex2++;
  1019. while (rightEndIndex2 < viewCount && (endpoint = rightEnds[rightEndIndex2]).Index < realindex - 1)
  1020. rightEndIndex2++;
  1021. }
  1022. }
  1023. internal void updateViewSizesAndCounts(int removed, int realindex)
  1024. {
  1025. if (viewCount > 0)
  1026. {
  1027. Position endpoint;
  1028. while (leftEndIndex < viewCount && (endpoint = leftEnds[leftEndIndex]).Index <= realindex)
  1029. {
  1030. LinkedList<T> view = endpoint.View;
  1031. view.offset = view.Offset - removed;
  1032. view.size += removed;
  1033. leftEndIndex++;
  1034. }
  1035. while (rightEndIndex < viewCount && (endpoint = rightEnds[rightEndIndex]).Index < realindex)
  1036. {
  1037. LinkedList<T> view = endpoint.View;
  1038. view.size -= removed;
  1039. rightEndIndex++;
  1040. }
  1041. }
  1042. }
  1043. internal void updateSentinels(int realindex, Node newstart, Node newend)
  1044. {
  1045. if (viewCount > 0)
  1046. {
  1047. Position endpoint;
  1048. while (leftEndIndex2 < viewCount && (endpoint = leftEnds[leftEndIndex2]).Index <= realindex)
  1049. {
  1050. LinkedList<T> view = endpoint.View;
  1051. view.startsentinel = newstart;
  1052. leftEndIndex2++;
  1053. }
  1054. while (rightEndIndex2 < viewCount && (endpoint = rightEnds[rightEndIndex2]).Index < realindex - 1)
  1055. {
  1056. LinkedList<T> view = endpoint.View;
  1057. view.endsentinel = newend;
  1058. rightEndIndex2++;
  1059. }
  1060. }
  1061. }
  1062. #endif
  1063. }
  1064. #endregion
  1065. #region Range nested class
  1066. class Range : DirectedCollectionValueBase<T>, IDirectedCollectionValue<T>
  1067. {
  1068. int start, count, rangestamp;
  1069. Node startnode, endnode;
  1070. LinkedList<T> list;
  1071. bool forwards;
  1072. internal Range(LinkedList<T> list, int start, int count, bool forwards)
  1073. {
  1074. this.list = list; this.rangestamp = list.underlying != null ? list.underlying.stamp : list.stamp;
  1075. this.start = start; this.count = count; this.forwards = forwards;
  1076. if (count > 0)
  1077. {
  1078. startnode = list.get(start);
  1079. endnode = list.get(start + count - 1);
  1080. }
  1081. }
  1082. public override bool IsEmpty { get { list.modifycheck(rangestamp); return count == 0; } }
  1083. [Tested]
  1084. public override int Count { [Tested]get { list.modifycheck(rangestamp); return count; } }
  1085. public override Speed CountSpeed { get { list.modifycheck(rangestamp); return Speed.Constant; } }
  1086. public override T Choose()
  1087. {
  1088. list.modifycheck(rangestamp);
  1089. if (count > 0) return startnode.item;
  1090. throw new NoSuchItemException();
  1091. }
  1092. [Tested]
  1093. public override SCG.IEnumerator<T> GetEnumerator()
  1094. {
  1095. int togo = count;
  1096. list.modifycheck(rangestamp);
  1097. if (togo == 0)
  1098. yield break;
  1099. Node cursor = forwards ? startnode : endnode;
  1100. yield return cursor.item;
  1101. while (--togo > 0)
  1102. {
  1103. cursor = forwards ? cursor.next : cursor.prev;
  1104. list.modifycheck(rangestamp);
  1105. yield return cursor.item;
  1106. }
  1107. }
  1108. [Tested]
  1109. public override IDirectedCollectionValue<T> Backwards()
  1110. {
  1111. list.modifycheck(rangestamp);
  1112. Range b = (Range)MemberwiseClone();
  1113. b.forwards = !forwards;
  1114. return b;
  1115. }
  1116. [Tested]
  1117. IDirectedEnumerable<T> IDirectedEnumerable<T>.Backwards() { return Backwards(); }
  1118. [Tested]
  1119. public override EnumerationDirection Direction
  1120. {
  1121. [Tested]
  1122. get
  1123. { return forwards ? EnumerationDirection.Forwards : EnumerationDirection.Backwards; }
  1124. }
  1125. }
  1126. #endregion
  1127. #region IDisposable Members
  1128. /// <summary>
  1129. /// Invalidate this list. If a view, just invalidate the view.
  1130. /// If not a view, invalidate the list and all views on it.
  1131. /// </summary>
  1132. public virtual void Dispose()
  1133. {
  1134. Dispose(false);
  1135. }
  1136. void Dispose(bool disposingUnderlying)
  1137. {
  1138. if (isValid)
  1139. {
  1140. if (underlying != null)
  1141. {
  1142. isValid = false;
  1143. if (!disposingUnderlying && views != null)
  1144. views.Remove(myWeakReference);
  1145. endsentinel = null;
  1146. startsentinel = null;
  1147. underlying = null;
  1148. views = null;
  1149. myWeakReference = null;
  1150. }
  1151. else
  1152. {
  1153. //isValid = false;
  1154. //endsentinel = null;
  1155. //startsentinel = null;
  1156. if (views != null)
  1157. foreach (LinkedList<T> view in views)
  1158. view.Dispose(true);
  1159. //views = null;
  1160. Clear();
  1161. }
  1162. }
  1163. }
  1164. #endregion IDisposable stuff
  1165. #region IList<T> Members
  1166. /// <summary>
  1167. /// </summary>
  1168. /// <exception cref="NoSuchItemException"> if this list is empty.</exception>
  1169. /// <value>The first item in this list.</value>
  1170. [Tested]
  1171. public virtual T First
  1172. {
  1173. [Tested]
  1174. get
  1175. {
  1176. validitycheck();
  1177. if (size == 0)
  1178. throw new NoSuchItemException();
  1179. return startsentinel.next.item;
  1180. }
  1181. }
  1182. /// <summary>
  1183. /// </summary>
  1184. /// <exception cref="NoSuchItemException"> if this list is empty.</exception>
  1185. /// <value>The last item in this list.</value>
  1186. [Tested]
  1187. public virtual T Last
  1188. {
  1189. [Tested]
  1190. get
  1191. {
  1192. validitycheck();
  1193. if (size == 0)
  1194. throw new NoSuchItemException();
  1195. return endsentinel.prev.item;
  1196. }
  1197. }
  1198. /// <summary>
  1199. /// Since <code>Add(T item)</code> always add at the end of the list,
  1200. /// this describes if list has FIFO or LIFO semantics.
  1201. /// </summary>
  1202. /// <value>True if the <code>Remove()</code> operation removes from the
  1203. /// start of the list, false if it removes from the end. THe default for a new linked list is true.</value>
  1204. [Tested]
  1205. public virtual bool FIFO
  1206. {
  1207. [Tested]
  1208. get { validitycheck(); return fIFO; }
  1209. [Tested]
  1210. set { updatecheck(); fIFO = value; }
  1211. }
  1212. /// <summary>
  1213. ///
  1214. /// </summary>
  1215. public virtual bool IsFixedSize
  1216. {
  1217. get { validitycheck(); return false; }
  1218. }
  1219. /// <summary>
  1220. /// On this list, this indexer is read/write.
  1221. /// <exception cref="IndexOutOfRangeException"/> if i is negative or
  1222. /// &gt;= the size of the collection.
  1223. /// </summary>
  1224. /// <value>The i'th item of this list.</value>
  1225. /// <param name="index">The index of the item to fetch or store.</param>
  1226. [Tested]
  1227. public virtual T this[int index]
  1228. {
  1229. [Tested]
  1230. get { validitycheck(); return get(index).item; }
  1231. [Tested]
  1232. set
  1233. {
  1234. updatecheck();
  1235. Node n = get(index);
  1236. //
  1237. T item = n.item;
  1238. #if HASHINDEX
  1239. if (itemequalityComparer.Equals(value, item))
  1240. {
  1241. n.item = value;
  1242. dict.Update(value, n);
  1243. }
  1244. else if (!dict.FindOrAdd(value, ref n))
  1245. {
  1246. dict.Remove(item);
  1247. n.item = value;
  1248. }
  1249. else
  1250. throw new ArgumentException("Item already in indexed list");
  1251. #else
  1252. n.item = value;
  1253. #endif
  1254. (underlying ?? this).raiseForSetThis(index, value, item);
  1255. }
  1256. }
  1257. /// <summary>
  1258. ///
  1259. /// </summary>
  1260. /// <value></value>
  1261. public virtual Speed IndexingSpeed { get { return Speed.Linear; } }
  1262. /// <summary>
  1263. /// Insert an item at a specific index location in this list.
  1264. /// <exception cref="IndexOutOfRangeException"/> if i is negative or
  1265. /// &gt; the size of the collection.</summary>
  1266. /// <param name="i">The index at which to insert.</param>
  1267. /// <param name="item">The item to insert.</param>
  1268. [Tested]
  1269. public virtual void Insert(int i, T item)
  1270. {
  1271. updatecheck();
  1272. insert(i, i == size ? endsentinel : get(i), item);
  1273. if (ActiveEvents != EventTypeEnum.None)
  1274. (underlying ?? this).raiseForInsert(i + Offset, item);
  1275. }
  1276. /// <summary>
  1277. /// Insert an item at the end of a compatible view, used as a pointer.
  1278. /// <para>The <code>pointer</code> must be a view on the same list as
  1279. /// <code>this</code> and the endpoitn of <code>pointer</code> must be
  1280. /// a valid insertion point of <code>this</code></para>
  1281. /// </summary>
  1282. /// <exception cref="IncompatibleViewException">If <code>pointer</code>
  1283. /// is not a view on the same list as <code>this</code></exception>
  1284. /// <exception cref="IndexOutOfRangeException"><b>??????</b> if the endpoint of
  1285. /// <code>pointer</code> is not inside <code>this</code></exception>
  1286. /// <exception cref="DuplicateNotAllowedException"> if the list has
  1287. /// <code>AllowsDuplicates==false</code> and the item is
  1288. /// already in the list.</exception>
  1289. /// <param name="pointer"></param>
  1290. /// <param name="item"></param>
  1291. public void Insert(IList<T> pointer, T item)
  1292. {
  1293. updatecheck();
  1294. if ((pointer == null) || ((pointer.Underlying ?? pointer) != (underlying ?? this)))
  1295. throw new IncompatibleViewException();
  1296. #warning INEFFICIENT
  1297. //TODO: make this efficient (the whole point of the method:
  1298. //Do NOT use Insert, but insert the node at pointer.endsentinel, checking
  1299. //via the ordering that this is a valid insertion point
  1300. Insert(pointer.Offset + pointer.Count - Offset, item);
  1301. }
  1302. /// <summary>
  1303. /// Insert into this list all items from an enumerable collection starting
  1304. /// at a particular index.
  1305. /// <exception cref="IndexOutOfRangeException"/> if i is negative or
  1306. /// &gt; the size of the collection.
  1307. /// </summary>
  1308. /// <param name="i">Index to start inserting at</param>
  1309. /// <param name="items">Items to insert</param>
  1310. /// <typeparam name="U"></typeparam>
  1311. [Tested]
  1312. public virtual void InsertAll<U>(int i, SCG.IEnumerable<U> items) where U : T
  1313. {
  1314. insertAll(i, items, true);
  1315. }
  1316. void insertAll<U>(int i, SCG.IEnumerable<U> items, bool insertion) where U : T
  1317. {
  1318. updatecheck();
  1319. Node succ, node, pred;
  1320. int count = 0;
  1321. succ = i == size ? endsentinel : get(i);
  1322. pred = node = succ.prev;
  1323. #if HASHINDEX
  1324. TagGroup taggroup = null;
  1325. int taglimit = 0, thetag = 0;
  1326. taggroup = gettaggroup(node, succ, out thetag, out taglimit);
  1327. try
  1328. {
  1329. foreach (T item in items)
  1330. {
  1331. Node tmp = new Node(item, node, null);
  1332. if (!dict.FindOrAdd(item, ref tmp))
  1333. {
  1334. tmp.tag = thetag < taglimit ? ++thetag : thetag;
  1335. tmp.taggroup = taggroup;
  1336. node.next = tmp;
  1337. count++;
  1338. node = tmp;
  1339. }
  1340. else
  1341. throw new DuplicateNotAllowedException("Item already in indexed list");
  1342. }
  1343. }
  1344. finally
  1345. {
  1346. if (count != 0)
  1347. {
  1348. taggroup.count += count;
  1349. if (taggroup != pred.taggroup)
  1350. taggroup.first = pred.next;
  1351. if (taggroup != succ.taggroup)
  1352. taggroup.last = node;
  1353. succ.prev = node;
  1354. node.next = succ;
  1355. if (node.tag == node.prev.tag)
  1356. splittaggroup(taggroup);
  1357. size += count;
  1358. if (underlying != null)
  1359. underlying.size += count;
  1360. fixViewsAfterInsert(succ, pred, count, 0);
  1361. raiseForInsertAll(pred, i, count, insertion);
  1362. }
  1363. }
  1364. #else
  1365. foreach (T item in items)
  1366. {
  1367. Node tmp = new Node(item, node, null);
  1368. node.next = tmp;
  1369. count++;
  1370. node = tmp;
  1371. }
  1372. if (count == 0)
  1373. return;
  1374. succ.prev = node;
  1375. node.next = succ;
  1376. size += count;
  1377. if (underlying != null)
  1378. underlying.size += count;
  1379. if (count > 0)
  1380. {
  1381. fixViewsAfterInsert(succ, pred, count, offset + i);
  1382. raiseForInsertAll(pred, i, count, insertion);
  1383. }
  1384. #endif
  1385. }
  1386. private void raiseForInsertAll(Node node, int i, int added, bool insertion)
  1387. {
  1388. if (ActiveEvents != 0)
  1389. {
  1390. int index = Offset + i;
  1391. if ((ActiveEvents & (EventTypeEnum.Added | EventTypeEnum.Inserted)) != 0)
  1392. for (int j = index; j < index + added; j++)
  1393. {
  1394. #warning must we check stamps here?
  1395. node = node.next;
  1396. T item = node.item;
  1397. if (insertion) raiseItemInserted(item, j);
  1398. raiseItemsAdded(item, 1);
  1399. }
  1400. raiseCollectionChanged();
  1401. }
  1402. }
  1403. /// <summary>
  1404. /// Insert an item at the front of this list.
  1405. /// </summary>
  1406. /// <param name="item">The item to insert.</param>
  1407. [Tested]
  1408. public virtual void InsertFirst(T item)
  1409. {
  1410. updatecheck();
  1411. insert(0, startsentinel.next, item);
  1412. if (ActiveEvents != EventTypeEnum.None)
  1413. (underlying ?? this).raiseForInsert(0 + Offset, item);
  1414. }
  1415. /// <summary>
  1416. /// Insert an item at the back of this list.
  1417. /// </summary>
  1418. /// <param name="item">The item to insert.</param>
  1419. [Tested]
  1420. public virtual void InsertLast(T item)
  1421. {
  1422. updatecheck();
  1423. insert(size, endsentinel, item);
  1424. if (ActiveEvents != EventTypeEnum.None)
  1425. (underlying ?? this).raiseForInsert(size - 1 + Offset, item);
  1426. }
  1427. /// <summary>
  1428. /// Create a new list consisting of the results of mapping all items of this
  1429. /// list.
  1430. /// </summary>
  1431. /// <param name="mapper">The delegate defining the map.</param>
  1432. /// <returns>The new list.</returns>
  1433. [Tested]
  1434. public IList<V> Map<V>(Fun<T, V> mapper)
  1435. {
  1436. validitycheck();
  1437. LinkedList<V> retval = new LinkedList<V>();
  1438. return map<V>(mapper, retval);
  1439. }
  1440. /// <summary>
  1441. /// Create a new list consisting of the results of mapping all items of this
  1442. /// list. The new list will use a specified equalityComparer for the item type.
  1443. /// </summary>
  1444. /// <typeparam name="V">The type of items of the new list</typeparam>
  1445. /// <param name="mapper">The delegate defining the map.</param>
  1446. /// <param name="equalityComparer">The equalityComparer to use for the new list</param>
  1447. /// <returns>The new list.</returns>
  1448. public IList<V> Map<V>(Fun<T, V> mapper, SCG.IEqualityComparer<V> equalityComparer)
  1449. {
  1450. validitycheck();
  1451. LinkedList<V> retval = new LinkedList<V>(equalityComparer);
  1452. return map<V>(mapper, retval);
  1453. }
  1454. private IList<V> map<V>(Fun<T, V> mapper, LinkedList<V> retval)
  1455. {
  1456. if (size == 0)
  1457. return retval;
  1458. int stamp = this.stamp;
  1459. Node cursor = startsentinel.next;
  1460. LinkedList<V>.Node mcursor = retval.startsentinel;
  1461. #if HASHINDEX
  1462. double tagdelta = int.MaxValue / (size + 1.0);
  1463. int count = 1;
  1464. LinkedList<V>.TagGroup taggroup = null;
  1465. taggroup = new LinkedList<V>.TagGroup();
  1466. retval.taggroups = 1;
  1467. taggroup.count = size;
  1468. #endif
  1469. while (cursor != endsentinel)
  1470. {
  1471. V v = mapper(cursor.item);

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