Add Uint saturated converters
[yangtools.git] / yang / yang-common / src / main / java / org / opendaylight / yangtools / yang / common / Uint32.java
index 6b3b39291483b9ce191b953a49d74709480a3bd4..5fa071378de0f3c5f47b163984ebecea9f9c46ad 100644 (file)
@@ -245,6 +245,57 @@ public class Uint32 extends Number implements CanonicalValue<Uint32> {
         return instanceFor(Integer.parseUnsignedInt(requireNonNull(string), radix));
     }
 
+    /**
+     * Returns an {@code Uint32} corresponding to a given {@code byteVal} if it is representable. If the value is
+     * negative {@link #ZERO} will be returned.
+     *
+     * @param byteVal byte value
+     * @return A Uint32 instance
+     */
+    public static Uint32 saturatedOf(final byte byteVal) {
+        return byteVal < 0 ? Uint32.ZERO : instanceFor(byteVal);
+    }
+
+    /**
+     * Returns an {@code Uint32} corresponding to a given {@code shortVal} if it is representable. If the value is
+     * negative {@link #ZERO} will be returned.
+     *
+     * @param shortVal short value
+     * @return A Uint32 instance
+     */
+    public static Uint32 saturatedOf(final short shortVal) {
+        return shortVal < 0 ? Uint32.ZERO : instanceFor(shortVal);
+    }
+
+    /**
+     * Returns an {@code Uint32} corresponding to a given {@code intVal} if it is representable. If the value is
+     * negative {@link #ZERO} will be returned.
+     *
+     * @param intVal int value
+     * @return A Uint32 instance
+     */
+    public static Uint32 saturatedOf(final int intVal) {
+        return intVal < 0 ? Uint32.ZERO : instanceFor(intVal);
+    }
+
+    /**
+     * Returns an {@code Uint32} corresponding to a given {@code longVal} if it is representable. If the value is
+     * negative {@link #ZERO} will be returned. If the value is greater than 4294967295, {@link #MAX_VALUE} will be
+     * returned.
+     *
+     * @param longVal long value
+     * @return A Uint32 instance
+     */
+    public static Uint32 saturatedOf(final long longVal) {
+        if (longVal < 0) {
+            return Uint32.ZERO;
+        }
+        if (longVal >= MAX_VALUE_LONG) {
+            return Uint32.MAX_VALUE;
+        }
+        return instanceFor((int) longVal);
+    }
+
     /**
      * {@inheritDoc}
      *
@@ -344,6 +395,16 @@ public class Uint32 extends Number implements CanonicalValue<Uint32> {
         return Uint64.fromLongBits(longValue());
     }
 
+    public final Uint8 toSaturatedUint8() {
+        return Uint8.saturatedOf(toJava());
+    }
+
+    public final Uint16 toSaturatedUint16() {
+        return Uint16.saturatedOf(toJava());
+    }
+
+    // FIXME: more saturated conversions
+
     @Override
     public final int hashCode() {
         return Integer.hashCode(value);