// 4-byte little-endian length prefix, used by the desktop client's TCP
// framing. WebSocket binary frames already preserve message boundaries, so
// we don't actually use these helpers on the WS path — they exist for
// testing against TCP captures and for any future TCP fallback.
//
// Reference: /Users/sn0/Desktop/rustdesk-server/libs/hbb_common/src/tcp.rs
//   uses `BytesCodec` which doesn't add framing itself, but the
//   `LengthDelimitedCodec` wrapping does (4-byte BE length per protobuf
//   default). Our WS path skips this entirely.

export function frame(payload: Uint8Array): Uint8Array {
  const out = new Uint8Array(4 + payload.length);
  const view = new DataView(out.buffer);
  view.setUint32(0, payload.length, /*littleEndian=*/ true);
  out.set(payload, 4);
  return out;
}

/**
 * Try to peel one length-prefixed message off `buf`. Returns null if there
 * isn't a complete message yet.
 */
export function unframe(
  buf: Uint8Array,
): { msg: Uint8Array; rest: Uint8Array } | null {
  if (buf.length < 4) return null;
  const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
  const len = view.getUint32(0, /*littleEndian=*/ true);
  if (buf.length < 4 + len) return null;
  return {
    msg: buf.subarray(4, 4 + len),
    rest: buf.subarray(4 + len),
  };
}
