static unsigned long long my_strntoull_8bit()

in cpp-ch/local-engine/Functions/SparkFunctionConv.cpp [59:137]


static unsigned long long my_strntoull_8bit(const char *nptr,
                                     size_t l, int base, const char **endptr,
                                     int *err)
{
    int negative;
    unsigned long long cutoff = 0;
    unsigned cutlim = 0;
    unsigned long long i = 0;
    const char *save = nullptr;
    int overflow = 0;

    *err = 0; /* Initialize error indicator */

    const char *s = nptr;
    const char *e = nptr + l;

    for (; s < e && std::isspace(*s); s++)
        ;

    if (s == e)
    {
        err[0] = EDOM;
        goto noconv;
    }

    if (*s == '-')
    {
        negative = 1;
        ++s;
    } else if (*s == '+') {
        negative = 0;
        ++s;
    } else
        negative = 0;

    save = s;

    cutoff = (~static_cast<unsigned long long>(0)) / static_cast<unsigned long int>(base);
    cutlim = static_cast<unsigned>(((~static_cast<unsigned long long>(0)) % static_cast<unsigned long int>(base)));

    overflow = 0;
    i = 0;
    for (; s != e; s++) {
        uint8_t c = *s;

        if (c >= '0' && c <= '9')
            c -= '0';
        else if (c >= 'A' && c <= 'Z')
            c = c - 'A' + 10;
        else if (c >= 'a' && c <= 'z')
            c = c - 'a' + 10;
        else
            break;
        if (c >= base) break;
        if (i > cutoff || (i == cutoff && c > cutlim))
            overflow = 1;
        else
        {
            i *= static_cast<unsigned long long>(base);
            i += c;
        }
    }

    if (s == save) goto noconv;

    if (endptr != nullptr) *endptr = s;

    if (overflow)
    {
        err[0] = ERANGE;
        return (~static_cast<unsigned long long>(0));
    }

    return negative ? -i : i;

noconv:
    if (endptr != nullptr) *endptr = nptr;
    return 0L;
}