Source code: mlsub/typing/lowlevel/BackableList.java
1 /**************************************************************************/
2 /* B O S S A */
3 /* A simple imperative object-oriented research language */
4 /* (c) Daniel Bonniot 1999 */
5 /* */
6 /* This program is free software; you can redistribute it and/or modify */
7 /* it under the terms of the GNU General Public License as published by */
8 /* the Free Software Foundation; either version 2 of the License, or */
9 /* (at your option) any later version. */
10 /* */
11 /**************************************************************************/
12
13 // File : BackableList.java
14 // Created : Wed Aug 25 12:52:31 1999 by bonniot
15 //$Modified: Wed Jun 07 18:55:46 2000 by Daniel Bonniot $
16
17 package mlsub.typing.lowlevel;
18
19 import java.util.*;
20
21 /**
22 * List with mark/backtrack facility
23 *
24 * @author bonniot
25 */
26
27 public class BackableList
28 {
29 public BackableList()
30 {
31 content=new ArrayList();
32 }
33
34 public BackableList(int capacity)
35 {
36 content=new ArrayList(capacity);
37 }
38
39 /****************************************************************
40 * Markup/Backtrack
41 ****************************************************************/
42
43 public void mark()
44 {
45 backups.push(content);
46 content=(ArrayList)content.clone();
47 }
48
49 public void backtrack()
50 {
51 content=(ArrayList)backups.pop();
52 }
53
54 /****************************************************************
55 * List implementation
56 ****************************************************************/
57
58 public void add(Object element)
59 {
60 if(iterationInProgress)
61 waitingElements.push(element);
62 else
63 content.add(element);
64 }
65
66 public void remove(Object element)
67 {
68 if(iterationInProgress)
69 throw new InternalError("remove during iteration in BackableList");
70
71 content.remove(element);
72 }
73
74 public boolean contains(Object element)
75 {
76 return content.contains(element);
77 }
78
79 public void clear()
80 {
81 content.clear();
82 }
83
84 public Iterator iterator()
85 {
86 if(iterationInProgress)
87 throw new InternalError("Concurrent iterations in BackableList");
88
89 iterationInProgress=true;
90 return content.iterator();
91 }
92
93 public void endOfIteration()
94 {
95 if(!iterationInProgress)
96 throw new InternalError("No iterations to end in BackableList");
97
98 iterationInProgress=false;
99 while(!waitingElements.empty())
100 content.add(waitingElements.pop());
101 }
102
103 public String toString()
104 {
105 return content.toString();
106 }
107
108 private ArrayList content;
109 private Stack backups=new Stack();
110
111 // We want to allow the addition of elements
112 // while iterating on the list.
113 // It is done by postponing the addition
114 // until the iteration is declared explicitely to be done
115 // ( with endOfIteration() ).
116 private boolean iterationInProgress=false;
117 private Stack waitingElements=new Stack();
118 }