aboutsummaryrefslogtreecommitdiffstats
path: root/vdslib/src/main/java/com/yahoo/vdslib/state/Node.java
blob: 445472bba4c016d63ed2d047751edaa07de62390 (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
54
55
56
57
58
59
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vdslib.state;

/**
 * A node in a content cluster. This is immutable.
 */
public class Node implements Comparable<Node> {

    private final NodeType type;
    private final int index;

    public Node(NodeType type, int index) {
        this.type = type;
        this.index = index;
    }

    public Node(String serialized) {
        int dot = serialized.lastIndexOf('.');
        if (dot < 0) throw new IllegalArgumentException("Not a legal node string '" + serialized + "'.");
        type = NodeType.get(serialized.substring(0, dot));
        index = Integer.parseInt(serialized.substring(dot + 1));
    }

    public static Node ofStorage(int index) {
        return new Node(NodeType.STORAGE, index);
    }

    public static Node ofDistributor(int index) {
        return new Node(NodeType.DISTRIBUTOR, index);
    }

    public String toString() {
        return type.toString() + "." + index;
    }

    public NodeType getType() { return type; }
    public int getIndex() { return index; }

    private int getOrdering() {
        return (type.equals(NodeType.STORAGE) ? 65536 : 0) + index;
    }

    @Override
    public int compareTo(Node n) {
        return getOrdering() - n.getOrdering();
    }

    @Override
    public int hashCode() {
        return type.hashCode() ^ index;
    }

    @Override
    public boolean equals(Object o) {
        if (!(o instanceof Node n)) return false;
        return (type.equals(n.type) && index == n.index);
    }

}