Garmin: fix CobsCoDec.encode

Co-authored-by: José Rebelo <joserebelo@outlook.com>
This commit is contained in:
Thomas Kuehne
2026-03-21 00:16:35 +01:00
committed by José Rebelo
co-authored by José Rebelo
parent 165cd803a0
commit 076a85d762
@@ -80,11 +80,13 @@ public class CobsCoDec {
// this implementation of COBS relies on a leading and a trailing 0 byte (the former is not part of default implementations) // this implementation of COBS relies on a leading and a trailing 0 byte (the former is not part of default implementations)
public static byte[] encode(byte[] data) { public static byte[] encode(byte[] data) {
ByteBuffer encodedBytesBuffer = ByteBuffer.allocate((data.length * 2) + 1); // Maximum expansion ByteBuffer encodedBytesBuffer = ByteBuffer.allocate((data.length * 2) + 2); // Maximum expansion
encodedBytesBuffer.put((byte) 0);// Garmin initial padding encodedBytesBuffer.put((byte) 0);// Garmin initial padding
ByteBuffer buffer = ByteBuffer.wrap(data); ByteBuffer buffer = ByteBuffer.wrap(data);
boolean lastByteWasZero = false;
while (buffer.position() < buffer.limit()) { while (buffer.position() < buffer.limit()) {
int startPos = buffer.position(); int startPos = buffer.position();
int zeroIndex = buffer.position(); int zeroIndex = buffer.position();
@@ -93,6 +95,8 @@ public class CobsCoDec {
zeroIndex++; zeroIndex++;
} }
lastByteWasZero = buffer.position() > zeroIndex;
int payloadSize = zeroIndex - startPos; int payloadSize = zeroIndex - startPos;
while (payloadSize >= 0xFE) { while (payloadSize >= 0xFE) {
@@ -104,16 +108,10 @@ public class CobsCoDec {
encodedBytesBuffer.put((byte) (payloadSize + 1)); encodedBytesBuffer.put((byte) (payloadSize + 1));
encodedBytesBuffer.put(data, startPos, payloadSize); encodedBytesBuffer.put(data, startPos, payloadSize);
}
if (buffer.hasRemaining()) { if (lastByteWasZero) {
zeroIndex++; // Include the zero byte in the next block encodedBytesBuffer.put((byte) 0x01);
}
if (!buffer.hasRemaining() && payloadSize == 0) {
break;
}
buffer.position(zeroIndex);
} }
encodedBytesBuffer.put((byte) 0); // Append a zero byte to indicate end of encoding encodedBytesBuffer.put((byte) 0); // Append a zero byte to indicate end of encoding