Debian Codegraph @

lib/utils_math.c

raw
1 // SPDX-License-Identifier: GPL-2.0+
2
3 #include <stdio.h>
4 #include <stdlib.h>
5 #include <string.h>
6 #include <math.h>
7 #include <limits.h>
8 #include <asm/types.h>
9
10 #include "utils.h"
11
12 /* See http://physics.nist.gov/cuu/Units/binary.html */
13 static const struct rate_suffix {
14 const char *name;
15 double scale;
16 } suffixes[] = {
17 { "bit", 1. },
18 { "Kibit", 1024. },
19 { "kbit", 1000. },
20 { "mibit", 1024.*1024. },
21 { "mbit", 1000000. },
22 { "gibit", 1024.*1024.*1024. },
23 { "gbit", 1000000000. },
24 { "tibit", 1024.*1024.*1024.*1024. },
25 { "tbit", 1000000000000. },
26 { "Bps", 8. },
27 { "KiBps", 8.*1024. },
28 { "KBps", 8000. },
29 { "MiBps", 8.*1024*1024. },
30 { "MBps", 8000000. },
31 { "GiBps", 8.*1024.*1024.*1024. },
32 { "GBps", 8000000000. },
33 { "TiBps", 8.*1024.*1024.*1024.*1024. },
34 { "TBps", 8000000000000. },
35 { NULL }
36 };
37
38 int get_rate(unsigned int *rate, const char *str)
39 {
40 char *p;
41 double bps = strtod(str, &p);
42 const struct rate_suffix *s;
43
44 if (p == str)
45 return -1;
46
47 for (s = suffixes; s->name; ++s) {
48 if (strcasecmp(s->name, p) == 0) {
49 bps *= s->scale;
50 p += strlen(p);
51 break;
52 }
53 }
54
55 if (*p)
56 return -1; /* unknown suffix */
57
58 bps /= 8; /* -> bytes per second */
59 *rate = bps;
60 /* detect if an overflow happened */
61 if (*rate != floor(bps))
62 return -1;
63 return 0;
64 }
65
66 int get_rate64(__u64 *rate, const char *str)
67 {
68 char *p;
69 double bps = strtod(str, &p);
70 const struct rate_suffix *s;
71
72 if (p == str)
73 return -1;
74
75 for (s = suffixes; s->name; ++s) {
76 if (strcasecmp(s->name, p) == 0) {
77 bps *= s->scale;
78 p += strlen(p);
79 break;
80 }
81 }
82
83 if (*p)
84 return -1; /* unknown suffix */
85
86 bps /= 8; /* -> bytes per second */
87 *rate = bps;
88 return 0;
89 }
90
91 int get_size64(__u64 *size, const char *str)
92 {
93 double sz;
94 char *p;
95
96 sz = strtod(str, &p);
97 if (p == str)
98 return -1;
99
100 if (*p) {
101 if (strcasecmp(p, "kb") == 0 || strcasecmp(p, "k") == 0)
102 sz *= 1024;
103 else if (strcasecmp(p, "gb") == 0 || strcasecmp(p, "g") == 0)
104 sz *= 1024*1024*1024;
105 else if (strcasecmp(p, "gbit") == 0)
106 sz *= 1024*1024*1024/8;
107 else if (strcasecmp(p, "mb") == 0 || strcasecmp(p, "m") == 0)
108 sz *= 1024*1024;
109 else if (strcasecmp(p, "mbit") == 0)
110 sz *= 1024*1024/8;
111 else if (strcasecmp(p, "kbit") == 0)
112 sz *= 1024/8;
113 else if (strcasecmp(p, "b") != 0)
114 return -1;
115 }
116
117 *size = sz;
118
119 /* detect if an overflow happened */
120 if (*size != floor(sz))
121 return -1;
122
123 return 0;
124 }
125
126 int get_size(unsigned int *size, const char *str)
127 {
128 __u64 sz64;
129 int rv;
130
131 rv = get_size64(&sz64, str);
132 *size = sz64;
133
134 if (rv)
135 return rv;
136
137 if (sz64 > UINT_MAX)
138 return -1;
139
140 return 0;
141 }