#ifndef INET_CHECKSUM
#define INET_CHECKSUM

#include <stdint.h>

// I'm surprised this isn't included in Linux...
// Maybe it is though and I just didn't look hard enough.
//
// Source: https://tools.ietf.org/html/rfc1071
//
// Compute Internet Checksum for "count" bytes
// beginning at location "addr".
uint16_t inet_checksum(void *a, uint32_t count) {
    uint32_t sum = 0;
    uint16_t *addr = a;

    while (count > 1)  {
        sum += *addr++;
        count -= 2;
    }

    /*  Add left-over byte, if any */
    if (count > 0)
        sum += *((uint8_t *) addr);

    /*  Fold 32-bit sum to 16 bits */
    while (sum >> 16)
        sum = (sum & 0xffff) + (sum >> 16);

    return ~sum;
}

#endif
