blob: f8d659c3f600eaf9269429978921a1dbd42f72ee [file] [log] [blame]
Jonathan Hart335ef462014-10-16 08:20:46 -07001package org.onlab.onos.sdnip;
2
3import static com.google.common.base.Preconditions.checkNotNull;
4
5import java.util.Objects;
6
7import org.onlab.packet.IpAddress;
8import org.onlab.packet.IpPrefix;
9
10import com.google.common.base.MoreObjects;
11
12/**
13 * Represents a route entry for an IP prefix.
14 */
15public class RouteEntry {
16 private final IpPrefix prefix; // The IP prefix
17 private final IpAddress nextHop; // Next-hop IP address
18
19 /**
20 * Class constructor.
21 *
22 * @param prefix the IP prefix of the route
23 * @param nextHop the next hop IP address for the route
24 */
25 public RouteEntry(IpPrefix prefix, IpAddress nextHop) {
26 this.prefix = checkNotNull(prefix);
27 this.nextHop = checkNotNull(nextHop);
28 }
29
30 /**
31 * Returns the IP prefix of the route.
32 *
33 * @return the IP prefix of the route
34 */
35 public IpPrefix prefix() {
36 return prefix;
37 }
38
39 /**
40 * Returns the next hop IP address for the route.
41 *
42 * @return the next hop IP address for the route
43 */
44 public IpAddress nextHop() {
45 return nextHop;
46 }
47
48 /**
49 * Creates the binary string representation of an IPv4 prefix.
50 * The string length is equal to the prefix length.
51 *
52 * @param ip4Prefix the IPv4 prefix to use
53 * @return the binary string representation
54 */
55 static String createBinaryString(IpPrefix ip4Prefix) {
56 if (ip4Prefix.prefixLength() == 0) {
57 return "";
58 }
59
60 StringBuilder result = new StringBuilder(ip4Prefix.prefixLength());
Jonathan Hartbcae7bd2014-10-16 10:24:41 -070061 long value = ip4Prefix.toInt();
Jonathan Hart335ef462014-10-16 08:20:46 -070062 for (int i = 0; i < ip4Prefix.prefixLength(); i++) {
63 long mask = 1 << (IpAddress.MAX_INET_MASK - 1 - i);
64 result.append(((value & mask) == 0) ? "0" : "1");
65 }
66 return result.toString();
67 }
68
69 @Override
70 public boolean equals(Object other) {
71 if (this == other) {
72 return true;
73 }
74
75 //
76 // NOTE: Subclasses are considered as change of identity, hence
77 // equals() will return false if the class type doesn't match.
78 //
79 if (other == null || getClass() != other.getClass()) {
80 return false;
81 }
82
83 RouteEntry otherRoute = (RouteEntry) other;
84 return Objects.equals(this.prefix, otherRoute.prefix) &&
85 Objects.equals(this.nextHop, otherRoute.nextHop);
86 }
87
88 @Override
89 public int hashCode() {
90 return Objects.hash(prefix, nextHop);
91 }
92
93 @Override
94 public String toString() {
95 return MoreObjects.toStringHelper(getClass())
96 .add("prefix", prefix)
97 .add("nextHop", nextHop)
98 .toString();
99 }
100}