#ifndef _CHECKSUM_H
#define _CHECKSUM_H

#ifdef __cplusplus
extern "C"
{
#endif

#include <stdint.h>

// https://datatracker.ietf.org/doc/html/rfc1071
static inline uint16_t checksum(char *data, int len)
{
    long sum = 0;
    uint16_t *addr = (uint16_t *)data;

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

    if (len > 0)
    {
        sum += *(unsigned char *)addr;
    }

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

    return (uint16_t)(~sum);
}

#ifdef __cplusplus
}
#endif

#endif
