yet another rewrite of the producers...
[mir.git] / source / mir / entity / adapter / EntityListAdapter.java
1 package mir.entity.adapter;
2
3 import java.util.*;
4 import mir.entity.*;
5
6 public class EntityListAdapter extends AbstractList {
7   private int skip;
8   private int maximumLength;
9   private EntityBrowser browser;
10   private boolean exhausted = false;
11   private boolean skipped = false;
12
13   private List cache;
14
15   protected EntityListAdapter(EntityBrowser aBrowser, int aSkip, int aMaximumLength) {
16     browser = aBrowser;
17     skip = aSkip;
18     maximumLength = aMaximumLength;
19     cache = new Vector();
20   }
21
22   protected EntityListAdapter(EntityBrowser aBrowser, int aMaximumLength) {
23     this(aBrowser, 0, aMaximumLength);
24   }
25
26   protected EntityListAdapter(EntityBrowser aBrowser) {
27     this(aBrowser, 0, -1);
28   }
29
30   private void skip() {
31     int i;
32
33     try {
34       if (!skipped) {
35         for(i=0; i<skip; i++)
36           if (browser.hasNext())
37             browser.next();
38       }
39       skipped=true;
40     }
41     catch (Throwable t) {
42       throw new RuntimeException(t.getMessage());
43     }
44   }
45
46   private void fetchNext() {
47     try {
48       if (!exhausted) {
49         if (browser.hasNext())
50           cache.add(browser.next());
51
52         exhausted = !browser.hasNext() || (maximumLength>0 && cache.size()>=maximumLength) ;
53       }
54     }
55     catch (Throwable t) {
56       throw new RuntimeException(t.getMessage());
57     }
58
59   }
60
61   private void exhaust() {
62     skip();
63
64     while (!exhausted)
65       fetchNext();
66   }
67
68   private void fetchUntil(int anIndex) {
69     skip();
70
71     while (!exhausted && anIndex>=cache.size())
72       fetchNext();
73   }
74
75   public int size() {
76     exhaust();
77
78     return cache.size();
79   }
80
81   public Object get(int anIndex) {
82     fetchUntil(anIndex);
83     return cache.get(anIndex);
84   }
85 }