673872a9180cf0a32422f34051ecf015adcd218c
[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(Fleet fleet, ShipPool ancestor) {
20         this.fleet = fleet;
21         this.ancestor = ancestor;
22     }
23
24     public Iterator<Ship> iterator() { return allocatedShips.iterator(); }
25
26     /** allocate a ship */
27     public Ship allocateShip(String type) {
28         Ship ship = null;
29         if (ancestor != null) {
30             ship = ancestor.allocateShip(type);
31         } else {
32             for(int i=0; ; i++) {
33                 ship = fleet.getShip(type, i);
34                 if (ship==null)
35                     throw new RuntimeException("no more ships of type " + type);
36                 if (!allocatedShips.contains(ship)) break;
37             }
38         }
39         allocatedShips.add(ship);
40         return ship;
41     }
42
43     /** release an allocated ship */
44     public void releaseShip(Ship ship) {
45         if (!allocatedShips.contains(ship))
46             throw new RuntimeException("ship " + ship + " released but was not allocated");
47         allocatedShips.remove(ship);
48         if (ancestor != null) ancestor.releaseShip(ship);
49     }
50
51 }