Add a utility method for testing if a number begins with a decimal prefix
This commit is contained in:
parent
7201938793
commit
96fb0ac3ae
|
@ -144,6 +144,35 @@ public class Util {
|
|||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests whether the decimal form of the given number (without leading zeroes) begins with the decimal form of the
|
||||
* given prefix (without leading zeroes).
|
||||
*
|
||||
* @param number the number to check for the given prefix
|
||||
* @param prefix the prefix
|
||||
*
|
||||
* @return {@code true} if the given number starts with the given prefix or {@code false} otherwise
|
||||
*
|
||||
* @throws IllegalArgumentException if {@code number} is negative or if {@code prefix} is zero or negative
|
||||
*/
|
||||
public static boolean startsWithDecimal(final long number, final long prefix) {
|
||||
if (number < 0) {
|
||||
throw new IllegalArgumentException("Number must be non-negative");
|
||||
}
|
||||
|
||||
if (prefix <= 0) {
|
||||
throw new IllegalArgumentException("Prefix must be positive");
|
||||
}
|
||||
|
||||
long workingCopy = number;
|
||||
|
||||
while (workingCopy > prefix) {
|
||||
workingCopy /= 10;
|
||||
}
|
||||
|
||||
return workingCopy == prefix;
|
||||
}
|
||||
|
||||
public static byte[] truncate(byte[] element, int length) {
|
||||
byte[] result = new byte[length];
|
||||
System.arraycopy(element, 0, result, 0, result.length);
|
||||
|
|
|
@ -5,16 +5,15 @@
|
|||
|
||||
package org.whispersystems.textsecuregcm.util;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import com.google.i18n.phonenumbers.PhoneNumberUtil;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import java.util.List;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.Arguments;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class UtilTest {
|
||||
|
||||
@ParameterizedTest
|
||||
|
@ -39,4 +38,15 @@ class UtilTest {
|
|||
Arguments.of(oldFormatBeninE164, List.of(oldFormatBeninE164, newFormatBeninE164))
|
||||
);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({
|
||||
"0, 1, false",
|
||||
"123456789, 1, true",
|
||||
"123456789, 123, true",
|
||||
"123456789, 456, false",
|
||||
})
|
||||
void startsWithDecimal(final long number, final long prefix, final boolean expectStartsWithPrefix) {
|
||||
assertEquals(expectStartsWithPrefix, Util.startsWithDecimal(number, prefix));
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue