Function atou

Synopsis

#include <src/c4/charconv.hpp>

template <class T>
bool atou(csubstr str, T *C4_RESTRICT v)

Description

Convert a trimmed string to an unsigned integral value. The string can be formatted as decimal, binary (prefix 0b or 0B), octal (prefix 0o or 0O) or hexadecimal (prefix 0x or 0X). Every character in the input string is read for the conversion; it must not contain any leading or trailing whitespace.

Returns
true if the conversion was successful.
Note
overflow is not detected: the return status is true even if the conversion would return a value outside of the type's range, in which case the result will wrap around the type's range.
Note
If the string has a minus character, the return status will be false.
See
atou_first() if the string is not trimmed to the value to read.

Mentioned in

Source

Lines 892-957 in src/c4/charconv.hpp.

template<class T>
bool atou(csubstr str, T * C4_RESTRICT v)
{
    C4_STATIC_ASSERT(std::is_integral<T>::value);

    if(C4_UNLIKELY(str.len == 0 || str.front() == '-'))
    {
        return false;
    }

    if(str.str[0] != '0')
    {
        if(C4_UNLIKELY( ! read_dec(str, v)))
        {
            return false;
        }
    }
    else
    {
        if(str.len == 1)
        {
            *v = 0; // we know the first character is 0
            return true;
        }
        else
        {
            char pfx = str.str[1];
            if(pfx == 'x' || pfx == 'X') // hexadecimal
            {
                if(C4_UNLIKELY(str.len <= 2))
                {
                    return false;
                }
                return read_hex(str.sub(2), v);
            }
            else if(pfx == 'b' || pfx == 'B') // binary
            {
                if(C4_UNLIKELY(str.len <= 2))
                {
                    return false;
                }
                return read_bin(str.sub(2), v);
            }
            else if(pfx == 'o' || pfx == 'O') // octal
            {
                if(C4_UNLIKELY(str.len <= 2))
                {
                    return false;
                }
                return read_oct(str.sub(2), v);
            }
            else
            {
                // we know the first character is 0
                auto fno = str.first_not_of('0');
                if(fno == csubstr::npos)
                {
                    *v = 0;
                    return true;
                }
                return read_dec(str.sub(fno), v);
            }
        }
    }
    return true;
}





Add Discussion as Guest

Log in