blob: b5a995d78db21aa1a548cbb88b0f01b6b2e4dc52 [file] [log] [blame]
tom0eb04ca2014-08-25 14:34:51 -07001package org.projectfloodlight.openflow.types;
2
3import com.google.common.hash.PrimitiveSink;
4
5
6
7public class Masked<T extends OFValueType<T>> implements OFValueType<Masked<T>> {
8 protected final T value;
9
10 /** bitmask of the value. Note: a set (1) bit in this mask means 'match on this value'.
11 * This the natural mask represenation as in IPv[46] netmasks. It is the inverse of the
12 * OpenFlow 1.0 'wildcard' meaning.
13 */
14 protected final T mask;
15
16 protected Masked(T value, T mask) {
17 this.value = value.applyMask(mask);
18 this.mask = mask;
19 }
20
21 public T getValue() {
22 return value;
23 }
24
25 public T getMask() {
26 return mask;
27 }
28
29 public static <T extends OFValueType<T>> Masked<T> of(T value, T mask) {
30 return new Masked<T>(value, mask);
31 }
32
33 @Override
34 public int getLength() {
35 return this.value.getLength() + this.mask.getLength();
36 }
37
38 @Override
39 public String toString() {
40 // General representation: value/mask
41 StringBuilder sb = new StringBuilder();
42 sb.append(value.toString()).append('/').append(mask.toString());
43 return sb.toString();
44 }
45
46 /** Determine whether candidate value is matched by this masked value
47 * (i.e., does candiate lie in the 'network/range' specified by this masked
48 * value).
49 *
50 * @param candidate the candidate value to test
51 * @return true iff the candidate lies in the area specified by this masked
52 * value.
53 */
54 public boolean matches(T candidate) {
55 // candidate lies in the area of this masked value if its
56 // value with the masked bit zero'ed out equals this's value
57 // (e.g., our 'network address' for networks)
58 return candidate.applyMask(this.mask).equals(this.value);
59 }
60
61 @Override
62 public Masked<T> applyMask(Masked<T> mask) {
63 return this;
64 }
65
66 @Override
67 public boolean equals(Object obj) {
68 if (!(obj instanceof Masked<?>))
69 return false;
70 Masked<?> mobj = (Masked<?>)obj;
71 return this.value.equals(mobj.value) && this.mask.equals(mobj.mask);
72 }
73
74 @Override
75 public int hashCode() {
76 final int prime = 59;
77 int result = 1;
78 result = prime * result + this.value.hashCode();
79 result = prime * result + this.mask.hashCode();
80 return result;
81 }
82
83 @Override
84 public int compareTo(Masked<T> o) {
85 int res = value.compareTo(o.value);
86 if(res != 0)
87 return res;
88 else
89 return mask.compareTo(o.mask);
90 }
91
92 @Override
93 public void putTo(PrimitiveSink sink) {
94 value.putTo(sink);
95 mask.putTo(sink);
96 }
97}