diff --git a/lib/java/com/google/android/material/color/ColorResourcesTableCreator.java b/lib/java/com/google/android/material/color/ColorResourcesTableCreator.java index cabc900189b..dc32c5cfb7a 100644 --- a/lib/java/com/google/android/material/color/ColorResourcesTableCreator.java +++ b/lib/java/com/google/android/material/color/ColorResourcesTableCreator.java @@ -21,7 +21,7 @@ import androidx.annotation.ColorInt; import java.io.ByteArrayOutputStream; import java.io.IOException; -import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; @@ -609,13 +609,36 @@ private static byte[] stringToByteArray(String value) { return bytes; } - private static byte[] stringToByteArrayUtf8(String value) { - byte[] rawBytes = value.getBytes(Charset.forName("UTF-8")); - byte stringLength = (byte) rawBytes.length; - byte[] bytes = new byte[rawBytes.length + 3]; - System.arraycopy(rawBytes, 0, bytes, 2, stringLength); - bytes[0] = bytes[1] = stringLength; - bytes[bytes.length - 1] = 0; // EOS - return bytes; + private static byte[] stringToByteArrayUtf8(String str) { + byte[] strBytes = str.getBytes(StandardCharsets.UTF_8); + byte[] strLengthBytes = encodeLengthUtf8((short) str.length()); + byte[] encStrLengthBytes = encodeLengthUtf8((short) strBytes.length); + + return concat( + strLengthBytes, + encStrLengthBytes, + strBytes, + new byte[] { 0 } // EOS + ); + } + + private static byte[] encodeLengthUtf8(short length) { + return length > 0x7F + ? new byte[] { (byte) (((length >> 8) & 0x7F) | 0x80), (byte) (length & 0xFF) } + : new byte[] { (byte) (length & 0xFF) }; + } + + private static byte[] concat(byte[]... arrays) { + int length = 0; + for (byte[] array : arrays) { + length += array.length; + } + byte[] result = new byte[length]; + int pos = 0; + for (byte[] array : arrays) { + System.arraycopy(array, 0, result, pos, array.length); + pos += array.length; + } + return result; } }