Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Color] ColorResourcesTableCreator: Fix length encoding for utf8 strings #4710

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -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;
}
}