Define a feature-parent
[yangtools.git] / common / concepts / src / main / java / org / opendaylight / yangtools / concepts / SemVer.java
1 /*
2  * Copyright (c) 2016 Pantheon Technologies s.r.o. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.yangtools.concepts;
9
10 import static com.google.common.base.Preconditions.checkArgument;
11
12 import java.io.Serializable;
13 import org.checkerframework.checker.index.qual.NonNegative;
14 import org.eclipse.jdt.annotation.NonNull;
15
16 /**
17  * A single version according to <a href="http://semver.org/">Semantic Versioning</a>.
18  *
19  * @param major Major version number
20  * @param minor Minor version number
21  * @param patch Patch version number
22  */
23 public record SemVer(@NonNegative int major, @NonNegative int minor, @NonNegative int patch)
24         implements Comparable<SemVer>, Serializable {
25     @java.io.Serial
26     private static final long serialVersionUID = 1L;
27
28     public SemVer {
29         checkArgument(major >= 0, "Major version has to be non-negative");
30         checkArgument(minor >= 0, "Minor version has to be non-negative");
31         checkArgument(patch >= 0, "Patch version has to be non-negative");
32     }
33
34     public SemVer(final @NonNegative int major) {
35         this(major, 0);
36     }
37
38     public SemVer(final @NonNegative int major, final @NonNegative int minor) {
39         this(major, minor, 0);
40     }
41
42     public static @NonNull SemVer valueOf(final @NonNull String str) {
43         final int minorIdx = str.indexOf('.');
44         if (minorIdx == -1) {
45             return new SemVer(Integer.parseInt(str));
46         }
47
48         final String minorStr;
49         final int patchIdx = str.indexOf('.', minorIdx + 1);
50         if (patchIdx == -1) {
51             minorStr = str.substring(minorIdx + 1);
52             return new SemVer(Integer.parseInt(str.substring(0, minorIdx), 10), Integer.parseInt(minorStr, 10));
53         }
54
55         minorStr = str.substring(minorIdx + 1, patchIdx);
56         return new SemVer(Integer.parseInt(str.substring(0, minorIdx), 10), Integer.parseInt(minorStr, 10),
57             Integer.parseInt(str.substring(patchIdx + 1), 10));
58     }
59
60     @Override
61     public int compareTo(final SemVer other) {
62         int cmp = Integer.compare(major, other.major);
63         if (cmp == 0) {
64             cmp = Integer.compare(minor, other.minor);
65             if (cmp == 0) {
66                 cmp = Integer.compare(patch, other.patch);
67             }
68         }
69         return cmp;
70     }
71
72     @Override
73     public String toString() {
74         return major + "." + minor + "." + patch;
75     }
76 }