Bump upstreams to 2022.09
[bgpcep.git] / bgp / parser-spi / src / main / java / org / opendaylight / protocol / bgp / parser / spi / ParameterUtil.java
1 /*
2  * Copyright (c) 2013 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.parser.spi;
9
10 import static com.google.common.base.Preconditions.checkArgument;
11
12 import io.netty.buffer.ByteBuf;
13 import org.opendaylight.protocol.util.Values;
14
15 /**
16  * Utility class which is intended for formatting parameter.
17  */
18 public final class ParameterUtil {
19     private ParameterUtil() {
20     }
21
22     /**
23      * Adds header to parameter value in RFC4271 format.
24      *
25      * @param type of the parameter
26      * @param value parameter value
27      * @param buffer ByteBuf where the parameter will be copied with its header
28      * @throws IllegalArgumentException if value length exceeds 255 bytes
29      */
30     public static void formatParameter(final int type, final ByteBuf value, final ByteBuf buffer)
31             throws ParameterLengthOverflowException {
32         final int valueLength = value.writerIndex();
33         ParameterLengthOverflowException.throwIf(valueLength > Values.UNSIGNED_BYTE_MAX_VALUE,
34             "Cannot encode %s-byte value", valueLength);
35
36         buffer.writeByte(type);
37         buffer.writeByte(valueLength);
38         buffer.writeBytes(value);
39     }
40
41     /**
42      * Adds header to parameter value in draft-ietf-idr-ext-opt-param-05 format.
43      *
44      * @param type of the parameter
45      * @param value parameter value
46      * @param buffer ByteBuf where the parameter will be copied with its header
47      * @throws IllegalArgumentException if value length exceeds 65535 bytes
48      */
49     public static void formatExtendedParameter(final int type, final ByteBuf value, final ByteBuf buffer) {
50         final int valueLength = value.writerIndex();
51         checkArgument(valueLength < Values.UNSIGNED_SHORT_MAX_VALUE, "Cannot encode %s-byte value", valueLength);
52
53         buffer.writeByte(type);
54         buffer.writeShort(valueLength);
55         buffer.writeBytes(value);
56     }
57 }