I am trying to translate a function from GO to javascript (I barely have any knowledge of GO).
This is the original function
func prepareMessage(data []byte) []byte {
// Compute CRC before modifying the message.
crc := crcCompute(data)
// Add the two CRC16 bytes before replacing control characters.
data = append(data, byte(crc&0xFF))
data = append(data, byte(crc>>8))
tmp := []byte{0x7E} // Flag start.
// Copy the message over, escaping 0x7E (Flag Byte) and 0x7D (Control-Escape).
for i := 0; i < len(data); i++ {
mv := data[i]
if (mv == 0x7E) || (mv == 0x7D) {
mv = mv ^ 0x20
tmp = append(tmp, 0x7D)
}
tmp = append(tmp, mv)
}
tmp = append(tmp, 0x7E) // Flag end.
return tmp
}
This is my attempt in JavaScript
var _appendBuffer = function (buffer1, buffer2) {
var tmp = new Uint8Array(buffer1.byteLength + buffer2.byteLength);
tmp.set(new Uint8Array(buffer1), 0);
tmp.set(new Uint8Array(buffer2), buffer1.byteLength);
return tmp.buffer;
};
function prepareMessage(data) {
// Compute CRC before modifying the message.
var crc = crcCompute(data)
// Add the two CRC16 bytes before replacing control characters.
data = data + (crc & 0xFF);
data = data + (crc >> 8);
var tmp = new ArrayBuffer(1000000000);
tmp[0] = [0x7E]; // Flag start.
// Copy the message over, escaping 0x7E (Flag Byte) and 0x7D (Control-Escape).
for (var i = 0; i < data.length; i++) {
var mv = data[i]
if ((mv == 0x7E) || (mv == 0x7D)) {
mv = mv ^ 0x20;
tmp = _appendBuffer(tmp, [0x7D]);
}
tmp = _appendBuffer(tmp, mv);
}
tmp = _appendBuffer(tmp, [0x7E]); // Flag end.
return tmp;
}
Getting this error in the prepareMessage function
RangeError: Range consisting of offset and length are of bounds
at line
tmp = _appendBuffer(tmp, mv);
I understand that something's wrong with the buffer sizes, but I don't get how to fix it.
Thanks Leon
tmp := []byte{0x7E} // Flag start. is declared and initiliazed as an array with only 1 item in it. It's already full, try making a slice with more capacity with the make() function.
That's a nice article with more details. https://www.godesignpatterns.com/2014/05/arrays-vs-slices.html