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"
29 #define LOG_PREFIX "strutil"
35 * Helper functions for handling or converting libsigrok-related strings.
39 * @defgroup grp_strutil String utilities
41 * Helper functions for handling or converting libsigrok-related strings.
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
54 * @param str The string representation to convert.
55 * @param ret Pointer to long where the result of the conversion will be stored.
57 * @return SR_OK if conversion is successful, otherwise SR_ERR.
61 SR_PRIV int sr_atol(const char *str, long *ret)
67 tmp = strtol(str, &endptr, 0);
69 if (!endptr || *endptr || errno) {
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
87 * @param str The string representation to convert.
88 * @param ret Pointer to int where the result of the conversion will be stored.
90 * @return SR_OK if conversion is successful, otherwise SR_ERR.
94 SR_PRIV int sr_atoi(const char *str, int *ret)
98 if (sr_atol(str, &tmp) != SR_OK)
101 if ((int) tmp != tmp) {
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
118 * @param str The string representation to convert.
119 * @param ret Pointer to double where the result of the conversion will be stored.
121 * @return SR_OK if conversion is successful, otherwise SR_ERR.
125 SR_PRIV int sr_atod(const char *str, double *ret)
131 tmp = strtof(str, &endptr);
133 if (!endptr || *endptr || errno) {
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
151 * @param str The string representation to convert.
152 * @param ret Pointer to float where the result of the conversion will be stored.
154 * @return SR_OK if conversion is successful, otherwise SR_ERR.
158 SR_PRIV int sr_atof(const char *str, float *ret)
162 if (sr_atod(str, &tmp) != SR_OK)
165 if ((float) tmp != tmp) {
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.
182 * @param str The string representation to convert.
183 * @param ret Pointer to float where the result of the conversion will be stored.
185 * @return SR_OK if conversion is successful, otherwise SR_ERR.
189 SR_PRIV int sr_atof_ascii(const char *str, float *ret)
195 tmp = g_ascii_strtod(str, &endptr);
197 if (!endptr || *endptr || errno) {
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. */
206 if ((float) tmp != tmp) {
208 sr_dbg("ERANGEEEE %e != %e", (float) tmp, tmp);
218 * Convert a numeric value value to its "natural" string representation
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".
224 * @param x The value to convert.
225 * @param unit The unit to append to the string, or NULL if the string
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
232 SR_API char *sr_si_string_u64(uint64_t x, const char *unit)
235 uint64_t quot, divisor[] = {
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),
239 const char *p, prefix[] = "\0kMGTPE";
240 char fmt[16], fract[20] = "", *f;
245 for (i = 0; (quot = x / divisor[i]) >= 1000; i++);
248 sprintf(fmt, ".%%0%d"PRIu64, i * 3);
249 f = fract + sprintf(fract, fmt, x % divisor[i]) - 1;
251 while (f >= fract && strchr("0.", *f))
257 return g_strdup_printf("%" PRIu64 "%s %.1s%s", quot, fract, p, unit);
261 * Convert a numeric samplerate value to its "natural" string representation.
263 * E.g. a value of 3000000 would be converted to "3 MHz", 20000 to "20 kHz",
264 * 31500 would become "31.5 kHz".
266 * @param samplerate The samplerate in Hz.
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
272 SR_API char *sr_samplerate_string(uint64_t samplerate)
274 return sr_si_string_u64(samplerate, "Hz");
278 * Convert a numeric frequency value to the "natural" string representation
281 * E.g. a value of 3000000 would be converted to "3 us", 20000 to "50 ms".
283 * @param frequency The frequency in Hz.
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
289 SR_API char *sr_period_string(uint64_t frequency)
294 /* Allocate enough for a uint64_t as string + " ms". */
295 if (!(o = g_try_malloc0(30 + 1))) {
296 sr_err("%s: o malloc failed", __func__);
300 if (frequency >= SR_GHZ(1))
301 r = snprintf(o, 30, "%" PRIu64 " ns", frequency / 1000000000);
302 else if (frequency >= SR_MHZ(1))
303 r = snprintf(o, 30, "%" PRIu64 " us", frequency / 1000000);
304 else if (frequency >= SR_KHZ(1))
305 r = snprintf(o, 30, "%" PRIu64 " ms", frequency / 1000);
307 r = snprintf(o, 30, "%" PRIu64 " s", frequency);
310 /* Something went wrong... */
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.
323 * E.g. a value of 300000 would be converted to "300mV", 2 to "2V".
325 * @param v_p The voltage numerator.
326 * @param v_q The voltage denominator.
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
332 SR_API char *sr_voltage_string(uint64_t v_p, uint64_t v_q)
337 if (!(o = g_try_malloc0(30 + 1))) {
338 sr_err("%s: o malloc failed", __func__);
343 r = snprintf(o, 30, "%" PRIu64 "mV", v_p);
345 r = snprintf(o, 30, "%" PRIu64 "V", v_p);
347 r = snprintf(o, 30, "%gV", (float)v_p / (float)v_q);
350 /* Something went wrong... */
359 * Parse a trigger specification string.
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.
364 * @param triggerstring The string containing the trigger specification for
365 * one or more channels of this device. Entries for multiple channels are
366 * comma-separated. Triggers are specified in the form key=value,
367 * where the key is a channel number (or channel name) and the value is
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"
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
375 * respective device has channels (all physically available channels,
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
379 * respective channel (e.g. "r", "c", and so on).
381 SR_API char **sr_parse_triggerstring(const struct sr_dev_inst *sdi,
382 const char *triggerstring)
386 struct sr_channel *ch;
387 int max_channels, channelnum, i;
388 char **tokens, **triggerlist, *trigger, *tc;
389 const char *trigger_types;
392 max_channels = g_slist_length(sdi->channels);
395 if (!(triggerlist = g_try_malloc0(max_channels * sizeof(char *)))) {
396 sr_err("%s: triggerlist malloc failed", __func__);
400 if (sdi->driver->config_list(SR_CONF_TRIGGER_TYPE,
401 &gvar, sdi, NULL) != SR_OK) {
402 sr_err("%s: Device doesn't support any triggers.", __func__);
405 trigger_types = g_variant_get_string(gvar, NULL);
407 tokens = g_strsplit(triggerstring, ",", max_channels);
408 for (i = 0; tokens[i]; i++) {
410 for (l = sdi->channels; l; l = l->next) {
411 ch = (struct sr_channel *)l->data;
413 && !strncmp(ch->name, tokens[i],
415 channelnum = ch->index;
420 if (channelnum < 0 || channelnum >= max_channels) {
421 sr_err("Invalid channel.");
426 if ((trigger = strchr(tokens[i], '='))) {
427 for (tc = ++trigger; *tc; tc++) {
428 if (strchr(trigger_types, *tc) == NULL) {
429 sr_err("Unsupported trigger "
436 triggerlist[channelnum] = g_strdup(trigger);
440 g_variant_unref(gvar);
443 for (i = 0; i < max_channels; i++)
444 g_free(triggerlist[i]);
453 * Convert a "natural" string representation of a size value to uint64_t.
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.
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.
462 * @param sizestring A string containing a (decimal) size value.
463 * @param size Pointer to uint64_t which will contain the string's size value.
465 * @return SR_OK upon success, SR_ERR upon errors.
467 SR_API int sr_parse_sizestring(const char *sizestring, uint64_t *size)
469 int multiplier, done;
473 *size = strtoull(sizestring, &s, 10);
477 while (s && *s && multiplier == 0 && !done) {
482 frac_part = g_ascii_strtod(s, &s);
486 multiplier = SR_KHZ(1);
490 multiplier = SR_MHZ(1);
494 multiplier = SR_GHZ(1);
502 if (multiplier > 0) {
504 *size += frac_part * multiplier;
508 if (*s && strcasecmp(s, "Hz"))
515 * Convert a "natural" string representation of a time value to an
516 * uint64_t value in milliseconds.
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.
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.
525 * @param timestring A string containing a (decimal) time value.
526 * @return The string's time value as uint64_t, in milliseconds.
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.
532 SR_API uint64_t sr_parse_timestring(const char *timestring)
537 /* TODO: Error handling, logging. */
539 time_msec = strtoull(timestring, &s, 10);
540 if (time_msec == 0 && s == timestring)
548 else if (!strcmp(s, "ms"))
557 SR_API gboolean sr_parse_boolstring(const char *boolstr)
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))
571 SR_API int sr_parse_period(const char *periodstr, uint64_t *p, uint64_t *q)
575 *p = strtoull(periodstr, &s, 10);
576 if (*p == 0 && s == periodstr)
577 /* No digits found. */
583 if (!strcmp(s, "fs"))
584 *q = 1000000000000000ULL;
585 else if (!strcmp(s, "ps"))
586 *q = 1000000000000ULL;
587 else if (!strcmp(s, "ns"))
589 else if (!strcmp(s, "us"))
591 else if (!strcmp(s, "ms"))
593 else if (!strcmp(s, "s"))
596 /* Must have a time suffix. */
604 SR_API int sr_parse_voltage(const char *voltstr, uint64_t *p, uint64_t *q)
608 *p = strtoull(voltstr, &s, 10);
609 if (*p == 0 && s == voltstr)
610 /* No digits found. */
616 if (!strcasecmp(s, "mv"))
618 else if (!strcasecmp(s, "v"))
621 /* Must have a base suffix. */