added am10 inbox/outbox support
[fleet.git] / src / edu / berkeley / fleet / InstructionPort.java
1 package edu.berkeley.fleet;
2
3 import java.util.*;
4
5 /** common superclass for any port which can take an instruction: inbox/outbox/tokenoutbox */
6 public abstract class InstructionPort extends Port {
7
8     public InstructionPort(Ship ship, String name) {
9         super(ship, name);
10     }
11
12     /** add an instruction to the box */
13     public void addInstruction(Instruction instr) {
14         if (currentlyExecuting != null && currentlyExecuting.count == Integer.MAX_VALUE) {
15             currentlyExecuting = null;
16             currentlyExecutingCount = 0;
17         }
18         if (currentlyExecuting == null) {
19             currentlyExecuting = instr;
20             currentlyExecutingCount = currentlyExecuting.count;
21         } else {
22             instructions.add(instr);
23         }
24     }
25
26     // inherited from Port
27     public abstract void addData(int data);
28
29     private Instruction currentlyExecuting = null;
30     private Queue<Instruction> instructions = new LinkedList<Instruction>();
31     private int currentlyExecutingCount;
32
33     // interface to subclass ///////////////////////////////////////////////////////////////////////
34
35     /** this will be invoked periodically; should return true to "consume" an instruction */
36     protected abstract boolean service(Instruction instr);
37
38     public void service() {
39         if (currentlyExecutingCount <= 0)
40             currentlyExecuting = null;
41         if (currentlyExecuting == null && instructions.size() > 0) {
42             currentlyExecuting = instructions.remove();
43             currentlyExecutingCount = currentlyExecuting.count;
44         }
45         boolean ret = service(currentlyExecuting);
46         if (ret && currentlyExecuting != null && currentlyExecutingCount != Integer.MAX_VALUE)
47             currentlyExecutingCount--;
48     }
49
50
51 }