summaryrefslogtreecommitdiffstats
path: root/src/common.c
diff options
context:
space:
mode:
Diffstat (limited to 'src/common.c')
-rw-r--r--src/common.c100
1 files changed, 100 insertions, 0 deletions
diff --git a/src/common.c b/src/common.c
new file mode 100644
index 0000000..0b11d57
--- /dev/null
+++ b/src/common.c
@@ -0,0 +1,100 @@
1/*
2 * common.c
3 * contains some common functions
4 *
5 * Copyright (c) 2026 Nikias Bassen, All Rights Reserved.
6 *
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
11 *
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
16 *
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with this library; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20 */
21#include <math.h>
22#include <stdio.h>
23#include <stdint.h>
24#include "common.h"
25
26size_t dtostr(char *buf, size_t bufsize, double realval)
27{
28 int slen = 0;
29 if (isnan(realval)) {
30 slen = snprintf(buf, bufsize, "nan");
31 } else if (isinf(realval)) {
32 slen = snprintf(buf, bufsize, "%cinfinity", (realval > 0.0) ? '+' : '-');
33 } else if (realval == 0.0f) {
34 slen = snprintf(buf, bufsize, "0.0");
35 } else {
36 slen = snprintf(buf, bufsize, "%.*g", 17, realval);
37 if (slen < 0) {
38 return 0;
39 }
40 if (!buf || bufsize == 0) {
41 return (size_t)slen;
42 }
43 size_t len = (size_t)slen;
44 if (len >= bufsize) {
45 len = bufsize - 1;
46 }
47 size_t i = 0;
48 for (i = 0; i < len; i++) {
49 if (buf[i] == ',') {
50 buf[i] = '.';
51 break;
52 } else if (buf[i] == '.') {
53 break;
54 }
55 }
56 return len;
57 }
58 if (slen < 0) {
59 return 0;
60 }
61 return (size_t)slen;
62}
63
64/* based on https://stackoverflow.com/a/4143288 */
65#define PO10i_LIMIT (INT64_MAX/10)
66int num_digits_i(int64_t i)
67{
68 int n;
69 int64_t po10;
70 n=1;
71 if (i < 0) {
72 i = (i == INT64_MIN) ? INT64_MAX : -i;
73 n++;
74 }
75 po10=10;
76 while (i>=po10) {
77 n++;
78 if (po10 > PO10i_LIMIT) break;
79 po10*=10;
80 }
81 return n;
82}
83#undef PO10i_LIMIT
84
85/* based on https://stackoverflow.com/a/4143288 */
86#define PO10u_LIMIT (UINT64_MAX/10)
87int num_digits_u(uint64_t i)
88{
89 int n;
90 uint64_t po10;
91 n=1;
92 po10=10;
93 while (i>=po10) {
94 n++;
95 if (po10 > PO10u_LIMIT) break;
96 po10*=10;
97 }
98 return n;
99}
100#undef PO10u_LIMIT