]> sigrok.org Git - libsigrok.git/blame - strutil.c
device: Pass sdi as an function argument to config_list in dev_has_option()
[libsigrok.git] / 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
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
19 */
20
21#include <stdint.h>
22#include <stdlib.h>
23#include <string.h>
9e4f8cf9 24#include <errno.h>
45c59c8b
BV
25#include "libsigrok.h"
26#include "libsigrok-internal.h"
25e7d9b1 27
3544f848 28#define LOG_PREFIX "strutil"
a885ce3e 29
393fb9cb
UH
30/**
31 * @file
32 *
33 * Helper functions for handling or converting libsigrok-related strings.
34 */
35
7b870c38
UH
36/**
37 * @defgroup grp_strutil String utilities
38 *
39 * Helper functions for handling or converting libsigrok-related strings.
40 *
41 * @{
42 */
43
9e4f8cf9 44/**
df823ac4
UH
45 * @private
46 *
9e4f8cf9
DJ
47 * Convert a string representation of a numeric value to a long integer. The
48 * conversion is strict and will fail if the complete string does not represent
49 * a valid long integer. The function sets errno according to the details of the
50 * failure.
51 *
52 * @param str The string representation to convert.
53 * @param ret Pointer to long where the result of the conversion will be stored.
54 *
55 * @return SR_OK if conversion is successful, otherwise SR_ERR.
56 *
57 * @since 0.3.0
58 */
8d558c7a 59SR_PRIV int sr_atol(const char *str, long *ret)
9e4f8cf9
DJ
60{
61 long tmp;
62 char *endptr = NULL;
63
64 errno = 0;
65 tmp = strtol(str, &endptr, 0);
66
67 if (!endptr || *endptr || errno) {
68 if (!errno)
69 errno = EINVAL;
70 return SR_ERR;
71 }
72
73 *ret = tmp;
74 return SR_OK;
75}
76
77/**
df823ac4
UH
78 * @private
79 *
9e4f8cf9
DJ
80 * Convert a string representation of a numeric value to an integer. The
81 * conversion is strict and will fail if the complete string does not represent
82 * a valid integer. The function sets errno according to the details of the
83 * failure.
84 *
85 * @param str The string representation to convert.
86 * @param ret Pointer to int where the result of the conversion will be stored.
87 *
88 * @return SR_OK if conversion is successful, otherwise SR_ERR.
89 *
90 * @since 0.3.0
91 */
8d558c7a 92SR_PRIV int sr_atoi(const char *str, int *ret)
9e4f8cf9
DJ
93{
94 long tmp;
95
96 if (sr_atol(str, &tmp) != SR_OK)
97 return SR_ERR;
98
99 if ((int) tmp != tmp) {
100 errno = ERANGE;
101 return SR_ERR;
102 }
103
104 *ret = (int) tmp;
105 return SR_OK;
106}
107
108/**
df823ac4
UH
109 * @private
110 *
9e4f8cf9
DJ
111 * Convert a string representation of a numeric value to a double. The
112 * conversion is strict and will fail if the complete string does not represent
113 * a valid double. The function sets errno according to the details of the
114 * failure.
115 *
116 * @param str The string representation to convert.
117 * @param ret Pointer to double where the result of the conversion will be stored.
118 *
119 * @return SR_OK if conversion is successful, otherwise SR_ERR.
120 *
121 * @since 0.3.0
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 *
152 * @return SR_OK if conversion is successful, otherwise SR_ERR.
153 *
154 * @since 0.3.0
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
25e7d9b1 172/**
b07b42f3
UH
173 * Convert a numeric value value to its "natural" string representation
174 * in SI units.
25e7d9b1 175 *
4cc9aea1
JH
176 * E.g. a value of 3000000, with units set to "W", would be converted
177 * to "3 MW", 20000 to "20 kW", 31500 would become "31.5 kW".
25e7d9b1 178 *
4cc9aea1
JH
179 * @param x The value to convert.
180 * @param unit The unit to append to the string, or NULL if the string
181 * has no units.
44dae539 182 *
133a37bf
UH
183 * @return A g_try_malloc()ed string representation of the samplerate value,
184 * or NULL upon errors. The caller is responsible to g_free() the
185 * memory.
25e7d9b1 186 */
4cc9aea1 187SR_API char *sr_si_string_u64(uint64_t x, const char *unit)
25e7d9b1 188{
094e6b81
PS
189 uint8_t i;
190 uint64_t quot, divisor[] = {
b07b42f3
UH
191 SR_HZ(1), SR_KHZ(1), SR_MHZ(1), SR_GHZ(1),
192 SR_GHZ(1000), SR_GHZ(1000 * 1000), SR_GHZ(1000 * 1000 * 1000),
094e6b81
PS
193 };
194 const char *p, prefix[] = "\0kMGTPE";
69d83be9 195 char fmt[16], fract[20] = "", *f;
094e6b81 196
a885ce3e 197 if (unit == NULL)
4cc9aea1 198 unit = "";
25e7d9b1 199
094e6b81
PS
200 for (i = 0; (quot = x / divisor[i]) >= 1000; i++);
201
202 if (i) {
69d83be9 203 sprintf(fmt, ".%%0%d"PRIu64, i * 3);
094e6b81
PS
204 f = fract + sprintf(fract, fmt, x % divisor[i]) - 1;
205
206 while (f >= fract && strchr("0.", *f))
207 *f-- = 0;
133a37bf 208 }
25e7d9b1 209
094e6b81
PS
210 p = prefix + i;
211
212 return g_strdup_printf("%" PRIu64 "%s %.1s%s", quot, fract, p, unit);
4cc9aea1 213}
25e7d9b1 214
4cc9aea1
JH
215/**
216 * Convert a numeric samplerate value to its "natural" string representation.
217 *
218 * E.g. a value of 3000000 would be converted to "3 MHz", 20000 to "20 kHz",
219 * 31500 would become "31.5 kHz".
220 *
221 * @param samplerate The samplerate in Hz.
222 *
223 * @return A g_try_malloc()ed string representation of the samplerate value,
224 * or NULL upon errors. The caller is responsible to g_free() the
225 * memory.
226 */
227SR_API char *sr_samplerate_string(uint64_t samplerate)
228{
229 return sr_si_string_u64(samplerate, "Hz");
25e7d9b1 230}
2a3f9541 231
2a3f9541 232/**
dfcc0bf9 233 * Convert a numeric frequency value to the "natural" string representation
2a3f9541
BV
234 * of its period.
235 *
2507648e 236 * E.g. a value of 3000000 would be converted to "3 us", 20000 to "50 ms".
2a3f9541
BV
237 *
238 * @param frequency The frequency in Hz.
44dae539 239 *
133a37bf
UH
240 * @return A g_try_malloc()ed string representation of the frequency value,
241 * or NULL upon errors. The caller is responsible to g_free() the
242 * memory.
2a3f9541 243 */
1a081ca6 244SR_API char *sr_period_string(uint64_t frequency)
2a3f9541
BV
245{
246 char *o;
247 int r;
248
133a37bf
UH
249 /* Allocate enough for a uint64_t as string + " ms". */
250 if (!(o = g_try_malloc0(30 + 1))) {
a885ce3e 251 sr_err("%s: o malloc failed", __func__);
2a3f9541 252 return NULL;
133a37bf 253 }
2a3f9541 254
59df0c77 255 if (frequency >= SR_GHZ(1))
2a3f9541 256 r = snprintf(o, 30, "%" PRIu64 " ns", frequency / 1000000000);
59df0c77 257 else if (frequency >= SR_MHZ(1))
2507648e 258 r = snprintf(o, 30, "%" PRIu64 " us", frequency / 1000000);
59df0c77 259 else if (frequency >= SR_KHZ(1))
2a3f9541
BV
260 r = snprintf(o, 30, "%" PRIu64 " ms", frequency / 1000);
261 else
262 r = snprintf(o, 30, "%" PRIu64 " s", frequency);
263
264 if (r < 0) {
265 /* Something went wrong... */
133a37bf 266 g_free(o);
2a3f9541
BV
267 return NULL;
268 }
269
270 return o;
271}
40f5ddac 272
79afc8ca 273/**
e0e15067
BV
274 * Convert a numeric voltage value to the "natural" string representation
275 * of its voltage value. The voltage is specified as a rational number's
276 * numerator and denominator.
79afc8ca
BV
277 *
278 * E.g. a value of 300000 would be converted to "300mV", 2 to "2V".
279 *
e0e15067
BV
280 * @param v_p The voltage numerator.
281 * @param v_q The voltage denominator.
79afc8ca
BV
282 *
283 * @return A g_try_malloc()ed string representation of the voltage value,
284 * or NULL upon errors. The caller is responsible to g_free() the
285 * memory.
286 */
e0e15067 287SR_API char *sr_voltage_string(uint64_t v_p, uint64_t v_q)
79afc8ca 288{
79afc8ca 289 int r;
d5a669a9 290 char *o;
79afc8ca
BV
291
292 if (!(o = g_try_malloc0(30 + 1))) {
a885ce3e 293 sr_err("%s: o malloc failed", __func__);
79afc8ca
BV
294 return NULL;
295 }
296
e0e15067
BV
297 if (v_q == 1000)
298 r = snprintf(o, 30, "%" PRIu64 "mV", v_p);
299 else if (v_q == 1)
300 r = snprintf(o, 30, "%" PRIu64 "V", v_p);
79afc8ca 301 else
e0e15067 302 r = snprintf(o, 30, "%gV", (float)v_p / (float)v_q);
79afc8ca
BV
303
304 if (r < 0) {
305 /* Something went wrong... */
306 g_free(o);
307 return NULL;
308 }
309
310 return o;
311}
312
dfcc0bf9 313/**
bf978d35 314 * Parse a trigger specification string.
dfcc0bf9 315 *
9c5332d2
UH
316 * @param sdi The device instance for which the trigger specification is
317 * intended. Must not be NULL. Also, sdi->driver and
318 * sdi->driver->info_get must not be NULL.
bf978d35
UH
319 * @param triggerstring The string containing the trigger specification for
320 * one or more probes of this device. Entries for multiple probes are
321 * comma-separated. Triggers are specified in the form key=value,
322 * where the key is a probe number (or probe name) and the value is
323 * the requested trigger type. Valid trigger types currently
324 * include 'r' (rising edge), 'f' (falling edge), 'c' (any pin value
325 * change), '0' (low value), or '1' (high value).
326 * Example: "1=r,sck=f,miso=0,7=c"
44dae539 327 *
bf978d35
UH
328 * @return Pointer to a list of trigger types (strings), or NULL upon errors.
329 * The pointer list (if non-NULL) has as many entries as the
330 * respective device has probes (all physically available probes,
331 * not just enabled ones). Entries of the list which don't have
332 * a trigger value set in 'triggerstring' are NULL, the other entries
333 * contain the respective trigger type which is requested for the
334 * respective probe (e.g. "r", "c", and so on).
dfcc0bf9 335 */
92ae7984 336SR_API char **sr_parse_triggerstring(const struct sr_dev_inst *sdi,
1a081ca6 337 const char *triggerstring)
40f5ddac
BV
338{
339 GSList *l;
003595ac 340 GVariant *gvar;
1afe8989 341 struct sr_probe *probe;
40f5ddac 342 int max_probes, probenum, i;
b7f578be
JH
343 char **tokens, **triggerlist, *trigger, *tc;
344 const char *trigger_types;
40f5ddac
BV
345 gboolean error;
346
92ae7984 347 max_probes = g_slist_length(sdi->probes);
40f5ddac 348 error = FALSE;
b53738ba
UH
349
350 if (!(triggerlist = g_try_malloc0(max_probes * sizeof(char *)))) {
a885ce3e 351 sr_err("%s: triggerlist malloc failed", __func__);
b53738ba
UH
352 return NULL;
353 }
354
8f996b89
ML
355 if (sdi->driver->config_list(SR_CONF_TRIGGER_TYPE,
356 &gvar, sdi, NULL) != SR_OK) {
a885ce3e 357 sr_err("%s: Device doesn't support any triggers.", __func__);
40f5ddac 358 return NULL;
bf978d35 359 }
003595ac 360 trigger_types = g_variant_get_string(gvar, NULL);
40f5ddac 361
31fc1fbc 362 tokens = g_strsplit(triggerstring, ",", max_probes);
40f5ddac 363 for (i = 0; tokens[i]; i++) {
17ff1124
BV
364 probenum = -1;
365 for (l = sdi->probes; l; l = l->next) {
366 probe = (struct sr_probe *)l->data;
367 if (probe->enabled
368 && !strncmp(probe->name, tokens[i],
369 strlen(probe->name))) {
370 probenum = probe->index;
371 break;
40f5ddac 372 }
40f5ddac
BV
373 }
374
31fc1fbc 375 if (probenum < 0 || probenum >= max_probes) {
a885ce3e 376 sr_err("Invalid probe.");
40f5ddac
BV
377 error = TRUE;
378 break;
379 }
380
381 if ((trigger = strchr(tokens[i], '='))) {
382 for (tc = ++trigger; *tc; tc++) {
383 if (strchr(trigger_types, *tc) == NULL) {
a885ce3e 384 sr_err("Unsupported trigger "
0aeb0ccd 385 "type '%c'.", *tc);
40f5ddac
BV
386 error = TRUE;
387 break;
388 }
389 }
390 if (!error)
31fc1fbc 391 triggerlist[probenum] = g_strdup(trigger);
40f5ddac
BV
392 }
393 }
394 g_strfreev(tokens);
003595ac 395 g_variant_unref(gvar);
40f5ddac
BV
396
397 if (error) {
398 for (i = 0; i < max_probes; i++)
66410a86 399 g_free(triggerlist[i]);
40f5ddac
BV
400 g_free(triggerlist);
401 triggerlist = NULL;
402 }
403
404 return triggerlist;
405}
406
dfcc0bf9
UH
407/**
408 * Convert a "natural" string representation of a size value to uint64_t.
409 *
410 * E.g. a value of "3k" or "3 K" would be converted to 3000, a value
411 * of "15M" would be converted to 15000000.
412 *
413 * Value representations other than decimal (such as hex or octal) are not
414 * supported. Only 'k' (kilo), 'm' (mega), 'g' (giga) suffixes are supported.
415 * Spaces (but not other whitespace) between value and suffix are allowed.
416 *
417 * @param sizestring A string containing a (decimal) size value.
f64c1414 418 * @param size Pointer to uint64_t which will contain the string's size value.
dfcc0bf9 419 *
44dae539 420 * @return SR_OK upon success, SR_ERR upon errors.
dfcc0bf9 421 */
1a081ca6 422SR_API int sr_parse_sizestring(const char *sizestring, uint64_t *size)
40f5ddac 423{
f64c1414 424 int multiplier, done;
580f3099 425 double frac_part;
40f5ddac
BV
426 char *s;
427
f64c1414 428 *size = strtoull(sizestring, &s, 10);
40f5ddac 429 multiplier = 0;
580f3099 430 frac_part = 0;
f64c1414
BV
431 done = FALSE;
432 while (s && *s && multiplier == 0 && !done) {
40f5ddac
BV
433 switch (*s) {
434 case ' ':
435 break;
580f3099
DJ
436 case '.':
437 frac_part = g_ascii_strtod(s, &s);
438 break;
40f5ddac
BV
439 case 'k':
440 case 'K':
59df0c77 441 multiplier = SR_KHZ(1);
40f5ddac
BV
442 break;
443 case 'm':
444 case 'M':
59df0c77 445 multiplier = SR_MHZ(1);
40f5ddac
BV
446 break;
447 case 'g':
448 case 'G':
59df0c77 449 multiplier = SR_GHZ(1);
40f5ddac
BV
450 break;
451 default:
f64c1414
BV
452 done = TRUE;
453 s--;
40f5ddac
BV
454 }
455 s++;
456 }
580f3099 457 if (multiplier > 0) {
f64c1414 458 *size *= multiplier;
580f3099
DJ
459 *size += frac_part * multiplier;
460 } else
461 *size += frac_part;
40f5ddac 462
f64c1414
BV
463 if (*s && strcasecmp(s, "Hz"))
464 return SR_ERR;
465
466 return SR_OK;
40f5ddac
BV
467}
468
dfcc0bf9
UH
469/**
470 * Convert a "natural" string representation of a time value to an
471 * uint64_t value in milliseconds.
472 *
473 * E.g. a value of "3s" or "3 s" would be converted to 3000, a value
474 * of "15ms" would be converted to 15.
475 *
476 * Value representations other than decimal (such as hex or octal) are not
477 * supported. Only lower-case "s" and "ms" time suffixes are supported.
478 * Spaces (but not other whitespace) between value and suffix are allowed.
479 *
480 * @param timestring A string containing a (decimal) time value.
481 * @return The string's time value as uint64_t, in milliseconds.
482 *
6b2d8d3e
UH
483 * @todo Add support for "m" (minutes) and others.
484 * @todo Add support for picoseconds?
485 * @todo Allow both lower-case and upper-case? If no, document it.
dfcc0bf9 486 */
1a081ca6 487SR_API uint64_t sr_parse_timestring(const char *timestring)
40f5ddac
BV
488{
489 uint64_t time_msec;
490 char *s;
491
6b2d8d3e
UH
492 /* TODO: Error handling, logging. */
493
40f5ddac
BV
494 time_msec = strtoull(timestring, &s, 10);
495 if (time_msec == 0 && s == timestring)
496 return 0;
497
498 if (s && *s) {
499 while (*s == ' ')
500 s++;
501 if (!strcmp(s, "s"))
502 time_msec *= 1000;
503 else if (!strcmp(s, "ms"))
504 ; /* redundant */
505 else
506 return 0;
507 }
508
509 return time_msec;
510}
4d436e71 511
1a081ca6 512SR_API gboolean sr_parse_boolstring(const char *boolstr)
4d436e71
GM
513{
514 if (!boolstr)
515 return FALSE;
516
993526f8
BV
517 if (!g_ascii_strncasecmp(boolstr, "true", 4) ||
518 !g_ascii_strncasecmp(boolstr, "yes", 3) ||
519 !g_ascii_strncasecmp(boolstr, "on", 2) ||
520 !g_ascii_strncasecmp(boolstr, "1", 1))
4d436e71
GM
521 return TRUE;
522
523 return FALSE;
524}
76f4c610 525
76e107d6 526SR_API int sr_parse_period(const char *periodstr, uint64_t *p, uint64_t *q)
76f4c610
BV
527{
528 char *s;
529
76e107d6
BV
530 *p = strtoull(periodstr, &s, 10);
531 if (*p == 0 && s == periodstr)
76f4c610
BV
532 /* No digits found. */
533 return SR_ERR_ARG;
534
535 if (s && *s) {
536 while (*s == ' ')
537 s++;
8c012adb 538 if (!strcmp(s, "fs"))
76e107d6 539 *q = 1000000000000000ULL;
8c012adb 540 else if (!strcmp(s, "ps"))
76e107d6 541 *q = 1000000000000ULL;
8c012adb 542 else if (!strcmp(s, "ns"))
76e107d6 543 *q = 1000000000ULL;
76f4c610 544 else if (!strcmp(s, "us"))
76e107d6 545 *q = 1000000;
76f4c610 546 else if (!strcmp(s, "ms"))
76e107d6 547 *q = 1000;
76f4c610 548 else if (!strcmp(s, "s"))
76e107d6 549 *q = 1;
76f4c610
BV
550 else
551 /* Must have a time suffix. */
552 return SR_ERR_ARG;
553 }
554
555 return SR_OK;
556}
557
558
76e107d6 559SR_API int sr_parse_voltage(const char *voltstr, uint64_t *p, uint64_t *q)
79afc8ca
BV
560{
561 char *s;
562
76e107d6
BV
563 *p = strtoull(voltstr, &s, 10);
564 if (*p == 0 && s == voltstr)
79afc8ca
BV
565 /* No digits found. */
566 return SR_ERR_ARG;
567
568 if (s && *s) {
569 while (*s == ' ')
570 s++;
571 if (!strcasecmp(s, "mv"))
76e107d6 572 *q = 1000L;
79afc8ca 573 else if (!strcasecmp(s, "v"))
76e107d6 574 *q = 1;
79afc8ca
BV
575 else
576 /* Must have a base suffix. */
577 return SR_ERR_ARG;
578 }
579
580 return SR_OK;
581}
582
7b870c38 583/** @} */