4923290ca7dd244b9e64e49f731d54e609b72b4c
[yangtools.git] / third-party / triemap / src / main / java / org / opendaylight / yangtools / triemap / Equivalence.java
1 /*
2  * (C) Copyright 2016 Pantheon Technologies, s.r.o. and others.
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 org.opendaylight.yangtools.triemap;
17
18 import java.io.Serializable;
19 import javax.annotation.Nonnull;
20
21 /**
22  * Internal equivalence class, similar to {@link com.google.common.base.Equivalence}, but explicitly not handling
23  * nulls. We use equivalence only for keys, which are guaranteed to be non-null.
24  *
25  * @author Robert Varga
26  */
27 abstract class Equivalence<T> implements Serializable {
28     private static final long serialVersionUID = 1L;
29
30     private static final class Equals extends Equivalence<Object> {
31         private static final long serialVersionUID = 1L;
32
33         static final Equals INSTANCE = new Equals();
34
35         @Override
36         boolean equivalent(final Object a, final Object b) {
37             return a.equals(b);
38         }
39
40         @Override
41         Object readResolve() {
42             return INSTANCE;
43         }
44     }
45
46     private static final class Identity extends Equivalence<Object> {
47         private static final long serialVersionUID = 1L;
48
49         static final Identity INSTANCE = new Identity();
50
51         @Override
52         boolean equivalent(final Object a, final Object b) {
53             return a == b;
54         }
55
56         @Override
57         Object readResolve() {
58             return INSTANCE;
59         }
60     }
61
62     static Equivalence<Object> equals() {
63         return Equals.INSTANCE;
64     }
65
66     static Equivalence<Object> identity() {
67         return Identity.INSTANCE;
68     }
69
70     final int hash(@Nonnull final T t) {
71         int h = t.hashCode();
72
73         // This function ensures that hashCodes that differ only by
74         // constant multiples at each bit position have a bounded
75         // number of collisions (approximately 8 at default load factor).
76         h ^= (h >>> 20) ^ (h >>> 12);
77         h ^= (h >>> 7) ^ (h >>> 4);
78         return h;
79     }
80
81     abstract boolean equivalent(@Nonnull T a, @Nonnull T b);
82
83     abstract Object readResolve();
84 }