Specialize Util.writeShortest() for Uint{16,32}
[bgpcep.git] / bgp / extensions / flowspec / src / main / java / org / opendaylight / protocol / bgp / flowspec / handlers / Util.java
1 /*
2  * Copyright (c) 2015 Cisco Systems, Inc. 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.protocol.bgp.flowspec.handlers;
9
10 import io.netty.buffer.ByteBuf;
11 import org.opendaylight.protocol.util.Values;
12 import org.opendaylight.yangtools.yang.common.Uint16;
13 import org.opendaylight.yangtools.yang.common.Uint32;
14
15 public final class Util {
16     private Util() {
17         // Hidden on purpose
18     }
19
20     /**
21      * Given an uint16, this method instead of writing the value in 2B field, compresses the value to lowest required
22      * byte field depending on the value.
23      *
24      * @param value uint16 to be written
25      * @param buffer ByteBuf where the value will be written
26      */
27     public static void writeShortest(final Uint16 value, final ByteBuf buffer) {
28         final int unsigned = value.toJava();
29         if (unsigned <= Values.UNSIGNED_BYTE_MAX_VALUE) {
30             buffer.writeByte(unsigned);
31         } else {
32             buffer.writeShort(unsigned);
33         }
34     }
35
36     /**
37      * Given an uint32, this method instead of writing the value in 4B field, compresses the value to lowest required
38      * byte field depending on the value.
39      *
40      * @param value uint32 to be written
41      * @param buffer ByteBuf where the value will be written
42      */
43     public static void writeShortest(final Uint32 value, final ByteBuf buffer) {
44         final long unsigned = value.toJava();
45         if (unsigned <= Values.UNSIGNED_BYTE_MAX_VALUE) {
46             buffer.writeByte((int) unsigned);
47         } else if (unsigned <= Values.UNSIGNED_SHORT_MAX_VALUE) {
48             buffer.writeShort((int) unsigned);
49         } else {
50             buffer.writeInt(value.intValue());
51         }
52     }
53 }