001/*
002 * To change this template, choose Tools | Templates
003 * and open the template in the editor.
004 */
005package org.anarres.qemu.exec.util;
006
007import javax.annotation.Nonnegative;
008import javax.annotation.Nonnull;
009
010/**
011 * An allocator for unique drive, network and PCI addresses.
012 *
013 * This class is basically a set of incrementing counters.
014 *
015 * @author shevek
016 */
017public class QEmuIdAllocator {
018
019    public static interface Consumer {
020
021        public void withAllocator(@Nonnull QEmuIdAllocator allocator);
022    }
023
024    private int driveIndex;
025    private int networkIndex;
026    private int networkBootIndex;
027    private int pciAddress;
028
029    public QEmuIdAllocator() {
030    }
031
032    public QEmuIdAllocator(@Nonnull QEmuIdAllocator predecessor) {
033        this.driveIndex = predecessor.driveIndex;
034        this.networkIndex = predecessor.networkIndex;
035        this.networkBootIndex = predecessor.networkBootIndex;
036        this.pciAddress = predecessor.pciAddress;
037    }
038
039    @Nonnegative
040    public int newDriveIndex() {
041        return ++driveIndex;
042    }
043
044    @Nonnegative
045    public int newNetworkIndex() {
046        return ++networkIndex;
047    }
048
049    @Nonnegative
050    public int newNetworkBootIndex() {
051        return ++networkBootIndex;
052    }
053
054    /**
055     * Returns a comma-separated list of new PCI addresses.
056     *
057     * @param count How many addresses to return.
058     * @param separator The separator to use between addresses.
059     * @return A separated String of new PCI addresses.
060     */
061    @Nonnull
062    public String newPciAddresses(@Nonnegative int count, @Nonnull String separator) {
063        StringBuilder buf = new StringBuilder();
064        for (int i = 0; i < count; i++) {
065            if (i > 0)
066                buf.append(separator);
067            buf.append(newPciAddress());
068        }
069        return buf.toString();
070    }
071
072    /** Returns a new PCI address. */
073    @Nonnull
074    public String newPciAddress() {
075        return "0x" + Integer.toHexString(++pciAddress);
076    }
077}