From 4f5a7ef5c566462470f0517110ad8afe25a8d58f Mon Sep 17 00:00:00 2001 From: "David M. Lloyd" Date: Fri, 27 Sep 2024 09:51:48 -0500 Subject: [PATCH] Use `compare` instead of `signum` 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. --- .../main/java/io/smallrye/common/net/CidrAddress.java | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/net/src/main/java/io/smallrye/common/net/CidrAddress.java b/net/src/main/java/io/smallrye/common/net/CidrAddress.java index 46b2723e..09e8b097 100644 --- a/net/src/main/java/io/smallrye/common/net/CidrAddress.java +++ b/net/src/main/java/io/smallrye/common/net/CidrAddress.java @@ -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; @@ -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 @@ -283,7 +282,7 @@ 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++; @@ -291,13 +290,13 @@ public int compareAddressBytesTo(final byte[] otherBytes, final int otherNetmask } 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) {