major refactoring of edu.berkeley.fleet.loops, includes renaming Context to CodeBag
[fleet.git] / src / edu / berkeley / fleet / loops / ShipPool.java
1 package edu.berkeley.fleet.loops;
2 import java.util.*;
3 import edu.berkeley.fleet.api.*;
4 import static edu.berkeley.fleet.util.BitManipulations.*;
5
6 /**
7  *  A ShipPool keeps track of ships which have been "allocated" and
8  *  are in use.  ShipPools may be arranged in a hierarchy; allocating
9  *  a ship in one pool will allocate it in all ancestors.
10  */
11 public class ShipPool implements Iterable<Ship> {
12
13     public final Fleet fleet;
14     public final ShipPool ancestor;
15
16     private HashSet<Ship> allocatedShips = new HashSet<Ship>();
17
18     public ShipPool(Fleet fleet) { this(fleet, null); }
19     public ShipPool(ShipPool ancestor) { this(ancestor.fleet, ancestor); }
20     public ShipPool(Fleet fleet, ShipPool ancestor) {
21         this.fleet = fleet;
22         this.ancestor = ancestor;
23     }
24
25     public Iterator<Ship> iterator() { return allocatedShips.iterator(); }
26
27     public void allocateShip(Ship ship) {
28         if (allocatedShips.contains(ship))
29             throw new RuntimeException("already allocated!");
30         allocatedShips.add(ship);
31     }
32
33     /** allocate a ship */
34     public Ship allocateShip(String type) {
35         Ship ship = null;
36         if (ancestor != null) {
37             ship = ancestor.allocateShip(type);
38         } else {
39             for(int i=0; ; i++) {
40                 ship = fleet.getShip(type, i);
41                 if (ship==null)
42                     throw new RuntimeException("no more ships of type " + type);
43                 if (!allocatedShips.contains(ship)) break;
44             }
45         }
46         allocatedShips.add(ship);
47         return ship;
48     }
49
50     /** release an allocated ship */
51     public void releaseShip(Ship ship) {
52         if (!allocatedShips.contains(ship))
53             throw new RuntimeException("ship " + ship + " released but was not allocated");
54         allocatedShips.remove(ship);
55         if (ancestor != null) ancestor.releaseShip(ship);
56     }
57
58     public void releaseAll() {
59         HashSet<Ship> toRelease = new HashSet<Ship>();
60         toRelease.addAll(allocatedShips);
61         for (Ship ship : toRelease)
62             releaseShip(ship);
63     }
64 }