#include "utf8.h"

uint8_t utf8_next(const unsigned char *utf8, uint32_t *out_unicode)
{
    unsigned char c = utf8[0];
    if (c == 0)
    {
        *out_unicode = 0;
        return 0;
    }
    if (c < 0x80)
    {
        *out_unicode = c;
        return 1;
    }
    if ((c & 0xE0) == 0xC0)
    {
        if (utf8[1] == 0)
        {
            return 0;
        }
        *out_unicode = (uint32_t)((c & 0x1F) << 6 | (utf8[1] & 0x3F));
        return 2;
    }
    if ((c & 0xF0) == 0xE0)
    {
        if (utf8[1] == 0 || utf8[2] == 0)
        {
            return 0;
        }
        *out_unicode = (uint32_t)((c & 0x0F) << 12 | (utf8[1] & 0x3F) << 6 | (utf8[2] & 0x3F));
        return 3;
    }
    *out_unicode = 0;
    return 0;
}
