Initial code drop
[bgpcep.git] / bgp / parser-impl / src / main / java / org / opendaylight / protocol / bgp / parser / impl / message / update / AsPathSegmentParser.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
9 package org.opendaylight.protocol.bgp.parser.impl.message.update;
10
11 import java.util.ArrayList;
12 import java.util.Collection;
13 import java.util.HashSet;
14
15 import org.opendaylight.protocol.util.ByteArray;
16 import org.opendaylight.protocol.concepts.ASNumber;
17
18 /**
19  *
20  * Representation of one AS Path Segment. It is, in fact, a TLV, but the length
21  * field is representing the count of AS Numbers in the collection (in its
22  * value). If the segment is of type AS_SEQUENCE, the collection is a List, if
23  * AS_SET, the collection is a Set.
24  *
25  */
26 public class AsPathSegmentParser {
27
28         public static final int TYPE_LENGTH = 1; // bytes
29
30         public static final int LENGTH_SIZE = 1; // bytes
31
32         public static final int AS_NUMBER_LENGTH = 4; // bytes
33
34         /**
35          * Possible types of AS Path segments.
36          */
37         public enum SegmentType {
38                 AS_SEQUENCE, AS_SET
39         }
40
41         private AsPathSegmentParser() {
42
43         }
44
45         static SegmentType parseType(final int type) {
46                 switch (type) {
47                 case 1:
48                         return SegmentType.AS_SET;
49                 case 2:
50                         return SegmentType.AS_SEQUENCE;
51                 default:
52                         return null;
53                 }
54         }
55
56         static Collection<ASNumber> parseAsPathSegment(final SegmentType type,
57                         final int count, final byte[] bytes) {
58                 final Collection<ASNumber> coll = (type == SegmentType.AS_SEQUENCE) ? new ArrayList<ASNumber>()
59                                 : new HashSet<ASNumber>();
60                 int byteOffset = 0;
61                 for (int i = 0; i < count; i++) {
62                         coll.add(new ASNumber(ByteArray.bytesToLong(ByteArray.subByte(
63                                         bytes, byteOffset, AS_NUMBER_LENGTH))));
64                         byteOffset += AS_NUMBER_LENGTH;
65                 }
66                 return coll;
67         }
68 }