Import atomix/{storage,utils}
[controller.git] / third-party / atomix / utils / src / main / java / io / atomix / utils / time / LogicalTimestamp.java
1 /*
2  * Copyright 2016-present Open Networking Foundation
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 package io.atomix.utils.time;
17
18 import com.google.common.base.Preconditions;
19 import com.google.common.collect.ComparisonChain;
20
21 import java.util.Objects;
22
23 import static com.google.common.base.MoreObjects.toStringHelper;
24
25 /**
26  * Timestamp based on logical sequence value.
27  * <p>
28  * LogicalTimestamps are ordered by their sequence values.
29  */
30 public class LogicalTimestamp implements Timestamp {
31
32   /**
33    * Returns a new logical timestamp for the given logical time.
34    *
35    * @param value the logical time for which to create a new logical timestamp
36    * @return the logical timestamp
37    */
38   public static LogicalTimestamp of(long value) {
39     return new LogicalTimestamp(value);
40   }
41
42   private final long value;
43
44   public LogicalTimestamp(long value) {
45     this.value = value;
46   }
47
48   /**
49    * Returns the sequence value.
50    *
51    * @return sequence value
52    */
53   public long value() {
54     return this.value;
55   }
56
57   /**
58    * Returns the timestamp as a version.
59    *
60    * @return the timestamp as a version
61    */
62   public Version asVersion() {
63     return new Version(value);
64   }
65
66   @Override
67   public int compareTo(Timestamp o) {
68     Preconditions.checkArgument(o instanceof LogicalTimestamp,
69         "Must be LogicalTimestamp", o);
70     LogicalTimestamp that = (LogicalTimestamp) o;
71
72     return ComparisonChain.start()
73         .compare(this.value, that.value)
74         .result();
75   }
76
77   @Override
78   public int hashCode() {
79     return Long.hashCode(value);
80   }
81
82   @Override
83   public boolean equals(Object obj) {
84     if (this == obj) {
85       return true;
86     }
87     if (!(obj instanceof LogicalTimestamp)) {
88       return false;
89     }
90     LogicalTimestamp that = (LogicalTimestamp) obj;
91     return Objects.equals(this.value, that.value);
92   }
93
94   @Override
95   public String toString() {
96     return toStringHelper(getClass())
97         .add("value", value)
98         .toString();
99   }
100 }