2 * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.protocol.util;
10 import io.netty.buffer.ByteBuf;
11 import io.netty.buffer.Unpooled;
12 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.network.concepts.rev131125.MplsLabel;
13 import org.opendaylight.yangtools.yang.common.Uint32;
16 * Util class for encoding/decoding 20bit leftmost value.
18 public final class MplsLabelUtil {
20 private static final int LABEL_OFFSET = 4;
21 private static final byte BOTTOM_LABEL_BIT = 0x1;
23 private MplsLabelUtil() {
24 throw new UnsupportedOperationException();
28 * Creates and returns MplsLabel object from 20 leftmost bits in the incoming buffer.
29 * Moves reader index by 3.
31 * @param buffer expecting 3 bytes with 20 leftmost bits as label
32 * @return MplsLabel object
34 public static MplsLabel mplsLabelForByteBuf(final ByteBuf buffer) {
35 return new MplsLabel(Uint32.valueOf(buffer.readUnsignedMedium() >> LABEL_OFFSET));
39 * Serializes incoming MplsLabel without bottom bit.
41 * @param label MplsLabel object
44 public static ByteBuf byteBufForMplsLabel(final MplsLabel label) {
45 return Unpooled.copyMedium(intForMplsLabel(label));
49 * Serializes incoming MplsLabel with bottom bit.
51 * @param label MplsLabel object
54 public static ByteBuf byteBufForMplsLabelWithBottomBit(final MplsLabel label) {
55 return Unpooled.copyMedium(intForMplsLabelWithBottomBit(label));
59 * Makes a value of incoming label 20 leftmost bits in 24bit number.
62 * @return shifted value
64 public static int intForMplsLabel(final MplsLabel label) {
65 return label.getValue().intValue() << LABEL_OFFSET;
69 * Makes a value of incoming label 20 leftmost bits in 24bit number and sets bottom bit.
72 * @return value with bottom bit
74 private static int intForMplsLabelWithBottomBit(final MplsLabel label) {
75 final int value = intForMplsLabel(label);
76 return setBottomBit(value);
80 * Sets bottom bit of 3 byte value.
82 * @param value where 20 leftmost bits are label
83 * @return value with set bottom bit
85 private static int setBottomBit(final int value) {
86 return value | BOTTOM_LABEL_BIT;
92 * @param slice with 20 leftmost bits as label
93 * @return value of bottom bit
95 public static boolean getBottomBit(final ByteBuf slice) {
96 return (slice.getUnsignedMedium(slice.readerIndex()) & BOTTOM_LABEL_BIT) == 1;