def lenprefix(data, nbytes=2):
    """Prefix `data` with its length, in `nbytes` big-endian bytes.
    If `data` is a string, it is first converted to bytes as UTF-8.
    """
    assert type(data) in (str, bytes)
    if type(data) is str:
        data = bytes(data, "utf8")
    return len(data).to_bytes(nbytes, "big") + data