Here is one I wrote just to talk about iterating a loop in reverse:
/*
* We iterate the v6 prefixes in reverse from longest prefix length
* to shortest. This is because the ipv6 address is a sequence of bytes,
* and we want to perturb the address iteratively to get the corresponding
* network address without making a copy for each perturbation as that
* would be expensive.
*
* For example take address: abcd:abcd:abcd:abcd:abcd:abcd:abcd:abcd.
*
* With masks /112, /64, /8 we want to create the following network addresses
* to lookup as follows:
*
* Lookup abcd:abcd:abcd:abcd:abcd:abcd:abcd:0000 in /112 bucket
* Lookup abcd:abcd:abcd:abcd:0000:0000:0000:0000 in /64 bucket
* Lookup abcd:0000:0000:0000:0000:0000:0000:0000 in /8 bucket
*
* In any other order aside from most specific to least, we'd have
* to create copies of the original address and apply the mask each
* time to get each network address; whereas in this case we can take
* the same address and clear lower bits to higher bits as we go from
* most specific to least specific masks without incurring any copies.
*/
for (auto it = m_v6_prefixes.crbegin(); it != m_v6_prefixes.crend(); ++it)
Or here is another for masking a v4 address, but also explaining why a uint64 is used (this is calculated in a hot loop [same as the previous comment example], so I felt it was imperative to explain what is going on as there is very little room otherwise to optimise): for (const auto & [ mask_len, bucket ] : m_v4_prefixes)
{
/*
* Example:
*
* netmask 255.255.128.0 (/17) or 0xffff8000:
*
* 0xffffffff ffffffff << (32-17)
* --------------------------------
* 0xffffffff ffff8000 (shifted left 15)
*
* Applying against address 192.168.85.146 or 0xc0a85592:
*
* (converted to uint64_t due to implicit integer promotion)
*
* 0x00000000 c0a85592
* &
* 0xffffffff ffff8000
* -------------------
* 0x00000000 c0a80000
* -------------------
* 0xc0a80000 (after conversion to uint32_t causing
* lower 32-bit truncation)
*/
std::uint64_t mask = (~0ULL) << (32 - mask_len);
std::uint32_t network_addr = addr & mask;
const auto itt = bucket.find(network_addr);