7e5d01844a8800453e89635c62b480ab82326924
[bgpcep.git] / bgp / flowspec / src / main / java / org / opendaylight / protocol / bgp / flowspec / handlers / AbstractOperandParser.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 com.google.common.annotations.VisibleForTesting;
11 import io.netty.buffer.ByteBuf;
12 import java.util.Set;
13
14 /**
15  * Top-level abstract class for all defined operands.
16  *
17  * @param <T> operand Type
18  */
19 public abstract class AbstractOperandParser<T> {
20
21     @VisibleForTesting
22     public static final String AND_BIT_VALUE = "and-bit";
23     @VisibleForTesting
24     public static final String END_OF_LIST_VALUE = "end-of-list";
25
26     protected static final int OPERAND_LENGTH = 8;
27
28     protected static final int END_OF_LIST = 0;
29     protected static final int AND_BIT = 1;
30
31     protected static final int LENGTH_SHIFT = 4;
32
33     private static final int LENGTH_BITMASK = 48;
34
35     @VisibleForTesting
36     public static short parseLength(final byte op) {
37         return (short) (1 << ((op & LENGTH_BITMASK) >> LENGTH_SHIFT));
38     }
39
40     /**
41      * Creates operand from a set of operand values.
42      *
43      * @param opValues set of operand values
44      * @return specific type of operand
45      */
46     protected abstract T create(final Set<String> opValues);
47
48     /**
49      * Serializes operand to bytes.
50      *
51      * @param op operand to be serialized
52      * @param length value of the 'length' field
53      * @param endOfList if this operand is at the end of the list
54      * @param buffer where the operand will be serialized to
55      */
56     protected abstract void serialize(final T op, final int length, final boolean endOfList,
57             final ByteBuf buffer);
58
59     /**
60      * Parses operand from byte value.
61      *
62      * @param op byte representation of an operand
63      * @return operand object
64      */
65     protected abstract T parse(final byte op);
66
67     /**
68      * Creates a string representation of the operand.
69      * E.g. : 'and does not match'
70      *
71      * @param op operand
72      * @param isFirst true if this operand is the first in list of operands
73      * @return String representation of the operand
74      */
75     protected abstract String toString(final T op, final boolean isFirst);
76 }