Skip to content

Commit 7c62429

Browse files
pubiqqleticiarossi
authored andcommitted
[Color] ColorResourcesTableCreator: Fix length encoding for utf8 strings
Resolves #4710 GIT_ORIGIN_REV_ID=93cfc26eaac6aff2e6ec1e80123f4eb2d98b42b7 PiperOrigin-RevId: 750282052
1 parent de1f5e1 commit 7c62429

File tree

1 file changed

+33
-9
lines changed

1 file changed

+33
-9
lines changed

lib/java/com/google/android/material/color/ColorResourcesTableCreator.java

Lines changed: 33 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -16,12 +16,13 @@
1616

1717
package com.google.android.material.color;
1818

19+
import static java.nio.charset.StandardCharsets.UTF_8;
20+
1921
import android.content.Context;
2022
import android.util.Pair;
2123
import androidx.annotation.ColorInt;
2224
import java.io.ByteArrayOutputStream;
2325
import java.io.IOException;
24-
import java.nio.charset.Charset;
2526
import java.util.ArrayList;
2627
import java.util.Collections;
2728
import java.util.Comparator;
@@ -630,13 +631,36 @@ private static byte[] stringToByteArray(String value) {
630631
return bytes;
631632
}
632633

633-
private static byte[] stringToByteArrayUtf8(String value) {
634-
byte[] rawBytes = value.getBytes(Charset.forName("UTF-8"));
635-
byte stringLength = (byte) rawBytes.length;
636-
byte[] bytes = new byte[rawBytes.length + 3];
637-
System.arraycopy(rawBytes, 0, bytes, 2, stringLength);
638-
bytes[0] = bytes[1] = stringLength;
639-
bytes[bytes.length - 1] = 0; // EOS
640-
return bytes;
634+
private static byte[] stringToByteArrayUtf8(String str) {
635+
byte[] strBytes = str.getBytes(UTF_8);
636+
byte[] strLengthBytes = encodeLengthUtf8((short) str.length());
637+
byte[] encStrLengthBytes = encodeLengthUtf8((short) strBytes.length);
638+
639+
return concat(
640+
strLengthBytes,
641+
encStrLengthBytes,
642+
strBytes,
643+
new byte[] { 0 } // EOS
644+
);
645+
}
646+
647+
private static byte[] encodeLengthUtf8(short length) {
648+
return length > 0x7F
649+
? new byte[] { (byte) (((length >> 8) & 0x7F) | 0x80), (byte) (length & 0xFF) }
650+
: new byte[] { (byte) (length & 0xFF) };
651+
}
652+
653+
private static byte[] concat(byte[]... arrays) {
654+
int length = 0;
655+
for (byte[] array : arrays) {
656+
length += array.length;
657+
}
658+
byte[] result = new byte[length];
659+
int pos = 0;
660+
for (byte[] array : arrays) {
661+
System.arraycopy(array, 0, result, pos, array.length);
662+
pos += array.length;
663+
}
664+
return result;
641665
}
642666
}

0 commit comments

Comments
 (0)