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