Skip to content

Commit

Permalink
Use compare instead of signum
Browse files Browse the repository at this point in the history
This will give the same result, however there are certain cases where using `signum` for comparisons fails, so it is best to stick with `Integer.compare` even if it is not a specific problem in this case.

While we're in here, we can also use `Byte.toUnsignedInt` for further code clarity in these cases.
  • Loading branch information
dmlloyd committed Sep 27, 2024
1 parent 521ecdb commit 4f5a7ef
Showing 1 changed file with 5 additions and 6 deletions.
11 changes: 5 additions & 6 deletions net/src/main/java/io/smallrye/common/net/CidrAddress.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
package io.smallrye.common.net;

import static java.lang.Integer.signum;
import static java.lang.Math.min;

import java.io.Serializable;
Expand Down Expand Up @@ -271,10 +270,10 @@ public int compareAddressBytesTo(final byte[] otherBytes, final int otherNetmask
}
// IPv4 before IPv6
final byte[] cachedBytes = this.cachedBytes;
int res = signum(cachedBytes.length - otherLength);
int res = Integer.compare(cachedBytes.length, otherLength);
if (res != 0)
return res;
res = signum(scopeId - getScopeId());
res = Integer.compare(scopeId, getScopeId());
if (res != 0)
return res;
// sorted numerically with long matches coming later
Expand All @@ -283,21 +282,21 @@ public int compareAddressBytesTo(final byte[] otherBytes, final int otherNetmask
// compare byte-wise as far as we can
int i = 0;
while (commonPrefix >= 8) {
res = signum((cachedBytes[i] & 0xff) - (otherBytes[i] & 0xff));
res = Integer.compare(Byte.toUnsignedInt(cachedBytes[i]), Byte.toUnsignedInt(otherBytes[i]));
if (res != 0)
return res;
i++;
commonPrefix -= 8;
}
while (commonPrefix > 0) {
final int bit = 1 << commonPrefix;
res = signum((cachedBytes[i] & bit) - (otherBytes[i] & bit));
res = Integer.compare(cachedBytes[i] & bit, otherBytes[i] & bit);
if (res != 0)
return res;
commonPrefix--;
}
// common prefix is a match; now the shortest mask wins
return signum(netmaskBits - otherNetmaskBits);
return Integer.compare(netmaskBits, otherNetmaskBits);
}

public boolean equals(final Object obj) {
Expand Down

0 comments on commit 4f5a7ef

Please sign in to comment.