ScanSet is iterable
[yaz4j-moved-to-github.git] / src / main / java / org / yaz4j / ScanSet.java
1 package org.yaz4j;
2
3 import java.util.Iterator;
4 import java.util.NoSuchElementException;
5 import org.yaz4j.exception.ZoomException;
6 import org.yaz4j.jni.SWIGTYPE_p_ZOOM_scanset_p;
7 import org.yaz4j.jni.SWIGTYPE_p_size_t;
8 import org.yaz4j.jni.yaz4jlib;
9
10 public class ScanSet implements Iterable<ScanTerm> {
11
12   //for GC ref-count
13   private Connection conn;
14   private SWIGTYPE_p_ZOOM_scanset_p scanSet;
15   private boolean disposed = false;
16   private long size = 0;
17
18   ScanSet(SWIGTYPE_p_ZOOM_scanset_p scanSet, Connection conn) {
19     this.scanSet = scanSet;
20     size = yaz4jlib.ZOOM_scanset_size(scanSet);
21     this.conn = conn;
22   }
23
24   public void finalize() {
25     _dispose();
26   }
27
28   public ScanTerm get(long index) {
29     SWIGTYPE_p_size_t occ = yaz4jlib.new_size_tp();
30     SWIGTYPE_p_size_t length = yaz4jlib.new_size_tp();
31     String term = yaz4jlib.ZOOM_scanset_term(scanSet, (long) index, occ, length);
32     long occurences = yaz4jlib.size_tp_value(occ);
33     yaz4jlib.delete_size_tp(occ);
34     yaz4jlib.delete_size_tp(length);
35     return new ScanTerm(term, occurences);
36   }
37
38   public long getSize() {
39     return size;
40   }
41
42   void _dispose() {
43     if (!disposed) {
44       yaz4jlib.ZOOM_scanset_destroy(scanSet);
45       scanSet = null;
46       conn = null;
47       disposed = true;
48     }
49   }
50
51   @Override
52   public Iterator<ScanTerm> iterator() {
53     return new Iterator<ScanTerm>() {
54       private long cur;
55       @Override
56       public boolean hasNext() {
57         return cur < size;
58       }
59
60       @Override
61       public ScanTerm next() {
62         return get(cur++);
63       }
64
65       @Override
66       public void remove() {
67         throw new UnsupportedOperationException("remove operation not supported");
68       }
69     };
70   }
71 }