]> sigrok.org Git - libsigrok.git/blame - strutil.c
Replace 'probe' with 'channel' in most places.
[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
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 *
183 * @return SR_OK if conversion is successful, otherwise SR_ERR.
184 *
185 * @since 0.3.0
186 */
187SR_PRIV int sr_atof_ascii(const char *str, float *ret)
188{
189 double tmp;
190 char *endptr = NULL;
191
192 errno = 0;
193 tmp = g_ascii_strtod(str, &endptr);
194
195 if (!endptr || *endptr || errno) {
196 if (!errno)
197 errno = EINVAL;
198 return SR_ERR;
199 }
200
201 /* FIXME This fails unexpectedly. Some other method to safel downcast
202 * needs to be found. Checking against FLT_MAX doesn't work as well. */
203 /*
204 if ((float) tmp != tmp) {
205 errno = ERANGE;
206 sr_dbg("ERANGEEEE %e != %e", (float) tmp, tmp);
207 return SR_ERR;
208 }
209 */
210
211 *ret = (float) tmp;
212 return SR_OK;
213}
214
25e7d9b1 215/**
b07b42f3
UH
216 * Convert a numeric value value to its "natural" string representation
217 * in SI units.
25e7d9b1 218 *
4cc9aea1
JH
219 * E.g. a value of 3000000, with units set to "W", would be converted
220 * to "3 MW", 20000 to "20 kW", 31500 would become "31.5 kW".
25e7d9b1 221 *
4cc9aea1
JH
222 * @param x The value to convert.
223 * @param unit The unit to append to the string, or NULL if the string
224 * has no units.
44dae539 225 *
133a37bf
UH
226 * @return A g_try_malloc()ed string representation of the samplerate value,
227 * or NULL upon errors. The caller is responsible to g_free() the
228 * memory.
25e7d9b1 229 */
4cc9aea1 230SR_API char *sr_si_string_u64(uint64_t x, const char *unit)
25e7d9b1 231{
094e6b81
PS
232 uint8_t i;
233 uint64_t quot, divisor[] = {
b07b42f3
UH
234 SR_HZ(1), SR_KHZ(1), SR_MHZ(1), SR_GHZ(1),
235 SR_GHZ(1000), SR_GHZ(1000 * 1000), SR_GHZ(1000 * 1000 * 1000),
094e6b81
PS
236 };
237 const char *p, prefix[] = "\0kMGTPE";
69d83be9 238 char fmt[16], fract[20] = "", *f;
094e6b81 239
a885ce3e 240 if (unit == NULL)
4cc9aea1 241 unit = "";
25e7d9b1 242
094e6b81
PS
243 for (i = 0; (quot = x / divisor[i]) >= 1000; i++);
244
245 if (i) {
69d83be9 246 sprintf(fmt, ".%%0%d"PRIu64, i * 3);
094e6b81
PS
247 f = fract + sprintf(fract, fmt, x % divisor[i]) - 1;
248
249 while (f >= fract && strchr("0.", *f))
250 *f-- = 0;
133a37bf 251 }
25e7d9b1 252
094e6b81
PS
253 p = prefix + i;
254
255 return g_strdup_printf("%" PRIu64 "%s %.1s%s", quot, fract, p, unit);
4cc9aea1 256}
25e7d9b1 257
4cc9aea1
JH
258/**
259 * Convert a numeric samplerate value to its "natural" string representation.
260 *
261 * E.g. a value of 3000000 would be converted to "3 MHz", 20000 to "20 kHz",
262 * 31500 would become "31.5 kHz".
263 *
264 * @param samplerate The samplerate in Hz.
265 *
266 * @return A g_try_malloc()ed string representation of the samplerate value,
267 * or NULL upon errors. The caller is responsible to g_free() the
268 * memory.
269 */
270SR_API char *sr_samplerate_string(uint64_t samplerate)
271{
272 return sr_si_string_u64(samplerate, "Hz");
25e7d9b1 273}
2a3f9541 274
2a3f9541 275/**
dfcc0bf9 276 * Convert a numeric frequency value to the "natural" string representation
2a3f9541
BV
277 * of its period.
278 *
2507648e 279 * E.g. a value of 3000000 would be converted to "3 us", 20000 to "50 ms".
2a3f9541
BV
280 *
281 * @param frequency The frequency in Hz.
44dae539 282 *
133a37bf
UH
283 * @return A g_try_malloc()ed string representation of the frequency value,
284 * or NULL upon errors. The caller is responsible to g_free() the
285 * memory.
2a3f9541 286 */
1a081ca6 287SR_API char *sr_period_string(uint64_t frequency)
2a3f9541
BV
288{
289 char *o;
290 int r;
291
133a37bf
UH
292 /* Allocate enough for a uint64_t as string + " ms". */
293 if (!(o = g_try_malloc0(30 + 1))) {
a885ce3e 294 sr_err("%s: o malloc failed", __func__);
2a3f9541 295 return NULL;
133a37bf 296 }
2a3f9541 297
59df0c77 298 if (frequency >= SR_GHZ(1))
2a3f9541 299 r = snprintf(o, 30, "%" PRIu64 " ns", frequency / 1000000000);
59df0c77 300 else if (frequency >= SR_MHZ(1))
2507648e 301 r = snprintf(o, 30, "%" PRIu64 " us", frequency / 1000000);
59df0c77 302 else if (frequency >= SR_KHZ(1))
2a3f9541
BV
303 r = snprintf(o, 30, "%" PRIu64 " ms", frequency / 1000);
304 else
305 r = snprintf(o, 30, "%" PRIu64 " s", frequency);
306
307 if (r < 0) {
308 /* Something went wrong... */
133a37bf 309 g_free(o);
2a3f9541
BV
310 return NULL;
311 }
312
313 return o;
314}
40f5ddac 315
79afc8ca 316/**
e0e15067
BV
317 * Convert a numeric voltage value to the "natural" string representation
318 * of its voltage value. The voltage is specified as a rational number's
319 * numerator and denominator.
79afc8ca
BV
320 *
321 * E.g. a value of 300000 would be converted to "300mV", 2 to "2V".
322 *
e0e15067
BV
323 * @param v_p The voltage numerator.
324 * @param v_q The voltage denominator.
79afc8ca
BV
325 *
326 * @return A g_try_malloc()ed string representation of the voltage value,
327 * or NULL upon errors. The caller is responsible to g_free() the
328 * memory.
329 */
e0e15067 330SR_API char *sr_voltage_string(uint64_t v_p, uint64_t v_q)
79afc8ca 331{
79afc8ca 332 int r;
d5a669a9 333 char *o;
79afc8ca
BV
334
335 if (!(o = g_try_malloc0(30 + 1))) {
a885ce3e 336 sr_err("%s: o malloc failed", __func__);
79afc8ca
BV
337 return NULL;
338 }
339
e0e15067
BV
340 if (v_q == 1000)
341 r = snprintf(o, 30, "%" PRIu64 "mV", v_p);
342 else if (v_q == 1)
343 r = snprintf(o, 30, "%" PRIu64 "V", v_p);
79afc8ca 344 else
e0e15067 345 r = snprintf(o, 30, "%gV", (float)v_p / (float)v_q);
79afc8ca
BV
346
347 if (r < 0) {
348 /* Something went wrong... */
349 g_free(o);
350 return NULL;
351 }
352
353 return o;
354}
355
dfcc0bf9 356/**
bf978d35 357 * Parse a trigger specification string.
dfcc0bf9 358 *
9c5332d2
UH
359 * @param sdi The device instance for which the trigger specification is
360 * intended. Must not be NULL. Also, sdi->driver and
361 * sdi->driver->info_get must not be NULL.
bf978d35 362 * @param triggerstring The string containing the trigger specification for
ba7dd8bb 363 * one or more channels of this device. Entries for multiple channels are
bf978d35 364 * comma-separated. Triggers are specified in the form key=value,
ba7dd8bb 365 * where the key is a channel number (or channel name) and the value is
bf978d35
UH
366 * the requested trigger type. Valid trigger types currently
367 * include 'r' (rising edge), 'f' (falling edge), 'c' (any pin value
368 * change), '0' (low value), or '1' (high value).
369 * Example: "1=r,sck=f,miso=0,7=c"
44dae539 370 *
bf978d35
UH
371 * @return Pointer to a list of trigger types (strings), or NULL upon errors.
372 * The pointer list (if non-NULL) has as many entries as the
ba7dd8bb 373 * respective device has channels (all physically available channels,
bf978d35
UH
374 * not just enabled ones). Entries of the list which don't have
375 * a trigger value set in 'triggerstring' are NULL, the other entries
376 * contain the respective trigger type which is requested for the
ba7dd8bb 377 * respective channel (e.g. "r", "c", and so on).
dfcc0bf9 378 */
92ae7984 379SR_API char **sr_parse_triggerstring(const struct sr_dev_inst *sdi,
1a081ca6 380 const char *triggerstring)
40f5ddac
BV
381{
382 GSList *l;
003595ac 383 GVariant *gvar;
ba7dd8bb
UH
384 struct sr_channel *ch;
385 int max_channels, channelnum, i;
b7f578be
JH
386 char **tokens, **triggerlist, *trigger, *tc;
387 const char *trigger_types;
40f5ddac
BV
388 gboolean error;
389
ba7dd8bb 390 max_channels = g_slist_length(sdi->channels);
40f5ddac 391 error = FALSE;
b53738ba 392
ba7dd8bb 393 if (!(triggerlist = g_try_malloc0(max_channels * sizeof(char *)))) {
a885ce3e 394 sr_err("%s: triggerlist malloc failed", __func__);
b53738ba
UH
395 return NULL;
396 }
397
8f996b89
ML
398 if (sdi->driver->config_list(SR_CONF_TRIGGER_TYPE,
399 &gvar, sdi, NULL) != SR_OK) {
a885ce3e 400 sr_err("%s: Device doesn't support any triggers.", __func__);
40f5ddac 401 return NULL;
bf978d35 402 }
003595ac 403 trigger_types = g_variant_get_string(gvar, NULL);
40f5ddac 404
ba7dd8bb 405 tokens = g_strsplit(triggerstring, ",", max_channels);
40f5ddac 406 for (i = 0; tokens[i]; i++) {
ba7dd8bb
UH
407 channelnum = -1;
408 for (l = sdi->channels; l; l = l->next) {
409 ch = (struct sr_channel *)l->data;
410 if (ch->enabled
411 && !strncmp(ch->name, tokens[i],
412 strlen(ch->name))) {
413 channelnum = ch->index;
17ff1124 414 break;
40f5ddac 415 }
40f5ddac
BV
416 }
417
ba7dd8bb
UH
418 if (channelnum < 0 || channelnum >= max_channels) {
419 sr_err("Invalid channel.");
40f5ddac
BV
420 error = TRUE;
421 break;
422 }
423
424 if ((trigger = strchr(tokens[i], '='))) {
425 for (tc = ++trigger; *tc; tc++) {
426 if (strchr(trigger_types, *tc) == NULL) {
a885ce3e 427 sr_err("Unsupported trigger "
0aeb0ccd 428 "type '%c'.", *tc);
40f5ddac
BV
429 error = TRUE;
430 break;
431 }
432 }
433 if (!error)
ba7dd8bb 434 triggerlist[channelnum] = g_strdup(trigger);
40f5ddac
BV
435 }
436 }
437 g_strfreev(tokens);
003595ac 438 g_variant_unref(gvar);
40f5ddac
BV
439
440 if (error) {
ba7dd8bb 441 for (i = 0; i < max_channels; i++)
66410a86 442 g_free(triggerlist[i]);
40f5ddac
BV
443 g_free(triggerlist);
444 triggerlist = NULL;
445 }
446
447 return triggerlist;
448}
449
dfcc0bf9
UH
450/**
451 * Convert a "natural" string representation of a size value to uint64_t.
452 *
453 * E.g. a value of "3k" or "3 K" would be converted to 3000, a value
454 * of "15M" would be converted to 15000000.
455 *
456 * Value representations other than decimal (such as hex or octal) are not
457 * supported. Only 'k' (kilo), 'm' (mega), 'g' (giga) suffixes are supported.
458 * Spaces (but not other whitespace) between value and suffix are allowed.
459 *
460 * @param sizestring A string containing a (decimal) size value.
f64c1414 461 * @param size Pointer to uint64_t which will contain the string's size value.
dfcc0bf9 462 *
44dae539 463 * @return SR_OK upon success, SR_ERR upon errors.
dfcc0bf9 464 */
1a081ca6 465SR_API int sr_parse_sizestring(const char *sizestring, uint64_t *size)
40f5ddac 466{
f64c1414 467 int multiplier, done;
580f3099 468 double frac_part;
40f5ddac
BV
469 char *s;
470
f64c1414 471 *size = strtoull(sizestring, &s, 10);
40f5ddac 472 multiplier = 0;
580f3099 473 frac_part = 0;
f64c1414
BV
474 done = FALSE;
475 while (s && *s && multiplier == 0 && !done) {
40f5ddac
BV
476 switch (*s) {
477 case ' ':
478 break;
580f3099
DJ
479 case '.':
480 frac_part = g_ascii_strtod(s, &s);
481 break;
40f5ddac
BV
482 case 'k':
483 case 'K':
59df0c77 484 multiplier = SR_KHZ(1);
40f5ddac
BV
485 break;
486 case 'm':
487 case 'M':
59df0c77 488 multiplier = SR_MHZ(1);
40f5ddac
BV
489 break;
490 case 'g':
491 case 'G':
59df0c77 492 multiplier = SR_GHZ(1);
40f5ddac
BV
493 break;
494 default:
f64c1414
BV
495 done = TRUE;
496 s--;
40f5ddac
BV
497 }
498 s++;
499 }
580f3099 500 if (multiplier > 0) {
f64c1414 501 *size *= multiplier;
580f3099
DJ
502 *size += frac_part * multiplier;
503 } else
504 *size += frac_part;
40f5ddac 505
f64c1414
BV
506 if (*s && strcasecmp(s, "Hz"))
507 return SR_ERR;
508
509 return SR_OK;
40f5ddac
BV
510}
511
dfcc0bf9
UH
512/**
513 * Convert a "natural" string representation of a time value to an
514 * uint64_t value in milliseconds.
515 *
516 * E.g. a value of "3s" or "3 s" would be converted to 3000, a value
517 * of "15ms" would be converted to 15.
518 *
519 * Value representations other than decimal (such as hex or octal) are not
520 * supported. Only lower-case "s" and "ms" time suffixes are supported.
521 * Spaces (but not other whitespace) between value and suffix are allowed.
522 *
523 * @param timestring A string containing a (decimal) time value.
524 * @return The string's time value as uint64_t, in milliseconds.
525 *
6b2d8d3e
UH
526 * @todo Add support for "m" (minutes) and others.
527 * @todo Add support for picoseconds?
528 * @todo Allow both lower-case and upper-case? If no, document it.
dfcc0bf9 529 */
1a081ca6 530SR_API uint64_t sr_parse_timestring(const char *timestring)
40f5ddac
BV
531{
532 uint64_t time_msec;
533 char *s;
534
6b2d8d3e
UH
535 /* TODO: Error handling, logging. */
536
40f5ddac
BV
537 time_msec = strtoull(timestring, &s, 10);
538 if (time_msec == 0 && s == timestring)
539 return 0;
540
541 if (s && *s) {
542 while (*s == ' ')
543 s++;
544 if (!strcmp(s, "s"))
545 time_msec *= 1000;
546 else if (!strcmp(s, "ms"))
547 ; /* redundant */
548 else
549 return 0;
550 }
551
552 return time_msec;
553}
4d436e71 554
1a081ca6 555SR_API gboolean sr_parse_boolstring(const char *boolstr)
4d436e71
GM
556{
557 if (!boolstr)
558 return FALSE;
559
993526f8
BV
560 if (!g_ascii_strncasecmp(boolstr, "true", 4) ||
561 !g_ascii_strncasecmp(boolstr, "yes", 3) ||
562 !g_ascii_strncasecmp(boolstr, "on", 2) ||
563 !g_ascii_strncasecmp(boolstr, "1", 1))
4d436e71
GM
564 return TRUE;
565
566 return FALSE;
567}
76f4c610 568
76e107d6 569SR_API int sr_parse_period(const char *periodstr, uint64_t *p, uint64_t *q)
76f4c610
BV
570{
571 char *s;
572
76e107d6
BV
573 *p = strtoull(periodstr, &s, 10);
574 if (*p == 0 && s == periodstr)
76f4c610
BV
575 /* No digits found. */
576 return SR_ERR_ARG;
577
578 if (s && *s) {
579 while (*s == ' ')
580 s++;
8c012adb 581 if (!strcmp(s, "fs"))
76e107d6 582 *q = 1000000000000000ULL;
8c012adb 583 else if (!strcmp(s, "ps"))
76e107d6 584 *q = 1000000000000ULL;
8c012adb 585 else if (!strcmp(s, "ns"))
76e107d6 586 *q = 1000000000ULL;
76f4c610 587 else if (!strcmp(s, "us"))
76e107d6 588 *q = 1000000;
76f4c610 589 else if (!strcmp(s, "ms"))
76e107d6 590 *q = 1000;
76f4c610 591 else if (!strcmp(s, "s"))
76e107d6 592 *q = 1;
76f4c610
BV
593 else
594 /* Must have a time suffix. */
595 return SR_ERR_ARG;
596 }
597
598 return SR_OK;
599}
600
601
76e107d6 602SR_API int sr_parse_voltage(const char *voltstr, uint64_t *p, uint64_t *q)
79afc8ca
BV
603{
604 char *s;
605
76e107d6
BV
606 *p = strtoull(voltstr, &s, 10);
607 if (*p == 0 && s == voltstr)
79afc8ca
BV
608 /* No digits found. */
609 return SR_ERR_ARG;
610
611 if (s && *s) {
612 while (*s == ' ')
613 s++;
614 if (!strcasecmp(s, "mv"))
76e107d6 615 *q = 1000L;
79afc8ca 616 else if (!strcasecmp(s, "v"))
76e107d6 617 *q = 1;
79afc8ca
BV
618 else
619 /* Must have a base suffix. */
620 return SR_ERR_ARG;
621 }
622
623 return SR_OK;
624}
625
7b870c38 626/** @} */