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 (base 10) 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 * @retval SR_OK Conversion successful.
58 * @retval SR_ERR Failure.
62 SR_PRIV int sr_atol(const char *str, long *ret)
68 tmp = strtol(str, &endptr, 10);
70 if (!endptr || *endptr || errno) {
83 * Convert a string representation of a numeric value (base 10) to an integer. The
84 * conversion is strict and will fail if the complete string does not represent
85 * a valid integer. The function sets errno according to the details of the
88 * @param str The string representation to convert.
89 * @param ret Pointer to int where the result of the conversion will be stored.
91 * @retval SR_OK Conversion successful.
92 * @retval SR_ERR Failure.
96 SR_PRIV int sr_atoi(const char *str, int *ret)
100 if (sr_atol(str, &tmp) != SR_OK)
103 if ((int) tmp != tmp) {
115 * Convert a string representation of a numeric value to a double. The
116 * conversion is strict and will fail if the complete string does not represent
117 * a valid double. The function sets errno according to the details of the
120 * @param str The string representation to convert.
121 * @param ret Pointer to double where the result of the conversion will be stored.
123 * @retval SR_OK Conversion successful.
124 * @retval SR_ERR Failure.
128 SR_PRIV int sr_atod(const char *str, double *ret)
134 tmp = strtof(str, &endptr);
136 if (!endptr || *endptr || errno) {
149 * Convert a string representation of a numeric value to a float. The
150 * conversion is strict and will fail if the complete string does not represent
151 * a valid float. The function sets errno according to the details of the
154 * @param str The string representation to convert.
155 * @param ret Pointer to float where the result of the conversion will be stored.
157 * @retval SR_OK Conversion successful.
158 * @retval SR_ERR Failure.
162 SR_PRIV int sr_atof(const char *str, float *ret)
166 if (sr_atod(str, &tmp) != SR_OK)
169 if ((float) tmp != tmp) {
181 * Convert a string representation of a numeric value to a float. The
182 * conversion is strict and will fail if the complete string does not represent
183 * a valid float. The function sets errno according to the details of the
184 * failure. This version ignores the locale.
186 * @param str The string representation to convert.
187 * @param ret Pointer to float where the result of the conversion will be stored.
189 * @retval SR_OK Conversion successful.
190 * @retval SR_ERR Failure.
194 SR_PRIV int sr_atof_ascii(const char *str, float *ret)
200 tmp = g_ascii_strtod(str, &endptr);
202 if (!endptr || *endptr || errno) {
208 /* FIXME This fails unexpectedly. Some other method to safel downcast
209 * needs to be found. Checking against FLT_MAX doesn't work as well. */
211 if ((float) tmp != tmp) {
213 sr_dbg("ERANGEEEE %e != %e", (float) tmp, tmp);
223 * Convert a numeric value value to its "natural" string representation
226 * E.g. a value of 3000000, with units set to "W", would be converted
227 * to "3 MW", 20000 to "20 kW", 31500 would become "31.5 kW".
229 * @param x The value to convert.
230 * @param unit The unit to append to the string, or NULL if the string
233 * @return A g_try_malloc()ed string representation of the samplerate value,
234 * or NULL upon errors. The caller is responsible to g_free() the
239 SR_API char *sr_si_string_u64(uint64_t x, const char *unit)
242 uint64_t quot, divisor[] = {
243 SR_HZ(1), SR_KHZ(1), SR_MHZ(1), SR_GHZ(1),
244 SR_GHZ(1000), SR_GHZ(1000 * 1000), SR_GHZ(1000 * 1000 * 1000),
246 const char *p, prefix[] = "\0kMGTPE";
247 char fmt[16], fract[20] = "", *f;
252 for (i = 0; (quot = x / divisor[i]) >= 1000; i++);
255 sprintf(fmt, ".%%0%d"PRIu64, i * 3);
256 f = fract + sprintf(fract, fmt, x % divisor[i]) - 1;
258 while (f >= fract && strchr("0.", *f))
264 return g_strdup_printf("%" PRIu64 "%s %.1s%s", quot, fract, p, unit);
268 * Convert a numeric samplerate value to its "natural" string representation.
270 * E.g. a value of 3000000 would be converted to "3 MHz", 20000 to "20 kHz",
271 * 31500 would become "31.5 kHz".
273 * @param samplerate The samplerate in Hz.
275 * @return A g_try_malloc()ed string representation of the samplerate value,
276 * or NULL upon errors. The caller is responsible to g_free() the
281 SR_API char *sr_samplerate_string(uint64_t samplerate)
283 return sr_si_string_u64(samplerate, "Hz");
287 * Convert a numeric frequency value to the "natural" string representation
290 * E.g. a value of 3000000 would be converted to "3 us", 20000 to "50 ms".
292 * @param frequency The frequency in Hz.
294 * @return A g_try_malloc()ed string representation of the frequency value,
295 * or NULL upon errors. The caller is responsible to g_free() the
300 SR_API char *sr_period_string(uint64_t frequency)
305 /* Allocate enough for a uint64_t as string + " ms". */
306 if (!(o = g_try_malloc0(30 + 1))) {
307 sr_err("%s: o malloc failed", __func__);
311 if (frequency >= SR_GHZ(1))
312 r = snprintf(o, 30, "%" PRIu64 " ns", frequency / 1000000000);
313 else if (frequency >= SR_MHZ(1))
314 r = snprintf(o, 30, "%" PRIu64 " us", frequency / 1000000);
315 else if (frequency >= SR_KHZ(1))
316 r = snprintf(o, 30, "%" PRIu64 " ms", frequency / 1000);
318 r = snprintf(o, 30, "%" PRIu64 " s", frequency);
321 /* Something went wrong... */
330 * Convert a numeric voltage value to the "natural" string representation
331 * of its voltage value. The voltage is specified as a rational number's
332 * numerator and denominator.
334 * E.g. a value of 300000 would be converted to "300mV", 2 to "2V".
336 * @param v_p The voltage numerator.
337 * @param v_q The voltage denominator.
339 * @return A g_try_malloc()ed string representation of the voltage value,
340 * or NULL upon errors. The caller is responsible to g_free() the
345 SR_API char *sr_voltage_string(uint64_t v_p, uint64_t v_q)
350 if (!(o = g_try_malloc0(30 + 1))) {
351 sr_err("%s: o malloc failed", __func__);
356 r = snprintf(o, 30, "%" PRIu64 "mV", v_p);
358 r = snprintf(o, 30, "%" PRIu64 "V", v_p);
360 r = snprintf(o, 30, "%gV", (float)v_p / (float)v_q);
363 /* Something went wrong... */
372 * Parse a trigger specification string.
374 * @param sdi The device instance for which the trigger specification is
375 * intended. Must not be NULL. Also, sdi->driver and
376 * sdi->driver->info_get must not be NULL.
377 * @param triggerstring The string containing the trigger specification for
378 * one or more channels of this device. Entries for multiple channels are
379 * comma-separated. Triggers are specified in the form key=value,
380 * where the key is a channel number (or channel name) and the value is
381 * the requested trigger type. Valid trigger types currently
382 * include 'r' (rising edge), 'f' (falling edge), 'c' (any pin value
383 * change), '0' (low value), or '1' (high value).
384 * Example: "1=r,sck=f,miso=0,7=c"
386 * @return Pointer to a list of trigger types (strings), or NULL upon errors.
387 * The pointer list (if non-NULL) has as many entries as the
388 * respective device has channels (all physically available channels,
389 * not just enabled ones). Entries of the list which don't have
390 * a trigger value set in 'triggerstring' are NULL, the other entries
391 * contain the respective trigger type which is requested for the
392 * respective channel (e.g. "r", "c", and so on).
396 SR_API char **sr_parse_triggerstring(const struct sr_dev_inst *sdi,
397 const char *triggerstring)
401 struct sr_channel *ch;
402 int max_channels, channelnum, i;
403 char **tokens, **triggerlist, *trigger, *tc;
404 const char *trigger_types;
407 max_channels = g_slist_length(sdi->channels);
410 if (!(triggerlist = g_try_malloc0(max_channels * sizeof(char *)))) {
411 sr_err("%s: triggerlist malloc failed", __func__);
415 if (sdi->driver->config_list(SR_CONF_TRIGGER_TYPE,
416 &gvar, sdi, NULL) != SR_OK) {
417 sr_err("%s: Device doesn't support any triggers.", __func__);
420 trigger_types = g_variant_get_string(gvar, NULL);
422 tokens = g_strsplit(triggerstring, ",", max_channels);
423 for (i = 0; tokens[i]; i++) {
425 for (l = sdi->channels; l; l = l->next) {
426 ch = (struct sr_channel *)l->data;
428 && !strncmp(ch->name, tokens[i],
430 channelnum = ch->index;
435 if (channelnum < 0 || channelnum >= max_channels) {
436 sr_err("Invalid channel.");
441 if ((trigger = strchr(tokens[i], '='))) {
442 for (tc = ++trigger; *tc; tc++) {
443 if (strchr(trigger_types, *tc) == NULL) {
444 sr_err("Unsupported trigger "
451 triggerlist[channelnum] = g_strdup(trigger);
455 g_variant_unref(gvar);
458 for (i = 0; i < max_channels; i++)
459 g_free(triggerlist[i]);
468 * Convert a "natural" string representation of a size value to uint64_t.
470 * E.g. a value of "3k" or "3 K" would be converted to 3000, a value
471 * of "15M" would be converted to 15000000.
473 * Value representations other than decimal (such as hex or octal) are not
474 * supported. Only 'k' (kilo), 'm' (mega), 'g' (giga) suffixes are supported.
475 * Spaces (but not other whitespace) between value and suffix are allowed.
477 * @param sizestring A string containing a (decimal) size value.
478 * @param size Pointer to uint64_t which will contain the string's size value.
480 * @return SR_OK upon success, SR_ERR upon errors.
484 SR_API int sr_parse_sizestring(const char *sizestring, uint64_t *size)
486 int multiplier, done;
490 *size = strtoull(sizestring, &s, 10);
494 while (s && *s && multiplier == 0 && !done) {
499 frac_part = g_ascii_strtod(s, &s);
503 multiplier = SR_KHZ(1);
507 multiplier = SR_MHZ(1);
511 multiplier = SR_GHZ(1);
519 if (multiplier > 0) {
521 *size += frac_part * multiplier;
525 if (*s && strcasecmp(s, "Hz"))
532 * Convert a "natural" string representation of a time value to an
533 * uint64_t value in milliseconds.
535 * E.g. a value of "3s" or "3 s" would be converted to 3000, a value
536 * of "15ms" would be converted to 15.
538 * Value representations other than decimal (such as hex or octal) are not
539 * supported. Only lower-case "s" and "ms" time suffixes are supported.
540 * Spaces (but not other whitespace) between value and suffix are allowed.
542 * @param timestring A string containing a (decimal) time value.
543 * @return The string's time value as uint64_t, in milliseconds.
545 * @todo Add support for "m" (minutes) and others.
546 * @todo Add support for picoseconds?
547 * @todo Allow both lower-case and upper-case? If no, document it.
551 SR_API uint64_t sr_parse_timestring(const char *timestring)
556 /* TODO: Error handling, logging. */
558 time_msec = strtoull(timestring, &s, 10);
559 if (time_msec == 0 && s == timestring)
567 else if (!strcmp(s, "ms"))
577 SR_API gboolean sr_parse_boolstring(const char *boolstr)
582 if (!g_ascii_strncasecmp(boolstr, "true", 4) ||
583 !g_ascii_strncasecmp(boolstr, "yes", 3) ||
584 !g_ascii_strncasecmp(boolstr, "on", 2) ||
585 !g_ascii_strncasecmp(boolstr, "1", 1))
592 SR_API int sr_parse_period(const char *periodstr, uint64_t *p, uint64_t *q)
596 *p = strtoull(periodstr, &s, 10);
597 if (*p == 0 && s == periodstr)
598 /* No digits found. */
604 if (!strcmp(s, "fs"))
605 *q = 1000000000000000ULL;
606 else if (!strcmp(s, "ps"))
607 *q = 1000000000000ULL;
608 else if (!strcmp(s, "ns"))
610 else if (!strcmp(s, "us"))
612 else if (!strcmp(s, "ms"))
614 else if (!strcmp(s, "s"))
617 /* Must have a time suffix. */
625 SR_API int sr_parse_voltage(const char *voltstr, uint64_t *p, uint64_t *q)
629 *p = strtoull(voltstr, &s, 10);
630 if (*p == 0 && s == voltstr)
631 /* No digits found. */
637 if (!strcasecmp(s, "mv"))
639 else if (!strcasecmp(s, "v"))
642 /* Must have a base suffix. */