Merge "Bug-612: ietf-stateful07 serializers - improved code defense."
[bgpcep.git] / bgp / parser-spi / src / main / java / org / opendaylight / protocol / bgp / parser / spi / MessageUtil.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 com.google.common.annotations.VisibleForTesting;
11 import com.google.common.primitives.UnsignedBytes;
12
13 import io.netty.buffer.ByteBuf;
14
15 import java.util.Arrays;
16
17 public final class MessageUtil {
18
19     @VisibleForTesting
20     public static final int MARKER_LENGTH = 16;
21     @VisibleForTesting
22     public static final int COMMON_HEADER_LENGTH = 19;
23     private static final byte[] MARKER = new byte[MARKER_LENGTH];
24
25     static {
26         Arrays.fill(MARKER, 0, MARKER_LENGTH, UnsignedBytes.MAX_VALUE);
27     }
28
29     private MessageUtil() {
30     }
31
32     /**
33      * Adds header to message value.
34      *
35      * @param type of the message
36      * @param value message value
37      * @param buffer ByteBuf where the message will be copied with its header
38      */
39     public static void formatMessage(final int type, final ByteBuf body, final ByteBuf buffer) {
40         buffer.writeBytes(MARKER);
41         buffer.writeShort(body.writerIndex() + COMMON_HEADER_LENGTH);
42         buffer.writeByte(type);
43         buffer.writeBytes(body);
44     }
45 }