summaryrefslogtreecommitdiffstats
path: root/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/provisioning/NodeIndices.java
blob: a5a098dbfd6a17a78718f2b335229ee80416299a (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.hosted.provision.provisioning;

import java.util.List;

import static java.util.Comparator.naturalOrder;

/**
 * Tracks indices of a node cluster, and proposes the index of the next allocation.
 *
 * @author jonmv
 */
class NodeIndices {

    private final List<Integer> used;

    private int last;
    private int probe;

    /** Pass the list of current indices in the cluster. */
    NodeIndices(List<Integer> used) {
        this.used = List.copyOf(used);
        this.last = -1;
        this.probe = last;
    }

    /** Returns the next available index and commits to using it. Throws if a probe is ongoing. */
    int next() {
        if (probe != last)
            throw new IllegalStateException("Must commit ongoing probe before calling 'next'");

        probeNext();
        commitProbe();
        return last;
    }

    /** Returns the next available index, without committing to using it. Yields increasing indices when called multiple times. */
    int probeNext() {
        while (used.contains(++probe));
        return probe;
    }

    /** Commits to using all indices returned by an ongoing probe. */
    void commitProbe() {
        last = probe;
    }

    /** Resets any probed state to what's currently committed. */
    void resetProbe() {
        probe = last;
    }

}