Yotam Harchol | f3f1115 | 2013-09-05 16:47:16 -0700 | [diff] [blame] | 1 | package org.projectfloodlight.openflow.types; |
| 2 | |
| 3 | import org.jboss.netty.buffer.ChannelBuffer; |
| 4 | import org.projectfloodlight.openflow.exceptions.OFParseError; |
| 5 | |
| 6 | public class VlanVid implements OFValueType<VlanVid> { |
| 7 | |
| 8 | private static final short VALIDATION_MASK = 0x0FFF; |
| 9 | final static int LENGTH = 2; |
| 10 | |
Yotam Harchol | 329f2b0 | 2013-09-11 15:05:26 -0700 | [diff] [blame] | 11 | public static final VlanVid NO_MASK = new VlanVid((short)0xFFFF); |
Yotam Harchol | f3f1115 | 2013-09-05 16:47:16 -0700 | [diff] [blame] | 12 | public static final VlanVid FULL_MASK = VlanVid.of((short)0x0); |
| 13 | |
| 14 | private final short vid; |
| 15 | |
| 16 | private VlanVid(short vid) { |
| 17 | this.vid = vid; |
| 18 | } |
| 19 | |
| 20 | public static VlanVid of(short vid) { |
| 21 | if ((vid & VALIDATION_MASK) != vid) |
| 22 | throw new IllegalArgumentException("Illegal VLAN VID value: " + vid); |
| 23 | return new VlanVid(vid); |
| 24 | } |
| 25 | |
| 26 | @Override |
| 27 | public boolean equals(Object obj) { |
| 28 | if (!(obj instanceof VlanVid)) |
| 29 | return false; |
| 30 | VlanVid other = (VlanVid)obj; |
| 31 | if (other.vid != this.vid) |
| 32 | return false; |
| 33 | return true; |
| 34 | } |
| 35 | |
| 36 | @Override |
| 37 | public int hashCode() { |
| 38 | int prime = 13873; |
| 39 | return this.vid * prime; |
| 40 | } |
| 41 | |
| 42 | @Override |
| 43 | public String toString() { |
| 44 | return "0x" + Integer.toHexString(vid); |
| 45 | } |
| 46 | |
| 47 | public short getValue() { |
| 48 | return vid; |
| 49 | } |
| 50 | |
| 51 | @Override |
| 52 | public int getLength() { |
| 53 | return LENGTH; |
| 54 | } |
| 55 | |
| 56 | |
| 57 | volatile byte[] bytesCache = null; |
| 58 | |
| 59 | public byte[] getBytes() { |
| 60 | if (bytesCache == null) { |
| 61 | synchronized (this) { |
| 62 | if (bytesCache == null) { |
| 63 | bytesCache = |
| 64 | new byte[] { (byte) ((vid >>> 8) & 0xFF), |
| 65 | (byte) ((vid >>> 0) & 0xFF) }; |
| 66 | } |
| 67 | } |
| 68 | } |
| 69 | return bytesCache; |
| 70 | } |
| 71 | |
| 72 | public void write2Bytes(ChannelBuffer c) { |
| 73 | c.writeShort(this.vid); |
| 74 | } |
| 75 | |
| 76 | public static VlanVid read2Bytes(ChannelBuffer c) throws OFParseError { |
| 77 | return VlanVid.of(c.readShort()); |
| 78 | } |
| 79 | |
| 80 | @Override |
| 81 | public VlanVid applyMask(VlanVid mask) { |
| 82 | return VlanVid.of((short)(this.vid & mask.vid)); |
| 83 | } |
| 84 | |
| 85 | } |