peerPriority

fun peerPriority(addr1: PeerAddress, port1: Int, addr2: PeerAddress, port2: Int): Int

Compute the BEP 40 peer priority of the (ordered) pair of endpoints (addr1:port1) and (addr2:port2). This is the pure-Kotlin port of std::uint32_t peer_priority(tcp::endpoint, tcp::endpoint) from src/torrent_peer.cpp. One endpoint should be our own and the other the peer's. The function is symmetric, so which is which does not matter.

The algorithm (https://www.bittorrent.org/beps/bep_0040.html), reproduced faithfully:

  1. Same address: CRC32C the two 16-bit ports in network byte order, lower port first.

  2. Different IPv4: order the endpoints, then mask both addresses with 0xffff5555 if they differ in the first two bytes, 0xffffff55 if they share /16 but differ in the third byte, otherwise 0xffffffff (i.e. same /24 keeps all bytes). CRC32C the concatenation, lower first.

  3. Different IPv6: order the endpoints; never mask the first 6 bytes, and from the first differing byte onward (but at index 5 at the earliest) mask each remaining byte with 0x55. CRC32C the 32-byte concatenation.

Both endpoints must be the same address family (the BEP requires it); this is the caller's responsibility, exactly as upstream TORRENT_ASSERTs it.

The result is returned as a 32-bit value held in an Int (read it as unsigned via Int.toUInt/and 0xFFFFFFFFL when a magnitude is needed). TorrentPeer.rank compares these as unsigned, matching std::uint32_t.