1
0
mirror of https://codeberg.org/Freeyourgadget/Gadgetbridge synced 2024-12-29 12:05:53 +01:00

Huami: Avoid cutting multibyte chars in half

This commit is contained in:
Zhong Jianxin 2020-06-15 17:44:58 +08:00 committed by Gitea
parent a8638a52fa
commit 55f9c8f519
2 changed files with 17 additions and 0 deletions

View File

@ -673,6 +673,9 @@ public class HuamiSupport extends AbstractBTLEDeviceSupport {
byte[] rawmessage = message.getBytes();
int length = Math.min(rawmessage.length, maxLength - prefixlength);
if (length < rawmessage.length) {
length = StringUtils.utf8ByteLength(message, length);
}
byte[] command = new byte[length + prefixlength + suffixlength];
int pos = 0;

View File

@ -17,6 +17,10 @@
along with this program. If not, see <http://www.gnu.org/licenses/>. */
package nodomain.freeyourgadget.gadgetbridge.util;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.StandardCharsets;
import androidx.annotation.NonNull;
public class StringUtils {
@ -37,6 +41,16 @@ public class StringUtils {
return s.substring(0, length);
}
public static int utf8ByteLength(String string, int length) {
if (string == null) {
return 0;
}
ByteBuffer outBuf = ByteBuffer.allocate(length);
CharBuffer inBuf = CharBuffer.wrap(string.toCharArray());
StandardCharsets.UTF_8.newEncoder().encode(inBuf, outBuf, true);
return outBuf.position();
}
public static String pad(String s, int length){
return pad(s, length, ' ');
}