Browse Source

Optimized the alphanumeric check by avoiding the use of regex (#3642)

* Optimized the alphanumeric check by avoiding the use of regex

* re-format the code lines

* Update MultiFileModeFileNameProvider.java
pull/3667/head
mandlil 1 year ago
committed by GitHub
parent
commit
a26720c198
No known key found for this signature in database GPG Key ID: B5690EEEBB952194
2 changed files with 30 additions and 3 deletions
  1. +19
    -3
      java/libphonenumber/src/com/google/i18n/phonenumbers/metadata/source/MultiFileModeFileNameProvider.java
  2. +11
    -0
      java/libphonenumber/test/com/google/i18n/phonenumbers/metadata/source/MultiFileModeFileNameProviderTest.java

+ 19
- 3
java/libphonenumber/src/com/google/i18n/phonenumbers/metadata/source/MultiFileModeFileNameProvider.java View File

@ -16,7 +16,6 @@
package com.google.i18n.phonenumbers.metadata.source;
import java.util.regex.Pattern;
/**
* {@link PhoneMetadataFileNameProvider} implementation which appends key as a suffix to the
@ -25,7 +24,6 @@ import java.util.regex.Pattern;
public final class MultiFileModeFileNameProvider implements PhoneMetadataFileNameProvider {
private final String phoneMetadataFileNamePrefix;
private static final Pattern ALPHANUMERIC = Pattern.compile("^[\\p{L}\\p{N}]+$");
public MultiFileModeFileNameProvider(String phoneMetadataFileNameBase) {
this.phoneMetadataFileNamePrefix = phoneMetadataFileNameBase + "_";
@ -34,9 +32,27 @@ public final class MultiFileModeFileNameProvider implements PhoneMetadataFileNam
@Override
public String getFor(Object key) {
String keyAsString = key.toString();
if (!ALPHANUMERIC.matcher(keyAsString).matches()) {
if (!isAlphanumeric(keyAsString)) {
throw new IllegalArgumentException("Invalid key: " + keyAsString);
}
return phoneMetadataFileNamePrefix + key;
}
private boolean isAlphanumeric(String key) {
if (key == null || key.length() == 0) {
return false;
}
// String#length doesn't actually return the number of
// code points in the String, it returns the number
// of char values.
int size = key.length();
for (int charIdx = 0; charIdx < size; ) {
final int codePoint = key.codePointAt(charIdx);
if (!Character.isLetterOrDigit(codePoint)) {
return false;
}
charIdx += Character.charCount(codePoint);
}
return true;
}
}

+ 11
- 0
java/libphonenumber/test/com/google/i18n/phonenumbers/metadata/source/MultiFileModeFileNameProviderTest.java View File

@ -42,4 +42,15 @@ public final class MultiFileModeFileNameProviderTest extends TestCase {
}
});
}
public void getFor_shouldThrowExceptionForEmptyKey() {
assertThrows(
IllegalArgumentException.class,
new ThrowingRunnable() {
@Override
public void run() {
metadataFileNameProvider.getFor("");
}
});
}
}

Loading…
Cancel
Save