xref: /openbmc/qemu/pc-bios/s390-ccw/libc.c (revision f0984d40)
1 /*
2  * libc-style definitions and functions
3  *
4  * Copyright 2018 IBM Corp.
5  * Author(s): Collin L. Walling <walling@linux.vnet.ibm.com>
6  *
7  * This code is free software; you can redistribute it and/or modify it
8  * under the terms of the GNU General Public License as published by the
9  * Free Software Foundation; either version 2 of the License, or (at your
10  * option) any later version.
11  */
12 
13 #include "libc.h"
14 #include "s390-ccw.h"
15 
16 /**
17  * atoui:
18  * @str: the string to be converted.
19  *
20  * Given a string @str, convert it to an integer. Leading spaces are
21  * ignored. Any other non-numerical value will terminate the conversion
22  * and return 0. This function only handles numbers between 0 and
23  * UINT64_MAX inclusive.
24  *
25  * Returns: an integer converted from the string @str, or the number 0
26  * if an error occurred.
27  */
28 uint64_t atoui(const char *str)
29 {
30     int val = 0;
31 
32     if (!str || !str[0]) {
33         return 0;
34     }
35 
36     while (*str == ' ') {
37         str++;
38     }
39 
40     while (*str) {
41         if (!isdigit(*(unsigned char *)str)) {
42             break;
43         }
44         val = val * 10 + *str - '0';
45         str++;
46     }
47 
48     return val;
49 }
50 
51 /**
52  * uitoa:
53  * @num: an integer (base 10) to be converted.
54  * @str: a pointer to a string to store the conversion.
55  * @len: the length of the passed string.
56  *
57  * Given an integer @num, convert it to a string. The string @str must be
58  * allocated beforehand. The resulting string will be null terminated and
59  * returned. This function only handles numbers between 0 and UINT64_MAX
60  * inclusive.
61  *
62  * Returns: the string @str of the converted integer @num
63  */
64 char *uitoa(uint64_t num, char *str, size_t len)
65 {
66     long num_idx = 1; /* account for NUL */
67     uint64_t tmp = num;
68 
69     IPL_assert(str != NULL, "uitoa: no space allocated to store string");
70 
71     /* Count indices of num */
72     while ((tmp /= 10) != 0) {
73         num_idx++;
74     }
75 
76     /* Check if we have enough space for num and NUL */
77     IPL_assert(len > num_idx, "uitoa: array too small for conversion");
78 
79     str[num_idx--] = '\0';
80 
81     /* Convert int to string */
82     while (num_idx >= 0) {
83         str[num_idx--] = num % 10 + '0';
84         num /= 10;
85     }
86 
87     return str;
88 }
89