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.
45 * Convert a string representation of a numeric value to a long integer. The
46 * conversion is strict and will fail if the complete string does not represent
47 * a valid long integer. The function sets errno according to the details of the
50 * @param str The string representation to convert.
51 * @param ret Pointer to long where the result of the conversion will be stored.
53 * @return SR_OK if conversion is successful, otherwise SR_ERR.
57 SR_PRIV int sr_atol(const char *str, long *ret)
63 tmp = strtol(str, &endptr, 0);
65 if (!endptr || *endptr || errno) {
76 * Convert a string representation of a numeric value to an integer. The
77 * conversion is strict and will fail if the complete string does not represent
78 * a valid integer. The function sets errno according to the details of the
81 * @param str The string representation to convert.
82 * @param ret Pointer to int where the result of the conversion will be stored.
84 * @return SR_OK if conversion is successful, otherwise SR_ERR.
88 SR_PRIV int sr_atoi(const char *str, int *ret)
92 if (sr_atol(str, &tmp) != SR_OK)
95 if ((int) tmp != tmp) {
105 * Convert a string representation of a numeric value to a double. The
106 * conversion is strict and will fail if the complete string does not represent
107 * a valid double. The function sets errno according to the details of the
110 * @param str The string representation to convert.
111 * @param ret Pointer to double where the result of the conversion will be stored.
113 * @return SR_OK if conversion is successful, otherwise SR_ERR.
117 SR_PRIV int sr_atod(const char *str, double *ret)
123 tmp = strtof(str, &endptr);
125 if (!endptr || *endptr || errno) {
136 * Convert a string representation of a numeric value to a float. The
137 * conversion is strict and will fail if the complete string does not represent
138 * a valid float. The function sets errno according to the details of the
141 * @param str The string representation to convert.
142 * @param ret Pointer to float where the result of the conversion will be stored.
144 * @return SR_OK if conversion is successful, otherwise SR_ERR.
148 SR_PRIV int sr_atof(const char *str, float *ret)
152 if (sr_atod(str, &tmp) != SR_OK)
155 if ((float) tmp != tmp) {
165 * Convert a numeric value value to its "natural" string representation
168 * E.g. a value of 3000000, with units set to "W", would be converted
169 * to "3 MW", 20000 to "20 kW", 31500 would become "31.5 kW".
171 * @param x The value to convert.
172 * @param unit The unit to append to the string, or NULL if the string
175 * @return A g_try_malloc()ed string representation of the samplerate value,
176 * or NULL upon errors. The caller is responsible to g_free() the
179 SR_API char *sr_si_string_u64(uint64_t x, const char *unit)
182 uint64_t quot, divisor[] = {
183 SR_HZ(1), SR_KHZ(1), SR_MHZ(1), SR_GHZ(1),
184 SR_GHZ(1000), SR_GHZ(1000 * 1000), SR_GHZ(1000 * 1000 * 1000),
186 const char *p, prefix[] = "\0kMGTPE";
187 char fmt[8], fract[20] = "", *f;
192 for (i = 0; (quot = x / divisor[i]) >= 1000; i++);
195 sprintf(fmt, ".%%0%dlu", i * 3);
196 f = fract + sprintf(fract, fmt, x % divisor[i]) - 1;
198 while (f >= fract && strchr("0.", *f))
204 return g_strdup_printf("%" PRIu64 "%s %.1s%s", quot, fract, p, unit);
208 * Convert a numeric samplerate value to its "natural" string representation.
210 * E.g. a value of 3000000 would be converted to "3 MHz", 20000 to "20 kHz",
211 * 31500 would become "31.5 kHz".
213 * @param samplerate The samplerate in Hz.
215 * @return A g_try_malloc()ed string representation of the samplerate value,
216 * or NULL upon errors. The caller is responsible to g_free() the
219 SR_API char *sr_samplerate_string(uint64_t samplerate)
221 return sr_si_string_u64(samplerate, "Hz");
225 * Convert a numeric frequency value to the "natural" string representation
228 * E.g. a value of 3000000 would be converted to "3 us", 20000 to "50 ms".
230 * @param frequency The frequency in Hz.
232 * @return A g_try_malloc()ed string representation of the frequency value,
233 * or NULL upon errors. The caller is responsible to g_free() the
236 SR_API char *sr_period_string(uint64_t frequency)
241 /* Allocate enough for a uint64_t as string + " ms". */
242 if (!(o = g_try_malloc0(30 + 1))) {
243 sr_err("%s: o malloc failed", __func__);
247 if (frequency >= SR_GHZ(1))
248 r = snprintf(o, 30, "%" PRIu64 " ns", frequency / 1000000000);
249 else if (frequency >= SR_MHZ(1))
250 r = snprintf(o, 30, "%" PRIu64 " us", frequency / 1000000);
251 else if (frequency >= SR_KHZ(1))
252 r = snprintf(o, 30, "%" PRIu64 " ms", frequency / 1000);
254 r = snprintf(o, 30, "%" PRIu64 " s", frequency);
257 /* Something went wrong... */
266 * Convert a numeric voltage value to the "natural" string representation
267 * of its voltage value. The voltage is specified as a rational number's
268 * numerator and denominator.
270 * E.g. a value of 300000 would be converted to "300mV", 2 to "2V".
272 * @param v_p The voltage numerator.
273 * @param v_q The voltage denominator.
275 * @return A g_try_malloc()ed string representation of the voltage value,
276 * or NULL upon errors. The caller is responsible to g_free() the
279 SR_API char *sr_voltage_string(uint64_t v_p, uint64_t v_q)
284 if (!(o = g_try_malloc0(30 + 1))) {
285 sr_err("%s: o malloc failed", __func__);
290 r = snprintf(o, 30, "%" PRIu64 "mV", v_p);
292 r = snprintf(o, 30, "%" PRIu64 "V", v_p);
294 r = snprintf(o, 30, "%gV", (float)v_p / (float)v_q);
297 /* Something went wrong... */
306 * Parse a trigger specification string.
308 * @param sdi The device instance for which the trigger specification is
309 * intended. Must not be NULL. Also, sdi->driver and
310 * sdi->driver->info_get must not be NULL.
311 * @param triggerstring The string containing the trigger specification for
312 * one or more probes of this device. Entries for multiple probes are
313 * comma-separated. Triggers are specified in the form key=value,
314 * where the key is a probe number (or probe name) and the value is
315 * the requested trigger type. Valid trigger types currently
316 * include 'r' (rising edge), 'f' (falling edge), 'c' (any pin value
317 * change), '0' (low value), or '1' (high value).
318 * Example: "1=r,sck=f,miso=0,7=c"
320 * @return Pointer to a list of trigger types (strings), or NULL upon errors.
321 * The pointer list (if non-NULL) has as many entries as the
322 * respective device has probes (all physically available probes,
323 * not just enabled ones). Entries of the list which don't have
324 * a trigger value set in 'triggerstring' are NULL, the other entries
325 * contain the respective trigger type which is requested for the
326 * respective probe (e.g. "r", "c", and so on).
328 SR_API char **sr_parse_triggerstring(const struct sr_dev_inst *sdi,
329 const char *triggerstring)
333 struct sr_probe *probe;
334 int max_probes, probenum, i;
335 char **tokens, **triggerlist, *trigger, *tc;
336 const char *trigger_types;
339 max_probes = g_slist_length(sdi->probes);
342 if (!(triggerlist = g_try_malloc0(max_probes * sizeof(char *)))) {
343 sr_err("%s: triggerlist malloc failed", __func__);
347 if (sdi->driver->config_list(SR_CONF_TRIGGER_TYPE,
348 &gvar, sdi, NULL) != SR_OK) {
349 sr_err("%s: Device doesn't support any triggers.", __func__);
352 trigger_types = g_variant_get_string(gvar, NULL);
354 tokens = g_strsplit(triggerstring, ",", max_probes);
355 for (i = 0; tokens[i]; i++) {
357 for (l = sdi->probes; l; l = l->next) {
358 probe = (struct sr_probe *)l->data;
360 && !strncmp(probe->name, tokens[i],
361 strlen(probe->name))) {
362 probenum = probe->index;
367 if (probenum < 0 || probenum >= max_probes) {
368 sr_err("Invalid probe.");
373 if ((trigger = strchr(tokens[i], '='))) {
374 for (tc = ++trigger; *tc; tc++) {
375 if (strchr(trigger_types, *tc) == NULL) {
376 sr_err("Unsupported trigger "
383 triggerlist[probenum] = g_strdup(trigger);
387 g_variant_unref(gvar);
390 for (i = 0; i < max_probes; i++)
391 g_free(triggerlist[i]);
400 * Convert a "natural" string representation of a size value to uint64_t.
402 * E.g. a value of "3k" or "3 K" would be converted to 3000, a value
403 * of "15M" would be converted to 15000000.
405 * Value representations other than decimal (such as hex or octal) are not
406 * supported. Only 'k' (kilo), 'm' (mega), 'g' (giga) suffixes are supported.
407 * Spaces (but not other whitespace) between value and suffix are allowed.
409 * @param sizestring A string containing a (decimal) size value.
410 * @param size Pointer to uint64_t which will contain the string's size value.
412 * @return SR_OK upon success, SR_ERR upon errors.
414 SR_API int sr_parse_sizestring(const char *sizestring, uint64_t *size)
416 int multiplier, done;
419 *size = strtoull(sizestring, &s, 10);
422 while (s && *s && multiplier == 0 && !done) {
428 multiplier = SR_KHZ(1);
432 multiplier = SR_MHZ(1);
436 multiplier = SR_GHZ(1);
447 if (*s && strcasecmp(s, "Hz"))
454 * Convert a "natural" string representation of a time value to an
455 * uint64_t value in milliseconds.
457 * E.g. a value of "3s" or "3 s" would be converted to 3000, a value
458 * of "15ms" would be converted to 15.
460 * Value representations other than decimal (such as hex or octal) are not
461 * supported. Only lower-case "s" and "ms" time suffixes are supported.
462 * Spaces (but not other whitespace) between value and suffix are allowed.
464 * @param timestring A string containing a (decimal) time value.
465 * @return The string's time value as uint64_t, in milliseconds.
467 * @todo Add support for "m" (minutes) and others.
468 * @todo Add support for picoseconds?
469 * @todo Allow both lower-case and upper-case? If no, document it.
471 SR_API uint64_t sr_parse_timestring(const char *timestring)
476 /* TODO: Error handling, logging. */
478 time_msec = strtoull(timestring, &s, 10);
479 if (time_msec == 0 && s == timestring)
487 else if (!strcmp(s, "ms"))
496 SR_API gboolean sr_parse_boolstring(const char *boolstr)
501 if (!g_ascii_strncasecmp(boolstr, "true", 4) ||
502 !g_ascii_strncasecmp(boolstr, "yes", 3) ||
503 !g_ascii_strncasecmp(boolstr, "on", 2) ||
504 !g_ascii_strncasecmp(boolstr, "1", 1))
510 SR_API int sr_parse_period(const char *periodstr, uint64_t *p, uint64_t *q)
514 *p = strtoull(periodstr, &s, 10);
515 if (*p == 0 && s == periodstr)
516 /* No digits found. */
522 if (!strcmp(s, "fs"))
523 *q = 1000000000000000ULL;
524 else if (!strcmp(s, "ps"))
525 *q = 1000000000000ULL;
526 else if (!strcmp(s, "ns"))
528 else if (!strcmp(s, "us"))
530 else if (!strcmp(s, "ms"))
532 else if (!strcmp(s, "s"))
535 /* Must have a time suffix. */
543 SR_API int sr_parse_voltage(const char *voltstr, uint64_t *p, uint64_t *q)
547 *p = strtoull(voltstr, &s, 10);
548 if (*p == 0 && s == voltstr)
549 /* No digits found. */
555 if (!strcasecmp(s, "mv"))
557 else if (!strcasecmp(s, "v"))
560 /* Must have a base suffix. */