From bf5ae382ce8fb6014576766e6643c5023c243789 Mon Sep 17 00:00:00 2001 From: Andrea Cavalli Date: Tue, 24 Aug 2021 11:23:39 +0200 Subject: [PATCH] Optimize speed of MoshiPolymorphic --- .../commonutils/moshi/MoshiPolymorphic.java | 6 ++++- .../commonutils/serialization/UTFUtils.java | 25 +++++++++++++++++-- 2 files changed, 28 insertions(+), 3 deletions(-) diff --git a/src/main/java/org/warp/commonutils/moshi/MoshiPolymorphic.java b/src/main/java/org/warp/commonutils/moshi/MoshiPolymorphic.java index b2a1b5c..33d7e8b 100644 --- a/src/main/java/org/warp/commonutils/moshi/MoshiPolymorphic.java +++ b/src/main/java/org/warp/commonutils/moshi/MoshiPolymorphic.java @@ -24,6 +24,7 @@ import java.util.function.Function; import org.apache.commons.lang3.StringUtils; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; +import org.warp.commonutils.serialization.UTFUtils; public abstract class MoshiPolymorphic { @@ -357,6 +358,9 @@ public abstract class MoshiPolymorphic { } private static String fixType(String nextString) { - return nextString.replaceAll("[^a-zA-Z0-9]", ""); + if (nextString.length() > 512) { + throw new IllegalArgumentException("Input too long: " + nextString.length()); + } + return UTFUtils.keepOnlyASCII(nextString); } } \ No newline at end of file diff --git a/src/main/java/org/warp/commonutils/serialization/UTFUtils.java b/src/main/java/org/warp/commonutils/serialization/UTFUtils.java index 8ee2ed2..67b278b 100644 --- a/src/main/java/org/warp/commonutils/serialization/UTFUtils.java +++ b/src/main/java/org/warp/commonutils/serialization/UTFUtils.java @@ -6,16 +6,37 @@ import java.io.IOException; import java.nio.charset.StandardCharsets; public class UTFUtils { - public static final void writeUTF(DataOutput out, String utf) throws IOException { + public static void writeUTF(DataOutput out, String utf) throws IOException { byte[] bytes = utf.getBytes(StandardCharsets.UTF_8); out.writeInt(bytes.length); out.write(bytes); } - public static final String readUTF(DataInput in) throws IOException { + public static String readUTF(DataInput in) throws IOException { int len = in.readInt(); byte[] data = new byte[len]; in.readFully(data, 0, len); return new String(data, StandardCharsets.UTF_8); } + + /** + * Keep only ascii alphanumeric letters + */ + public static String keepOnlyASCII(String nextString) { + char[] chars = nextString.toCharArray(); + //noinspection UnusedAssignment + nextString = null; + int writeIndex = 0; + char c; + for (int checkIndex = 0; checkIndex < chars.length; checkIndex++) { + c = chars[checkIndex]; + if ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z')) { + if (writeIndex != checkIndex) { + chars[writeIndex] = c; + } + writeIndex++; + } + } + return new String(chars, 0, writeIndex); + } }