#include "lip_misc_string.h"
#include "lip/net/ipv4/lip_ipv4.h"

char *lip_str_put_str(char *str, const char *text) {
    while (*text) {
        *str++ = *text++;
    }
    return str;
}

char *lip_str_put_str_s(char *str, const char *text, const char *endstr) {
    while (*text && (str != endstr)) {
        *str++ = *text++;
    }
    return str;
}

char *lip_str_put_uint8(char *str, uint8_t val) {
    uint8_t dig100 = 0, dig10 = 0;
    while (val >= 100) {
        val-=100;
        ++dig100;
    }
    while (val >= 10) {
        val-=10;
        ++dig10;
    }
    if (dig100 > 0) {
        *str++ = '0' + dig100;
    }
    if ((dig100 > 0) || (dig10 > 0)) {
        *str++ = '0' + dig10;
    }
    *str++ = '0' + val;
    return str;
}


char *lip_str_put_uint16(char *str, uint16_t val) {
    int start = 0;
    static const uint16_t div_vals[] = { 10000, 1000, 100, 10, 1};
    for (const uint16_t *pdiv = &div_vals[0]; *pdiv > 1; ++pdiv) {
        uint16_t div = *pdiv;
        uint8_t dig = 0;
        if (val > div) {
            dig = val/div;
            val -= div * dig;
        }
        if ((dig != 0) || start) {
            *str++ = '0' + dig;
        }
    }
    *str++ = '0' + val;
    return str;
}

char *lip_str_put_uint32(char *str, uint32_t val) {
    int start = 0;
    static const uint32_t div_vals[] = {1000000000, 100000000, 10000000, 1000000, 100000, 10000, 1000, 100, 10, 1};

    for (const uint32_t *pdiv = &div_vals[0]; *pdiv > 1; ++pdiv) {
        uint32_t div = *pdiv;
        uint8_t dig = 0;
        if (val > div) {
            dig = val/div;
            val -= div * dig;
        }
        if ((dig != 0) || start) {
            *str++ = '0' + dig;
        }
    }
    *str++ = '0' + val;
    return str;
}




char *lip_str_put_ipv4_addr(char *str, const uint8_t *ipaddr) {
    for (uint8_t i = 0; i < LIP_IPV4_ADDR_SIZE; ++i) {
        if (i != 0) {
            *str++ = '.';
        }
        str = lip_str_put_uint8(str, *ipaddr++);
    }
    return str;
}

char *lip_str_put_hex_digit(char *str, uint8_t val) {
    static const char f_hexdig[16] = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
    *str++ = f_hexdig[val & 0xF];
    return str;
}
