|
16 | 16 |
|
17 | 17 | package com.google.android.material.color; |
18 | 18 |
|
| 19 | +import static java.nio.charset.StandardCharsets.UTF_8; |
| 20 | + |
19 | 21 | import android.content.Context; |
20 | 22 | import android.util.Pair; |
21 | 23 | import androidx.annotation.ColorInt; |
22 | 24 | import java.io.ByteArrayOutputStream; |
23 | 25 | import java.io.IOException; |
24 | | -import java.nio.charset.Charset; |
25 | 26 | import java.util.ArrayList; |
26 | 27 | import java.util.Collections; |
27 | 28 | import java.util.Comparator; |
@@ -630,13 +631,36 @@ private static byte[] stringToByteArray(String value) { |
630 | 631 | return bytes; |
631 | 632 | } |
632 | 633 |
|
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; |
641 | 665 | } |
642 | 666 | } |
0 commit comments