b2e2e4b0cf9e545b75f421d259d70d6970f5283a
[yangtools.git] / common / yang-common / src / main / java / org / opendaylight / yangtools / yang / common / Uint64.java
1 /*
2  * Copyright (c) 2015 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.yang.common;
9
10 import static java.util.Objects.requireNonNull;
11
12 import com.google.common.annotations.Beta;
13 import com.google.common.collect.Interner;
14 import com.google.common.collect.Interners;
15 import com.google.common.primitives.UnsignedLong;
16 import java.math.BigInteger;
17 import org.eclipse.jdt.annotation.NonNull;
18 import org.eclipse.jdt.annotation.NonNullByDefault;
19 import org.eclipse.jdt.annotation.Nullable;
20 import org.opendaylight.yangtools.concepts.Either;
21
22 /**
23  * Dedicated type for YANG's 'type uint64' type.
24  *
25  * @author Robert Varga
26  */
27 @Beta
28 @NonNullByDefault
29 public class Uint64 extends Number implements CanonicalValue<Uint64> {
30     public static final class Support extends AbstractCanonicalValueSupport<Uint64> {
31         public Support() {
32             super(Uint64.class);
33         }
34
35         @Override
36         public Either<Uint64, CanonicalValueViolation> fromString(final String str) {
37             try {
38                 return Either.ofFirst(Uint64.valueOf(str));
39             } catch (IllegalArgumentException e) {
40                 return CanonicalValueViolation.variantOf(e);
41             }
42         }
43     }
44
45     private static final CanonicalValueSupport<Uint64> SUPPORT = new Support();
46     private static final long serialVersionUID = 1L;
47     private static final String MAX_VALUE_STR = Long.toUnsignedString(-1);
48
49     private static final String CACHE_SIZE_PROPERTY = "org.opendaylight.yangtools.yang.common.Uint64.cache.size";
50     private static final int DEFAULT_CACHE_SIZE = 256;
51
52     /**
53      * Tunable cache for values. By default it holds {@value #DEFAULT_CACHE_SIZE} entries. This can be
54      * changed via {@value #CACHE_SIZE_PROPERTY} system property.
55      */
56     private static final long CACHE_SIZE;
57
58     static {
59         final int p = Integer.getInteger(CACHE_SIZE_PROPERTY, DEFAULT_CACHE_SIZE);
60         CACHE_SIZE = p >= 0 ? Math.min(p, Integer.MAX_VALUE) : DEFAULT_CACHE_SIZE;
61     }
62
63     private static final @NonNull Uint64[] CACHE;
64
65     static {
66         final Uint64[] c = new Uint64[(int) CACHE_SIZE];
67         for (int i = 0; i < c.length; ++i) {
68             c[i] = new Uint64(i);
69         }
70         CACHE = c;
71     }
72
73     private static final Interner<Uint64> INTERNER = Interners.newWeakInterner();
74
75     /**
76      * Value of {@code 0}.
77      */
78     public static final Uint64 ZERO = valueOf(0).intern();
79     /**
80      * Value of {@code 1}.
81      */
82     public static final Uint64 ONE = valueOf(1).intern();
83     /**
84      * Value of {@code 2}.
85      */
86     public static final Uint64 TWO = valueOf(2).intern();
87     /**
88      * Value of {@code 10}.
89      */
90     public static final Uint64 TEN = valueOf(10).intern();
91     /**
92      * Value of {@code 18446744073709551615}.
93      */
94     public static final Uint64 MAX_VALUE = fromLongBits(-1).intern();
95
96     private final long value;
97
98     private Uint64(final long value) {
99         this.value = value;
100     }
101
102     protected Uint64(final Uint64 other) {
103         this(other.value);
104     }
105
106     private static Uint64 instanceFor(final long value) {
107         return value >= 0 && value < CACHE.length ? CACHE[(int) value] : new Uint64(value);
108     }
109
110     /**
111      * Returns an {@code Uint64} corresponding to a given bit representation. The argument is interpreted as an
112      * unsigned 64-bit value.
113      *
114      * @param bits unsigned bit representation
115      * @return A Uint64 instance
116      */
117     public static Uint64 fromLongBits(final long bits) {
118         return instanceFor(bits);
119     }
120
121     /**
122      * Returns an {@code Uint64} corresponding to a given {@code byteVal}. The inverse operation is
123      * {@link #byteValue()}.
124      *
125      * @param byteVal byte value
126      * @return A Uint64 instance
127      * @throws IllegalArgumentException if byteVal is less than zero
128      */
129     public static Uint64 valueOf(final byte byteVal) {
130         UintConversions.checkNonNegative(byteVal, MAX_VALUE_STR);
131         return instanceFor(byteVal);
132     }
133
134     /**
135      * Returns an {@code Uint64} corresponding to a given {@code shortVal}. The inverse operation is
136      * {@link #shortValue()}.
137      *
138      * @param shortVal short value
139      * @return A Uint64 instance
140      * @throws IllegalArgumentException if shortVal is less than zero
141      */
142     public static Uint64 valueOf(final short shortVal) {
143         UintConversions.checkNonNegative(shortVal, MAX_VALUE_STR);
144         return instanceFor(shortVal);
145     }
146
147     /**
148      * Returns an {@code Uint64} corresponding to a given {@code intVal}. The inverse operation is {@link #intValue()}.
149      *
150      * @param intVal int value
151      * @return A Uint64 instance
152      * @throws IllegalArgumentException if intVal is less than zero
153      */
154     public static Uint64 valueOf(final int intVal) {
155         UintConversions.checkNonNegative(intVal, MAX_VALUE_STR);
156         return instanceFor(intVal);
157     }
158
159     /**
160      * Returns an {@code Uint64} corresponding to a given {@code longVal}, which is checked for range.
161      * See also {@link #longValue()} and {@link #fromLongBits(long)}.
162      *
163      * @param longVal long value
164      * @return A Uint8 instance
165      * @throws IllegalArgumentException if longVal is less than zero
166      */
167     public static Uint64 valueOf(final long longVal) {
168         if (longVal >= 0) {
169             return instanceFor(longVal);
170         }
171         throw new IllegalArgumentException("Invalid range: " + longVal + ", expected: [[0..18446744073709551615]].");
172     }
173
174     /**
175      * Returns an {@code Uint64} corresponding to a given {@code uint}.
176      *
177      * @param uint Uint8 value
178      * @return A Uint64 instance
179      * @throws NullPointerException if uint is null
180      */
181     public static Uint64 valueOf(final Uint8 uint) {
182         return instanceFor(uint.shortValue());
183     }
184
185     /**
186      * Returns an {@code Uint64} corresponding to a given {@code uint}.
187      *
188      * @param uint Uint16 value
189      * @return A Uint64 instance
190      * @throws NullPointerException if uint is null
191      */
192     public static Uint64 valueOf(final Uint16 uint) {
193         return instanceFor(uint.intValue());
194     }
195
196     /**
197      * Returns an {@code Uint64} corresponding to a given {@code uint}.
198      *
199      * @param uint Uint32 value
200      * @return A Uint64 instance
201      * @throws NullPointerException if uint is null
202      */
203     public static Uint64 valueOf(final Uint32 uint) {
204         return instanceFor(uint.longValue());
205     }
206
207     /**
208      * Returns an {@code Uint64} corresponding to a given {@code ulong}.
209      *
210      * @param ulong UnsignedLong value
211      * @return A Uint64 instance
212      * @throws NullPointerException if ulong is null
213      */
214     public static Uint64 valueOf(final UnsignedLong ulong) {
215         return instanceFor(ulong.longValue());
216     }
217
218     /**
219      * Returns an {@code Uint64} corresponding to a given {@code bigInt}.
220      *
221      * @param bigInt BigInteger value
222      * @return A Uint64 instance
223      * @throws NullPointerException if bigInt is null
224      * @throws IllegalArgumentException if bigInt is less than zero or greater than 18446744073709551615
225      */
226     public static Uint64 valueOf(final BigInteger bigInt) {
227         if (bigInt.signum() >= 0 && bigInt.bitLength() <= Long.SIZE) {
228             return instanceFor(bigInt.longValue());
229         }
230         throw new IllegalArgumentException("Invalid range: " + bigInt + ", expected: [[0..18446744073709551615]].");
231     }
232
233     /**
234      * Returns an {@code Uint32} holding the value of the specified {@code String}, parsed as an unsigned {@code long}
235      * value.
236      *
237      * @param string String to parse
238      * @return A Uint64 instance
239      * @throws NullPointerException if string is null
240      * @throws IllegalArgumentException if the parsed value is less than zero or greater than 18446744073709551615
241      * @throws NumberFormatException if the string does not contain a parsable unsigned {@code long} value.
242      */
243     public static Uint64 valueOf(final String string) {
244         return valueOf(string, 10);
245     }
246
247     /**
248      * Returns an {@code Uint64} holding the value of the specified {@code String}, parsed as an unsigned {@code long}
249      * value.
250      *
251      * @param string String to parse
252      * @param radix Radix to use
253      * @return A Uint64 instance
254      * @throws NullPointerException if string is null
255      * @throws IllegalArgumentException if the parsed value is less than zero or greater than 18446744073709551615
256      * @throws NumberFormatException if the string does not contain a parsable unsigned {@code long} value, or if the
257      *                               {@code radix} is outside of allowed range.
258      */
259     public static Uint64 valueOf(final String string, final int radix) {
260         return instanceFor(Long.parseUnsignedLong(requireNonNull(string), radix));
261     }
262
263     /**
264      * Returns an {@code Uint64} corresponding to a given {@code byteVal} if it is representable. If the value is
265      * negative {@link #ZERO} will be returned.
266      *
267      * @param byteVal byte value
268      * @return A Uint64 instance
269      */
270     public static Uint64 saturatedOf(final byte byteVal) {
271         return byteVal <= 0 ? Uint64.ZERO : instanceFor(byteVal);
272     }
273
274     /**
275      * Returns an {@code Uint32} corresponding to a given {@code shortVal} if it is representable. If the value is
276      * negative {@link #ZERO} will be returned.
277      *
278      * @param shortVal short value
279      * @return A Uint32 instance
280      */
281     public static Uint64 saturatedOf(final short shortVal) {
282         return shortVal <= 0 ? Uint64.ZERO : instanceFor(shortVal);
283     }
284
285     /**
286      * Returns an {@code Uint64} corresponding to a given {@code intVal} if it is representable. If the value is
287      * negative {@link #ZERO} will be returned.
288      *
289      * @param intVal int value
290      * @return A Uint64 instance
291      */
292     public static Uint64 saturatedOf(final int intVal) {
293         return intVal <= 0 ? Uint64.ZERO : instanceFor(intVal);
294     }
295
296     /**
297      * Returns an {@code Uint64} corresponding to a given {@code longVal} if it is representable. If the value is
298      * negative {@link #ZERO} will be returned.
299      *
300      * @param longVal long value
301      * @return A Uint64 instance
302      */
303     public static Uint64 saturatedOf(final long longVal) {
304         return longVal <= 0 ? Uint64.ZERO : instanceFor(longVal);
305     }
306
307     /**
308      * Returns an {@code Uint64} corresponding to a given {@code longVal} if it is representable. If the value is
309      * negative {@link #ZERO} will be returned. If the value is greater than 18446744073709551615, {@link #MAX_VALUE}
310      * will be returned.
311      *
312      * @param bigInt BigInteger value
313      * @return A Uint64 instance
314      * @throws NullPointerException if bigInt is null
315      */
316     public static Uint64 saturatedOf(final BigInteger bigInt) {
317         if (bigInt.signum() <= 0) {
318             return Uint64.ZERO;
319         }
320         return bigInt.bitLength() > Long.SIZE ? Uint64.MAX_VALUE : instanceFor(bigInt.longValue());
321     }
322
323     @Override
324     public final int intValue() {
325         return (int)value;
326     }
327
328     /**
329      * {@inheritDoc}
330      *
331      * <p>
332      * The inverse operation is {@link #fromLongBits(long)}. In case this value is greater than {@link Long#MAX_VALUE},
333      * the returned value will be equal to {@code this - 2^64}.
334      */
335     @Override
336     public final long longValue() {
337         return value;
338     }
339
340     @Override
341     public final float floatValue() {
342         // TODO: ditch Guava
343         return UnsignedLong.fromLongBits(value).floatValue();
344     }
345
346     @Override
347     public final double doubleValue() {
348         // TODO: ditch Guava
349         return UnsignedLong.fromLongBits(value).doubleValue();
350     }
351
352     @Override
353     @SuppressWarnings("checkstyle:parameterName")
354     public final int compareTo(final Uint64 o) {
355         return Long.compareUnsigned(value, o.value);
356     }
357
358     @Override
359     public final String toCanonicalString() {
360         return Long.toUnsignedString(value);
361     }
362
363     @Override
364     public final CanonicalValueSupport<Uint64> support() {
365         return SUPPORT;
366     }
367
368     /**
369      * Return an interned (shared) instance equivalent to this object. This may return the same object.
370      *
371      * @return A shared instance.
372      */
373     public final Uint64 intern() {
374         return value >= 0 && value < CACHE_SIZE ? this : INTERNER.intern(this);
375     }
376
377     /**
378      * Convert this value to a {@link BigInteger}.
379      *
380      * @return A BigInteger instance
381      */
382     public final BigInteger toJava() {
383         // FIXME: ditch the Guava transition
384         return toGuava().bigIntegerValue();
385     }
386
387     /**
388      * Convert this value to an {@link UnsignedLong}.
389      *
390      * @return An UnsignedLong instance
391      */
392     public final UnsignedLong toGuava() {
393         return UnsignedLong.fromLongBits(value);
394     }
395
396     /**
397      * Convert this value to a {@code Uint8}.
398      *
399      * @return A Uint8
400      * @throws IllegalArgumentException if this value is greater than 255.
401      */
402     public final Uint8 toUint8() {
403         if ((value & 0xFFFFFFFFFFFFFF00L) != 0) {
404             UintConversions.throwIAE(toString(), 255);
405         }
406         return Uint8.fromByteBits((byte) value);
407     }
408
409     /**
410      * Convert this value to a {@code Uint16}.
411      *
412      * @return A Uint16
413      * @throws IllegalArgumentException if this value is greater than 65535.
414      */
415     public final Uint16 toUint16() {
416         if ((value & 0xFFFFFFFFFFFF0000L) != 0) {
417             UintConversions.throwIAE(toString(), 65535);
418         }
419         return Uint16.fromShortBits((short) value);
420     }
421
422     /**
423      * Convert this value to a {@code Uint64}.
424      *
425      * @return A Uint32
426      * @throws IllegalArgumentException if this value is greater than 4294967295.
427      */
428     public final Uint32 toUint32() {
429         if ((value & 0xFFFFFFFF00000000L) != 0) {
430             UintConversions.throwIAE(toString(), 4294967295L);
431         }
432         return Uint32.fromIntBits((int) value);
433     }
434
435     @Override
436     public final int hashCode() {
437         return Long.hashCode(value);
438     }
439
440     @Override
441     public final boolean equals(final @Nullable Object obj) {
442         return this == obj || obj instanceof Uint64 && value == ((Uint64)obj).value;
443     }
444
445     /**
446      * A slightly faster version of {@link #equals(Object)}.
447      *
448      * @param obj Uint64 object
449      * @return {@code true} if this object is the same as the obj argument; {@code false} otherwise.
450      */
451     public final boolean equals(final @Nullable Uint64 obj) {
452         return this == obj || obj != null && value == obj.value;
453     }
454
455     @Override
456     public final String toString() {
457         return toCanonicalString();
458     }
459
460     private Object readResolve() {
461         return instanceFor(value);
462     }
463 }