This is an automated email from the ASF dual-hosted git repository.
chaokunyang pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/incubator-fury.git
The following commit(s) were added to refs/heads/main by this push:
new 225f2b42 feat(java): meta string encoding algorithm in java (#1514)
225f2b42 is described below
commit 225f2b420ba6d4424287dc1121067523ace0f054
Author: Shawn Yang <[email protected]>
AuthorDate: Mon Apr 15 23:28:55 2024 +0800
feat(java): meta string encoding algorithm in java (#1514)
<!--
**Thanks for contributing to Fury.**
**If this is your first time opening a PR on fury, you can refer to
[CONTRIBUTING.md](https://github.com/apache/incubator-fury/blob/main/CONTRIBUTING.md).**
Contribution Checklist
- The **Apache Fury (incubating)** community has restrictions on the
naming of pr titles. You can also find instructions in
[CONTRIBUTING.md](https://github.com/apache/incubator-fury/blob/main/CONTRIBUTING.md).
- Fury has a strong focus on performance. If the PR you submit will have
an impact on performance, please benchmark it first and provide the
benchmark result here.
-->
## What does this PR do?
This PR implements meta string encoding described in [fury java
serialization
spec](https://fury.apache.org/docs/specification/fury_java_serialization_spec#meta-string)
and [xlang serialization
spec](https://fury.apache.org/docs/specification/fury_xlang_serialization_spec#meta-string)
We have `3/8` space saveing for most string:
```java
// utf8 use 30 bytes, we use only 19 bytes
assertEquals(encoder.encode("org.apache.fury.benchmark.data").getBytes().length,
19);
// utf8 use 12 bytes, we use only 9 bytes.
assertEquals(encoder.encode("MediaContent").getBytes().length, 9);
```
The integration with ClassResolver is left in another PR.
## Related issues
#1240
#1413
## Does this PR introduce any user-facing change?
<!--
If any user-facing interface changes, please [open an
issue](https://github.com/apache/incubator-fury/issues/new/choose)
describing the need to do so and update the document if necessary.
-->
- [ ] Does this PR introduce any public API change?
- [ ] Does this PR introduce any binary protocol compatibility change?
## Benchmark
<!--
When the PR has an impact on performance (if you don't know whether the
PR will have an impact on performance, you can submit the PR first, and
if it will have impact on performance, the code reviewer will explain
it), be sure to attach a benchmark data here.
-->
---
.../main/java/org/apache/fury/meta/MetaString.java | 152 +++++++++++
.../org/apache/fury/meta/MetaStringDecoder.java | 182 +++++++++++++
.../org/apache/fury/meta/MetaStringEncoder.java | 283 +++++++++++++++++++++
.../java/org/apache/fury/util/StringUtils.java | 14 +
.../java/org/apache/fury/meta/MetaStringTest.java | 203 +++++++++++++++
5 files changed, 834 insertions(+)
diff --git a/java/fury-core/src/main/java/org/apache/fury/meta/MetaString.java
b/java/fury-core/src/main/java/org/apache/fury/meta/MetaString.java
new file mode 100644
index 00000000..290c3788
--- /dev/null
+++ b/java/fury-core/src/main/java/org/apache/fury/meta/MetaString.java
@@ -0,0 +1,152 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.fury.meta;
+
+import java.util.Arrays;
+import java.util.Objects;
+
+/**
+ * Represents a string with metadata that describes its encoding. It supports
different encodings
+ * including special mechanisms for lower-case alphabets with special
characters, and upper-case and
+ * digit encoding.
+ */
+public class MetaString {
+ /** Defines the types of supported encodings for MetaStrings. */
+ public enum Encoding {
+ LOWER_SPECIAL(0x00),
+ LOWER_UPPER_DIGIT_SPECIAL(0x01),
+ FIRST_TO_LOWER_SPECIAL(0x02),
+ ALL_TO_LOWER_SPECIAL(0x03),
+ UTF_8(0x04); // Using UTF-8 as the fallback
+
+ private final int value;
+
+ Encoding(int value) {
+ this.value = value;
+ }
+
+ public int getValue() {
+ return value;
+ }
+
+ public static Encoding fromInt(int value) {
+ for (Encoding encoding : values()) {
+ if (encoding.getValue() == value) {
+ return encoding;
+ }
+ }
+ throw new IllegalArgumentException("Encoding flag not recognized: " +
value);
+ }
+ }
+
+ private final String string;
+ private final Encoding encoding;
+ private final char specialChar1;
+ private final char specialChar2;
+ private final byte[] bytes;
+ private final int numBits;
+
+ /**
+ * Constructs a MetaString with the specified encoding and data.
+ *
+ * @param encoding The type of encoding used for the string data.
+ * @param bytes The encoded string data as a byte array.
+ * @param numBits The number of bits used for encoding.
+ */
+ public MetaString(
+ String string,
+ Encoding encoding,
+ char specialChar1,
+ char specialChar2,
+ byte[] bytes,
+ int numBits) {
+ this.string = string;
+ this.encoding = encoding;
+ this.specialChar1 = specialChar1;
+ this.specialChar2 = specialChar2;
+ this.bytes = bytes;
+ this.numBits = numBits;
+ }
+
+ public String getString() {
+ return string;
+ }
+
+ public Encoding getEncoding() {
+ return encoding;
+ }
+
+ public char getSpecialChar1() {
+ return specialChar1;
+ }
+
+ public char getSpecialChar2() {
+ return specialChar2;
+ }
+
+ public byte[] getBytes() {
+ return bytes;
+ }
+
+ public int getNumBits() {
+ return numBits;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) {
+ return true;
+ }
+ if (o == null || getClass() != o.getClass()) {
+ return false;
+ }
+ MetaString that = (MetaString) o;
+ return specialChar1 == that.specialChar1
+ && specialChar2 == that.specialChar2
+ && numBits == that.numBits
+ && encoding == that.encoding
+ && Arrays.equals(bytes, that.bytes);
+ }
+
+ @Override
+ public int hashCode() {
+ int result = Objects.hash(encoding, specialChar1, specialChar2, numBits);
+ result = 31 * result + Arrays.hashCode(bytes);
+ return result;
+ }
+
+ @Override
+ public String toString() {
+ return "MetaString{"
+ + "str="
+ + string
+ + ", encoding="
+ + encoding
+ + ", specialChar1="
+ + specialChar1
+ + ", specialChar2="
+ + specialChar2
+ + ", bytes="
+ + Arrays.toString(bytes)
+ + ", numBits="
+ + numBits
+ + '}';
+ }
+}
diff --git
a/java/fury-core/src/main/java/org/apache/fury/meta/MetaStringDecoder.java
b/java/fury-core/src/main/java/org/apache/fury/meta/MetaStringDecoder.java
new file mode 100644
index 00000000..35904d64
--- /dev/null
+++ b/java/fury-core/src/main/java/org/apache/fury/meta/MetaStringDecoder.java
@@ -0,0 +1,182 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.fury.meta;
+
+import java.nio.charset.StandardCharsets;
+import java.util.Arrays;
+import org.apache.fury.meta.MetaString.Encoding;
+import org.apache.fury.util.StringUtils;
+
+/** Decodes MetaString objects back into their original plain text form. */
+public class MetaStringDecoder {
+ private final char specialChar1;
+ private final char specialChar2;
+
+ /**
+ * Creates a MetaStringDecoder with specified special characters used for
decoding.
+ *
+ * @param specialChar1 The first special character used in custom decoding.
+ * @param specialChar2 The second special character used in custom decoding.
+ */
+ public MetaStringDecoder(char specialChar1, char specialChar2) {
+ this.specialChar1 = specialChar1;
+ this.specialChar2 = specialChar2;
+ }
+
+ /**
+ * Decodes the encoded data back into a string based on the provided number
of bits and encoding
+ * type.
+ *
+ * @param encodedData The encoded string data as a byte array.
+ * @param numBits The number of bits used for encoding.
+ * @return The decoded original string.
+ */
+ public String decode(byte[] encodedData, int numBits) {
+ if (encodedData.length == 0) {
+ return "";
+ }
+ // The very first byte signifies the encoding used
+ Encoding chosenEncoding = Encoding.fromInt(encodedData[0] & 0xFF);
+ // Extract actual data, skipping the first byte (encoding flag)
+ encodedData = Arrays.copyOfRange(encodedData, 1, encodedData.length);
+ return decode(encodedData, chosenEncoding, numBits);
+ }
+
+ /**
+ * Decode data based on passed <code>encoding</code>. The data must be
encoded using passed
+ * encoding.
+ *
+ * @param encodedData encoded data using passed <code>encoding</code>.
+ * @param encoding encoding the passed data.
+ * @param numBits total bits for encoded data.
+ * @return Decoded string.
+ */
+ public String decode(byte[] encodedData, Encoding encoding, int numBits) {
+ switch (encoding) {
+ case LOWER_SPECIAL:
+ return decodeLowerSpecial(encodedData, numBits);
+ case LOWER_UPPER_DIGIT_SPECIAL:
+ return decodeLowerUpperDigitSpecial(encodedData, numBits);
+ case FIRST_TO_LOWER_SPECIAL:
+ return decodeRepFirstLowerSpecial(encodedData, numBits);
+ case ALL_TO_LOWER_SPECIAL:
+ return decodeRepAllToLowerSpecial(encodedData, numBits);
+ case UTF_8:
+ return new String(encodedData, StandardCharsets.UTF_8);
+ default:
+ throw new IllegalStateException("Unexpected encoding flag: " +
encoding);
+ }
+ }
+
+ /** Decoding method for {@link Encoding#LOWER_SPECIAL}. */
+ private String decodeLowerSpecial(byte[] data, int numBits) {
+ StringBuilder decoded = new StringBuilder();
+ int bitIndex = 0;
+ int bitMask = 0b11111; // 5 bits for mask
+ while (bitIndex + 5 <= numBits) {
+ int byteIndex = bitIndex / 8;
+ int intraByteIndex = bitIndex % 8;
+ // Extract the 5-bit character value across byte boundaries if needed
+ int charValue =
+ ((data[byteIndex] & 0xFF) << 8)
+ | (byteIndex + 1 < data.length ? (data[byteIndex + 1] & 0xFF) :
0);
+ charValue = ((byte) ((charValue >> (11 - intraByteIndex)) & bitMask));
+ bitIndex += 5;
+ decoded.append(decodeLowerSpecialChar(charValue));
+ }
+
+ return decoded.toString();
+ }
+
+ /** Decoding method for {@link Encoding#LOWER_UPPER_DIGIT_SPECIAL}. */
+ private String decodeLowerUpperDigitSpecial(byte[] data, int numBits) {
+ StringBuilder decoded = new StringBuilder();
+ int bitIndex = 0;
+ int bitMask = 0b111111; // 6 bits for mask
+ while (bitIndex + 6 <= numBits) {
+ int byteIndex = bitIndex / 8;
+ int intraByteIndex = bitIndex % 8;
+
+ // Extract the 6-bit character value across byte boundaries if needed
+ int charValue =
+ ((data[byteIndex] & 0xFF) << 8)
+ | (byteIndex + 1 < data.length ? (data[byteIndex + 1] & 0xFF) :
0);
+ charValue = ((byte) ((charValue >> (10 - intraByteIndex)) & bitMask));
+ bitIndex += 6;
+ decoded.append(decodeLowerUpperDigitSpecialChar(charValue));
+ }
+ return decoded.toString();
+ }
+
+ /** Decoding special char for LOWER_SPECIAL based on encoding mapping. */
+ private char decodeLowerSpecialChar(int charValue) {
+ if (charValue >= 0 && charValue <= 25) {
+ return (char) ('a' + charValue);
+ } else if (charValue == 26) {
+ return '.';
+ } else if (charValue == 27) {
+ return '_';
+ } else if (charValue == 28) {
+ return '$';
+ } else if (charValue == 29) {
+ return '|';
+ } else {
+ throw new IllegalArgumentException("Invalid character value for
LOWER_SPECIAL: " + charValue);
+ }
+ }
+
+ /** Decoding special char for LOWER_UPPER_DIGIT_SPECIAL based on encoding
mapping. */
+ private char decodeLowerUpperDigitSpecialChar(int charValue) {
+ if (charValue >= 0 && charValue <= 25) {
+ return (char) ('a' + charValue);
+ } else if (charValue >= 26 && charValue <= 51) {
+ return (char) ('A' + (charValue - 26));
+ } else if (charValue >= 52 && charValue <= 61) {
+ return (char) ('0' + (charValue - 52));
+ } else if (charValue == 62) {
+ return specialChar1;
+ } else if (charValue == 63) {
+ return specialChar2;
+ } else {
+ throw new IllegalArgumentException(
+ "Invalid character value for LOWER_UPPER_DIGIT_SPECIAL: " +
charValue);
+ }
+ }
+
+ private String decodeRepFirstLowerSpecial(byte[] data, int numBits) {
+ String str = decodeLowerSpecial(data, numBits);
+ return StringUtils.capitalize(str);
+ }
+
+ private String decodeRepAllToLowerSpecial(byte[] data, int numBits) {
+ String str = decodeLowerSpecial(data, numBits);
+ StringBuilder builder = new StringBuilder();
+ char[] chars = str.toCharArray();
+ for (int i = 0; i < chars.length; i++) {
+ if (chars[i] == '|') {
+ char c = chars[++i];
+ builder.append(Character.toUpperCase(c));
+ } else {
+ builder.append(chars[i]);
+ }
+ }
+ return builder.toString();
+ }
+}
diff --git
a/java/fury-core/src/main/java/org/apache/fury/meta/MetaStringEncoder.java
b/java/fury-core/src/main/java/org/apache/fury/meta/MetaStringEncoder.java
new file mode 100644
index 00000000..60a6b393
--- /dev/null
+++ b/java/fury-core/src/main/java/org/apache/fury/meta/MetaStringEncoder.java
@@ -0,0 +1,283 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.fury.meta;
+
+import java.nio.charset.StandardCharsets;
+import org.apache.fury.meta.MetaString.Encoding;
+
+/** Encodes plain text strings into MetaString objects with specified encoding
mechanisms. */
+public class MetaStringEncoder {
+ private final char specialChar1;
+ private final char specialChar2;
+
+ /**
+ * Creates a MetaStringEncoder with specified special characters used for
encoding.
+ *
+ * @param specialChar1 The first special character used in custom encoding.
+ * @param specialChar2 The second special character used in custom encoding.
+ */
+ public MetaStringEncoder(char specialChar1, char specialChar2) {
+ this.specialChar1 = specialChar1;
+ this.specialChar2 = specialChar2;
+ }
+
+ /**
+ * Encodes the input string to MetaString using adaptive encoding, which
intelligently chooses the
+ * best encoding based on the string's content.
+ *
+ * @param input The string to encode.
+ * @return A MetaString object representing the encoded string.
+ */
+ public MetaString encode(String input) {
+ if (input.isEmpty()) {
+ return new MetaString(
+ input, Encoding.LOWER_SPECIAL, specialChar1, specialChar2, new
byte[0], 0);
+ }
+ Encoding encoding = computeEncoding(input);
+ return encode(input, encoding);
+ }
+
+ /**
+ * Encodes the input string to MetaString using specified encoding.
+ *
+ * @param input The string to encode.
+ * @param encoding The encoding to use.
+ * @return A MetaString object representing the encoded string.
+ */
+ public MetaString encode(String input, Encoding encoding) {
+ if (input.isEmpty()) {
+ return new MetaString(
+ input, Encoding.LOWER_SPECIAL, specialChar1, specialChar2, new
byte[0], 0);
+ }
+ int length = input.length();
+ switch (encoding) {
+ case LOWER_SPECIAL:
+ return new MetaString(
+ input, encoding, specialChar1, specialChar2,
encodeLowerSpecial(input), length * 5);
+ case LOWER_UPPER_DIGIT_SPECIAL:
+ return new MetaString(
+ input,
+ encoding,
+ specialChar1,
+ specialChar2,
+ encodeLowerUpperDigitSpecial(input),
+ length * 6);
+ case FIRST_TO_LOWER_SPECIAL:
+ return new MetaString(
+ input,
+ encoding,
+ specialChar1,
+ specialChar2,
+ encodeFirstToLowerSpecial(input),
+ length * 5);
+ case ALL_TO_LOWER_SPECIAL:
+ char[] chars = input.toCharArray();
+ int upperCount = countUppers(chars);
+ return new MetaString(
+ input,
+ encoding,
+ specialChar1,
+ specialChar2,
+ encodeAllToLowerSpecial(chars, upperCount),
+ (upperCount + length) * 5);
+ default:
+ byte[] bytes = input.getBytes(StandardCharsets.UTF_8);
+ return new MetaString(
+ input, Encoding.UTF_8, specialChar1, specialChar2, bytes,
bytes.length * 8);
+ }
+ }
+
+ public Encoding computeEncoding(String input) {
+ if (input.isEmpty()) {
+ return Encoding.LOWER_SPECIAL;
+ }
+ char[] chars = input.toCharArray();
+ StringStatistics statistics = computeStatistics(chars);
+ if (statistics.canLowerSpecialEncoded) {
+ return Encoding.LOWER_SPECIAL;
+ } else if (statistics.canLowerUpperDigitSpecialEncoded) {
+ if (statistics.digitCount != 0) {
+ return Encoding.LOWER_UPPER_DIGIT_SPECIAL;
+ } else {
+ int upperCount = statistics.upperCount;
+ if (upperCount == 1 && Character.isUpperCase(chars[0])) {
+ return Encoding.FIRST_TO_LOWER_SPECIAL;
+ }
+ if ((chars.length + upperCount) * 5 < (chars.length * 6)) {
+ return Encoding.ALL_TO_LOWER_SPECIAL;
+ } else {
+ return Encoding.LOWER_UPPER_DIGIT_SPECIAL;
+ }
+ }
+ }
+ return Encoding.UTF_8;
+ }
+
+ private static class StringStatistics {
+ final int digitCount;
+ final int upperCount;
+ final boolean canLowerUpperDigitSpecialEncoded;
+ final boolean canLowerSpecialEncoded;
+
+ public StringStatistics(
+ int digitCount,
+ int upperCount,
+ boolean canLowerSpecialEncoded,
+ boolean canLowerUpperDigitSpecialEncoded) {
+ this.digitCount = digitCount;
+ this.upperCount = upperCount;
+ this.canLowerSpecialEncoded = canLowerSpecialEncoded;
+ this.canLowerUpperDigitSpecialEncoded = canLowerUpperDigitSpecialEncoded;
+ }
+ }
+
+ private StringStatistics computeStatistics(char[] chars) {
+ boolean canLowerUpperDigitSpecialEncoded = true;
+ boolean canLowerSpecialEncoded = true;
+ int digitCount = 0;
+ int upperCount = 0;
+ for (char c : chars) {
+ if (canLowerUpperDigitSpecialEncoded) {
+ if (!((c >= 'a' && c <= 'z')
+ || (c >= 'A' && c <= 'Z')
+ || (c >= '0' && c <= '9')
+ || (c == specialChar1 || c == specialChar2))) {
+ // Character outside of LOWER_UPPER_DIGIT_SPECIAL set
+ canLowerUpperDigitSpecialEncoded = false;
+ }
+ }
+ if (canLowerSpecialEncoded) {
+ if (!((c >= 'a' && c <= 'z') || (c == '.' || c == '_' || c == '$' || c
== '|'))) {
+ // Character outside of LOWER_SPECIAL set
+ canLowerSpecialEncoded = false;
+ }
+ }
+ if (Character.isDigit(c)) {
+ digitCount++;
+ }
+ if (Character.isUpperCase(c)) {
+ upperCount++;
+ }
+ }
+ return new StringStatistics(
+ digitCount, upperCount, canLowerSpecialEncoded,
canLowerUpperDigitSpecialEncoded);
+ }
+
+ private int countUppers(char[] chars) {
+ int upperCount = 0;
+ for (char c : chars) {
+ if (Character.isUpperCase(c)) {
+ upperCount++;
+ }
+ }
+ return upperCount;
+ }
+
+ public byte[] encodeLowerSpecial(String input) {
+ return encodeGeneric(input, 5);
+ }
+
+ public byte[] encodeLowerUpperDigitSpecial(String input) {
+ return encodeGeneric(input, 6);
+ }
+
+ public byte[] encodeFirstToLowerSpecial(String input) {
+ return encodeFirstToLowerSpecial(input.toCharArray());
+ }
+
+ public byte[] encodeFirstToLowerSpecial(char[] chars) {
+ chars[0] = Character.toLowerCase(chars[0]);
+ return encodeGeneric(chars, 5);
+ }
+
+ public byte[] encodeAllToLowerSpecial(char[] chars, int upperCount) {
+ char[] newChars = new char[chars.length + upperCount];
+ int newIdx = 0;
+ for (char c : chars) {
+ if (Character.isUpperCase(c)) {
+ newChars[newIdx++] = '|';
+ newChars[newIdx++] = Character.toLowerCase(c);
+ } else {
+ newChars[newIdx++] = c;
+ }
+ }
+ return encodeGeneric(newChars, 5);
+ }
+
+ private byte[] encodeGeneric(String input, int bitsPerChar) {
+ return encodeGeneric(input.toCharArray(), bitsPerChar);
+ }
+
+ private byte[] encodeGeneric(char[] chars, int bitsPerChar) {
+ int totalBits = chars.length * bitsPerChar;
+ int byteLength = (totalBits + 7) / 8; // Calculate number of needed bytes
+ byte[] bytes = new byte[byteLength];
+ int currentBit = 0;
+ for (char c : chars) {
+ int value =
+ (bitsPerChar == 5) ? charToValueLowerSpecial(c) :
charToValueLowerUpperDigitSpecial(c);
+ // Encode the value in bitsPerChar bits
+ for (int i = bitsPerChar - 1; i >= 0; i--) {
+ if ((value & (1 << i)) != 0) {
+ // Set the bit in the byte array
+ int bytePos = currentBit / 8;
+ int bitPos = currentBit % 8;
+ bytes[bytePos] |= (byte) (1 << (7 - bitPos));
+ }
+ currentBit++;
+ }
+ }
+
+ return bytes;
+ }
+
+ private int charToValueLowerSpecial(char c) {
+ if (c >= 'a' && c <= 'z') {
+ return c - 'a';
+ } else if (c == '.') {
+ return 26;
+ } else if (c == '_') {
+ return 27;
+ } else if (c == '$') {
+ return 28;
+ } else if (c == '|') {
+ return 29;
+ } else {
+ throw new IllegalArgumentException("Unsupported character for
LOWER_SPECIAL encoding: " + c);
+ }
+ }
+
+ private int charToValueLowerUpperDigitSpecial(char c) {
+ if (c >= 'a' && c <= 'z') {
+ return c - 'a';
+ } else if (c >= 'A' && c <= 'Z') {
+ return 26 + (c - 'A');
+ } else if (c >= '0' && c <= '9') {
+ return 52 + (c - '0');
+ } else if (c == specialChar1) {
+ return 62;
+ } else if (c == specialChar2) {
+ return 63;
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported character for LOWER_UPPER_DIGIT_SPECIAL encoding: " +
c);
+ }
+ }
+}
diff --git a/java/fury-core/src/main/java/org/apache/fury/util/StringUtils.java
b/java/fury-core/src/main/java/org/apache/fury/util/StringUtils.java
index b317503a..43362d7c 100644
--- a/java/fury-core/src/main/java/org/apache/fury/util/StringUtils.java
+++ b/java/fury-core/src/main/java/org/apache/fury/util/StringUtils.java
@@ -170,4 +170,18 @@ public class StringUtils {
public static boolean isNotBlank(final CharSequence cs) {
return !isBlank(cs);
}
+
+ public static void shuffle(StringBuilder sb) {
+ shuffle(sb, 7);
+ }
+
+ public static void shuffle(StringBuilder sb, int seed) {
+ Random rand = new Random(seed);
+ for (int i = sb.length() - 1; i > 1; i--) {
+ int swapWith = rand.nextInt(i);
+ char tmp = sb.charAt(swapWith);
+ sb.setCharAt(swapWith, sb.charAt(i));
+ sb.setCharAt(i, tmp);
+ }
+ }
}
diff --git
a/java/fury-core/src/test/java/org/apache/fury/meta/MetaStringTest.java
b/java/fury-core/src/test/java/org/apache/fury/meta/MetaStringTest.java
new file mode 100644
index 00000000..312cd8e5
--- /dev/null
+++ b/java/fury-core/src/test/java/org/apache/fury/meta/MetaStringTest.java
@@ -0,0 +1,203 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.fury.meta;
+
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertNotSame;
+import static org.testng.AssertJUnit.assertSame;
+
+import org.apache.fury.util.StringUtils;
+import org.testng.annotations.DataProvider;
+import org.testng.annotations.Test;
+
+public class MetaStringTest {
+
+ @Test
+ public void testEncodeMetaStringLowerSpecial() {
+ // special chars not matter for encodeLowerSpecial
+ MetaStringEncoder encoder = new MetaStringEncoder('_', '$');
+ byte[] encoded = encoder.encodeLowerSpecial("abc_def");
+ assertEquals(encoded.length, 5);
+ // utf8 use 30 bytes, we use only 19 bytes
+
assertEquals(encoder.encode("org.apache.fury.benchmark.data").getBytes().length,
19);
+ // utf8 use 12 bytes, we use only 9 bytes.
+ assertEquals(encoder.encode("MediaContent").getBytes().length, 9);
+ MetaStringDecoder decoder = new MetaStringDecoder('_', '$');
+ String decoded = decoder.decode(encoded,
MetaString.Encoding.LOWER_SPECIAL, 7 * 5);
+ assertEquals(decoded, "abc_def");
+ for (int i = 0; i < 128; i++) {
+ StringBuilder builder = new StringBuilder();
+ for (int j = 0; j < i; j++) {
+ builder.append((char) ('a' + j % 26));
+ }
+ String str = builder.toString();
+ encoded = encoder.encodeLowerSpecial(str);
+ decoded = decoder.decode(encoded, MetaString.Encoding.LOWER_SPECIAL, i *
5);
+ assertEquals(decoded, str);
+ }
+ }
+
+ @Test
+ public void testEncodeMetaStringLowerUpperDigitSpecial() {
+ char specialChar1 = '.';
+ char specialChar2 = '_';
+ MetaStringEncoder encoder = new MetaStringEncoder(specialChar1,
specialChar2);
+ byte[] encoded = encoder.encodeLowerUpperDigitSpecial("ExampleInput123");
+ assertEquals(encoded.length, 12);
+ MetaStringDecoder decoder = new MetaStringDecoder(specialChar1,
specialChar2);
+ String decoded = decoder.decode(encoded,
MetaString.Encoding.LOWER_UPPER_DIGIT_SPECIAL, 15 * 6);
+ assertEquals(decoded, "ExampleInput123");
+
+ for (int i = 1; i < 128; i++) {
+ String str = createString(i, specialChar1, specialChar2);
+ encoded = encoder.encodeLowerUpperDigitSpecial(str);
+ decoded = decoder.decode(encoded,
MetaString.Encoding.LOWER_UPPER_DIGIT_SPECIAL, i * 6);
+ assertEquals(decoded, str, "Failed at " + i);
+ }
+ }
+
+ private static String createString(int i, char specialChar1, char
specialChar2) {
+ StringBuilder builder = new StringBuilder();
+ for (int j = 0; j < i; j++) {
+ int n = j % 64;
+ char c;
+ if (n < 26) {
+ c = (char) ('a' + n);
+ } else if (n < 52) {
+ c = (char) ('A' + n - 26);
+ } else if (n < 62) {
+ c = (char) ('0' + n - 52);
+ } else if (n == 62) {
+ c = specialChar1;
+ } else {
+ c = specialChar2;
+ }
+ builder.append(c);
+ }
+ StringUtils.shuffle(builder);
+ return builder.toString();
+ }
+
+ @DataProvider
+ public static Object[][] specialChars() {
+ return new Object[][] {{'.', '_'}, {'.', '$'}, {'_', '$'}};
+ }
+
+ @Test(dataProvider = "specialChars")
+ public void testMetaString(char specialChar1, char specialChar2) {
+ MetaStringEncoder encoder = new MetaStringEncoder(specialChar1,
specialChar2);
+ for (int i = 0; i < 128; i++) {
+ try {
+ String str = createString(i, specialChar1, specialChar2);
+ MetaString metaString = encoder.encode(str);
+ assertNotSame(metaString.getEncoding(), MetaString.Encoding.UTF_8);
+ assertEquals(metaString.getString(), str);
+ assertEquals(metaString.getSpecialChar1(), specialChar1);
+ assertEquals(metaString.getSpecialChar2(), specialChar2);
+ MetaStringDecoder decoder = new MetaStringDecoder(specialChar1,
specialChar2);
+ String newStr =
+ decoder.decode(
+ metaString.getBytes(), metaString.getEncoding(),
metaString.getNumBits());
+ assertEquals(newStr, str);
+ } catch (Throwable e) {
+ throw new RuntimeException("Failed at " + i, e);
+ }
+ }
+ }
+
+ @DataProvider(name = "emptyStringProvider")
+ public Object[][] emptyStringProvider() {
+ return new Object[][] {
+ {MetaString.Encoding.LOWER_SPECIAL},
+ {MetaString.Encoding.LOWER_UPPER_DIGIT_SPECIAL},
+ {MetaString.Encoding.FIRST_TO_LOWER_SPECIAL},
+ {MetaString.Encoding.ALL_TO_LOWER_SPECIAL},
+ {MetaString.Encoding.UTF_8}
+ };
+ }
+
+ @Test(dataProvider = "emptyStringProvider")
+ public void testEncodeEmptyString(MetaString.Encoding encoding) {
+ MetaStringEncoder encoder = new MetaStringEncoder('_', '$');
+ MetaString metaString = encoder.encode("", encoding);
+ assertEquals(metaString.getBytes().length, 0);
+ MetaStringDecoder decoder = new MetaStringDecoder('_', '$');
+ String decoded =
+ decoder.decode(metaString.getBytes(), metaString.getEncoding(),
metaString.getNumBits());
+ assertEquals(decoded, "");
+ }
+
+ @Test
+ public void testEncodeCharactersOutsideOfLowerSpecial() {
+ // Contains characters outside LOWER_SPECIAL
+ String testString = "abcdefABCDEF1234!@#";
+ MetaStringEncoder encoder = new MetaStringEncoder('_', '$');
+ MetaString encodedMetaString = encoder.encode(testString);
+ assertSame(encodedMetaString.getEncoding(), MetaString.Encoding.UTF_8);
+ }
+
+ @Test
+ public void testAllToUpperSpecialEncoding() {
+ String testString = "ABC_DEF";
+ MetaStringEncoder encoder = new MetaStringEncoder('_', '$');
+ MetaString encodedMetaString = encoder.encode(testString);
+ assertEquals(encodedMetaString.getEncoding(),
MetaString.Encoding.LOWER_UPPER_DIGIT_SPECIAL);
+
+ MetaStringDecoder decoder = new MetaStringDecoder('_', '$');
+ String decodedString =
+ decoder.decode(
+ encodedMetaString.getBytes(),
+ encodedMetaString.getEncoding(),
+ encodedMetaString.getNumBits());
+ assertEquals(decodedString, testString);
+ }
+
+ @Test
+ public void testFirstToLowerSpecialEncoding() {
+ String testString = "Aabcdef";
+ MetaStringEncoder encoder = new MetaStringEncoder('_', '$');
+ MetaString encodedMetaString = encoder.encode(testString);
+ assertEquals(encodedMetaString.getEncoding(),
MetaString.Encoding.FIRST_TO_LOWER_SPECIAL);
+
+ MetaStringDecoder decoder = new MetaStringDecoder('_', '$');
+ String decodedString =
+ decoder.decode(
+ encodedMetaString.getBytes(),
+ encodedMetaString.getEncoding(),
+ encodedMetaString.getNumBits());
+ assertEquals(decodedString, testString);
+ }
+
+ @Test
+ public void testUtf8Encoding() {
+ String testString = "你好,世界"; // Non-Latin characters
+ MetaStringEncoder encoder = new MetaStringEncoder('_', '$');
+ MetaString encodedMetaString = encoder.encode(testString);
+ assertEquals(encodedMetaString.getEncoding(), MetaString.Encoding.UTF_8);
+
+ MetaStringDecoder decoder = new MetaStringDecoder('_', '$');
+ String decodedString =
+ decoder.decode(
+ encodedMetaString.getBytes(),
+ encodedMetaString.getEncoding(),
+ encodedMetaString.getNumBits());
+ assertEquals(decodedString, testString);
+ }
+}
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]