View Javadoc

1   package simpledb.log;
2   
3   import static simpledb.file.Page.INT_SIZE;
4   import simpledb.file.*;
5   import java.util.Iterator;
6   
7   /**
8    * A class that provides the ability to move through the
9    * records of the log file in reverse order.
10   * 
11   * @author Edward Sciore
12   */
13  class LogIterator implements Iterator<BasicLogRecord> {
14     private Block blk;
15     private Page pg = new Page();
16     private int currentrec;
17     
18     /**
19      * Creates an iterator for the records in the log file,
20      * positioned after the last log record.
21      * This constructor is called exclusively by
22      * {@link LogMgr#iterator()}.
23      */
24     LogIterator(Block blk) {
25        this.blk = blk;
26        pg.read(blk);
27        currentrec = pg.getInt(LogMgr.LAST_POS);
28     }
29     
30     /**
31      * Determines if the current log record
32      * is the earliest record in the log file.
33      * @return true if there is an earlier record
34      */
35     public boolean hasNext() {
36        return currentrec>0 || blk.number()>0;
37     }
38     
39     /**
40      * Moves to the next log record in reverse order.
41      * If the current log record is the earliest in its block,
42      * then the method moves to the next oldest block,
43      * and returns the log record from there.
44      * @return the next earliest log record
45      */
46     public BasicLogRecord next() {
47        if (currentrec == 0) 
48           moveToNextBlock();
49        currentrec = pg.getInt(currentrec);
50        return new BasicLogRecord(pg, currentrec+INT_SIZE);
51     }
52     
53     public void remove() {
54        throw new UnsupportedOperationException();
55     }
56     
57     /**
58      * Moves to the next log block in reverse order,
59      * and positions it after the last record in that block.
60      */
61     private void moveToNextBlock() {
62        blk = new Block(blk.fileName(), blk.number()-1);
63        pg.read(blk);
64        currentrec = pg.getInt(LogMgr.LAST_POS);
65     }
66  }