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) {
173 * Convert a numeric value value to its "natural" string representation
176 * E.g. a value of 3000000, with units set to "W", would be converted
177 * to "3 MW", 20000 to "20 kW", 31500 would become "31.5 kW".
179 * @param x The value to convert.
180 * @param unit The unit to append to the string, or NULL if the string
183 * @return A g_try_malloc()ed string representation of the samplerate value,
184 * or NULL upon errors. The caller is responsible to g_free() the
187 SR_API char *sr_si_string_u64(uint64_t x, const char *unit)
190 uint64_t quot, divisor[] = {
191 SR_HZ(1), SR_KHZ(1), SR_MHZ(1), SR_GHZ(1),
192 SR_GHZ(1000), SR_GHZ(1000 * 1000), SR_GHZ(1000 * 1000 * 1000),
194 const char *p, prefix[] = "\0kMGTPE";
195 char fmt[16], fract[20] = "", *f;
200 for (i = 0; (quot = x / divisor[i]) >= 1000; i++);
203 sprintf(fmt, ".%%0%d"PRIu64, i * 3);
204 f = fract + sprintf(fract, fmt, x % divisor[i]) - 1;
206 while (f >= fract && strchr("0.", *f))
212 return g_strdup_printf("%" PRIu64 "%s %.1s%s", quot, fract, p, unit);
216 * Convert a numeric samplerate value to its "natural" string representation.
218 * E.g. a value of 3000000 would be converted to "3 MHz", 20000 to "20 kHz",
219 * 31500 would become "31.5 kHz".
221 * @param samplerate The samplerate in Hz.
223 * @return A g_try_malloc()ed string representation of the samplerate value,
224 * or NULL upon errors. The caller is responsible to g_free() the
227 SR_API char *sr_samplerate_string(uint64_t samplerate)
229 return sr_si_string_u64(samplerate, "Hz");
233 * Convert a numeric frequency value to the "natural" string representation
236 * E.g. a value of 3000000 would be converted to "3 us", 20000 to "50 ms".
238 * @param frequency The frequency in Hz.
240 * @return A g_try_malloc()ed string representation of the frequency value,
241 * or NULL upon errors. The caller is responsible to g_free() the
244 SR_API char *sr_period_string(uint64_t frequency)
249 /* Allocate enough for a uint64_t as string + " ms". */
250 if (!(o = g_try_malloc0(30 + 1))) {
251 sr_err("%s: o malloc failed", __func__);
255 if (frequency >= SR_GHZ(1))
256 r = snprintf(o, 30, "%" PRIu64 " ns", frequency / 1000000000);
257 else if (frequency >= SR_MHZ(1))
258 r = snprintf(o, 30, "%" PRIu64 " us", frequency / 1000000);
259 else if (frequency >= SR_KHZ(1))
260 r = snprintf(o, 30, "%" PRIu64 " ms", frequency / 1000);
262 r = snprintf(o, 30, "%" PRIu64 " s", frequency);
265 /* Something went wrong... */
274 * Convert a numeric voltage value to the "natural" string representation
275 * of its voltage value. The voltage is specified as a rational number's
276 * numerator and denominator.
278 * E.g. a value of 300000 would be converted to "300mV", 2 to "2V".
280 * @param v_p The voltage numerator.
281 * @param v_q The voltage denominator.
283 * @return A g_try_malloc()ed string representation of the voltage value,
284 * or NULL upon errors. The caller is responsible to g_free() the
287 SR_API char *sr_voltage_string(uint64_t v_p, uint64_t v_q)
292 if (!(o = g_try_malloc0(30 + 1))) {
293 sr_err("%s: o malloc failed", __func__);
298 r = snprintf(o, 30, "%" PRIu64 "mV", v_p);
300 r = snprintf(o, 30, "%" PRIu64 "V", v_p);
302 r = snprintf(o, 30, "%gV", (float)v_p / (float)v_q);
305 /* Something went wrong... */
314 * Parse a trigger specification string.
316 * @param sdi The device instance for which the trigger specification is
317 * intended. Must not be NULL. Also, sdi->driver and
318 * sdi->driver->info_get must not be NULL.
319 * @param triggerstring The string containing the trigger specification for
320 * one or more probes of this device. Entries for multiple probes are
321 * comma-separated. Triggers are specified in the form key=value,
322 * where the key is a probe number (or probe name) and the value is
323 * the requested trigger type. Valid trigger types currently
324 * include 'r' (rising edge), 'f' (falling edge), 'c' (any pin value
325 * change), '0' (low value), or '1' (high value).
326 * Example: "1=r,sck=f,miso=0,7=c"
328 * @return Pointer to a list of trigger types (strings), or NULL upon errors.
329 * The pointer list (if non-NULL) has as many entries as the
330 * respective device has probes (all physically available probes,
331 * not just enabled ones). Entries of the list which don't have
332 * a trigger value set in 'triggerstring' are NULL, the other entries
333 * contain the respective trigger type which is requested for the
334 * respective probe (e.g. "r", "c", and so on).
336 SR_API char **sr_parse_triggerstring(const struct sr_dev_inst *sdi,
337 const char *triggerstring)
341 struct sr_probe *probe;
342 int max_probes, probenum, i;
343 char **tokens, **triggerlist, *trigger, *tc;
344 const char *trigger_types;
347 max_probes = g_slist_length(sdi->probes);
350 if (!(triggerlist = g_try_malloc0(max_probes * sizeof(char *)))) {
351 sr_err("%s: triggerlist malloc failed", __func__);
355 if (sdi->driver->config_list(SR_CONF_TRIGGER_TYPE,
356 &gvar, sdi, NULL) != SR_OK) {
357 sr_err("%s: Device doesn't support any triggers.", __func__);
360 trigger_types = g_variant_get_string(gvar, NULL);
362 tokens = g_strsplit(triggerstring, ",", max_probes);
363 for (i = 0; tokens[i]; i++) {
365 for (l = sdi->probes; l; l = l->next) {
366 probe = (struct sr_probe *)l->data;
368 && !strncmp(probe->name, tokens[i],
369 strlen(probe->name))) {
370 probenum = probe->index;
375 if (probenum < 0 || probenum >= max_probes) {
376 sr_err("Invalid probe.");
381 if ((trigger = strchr(tokens[i], '='))) {
382 for (tc = ++trigger; *tc; tc++) {
383 if (strchr(trigger_types, *tc) == NULL) {
384 sr_err("Unsupported trigger "
391 triggerlist[probenum] = g_strdup(trigger);
395 g_variant_unref(gvar);
398 for (i = 0; i < max_probes; i++)
399 g_free(triggerlist[i]);
408 * Convert a "natural" string representation of a size value to uint64_t.
410 * E.g. a value of "3k" or "3 K" would be converted to 3000, a value
411 * of "15M" would be converted to 15000000.
413 * Value representations other than decimal (such as hex or octal) are not
414 * supported. Only 'k' (kilo), 'm' (mega), 'g' (giga) suffixes are supported.
415 * Spaces (but not other whitespace) between value and suffix are allowed.
417 * @param sizestring A string containing a (decimal) size value.
418 * @param size Pointer to uint64_t which will contain the string's size value.
420 * @return SR_OK upon success, SR_ERR upon errors.
422 SR_API int sr_parse_sizestring(const char *sizestring, uint64_t *size)
424 int multiplier, done;
427 *size = strtoull(sizestring, &s, 10);
430 while (s && *s && multiplier == 0 && !done) {
436 multiplier = SR_KHZ(1);
440 multiplier = SR_MHZ(1);
444 multiplier = SR_GHZ(1);
455 if (*s && strcasecmp(s, "Hz"))
462 * Convert a "natural" string representation of a time value to an
463 * uint64_t value in milliseconds.
465 * E.g. a value of "3s" or "3 s" would be converted to 3000, a value
466 * of "15ms" would be converted to 15.
468 * Value representations other than decimal (such as hex or octal) are not
469 * supported. Only lower-case "s" and "ms" time suffixes are supported.
470 * Spaces (but not other whitespace) between value and suffix are allowed.
472 * @param timestring A string containing a (decimal) time value.
473 * @return The string's time value as uint64_t, in milliseconds.
475 * @todo Add support for "m" (minutes) and others.
476 * @todo Add support for picoseconds?
477 * @todo Allow both lower-case and upper-case? If no, document it.
479 SR_API uint64_t sr_parse_timestring(const char *timestring)
484 /* TODO: Error handling, logging. */
486 time_msec = strtoull(timestring, &s, 10);
487 if (time_msec == 0 && s == timestring)
495 else if (!strcmp(s, "ms"))
504 SR_API gboolean sr_parse_boolstring(const char *boolstr)
509 if (!g_ascii_strncasecmp(boolstr, "true", 4) ||
510 !g_ascii_strncasecmp(boolstr, "yes", 3) ||
511 !g_ascii_strncasecmp(boolstr, "on", 2) ||
512 !g_ascii_strncasecmp(boolstr, "1", 1))
518 SR_API int sr_parse_period(const char *periodstr, uint64_t *p, uint64_t *q)
522 *p = strtoull(periodstr, &s, 10);
523 if (*p == 0 && s == periodstr)
524 /* No digits found. */
530 if (!strcmp(s, "fs"))
531 *q = 1000000000000000ULL;
532 else if (!strcmp(s, "ps"))
533 *q = 1000000000000ULL;
534 else if (!strcmp(s, "ns"))
536 else if (!strcmp(s, "us"))
538 else if (!strcmp(s, "ms"))
540 else if (!strcmp(s, "s"))
543 /* Must have a time suffix. */
551 SR_API int sr_parse_voltage(const char *voltstr, uint64_t *p, uint64_t *q)
555 *p = strtoull(voltstr, &s, 10);
556 if (*p == 0 && s == voltstr)
557 /* No digits found. */
563 if (!strcasecmp(s, "mv"))
565 else if (!strcasecmp(s, "v"))
568 /* Must have a base suffix. */