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