1/*********************************************************************
2   PicoTCP. Copyright (c) 2015-2017 Altran ISY BeNeLux. Some rights reserved.
3   See COPYING, LICENSE.GPLv2 and LICENSE.GPLv3 for usage.
4
5
6
7   Author: Michele Di Pede
8 *********************************************************************/
9
10#include <ctype.h>
11#include <stdlib.h>
12#include "pico_strings.h"
13
14char *get_string_terminator_position(char *const block, size_t len)
15{
16    size_t length = pico_strnlen(block, len);
17
18    return (len != length) ? (block + length) : 0;
19}
20
21int pico_strncasecmp(const char *const str1, const char *const str2, size_t n)
22{
23    int ch1;
24    int ch2;
25    size_t i;
26
27    for (i = 0; i < n; ++i) {
28        ch1 = toupper(*(str1 + i));
29        ch2 = toupper(*(str2 + i));
30        if (ch1 < ch2)
31            return -1;
32
33        if (ch1 > ch2)
34            return 1;
35
36        if ((!ch1) && (!ch2))
37            return 0;
38    }
39    return 0;
40}
41
42size_t pico_strnlen(const char *str, size_t n)
43{
44    size_t len = 0;
45
46    if (!str)
47        return 0;
48
49    for (; len < n && *(str + len); ++len)
50        ; /* TICS require this empty statement here */
51
52    return len;
53}
54
55static inline int num2string_validate(int32_t num, char *buf, int len)
56{
57    if (num < 0)
58        return -1;
59
60    if (!buf)
61        return -2;
62
63    if (len < 2)
64        return -3;
65
66    return 0;
67}
68
69static inline int revert_and_shift(char *buf, int len, int pos)
70{
71    int i;
72
73    len -= pos;
74    for (i = 0; i < len; ++i)
75        buf[i] = buf[i + pos];
76    return len;
77}
78
79int num2string(int32_t num, char *buf, int len)
80{
81    ldiv_t res;
82    int pos = 0;
83
84    if (num2string_validate(num, buf, len))
85        return -1;
86
87    pos = len;
88    buf[--pos] = '\0';
89
90    res.quot = (long)num;
91
92    do {
93        if (!pos)
94            return -3;
95
96        res = ldiv(res.quot, 10);
97        buf[--pos] = (char)((res.rem + '0') & 0xFF);
98    } while (res.quot);
99
100    return revert_and_shift(buf, len, pos);
101}
102