blob: d6f65d58aeca85c67615795f7d1c0ba0a7f482c8 [file] [log] [blame]
Yotam Harcholf3f11152013-09-05 16:47:16 -07001package org.projectfloodlight.openflow.types;
2
3import org.jboss.netty.buffer.ChannelBuffer;
4import org.projectfloodlight.openflow.exceptions.OFParseError;
5
Andreas Wundsam85c961f2013-09-29 21:22:12 -07006import com.google.common.primitives.Shorts;
7
Yotam Harcholf3f11152013-09-05 16:47:16 -07008public class VlanVid implements OFValueType<VlanVid> {
9
10 private static final short VALIDATION_MASK = 0x0FFF;
Andreas Wundsamb75c4ad2013-09-23 14:45:35 -070011 private static final short NONE_VAL = 0x0000;
Yotam Harcholf3f11152013-09-05 16:47:16 -070012 final static int LENGTH = 2;
13
Andreas Wundsamb75c4ad2013-09-23 14:45:35 -070014 public static final VlanVid NONE = new VlanVid(NONE_VAL);
Yotam Harchol329f2b02013-09-11 15:05:26 -070015 public static final VlanVid NO_MASK = new VlanVid((short)0xFFFF);
Yotam Harcholf3f11152013-09-05 16:47:16 -070016 public static final VlanVid FULL_MASK = VlanVid.of((short)0x0);
17
18 private final short vid;
19
20 private VlanVid(short vid) {
21 this.vid = vid;
22 }
23
24 public static VlanVid of(short vid) {
Andreas Wundsamb75c4ad2013-09-23 14:45:35 -070025 if(vid == NONE_VAL)
26 return NONE;
27 else if ((vid & VALIDATION_MASK) != vid)
Yotam Harcholf3f11152013-09-05 16:47:16 -070028 throw new IllegalArgumentException("Illegal VLAN VID value: " + vid);
29 return new VlanVid(vid);
30 }
31
32 @Override
33 public boolean equals(Object obj) {
34 if (!(obj instanceof VlanVid))
35 return false;
36 VlanVid other = (VlanVid)obj;
37 if (other.vid != this.vid)
38 return false;
39 return true;
40 }
41
42 @Override
43 public int hashCode() {
44 int prime = 13873;
45 return this.vid * prime;
46 }
47
48 @Override
49 public String toString() {
50 return "0x" + Integer.toHexString(vid);
51 }
52
53 public short getValue() {
54 return vid;
55 }
56
57 @Override
58 public int getLength() {
59 return LENGTH;
60 }
61
62
63 volatile byte[] bytesCache = null;
64
65 public byte[] getBytes() {
66 if (bytesCache == null) {
67 synchronized (this) {
68 if (bytesCache == null) {
69 bytesCache =
70 new byte[] { (byte) ((vid >>> 8) & 0xFF),
71 (byte) ((vid >>> 0) & 0xFF) };
72 }
73 }
74 }
75 return bytesCache;
76 }
77
78 public void write2Bytes(ChannelBuffer c) {
79 c.writeShort(this.vid);
80 }
81
82 public static VlanVid read2Bytes(ChannelBuffer c) throws OFParseError {
83 return VlanVid.of(c.readShort());
84 }
85
86 @Override
87 public VlanVid applyMask(VlanVid mask) {
88 return VlanVid.of((short)(this.vid & mask.vid));
89 }
90
Andreas Wundsam85c961f2013-09-29 21:22:12 -070091 @Override
92 public int compareTo(VlanVid o) {
93 return Shorts.compare(vid, o.vid);
94 }
95
Yotam Harcholf3f11152013-09-05 16:47:16 -070096}