]> sigrok.org Git - libsigrok.git/blame - src/strutil.c
Rework sr_period_string
[libsigrok.git] / src / strutil.c
CommitLineData
25e7d9b1 1/*
50985c20 2 * This file is part of the libsigrok project.
25e7d9b1
UH
3 *
4 * Copyright (C) 2010 Uwe Hermann <uwe@hermann-uwe.de>
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
2ea1fdf1 17 * along with this program; if not, see <http://www.gnu.org/licenses/>.
25e7d9b1
UH
18 */
19
6ec6c43b 20#include <config.h>
25e7d9b1
UH
21#include <stdint.h>
22#include <stdlib.h>
23#include <string.h>
ba464a12 24#include <strings.h>
9e4f8cf9 25#include <errno.h>
c1aae900 26#include <libsigrok/libsigrok.h>
45c59c8b 27#include "libsigrok-internal.h"
25e7d9b1 28
2ad1deb8 29/** @cond PRIVATE */
3544f848 30#define LOG_PREFIX "strutil"
2ad1deb8 31/** @endcond */
a885ce3e 32
393fb9cb
UH
33/**
34 * @file
35 *
36 * Helper functions for handling or converting libsigrok-related strings.
37 */
38
7b870c38
UH
39/**
40 * @defgroup grp_strutil String utilities
41 *
42 * Helper functions for handling or converting libsigrok-related strings.
43 *
44 * @{
45 */
46
9e4f8cf9 47/**
df823ac4
UH
48 * @private
49 *
1ba4a1cf 50 * Convert a string representation of a numeric value (base 10) to a long integer. The
9e4f8cf9
DJ
51 * conversion is strict and will fail if the complete string does not represent
52 * a valid long integer. The function sets errno according to the details of the
53 * failure.
54 *
55 * @param str The string representation to convert.
56 * @param ret Pointer to long where the result of the conversion will be stored.
57 *
1ba4a1cf
MH
58 * @retval SR_OK Conversion successful.
59 * @retval SR_ERR Failure.
9e4f8cf9 60 */
8d558c7a 61SR_PRIV int sr_atol(const char *str, long *ret)
9e4f8cf9
DJ
62{
63 long tmp;
64 char *endptr = NULL;
65
66 errno = 0;
1ba4a1cf 67 tmp = strtol(str, &endptr, 10);
9e4f8cf9
DJ
68
69 if (!endptr || *endptr || errno) {
70 if (!errno)
71 errno = EINVAL;
72 return SR_ERR;
73 }
74
75 *ret = tmp;
76 return SR_OK;
77}
78
79/**
df823ac4
UH
80 * @private
81 *
1ba4a1cf 82 * Convert a string representation of a numeric value (base 10) to an integer. The
9e4f8cf9
DJ
83 * conversion is strict and will fail if the complete string does not represent
84 * a valid integer. The function sets errno according to the details of the
85 * failure.
86 *
87 * @param str The string representation to convert.
88 * @param ret Pointer to int where the result of the conversion will be stored.
89 *
1ba4a1cf
MH
90 * @retval SR_OK Conversion successful.
91 * @retval SR_ERR Failure.
9e4f8cf9 92 */
8d558c7a 93SR_PRIV int sr_atoi(const char *str, int *ret)
9e4f8cf9
DJ
94{
95 long tmp;
96
97 if (sr_atol(str, &tmp) != SR_OK)
98 return SR_ERR;
99
100 if ((int) tmp != tmp) {
101 errno = ERANGE;
102 return SR_ERR;
103 }
104
105 *ret = (int) tmp;
106 return SR_OK;
107}
108
109/**
df823ac4
UH
110 * @private
111 *
9e4f8cf9
DJ
112 * Convert a string representation of a numeric value to a double. The
113 * conversion is strict and will fail if the complete string does not represent
114 * a valid double. The function sets errno according to the details of the
115 * failure.
116 *
117 * @param str The string representation to convert.
118 * @param ret Pointer to double where the result of the conversion will be stored.
119 *
1ba4a1cf
MH
120 * @retval SR_OK Conversion successful.
121 * @retval SR_ERR Failure.
9e4f8cf9 122 */
8d558c7a 123SR_PRIV int sr_atod(const char *str, double *ret)
9e4f8cf9
DJ
124{
125 double tmp;
126 char *endptr = NULL;
127
128 errno = 0;
129 tmp = strtof(str, &endptr);
130
131 if (!endptr || *endptr || errno) {
132 if (!errno)
133 errno = EINVAL;
134 return SR_ERR;
135 }
136
137 *ret = tmp;
138 return SR_OK;
139}
140
141/**
df823ac4
UH
142 * @private
143 *
9e4f8cf9
DJ
144 * Convert a string representation of a numeric value to a float. The
145 * conversion is strict and will fail if the complete string does not represent
146 * a valid float. The function sets errno according to the details of the
147 * failure.
148 *
149 * @param str The string representation to convert.
150 * @param ret Pointer to float where the result of the conversion will be stored.
151 *
1ba4a1cf
MH
152 * @retval SR_OK Conversion successful.
153 * @retval SR_ERR Failure.
9e4f8cf9 154 */
8d558c7a 155SR_PRIV int sr_atof(const char *str, float *ret)
9e4f8cf9
DJ
156{
157 double tmp;
158
159 if (sr_atod(str, &tmp) != SR_OK)
160 return SR_ERR;
161
162 if ((float) tmp != tmp) {
163 errno = ERANGE;
164 return SR_ERR;
165 }
166
167 *ret = (float) tmp;
168 return SR_OK;
169}
170
9806c2d5
DJ
171/**
172 * @private
173 *
174 * Convert a string representation of a numeric value to a float. The
175 * conversion is strict and will fail if the complete string does not represent
176 * a valid float. The function sets errno according to the details of the
177 * failure. This version ignores the locale.
178 *
179 * @param str The string representation to convert.
180 * @param ret Pointer to float where the result of the conversion will be stored.
181 *
1ba4a1cf
MH
182 * @retval SR_OK Conversion successful.
183 * @retval SR_ERR Failure.
9806c2d5
DJ
184 */
185SR_PRIV int sr_atof_ascii(const char *str, float *ret)
186{
187 double tmp;
188 char *endptr = NULL;
189
190 errno = 0;
191 tmp = g_ascii_strtod(str, &endptr);
192
193 if (!endptr || *endptr || errno) {
194 if (!errno)
195 errno = EINVAL;
196 return SR_ERR;
197 }
198
199 /* FIXME This fails unexpectedly. Some other method to safel downcast
200 * needs to be found. Checking against FLT_MAX doesn't work as well. */
201 /*
202 if ((float) tmp != tmp) {
203 errno = ERANGE;
204 sr_dbg("ERANGEEEE %e != %e", (float) tmp, tmp);
205 return SR_ERR;
206 }
207 */
208
209 *ret = (float) tmp;
210 return SR_OK;
211}
212
5ec172d7 213/**
5c436a3b
UH
214 * Convert a string representation of a numeric value to a sr_rational.
215 *
216 * The conversion is strict and will fail if the complete string does not
217 * represent a valid number. The function sets errno according to the details
218 * of the failure. This version ignores the locale.
5ec172d7
SB
219 *
220 * @param str The string representation to convert.
221 * @param ret Pointer to sr_rational where the result of the conversion will be stored.
222 *
223 * @retval SR_OK Conversion successful.
224 * @retval SR_ERR Failure.
225 *
226 * @since 0.5.0
227 */
228SR_API int sr_parse_rational(const char *str, struct sr_rational *ret)
229{
230 char *endptr = NULL;
231 int64_t integral;
232 int64_t fractional = 0;
233 int64_t denominator = 1;
234 int32_t fractional_len = 0;
235 int32_t exponent = 0;
236
237 errno = 0;
238 integral = g_ascii_strtoll(str, &endptr, 10);
239
240 if (errno)
241 return SR_ERR;
242
243 if (*endptr == '.') {
244 const char* start = endptr + 1;
245 fractional = g_ascii_strtoll(start, &endptr, 10);
246 if (errno)
247 return SR_ERR;
248 fractional_len = endptr - start;
249 }
250
251 if ((*endptr == 'E') || (*endptr == 'e')) {
252 exponent = g_ascii_strtoll(endptr + 1, &endptr, 10);
253 if (errno)
254 return SR_ERR;
255 }
256
257 if (*endptr != '\0')
258 return SR_ERR;
259
260 for (int i = 0; i < fractional_len; i++)
261 integral *= 10;
262 exponent -= fractional_len;
263
264 if (integral >= 0)
265 integral += fractional;
266 else
267 integral -= fractional;
268
269 while (exponent > 0) {
270 integral *= 10;
271 exponent--;
272 }
273
274 while (exponent < 0) {
275 denominator *= 10;
276 exponent++;
277 }
278
279 ret->p = integral;
280 ret->q = denominator;
281
282 return SR_OK;
283}
284
25e7d9b1 285/**
b07b42f3
UH
286 * Convert a numeric value value to its "natural" string representation
287 * in SI units.
25e7d9b1 288 *
4cc9aea1
JH
289 * E.g. a value of 3000000, with units set to "W", would be converted
290 * to "3 MW", 20000 to "20 kW", 31500 would become "31.5 kW".
25e7d9b1 291 *
4cc9aea1
JH
292 * @param x The value to convert.
293 * @param unit The unit to append to the string, or NULL if the string
294 * has no units.
44dae539 295 *
91219afc 296 * @return A newly allocated string representation of the samplerate value,
133a37bf
UH
297 * or NULL upon errors. The caller is responsible to g_free() the
298 * memory.
47117241
UH
299 *
300 * @since 0.2.0
25e7d9b1 301 */
4cc9aea1 302SR_API char *sr_si_string_u64(uint64_t x, const char *unit)
25e7d9b1 303{
094e6b81
PS
304 uint8_t i;
305 uint64_t quot, divisor[] = {
b07b42f3
UH
306 SR_HZ(1), SR_KHZ(1), SR_MHZ(1), SR_GHZ(1),
307 SR_GHZ(1000), SR_GHZ(1000 * 1000), SR_GHZ(1000 * 1000 * 1000),
094e6b81
PS
308 };
309 const char *p, prefix[] = "\0kMGTPE";
69d83be9 310 char fmt[16], fract[20] = "", *f;
094e6b81 311
98fec29e 312 if (!unit)
4cc9aea1 313 unit = "";
25e7d9b1 314
094e6b81
PS
315 for (i = 0; (quot = x / divisor[i]) >= 1000; i++);
316
317 if (i) {
69d83be9 318 sprintf(fmt, ".%%0%d"PRIu64, i * 3);
094e6b81
PS
319 f = fract + sprintf(fract, fmt, x % divisor[i]) - 1;
320
321 while (f >= fract && strchr("0.", *f))
322 *f-- = 0;
133a37bf 323 }
25e7d9b1 324
094e6b81
PS
325 p = prefix + i;
326
327 return g_strdup_printf("%" PRIu64 "%s %.1s%s", quot, fract, p, unit);
4cc9aea1 328}
25e7d9b1 329
4cc9aea1
JH
330/**
331 * Convert a numeric samplerate value to its "natural" string representation.
332 *
333 * E.g. a value of 3000000 would be converted to "3 MHz", 20000 to "20 kHz",
334 * 31500 would become "31.5 kHz".
335 *
336 * @param samplerate The samplerate in Hz.
337 *
91219afc 338 * @return A newly allocated string representation of the samplerate value,
4cc9aea1
JH
339 * or NULL upon errors. The caller is responsible to g_free() the
340 * memory.
47117241
UH
341 *
342 * @since 0.1.0
4cc9aea1
JH
343 */
344SR_API char *sr_samplerate_string(uint64_t samplerate)
345{
346 return sr_si_string_u64(samplerate, "Hz");
25e7d9b1 347}
2a3f9541 348
2a3f9541 349/**
dfcc0bf9 350 * Convert a numeric frequency value to the "natural" string representation
2a3f9541
BV
351 * of its period.
352 *
2507648e 353 * E.g. a value of 3000000 would be converted to "3 us", 20000 to "50 ms".
2a3f9541
BV
354 *
355 * @param frequency The frequency in Hz.
44dae539 356 *
91219afc 357 * @return A newly allocated string representation of the frequency value,
133a37bf
UH
358 * or NULL upon errors. The caller is responsible to g_free() the
359 * memory.
47117241
UH
360 *
361 * @since 0.1.0
2a3f9541 362 */
6984cfb2 363SR_API char *sr_period_string(uint64_t v_p, uint64_t v_q)
2a3f9541 364{
6984cfb2 365 double freq, v;
2a3f9541 366 char *o;
6984cfb2
SA
367 int prec, r;
368
369 freq = 1 / ((double)v_p / v_q);
2a3f9541 370
91219afc 371 o = g_malloc0(30 + 1);
2a3f9541 372
6984cfb2
SA
373 if (freq > SR_GHZ(1)) {
374 v = (double)v_p / v_q * 1000000000000.0;
375 prec = ((v - (uint64_t)v) < FLT_MIN) ? 0 : 3;
376 r = snprintf(o, 30, "%.*f ps", prec, v);
377 } else if (freq > SR_MHZ(1)) {
378 v = (double)v_p / v_q * 1000000000.0;
379 prec = ((v - (uint64_t)v) < FLT_MIN) ? 0 : 3;
380 r = snprintf(o, 30, "%.*f ns", prec, v);
381 } else if (freq > SR_KHZ(1)) {
382 v = (double)v_p / v_q * 1000000.0;
383 prec = ((v - (uint64_t)v) < FLT_MIN) ? 0 : 3;
384 r = snprintf(o, 30, "%.*f us", prec, v);
385 } else if (freq > 1) {
386 v = (double)v_p / v_q * 1000.0;
387 prec = ((v - (uint64_t)v) < FLT_MIN) ? 0 : 3;
388 r = snprintf(o, 30, "%.*f ms", prec, v);
389 } else {
390 v = (double)v_p / v_q;
391 prec = ((v - (uint64_t)v) < FLT_MIN) ? 0 : 3;
392 r = snprintf(o, 30, "%.*f s", prec, v);
393 }
2a3f9541
BV
394
395 if (r < 0) {
396 /* Something went wrong... */
133a37bf 397 g_free(o);
2a3f9541
BV
398 return NULL;
399 }
400
401 return o;
402}
40f5ddac 403
79afc8ca 404/**
e0e15067
BV
405 * Convert a numeric voltage value to the "natural" string representation
406 * of its voltage value. The voltage is specified as a rational number's
407 * numerator and denominator.
79afc8ca
BV
408 *
409 * E.g. a value of 300000 would be converted to "300mV", 2 to "2V".
410 *
e0e15067
BV
411 * @param v_p The voltage numerator.
412 * @param v_q The voltage denominator.
79afc8ca 413 *
91219afc 414 * @return A newly allocated string representation of the voltage value,
79afc8ca
BV
415 * or NULL upon errors. The caller is responsible to g_free() the
416 * memory.
47117241
UH
417 *
418 * @since 0.2.0
79afc8ca 419 */
e0e15067 420SR_API char *sr_voltage_string(uint64_t v_p, uint64_t v_q)
79afc8ca 421{
79afc8ca 422 int r;
d5a669a9 423 char *o;
79afc8ca 424
91219afc 425 o = g_malloc0(30 + 1);
79afc8ca 426
e0e15067
BV
427 if (v_q == 1000)
428 r = snprintf(o, 30, "%" PRIu64 "mV", v_p);
429 else if (v_q == 1)
430 r = snprintf(o, 30, "%" PRIu64 "V", v_p);
79afc8ca 431 else
e0e15067 432 r = snprintf(o, 30, "%gV", (float)v_p / (float)v_q);
79afc8ca
BV
433
434 if (r < 0) {
435 /* Something went wrong... */
436 g_free(o);
437 return NULL;
438 }
439
440 return o;
441}
442
dfcc0bf9
UH
443/**
444 * Convert a "natural" string representation of a size value to uint64_t.
445 *
446 * E.g. a value of "3k" or "3 K" would be converted to 3000, a value
447 * of "15M" would be converted to 15000000.
448 *
449 * Value representations other than decimal (such as hex or octal) are not
450 * supported. Only 'k' (kilo), 'm' (mega), 'g' (giga) suffixes are supported.
451 * Spaces (but not other whitespace) between value and suffix are allowed.
452 *
453 * @param sizestring A string containing a (decimal) size value.
f64c1414 454 * @param size Pointer to uint64_t which will contain the string's size value.
dfcc0bf9 455 *
44dae539 456 * @return SR_OK upon success, SR_ERR upon errors.
47117241
UH
457 *
458 * @since 0.1.0
dfcc0bf9 459 */
1a081ca6 460SR_API int sr_parse_sizestring(const char *sizestring, uint64_t *size)
40f5ddac 461{
f64c1414 462 int multiplier, done;
580f3099 463 double frac_part;
40f5ddac
BV
464 char *s;
465
f64c1414 466 *size = strtoull(sizestring, &s, 10);
40f5ddac 467 multiplier = 0;
580f3099 468 frac_part = 0;
f64c1414
BV
469 done = FALSE;
470 while (s && *s && multiplier == 0 && !done) {
40f5ddac
BV
471 switch (*s) {
472 case ' ':
473 break;
580f3099
DJ
474 case '.':
475 frac_part = g_ascii_strtod(s, &s);
476 break;
40f5ddac
BV
477 case 'k':
478 case 'K':
59df0c77 479 multiplier = SR_KHZ(1);
40f5ddac
BV
480 break;
481 case 'm':
482 case 'M':
59df0c77 483 multiplier = SR_MHZ(1);
40f5ddac
BV
484 break;
485 case 'g':
486 case 'G':
59df0c77 487 multiplier = SR_GHZ(1);
40f5ddac
BV
488 break;
489 default:
f64c1414
BV
490 done = TRUE;
491 s--;
40f5ddac
BV
492 }
493 s++;
494 }
580f3099 495 if (multiplier > 0) {
f64c1414 496 *size *= multiplier;
580f3099
DJ
497 *size += frac_part * multiplier;
498 } else
499 *size += frac_part;
40f5ddac 500
34577da6 501 if (s && *s && g_ascii_strcasecmp(s, "Hz"))
f64c1414
BV
502 return SR_ERR;
503
504 return SR_OK;
40f5ddac
BV
505}
506
dfcc0bf9
UH
507/**
508 * Convert a "natural" string representation of a time value to an
509 * uint64_t value in milliseconds.
510 *
511 * E.g. a value of "3s" or "3 s" would be converted to 3000, a value
512 * of "15ms" would be converted to 15.
513 *
514 * Value representations other than decimal (such as hex or octal) are not
515 * supported. Only lower-case "s" and "ms" time suffixes are supported.
516 * Spaces (but not other whitespace) between value and suffix are allowed.
517 *
518 * @param timestring A string containing a (decimal) time value.
519 * @return The string's time value as uint64_t, in milliseconds.
520 *
6b2d8d3e
UH
521 * @todo Add support for "m" (minutes) and others.
522 * @todo Add support for picoseconds?
523 * @todo Allow both lower-case and upper-case? If no, document it.
47117241
UH
524 *
525 * @since 0.1.0
dfcc0bf9 526 */
1a081ca6 527SR_API uint64_t sr_parse_timestring(const char *timestring)
40f5ddac
BV
528{
529 uint64_t time_msec;
530 char *s;
531
6b2d8d3e
UH
532 /* TODO: Error handling, logging. */
533
40f5ddac
BV
534 time_msec = strtoull(timestring, &s, 10);
535 if (time_msec == 0 && s == timestring)
536 return 0;
537
538 if (s && *s) {
539 while (*s == ' ')
540 s++;
541 if (!strcmp(s, "s"))
542 time_msec *= 1000;
543 else if (!strcmp(s, "ms"))
544 ; /* redundant */
545 else
546 return 0;
547 }
548
549 return time_msec;
550}
4d436e71 551
47117241 552/** @since 0.1.0 */
1a081ca6 553SR_API gboolean sr_parse_boolstring(const char *boolstr)
4d436e71
GM
554{
555 if (!boolstr)
556 return FALSE;
557
993526f8
BV
558 if (!g_ascii_strncasecmp(boolstr, "true", 4) ||
559 !g_ascii_strncasecmp(boolstr, "yes", 3) ||
560 !g_ascii_strncasecmp(boolstr, "on", 2) ||
561 !g_ascii_strncasecmp(boolstr, "1", 1))
4d436e71
GM
562 return TRUE;
563
564 return FALSE;
565}
76f4c610 566
47117241 567/** @since 0.2.0 */
76e107d6 568SR_API int sr_parse_period(const char *periodstr, uint64_t *p, uint64_t *q)
76f4c610
BV
569{
570 char *s;
571
76e107d6
BV
572 *p = strtoull(periodstr, &s, 10);
573 if (*p == 0 && s == periodstr)
76f4c610
BV
574 /* No digits found. */
575 return SR_ERR_ARG;
576
577 if (s && *s) {
578 while (*s == ' ')
579 s++;
8c012adb 580 if (!strcmp(s, "fs"))
76e107d6 581 *q = 1000000000000000ULL;
8c012adb 582 else if (!strcmp(s, "ps"))
76e107d6 583 *q = 1000000000000ULL;
8c012adb 584 else if (!strcmp(s, "ns"))
76e107d6 585 *q = 1000000000ULL;
76f4c610 586 else if (!strcmp(s, "us"))
76e107d6 587 *q = 1000000;
76f4c610 588 else if (!strcmp(s, "ms"))
76e107d6 589 *q = 1000;
76f4c610 590 else if (!strcmp(s, "s"))
76e107d6 591 *q = 1;
76f4c610
BV
592 else
593 /* Must have a time suffix. */
594 return SR_ERR_ARG;
595 }
596
597 return SR_OK;
598}
599
47117241 600/** @since 0.2.0 */
76e107d6 601SR_API int sr_parse_voltage(const char *voltstr, uint64_t *p, uint64_t *q)
79afc8ca
BV
602{
603 char *s;
604
76e107d6
BV
605 *p = strtoull(voltstr, &s, 10);
606 if (*p == 0 && s == voltstr)
79afc8ca
BV
607 /* No digits found. */
608 return SR_ERR_ARG;
609
610 if (s && *s) {
611 while (*s == ' ')
612 s++;
34577da6 613 if (!g_ascii_strcasecmp(s, "mv"))
76e107d6 614 *q = 1000L;
34577da6 615 else if (!g_ascii_strcasecmp(s, "v"))
76e107d6 616 *q = 1;
79afc8ca
BV
617 else
618 /* Must have a base suffix. */
619 return SR_ERR_ARG;
620 }
621
622 return SR_OK;
623}
624
7b870c38 625/** @} */