2 * This file is part of the libsigrok project.
4 * Copyright (C) 2010 Uwe Hermann <uwe@hermann-uwe.de>
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.
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.
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
25 #include "libsigrok.h"
26 #include "libsigrok-internal.h"
28 #define LOG_PREFIX "strutil"
33 * Helper functions for handling or converting libsigrok-related strings.
37 * @defgroup grp_strutil String utilities
39 * Helper functions for handling or converting libsigrok-related strings.
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
52 * @param str The string representation to convert.
53 * @param ret Pointer to long where the result of the conversion will be stored.
55 * @return SR_OK if conversion is successful, otherwise SR_ERR.
59 SR_PRIV int sr_atol(const char *str, long *ret)
65 tmp = strtol(str, &endptr, 0);
67 if (!endptr || *endptr || errno) {
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
85 * @param str The string representation to convert.
86 * @param ret Pointer to int where the result of the conversion will be stored.
88 * @return SR_OK if conversion is successful, otherwise SR_ERR.
92 SR_PRIV int sr_atoi(const char *str, int *ret)
96 if (sr_atol(str, &tmp) != SR_OK)
99 if ((int) tmp != tmp) {
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
116 * @param str The string representation to convert.
117 * @param ret Pointer to double where the result of the conversion will be stored.
119 * @return SR_OK if conversion is successful, otherwise SR_ERR.
123 SR_PRIV int sr_atod(const char *str, double *ret)
129 tmp = strtof(str, &endptr);
131 if (!endptr || *endptr || errno) {
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
149 * @param str The string representation to convert.
150 * @param ret Pointer to float where the result of the conversion will be stored.
152 * @return SR_OK if conversion is successful, otherwise SR_ERR.
156 SR_PRIV int sr_atof(const char *str, float *ret)
160 if (sr_atod(str, &tmp) != SR_OK)
163 if ((float) tmp != tmp) {
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.
180 * @param str The string representation to convert.
181 * @param ret Pointer to float where the result of the conversion will be stored.
183 * @return SR_OK if conversion is successful, otherwise SR_ERR.
187 SR_PRIV int sr_atof_ascii(const char *str, float *ret)
193 tmp = g_ascii_strtod(str, &endptr);
195 if (!endptr || *endptr || errno) {
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. */
204 if ((float) tmp != tmp) {
206 sr_dbg("ERANGEEEE %e != %e", (float) tmp, tmp);
216 * Convert a numeric value value to its "natural" string representation
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".
222 * @param x The value to convert.
223 * @param unit The unit to append to the string, or NULL if the string
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
230 SR_API char *sr_si_string_u64(uint64_t x, const char *unit)
233 uint64_t quot, divisor[] = {
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),
237 const char *p, prefix[] = "\0kMGTPE";
238 char fmt[16], fract[20] = "", *f;
243 for (i = 0; (quot = x / divisor[i]) >= 1000; i++);
246 sprintf(fmt, ".%%0%d"PRIu64, i * 3);
247 f = fract + sprintf(fract, fmt, x % divisor[i]) - 1;
249 while (f >= fract && strchr("0.", *f))
255 return g_strdup_printf("%" PRIu64 "%s %.1s%s", quot, fract, p, unit);
259 * Convert a numeric samplerate value to its "natural" string representation.
261 * E.g. a value of 3000000 would be converted to "3 MHz", 20000 to "20 kHz",
262 * 31500 would become "31.5 kHz".
264 * @param samplerate The samplerate in Hz.
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
270 SR_API char *sr_samplerate_string(uint64_t samplerate)
272 return sr_si_string_u64(samplerate, "Hz");
276 * Convert a numeric frequency value to the "natural" string representation
279 * E.g. a value of 3000000 would be converted to "3 us", 20000 to "50 ms".
281 * @param frequency The frequency in Hz.
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
287 SR_API char *sr_period_string(uint64_t frequency)
292 /* Allocate enough for a uint64_t as string + " ms". */
293 if (!(o = g_try_malloc0(30 + 1))) {
294 sr_err("%s: o malloc failed", __func__);
298 if (frequency >= SR_GHZ(1))
299 r = snprintf(o, 30, "%" PRIu64 " ns", frequency / 1000000000);
300 else if (frequency >= SR_MHZ(1))
301 r = snprintf(o, 30, "%" PRIu64 " us", frequency / 1000000);
302 else if (frequency >= SR_KHZ(1))
303 r = snprintf(o, 30, "%" PRIu64 " ms", frequency / 1000);
305 r = snprintf(o, 30, "%" PRIu64 " s", frequency);
308 /* Something went wrong... */
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.
321 * E.g. a value of 300000 would be converted to "300mV", 2 to "2V".
323 * @param v_p The voltage numerator.
324 * @param v_q The voltage denominator.
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
330 SR_API char *sr_voltage_string(uint64_t v_p, uint64_t v_q)
335 if (!(o = g_try_malloc0(30 + 1))) {
336 sr_err("%s: o malloc failed", __func__);
341 r = snprintf(o, 30, "%" PRIu64 "mV", v_p);
343 r = snprintf(o, 30, "%" PRIu64 "V", v_p);
345 r = snprintf(o, 30, "%gV", (float)v_p / (float)v_q);
348 /* Something went wrong... */
357 * Parse a trigger specification string.
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.
362 * @param triggerstring The string containing the trigger specification for
363 * one or more probes of this device. Entries for multiple probes are
364 * comma-separated. Triggers are specified in the form key=value,
365 * where the key is a probe number (or probe name) and the value is
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"
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
373 * respective device has probes (all physically available probes,
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
377 * respective probe (e.g. "r", "c", and so on).
379 SR_API char **sr_parse_triggerstring(const struct sr_dev_inst *sdi,
380 const char *triggerstring)
384 struct sr_probe *probe;
385 int max_probes, probenum, i;
386 char **tokens, **triggerlist, *trigger, *tc;
387 const char *trigger_types;
390 max_probes = g_slist_length(sdi->probes);
393 if (!(triggerlist = g_try_malloc0(max_probes * sizeof(char *)))) {
394 sr_err("%s: triggerlist malloc failed", __func__);
398 if (sdi->driver->config_list(SR_CONF_TRIGGER_TYPE,
399 &gvar, sdi, NULL) != SR_OK) {
400 sr_err("%s: Device doesn't support any triggers.", __func__);
403 trigger_types = g_variant_get_string(gvar, NULL);
405 tokens = g_strsplit(triggerstring, ",", max_probes);
406 for (i = 0; tokens[i]; i++) {
408 for (l = sdi->probes; l; l = l->next) {
409 probe = (struct sr_probe *)l->data;
411 && !strncmp(probe->name, tokens[i],
412 strlen(probe->name))) {
413 probenum = probe->index;
418 if (probenum < 0 || probenum >= max_probes) {
419 sr_err("Invalid probe.");
424 if ((trigger = strchr(tokens[i], '='))) {
425 for (tc = ++trigger; *tc; tc++) {
426 if (strchr(trigger_types, *tc) == NULL) {
427 sr_err("Unsupported trigger "
434 triggerlist[probenum] = g_strdup(trigger);
438 g_variant_unref(gvar);
441 for (i = 0; i < max_probes; i++)
442 g_free(triggerlist[i]);
451 * Convert a "natural" string representation of a size value to uint64_t.
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.
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.
460 * @param sizestring A string containing a (decimal) size value.
461 * @param size Pointer to uint64_t which will contain the string's size value.
463 * @return SR_OK upon success, SR_ERR upon errors.
465 SR_API int sr_parse_sizestring(const char *sizestring, uint64_t *size)
467 int multiplier, done;
471 *size = strtoull(sizestring, &s, 10);
475 while (s && *s && multiplier == 0 && !done) {
480 frac_part = g_ascii_strtod(s, &s);
484 multiplier = SR_KHZ(1);
488 multiplier = SR_MHZ(1);
492 multiplier = SR_GHZ(1);
500 if (multiplier > 0) {
502 *size += frac_part * multiplier;
506 if (*s && strcasecmp(s, "Hz"))
513 * Convert a "natural" string representation of a time value to an
514 * uint64_t value in milliseconds.
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.
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.
523 * @param timestring A string containing a (decimal) time value.
524 * @return The string's time value as uint64_t, in milliseconds.
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.
530 SR_API uint64_t sr_parse_timestring(const char *timestring)
535 /* TODO: Error handling, logging. */
537 time_msec = strtoull(timestring, &s, 10);
538 if (time_msec == 0 && s == timestring)
546 else if (!strcmp(s, "ms"))
555 SR_API gboolean sr_parse_boolstring(const char *boolstr)
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))
569 SR_API int sr_parse_period(const char *periodstr, uint64_t *p, uint64_t *q)
573 *p = strtoull(periodstr, &s, 10);
574 if (*p == 0 && s == periodstr)
575 /* No digits found. */
581 if (!strcmp(s, "fs"))
582 *q = 1000000000000000ULL;
583 else if (!strcmp(s, "ps"))
584 *q = 1000000000000ULL;
585 else if (!strcmp(s, "ns"))
587 else if (!strcmp(s, "us"))
589 else if (!strcmp(s, "ms"))
591 else if (!strcmp(s, "s"))
594 /* Must have a time suffix. */
602 SR_API int sr_parse_voltage(const char *voltstr, uint64_t *p, uint64_t *q)
606 *p = strtoull(voltstr, &s, 10);
607 if (*p == 0 && s == voltstr)
608 /* No digits found. */
614 if (!strcasecmp(s, "mv"))
616 else if (!strcasecmp(s, "v"))
619 /* Must have a base suffix. */