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, see <http://www.gnu.org/licenses/>.
28 #include <libsigrok/libsigrok.h>
29 #include "libsigrok-internal.h"
32 #define LOG_PREFIX "strutil"
38 * Helper functions for handling or converting libsigrok-related strings.
42 * @defgroup grp_strutil String utilities
44 * Helper functions for handling or converting libsigrok-related strings.
52 * Convert a string representation of a numeric value (base 10) to a long integer. The
53 * conversion is strict and will fail if the complete string does not represent
54 * a valid long integer. The function sets errno according to the details of the
57 * @param str The string representation to convert.
58 * @param ret Pointer to long where the result of the conversion will be stored.
60 * @retval SR_OK Conversion successful.
61 * @retval SR_ERR Failure.
63 SR_PRIV int sr_atol(const char *str, long *ret)
69 tmp = strtol(str, &endptr, 10);
71 while (endptr && isspace(*endptr))
74 if (!endptr || *endptr || errno) {
87 * Convert a string representation of a numeric value (base 10) to an integer. The
88 * conversion is strict and will fail if the complete string does not represent
89 * a valid integer. The function sets errno according to the details of the
92 * @param str The string representation to convert.
93 * @param ret Pointer to int where the result of the conversion will be stored.
95 * @retval SR_OK Conversion successful.
96 * @retval SR_ERR Failure.
98 SR_PRIV int sr_atoi(const char *str, int *ret)
102 if (sr_atol(str, &tmp) != SR_OK)
105 if ((int) tmp != tmp) {
117 * Convert a string representation of a numeric value to a double. The
118 * conversion is strict and will fail if the complete string does not represent
119 * a valid double. The function sets errno according to the details of the
122 * @param str The string representation to convert.
123 * @param ret Pointer to double where the result of the conversion will be stored.
125 * @retval SR_OK Conversion successful.
126 * @retval SR_ERR Failure.
128 SR_PRIV int sr_atod(const char *str, double *ret)
134 tmp = strtof(str, &endptr);
136 while (endptr && isspace(*endptr))
139 if (!endptr || *endptr || errno) {
152 * Convert a string representation of a numeric value to a float. The
153 * conversion is strict and will fail if the complete string does not represent
154 * a valid float. The function sets errno according to the details of the
157 * @param str The string representation to convert.
158 * @param ret Pointer to float where the result of the conversion will be stored.
160 * @retval SR_OK Conversion successful.
161 * @retval SR_ERR Failure.
163 SR_PRIV int sr_atof(const char *str, float *ret)
167 if (sr_atod(str, &tmp) != SR_OK)
170 if ((float) tmp != tmp) {
182 * Convert a string representation of a numeric value to a double. The
183 * conversion is strict and will fail if the complete string does not represent
184 * a valid double. The function sets errno according to the details of the
185 * failure. This version ignores the locale.
187 * @param str The string representation to convert.
188 * @param ret Pointer to double where the result of the conversion will be stored.
190 * @retval SR_OK Conversion successful.
191 * @retval SR_ERR Failure.
193 SR_PRIV int sr_atod_ascii(const char *str, double *ret)
199 tmp = g_ascii_strtod(str, &endptr);
201 if (!endptr || *endptr || errno) {
214 * Convert a string representation of a numeric value to a float. The
215 * conversion is strict and will fail if the complete string does not represent
216 * a valid float. The function sets errno according to the details of the
217 * failure. This version ignores the locale.
219 * @param str The string representation to convert.
220 * @param ret Pointer to float where the result of the conversion will be stored.
222 * @retval SR_OK Conversion successful.
223 * @retval SR_ERR Failure.
225 SR_PRIV int sr_atof_ascii(const char *str, float *ret)
231 tmp = g_ascii_strtod(str, &endptr);
233 if (!endptr || *endptr || errno) {
239 /* FIXME This fails unexpectedly. Some other method to safel downcast
240 * needs to be found. Checking against FLT_MAX doesn't work as well. */
242 if ((float) tmp != tmp) {
244 sr_dbg("ERANGEEEE %e != %e", (float) tmp, tmp);
254 * Convert a string representation of a numeric value to a sr_rational.
256 * The conversion is strict and will fail if the complete string does not
257 * represent a valid number. The function sets errno according to the details
258 * of the failure. This version ignores the locale.
260 * @param str The string representation to convert.
261 * @param ret Pointer to sr_rational where the result of the conversion will be stored.
263 * @retval SR_OK Conversion successful.
264 * @retval SR_ERR Failure.
268 SR_API int sr_parse_rational(const char *str, struct sr_rational *ret)
272 int64_t fractional = 0;
273 int64_t denominator = 1;
274 int32_t fractional_len = 0;
275 int32_t exponent = 0;
276 bool is_negative = false;
279 integral = g_ascii_strtoll(str, &endptr, 10);
281 if (str == endptr && (str[0] == '-' || str[0] == '+') && str[1] == '.')
286 if (integral < 0 || str[0] == '-')
289 if (*endptr == '.') {
290 const char* start = endptr + 1;
291 fractional = g_ascii_strtoll(start, &endptr, 10);
294 fractional_len = endptr - start;
297 if ((*endptr == 'E') || (*endptr == 'e')) {
298 exponent = g_ascii_strtoll(endptr + 1, &endptr, 10);
306 for (int i = 0; i < fractional_len; i++)
308 exponent -= fractional_len;
311 integral += fractional;
313 integral -= fractional;
315 while (exponent > 0) {
320 while (exponent < 0) {
326 ret->q = denominator;
332 * Convert a numeric value value to its "natural" string representation
335 * E.g. a value of 3000000, with units set to "W", would be converted
336 * to "3 MW", 20000 to "20 kW", 31500 would become "31.5 kW".
338 * @param x The value to convert.
339 * @param unit The unit to append to the string, or NULL if the string
342 * @return A newly allocated string representation of the samplerate value,
343 * or NULL upon errors. The caller is responsible to g_free() the
348 SR_API char *sr_si_string_u64(uint64_t x, const char *unit)
351 uint64_t quot, divisor[] = {
352 SR_HZ(1), SR_KHZ(1), SR_MHZ(1), SR_GHZ(1),
353 SR_GHZ(1000), SR_GHZ(1000 * 1000), SR_GHZ(1000 * 1000 * 1000),
355 const char *p, prefix[] = "\0kMGTPE";
356 char fmt[16], fract[20] = "", *f;
361 for (i = 0; (quot = x / divisor[i]) >= 1000; i++);
364 sprintf(fmt, ".%%0%d"PRIu64, i * 3);
365 f = fract + sprintf(fract, fmt, x % divisor[i]) - 1;
367 while (f >= fract && strchr("0.", *f))
373 return g_strdup_printf("%" PRIu64 "%s %.1s%s", quot, fract, p, unit);
377 * Convert a numeric samplerate value to its "natural" string representation.
379 * E.g. a value of 3000000 would be converted to "3 MHz", 20000 to "20 kHz",
380 * 31500 would become "31.5 kHz".
382 * @param samplerate The samplerate in Hz.
384 * @return A newly allocated string representation of the samplerate value,
385 * or NULL upon errors. The caller is responsible to g_free() the
390 SR_API char *sr_samplerate_string(uint64_t samplerate)
392 return sr_si_string_u64(samplerate, "Hz");
396 * Convert a numeric period value to the "natural" string representation
397 * of its period value.
399 * The period is specified as a rational number's numerator and denominator.
401 * E.g. a pair of (1, 5) would be converted to "200 ms", (10, 100) to "100 ms".
403 * @param v_p The period numerator.
404 * @param v_q The period denominator.
406 * @return A newly allocated string representation of the period value,
407 * or NULL upon errors. The caller is responsible to g_free() the
412 SR_API char *sr_period_string(uint64_t v_p, uint64_t v_q)
417 freq = 1 / ((double)v_p / v_q);
419 if (freq > SR_GHZ(1)) {
420 v = (double)v_p / v_q * 1000000000000.0;
421 prec = ((v - (uint64_t)v) < FLT_MIN) ? 0 : 3;
422 return g_strdup_printf("%.*f ps", prec, v);
423 } else if (freq > SR_MHZ(1)) {
424 v = (double)v_p / v_q * 1000000000.0;
425 prec = ((v - (uint64_t)v) < FLT_MIN) ? 0 : 3;
426 return g_strdup_printf("%.*f ns", prec, v);
427 } else if (freq > SR_KHZ(1)) {
428 v = (double)v_p / v_q * 1000000.0;
429 prec = ((v - (uint64_t)v) < FLT_MIN) ? 0 : 3;
430 return g_strdup_printf("%.*f us", prec, v);
431 } else if (freq > 1) {
432 v = (double)v_p / v_q * 1000.0;
433 prec = ((v - (uint64_t)v) < FLT_MIN) ? 0 : 3;
434 return g_strdup_printf("%.*f ms", prec, v);
436 v = (double)v_p / v_q;
437 prec = ((v - (uint64_t)v) < FLT_MIN) ? 0 : 3;
438 return g_strdup_printf("%.*f s", prec, v);
443 * Convert a numeric voltage value to the "natural" string representation
444 * of its voltage value. The voltage is specified as a rational number's
445 * numerator and denominator.
447 * E.g. a value of 300000 would be converted to "300mV", 2 to "2V".
449 * @param v_p The voltage numerator.
450 * @param v_q The voltage denominator.
452 * @return A newly allocated string representation of the voltage value,
453 * or NULL upon errors. The caller is responsible to g_free() the
458 SR_API char *sr_voltage_string(uint64_t v_p, uint64_t v_q)
461 return g_strdup_printf("%" PRIu64 " mV", v_p);
463 return g_strdup_printf("%" PRIu64 " V", v_p);
465 return g_strdup_printf("%g V", (float)v_p / (float)v_q);
469 * Convert a "natural" string representation of a size value to uint64_t.
471 * E.g. a value of "3k" or "3 K" would be converted to 3000, a value
472 * of "15M" would be converted to 15000000.
474 * Value representations other than decimal (such as hex or octal) are not
475 * supported. Only 'k' (kilo), 'm' (mega), 'g' (giga) suffixes are supported.
476 * Spaces (but not other whitespace) between value and suffix are allowed.
478 * @param sizestring A string containing a (decimal) size value.
479 * @param size Pointer to uint64_t which will contain the string's size value.
481 * @return SR_OK upon success, SR_ERR upon errors.
485 SR_API int sr_parse_sizestring(const char *sizestring, uint64_t *size)
492 *size = strtoull(sizestring, &s, 10);
496 while (s && *s && multiplier == 0 && !done) {
501 frac_part = g_ascii_strtod(s, &s);
505 multiplier = SR_KHZ(1);
509 multiplier = SR_MHZ(1);
513 multiplier = SR_GHZ(1);
517 multiplier = SR_GHZ(1000);
521 multiplier = SR_GHZ(1000 * 1000);
525 multiplier = SR_GHZ(1000 * 1000 * 1000);
533 if (multiplier > 0) {
535 *size += frac_part * multiplier;
540 if (s && *s && g_ascii_strcasecmp(s, "Hz"))
547 * Convert a "natural" string representation of a time value to an
548 * uint64_t value in milliseconds.
550 * E.g. a value of "3s" or "3 s" would be converted to 3000, a value
551 * of "15ms" would be converted to 15.
553 * Value representations other than decimal (such as hex or octal) are not
554 * supported. Only lower-case "s" and "ms" time suffixes are supported.
555 * Spaces (but not other whitespace) between value and suffix are allowed.
557 * @param timestring A string containing a (decimal) time value.
558 * @return The string's time value as uint64_t, in milliseconds.
560 * @todo Add support for "m" (minutes) and others.
561 * @todo Add support for picoseconds?
562 * @todo Allow both lower-case and upper-case? If no, document it.
566 SR_API uint64_t sr_parse_timestring(const char *timestring)
571 /* TODO: Error handling, logging. */
573 time_msec = strtoull(timestring, &s, 10);
574 if (time_msec == 0 && s == timestring)
582 else if (!strcmp(s, "ms"))
592 SR_API gboolean sr_parse_boolstring(const char *boolstr)
595 * Complete absence of an input spec is assumed to mean TRUE,
596 * as in command line option strings like this:
597 * ...:samplerate=100k:header:numchannels=4:...
599 if (!boolstr || !*boolstr)
602 if (!g_ascii_strncasecmp(boolstr, "true", 4) ||
603 !g_ascii_strncasecmp(boolstr, "yes", 3) ||
604 !g_ascii_strncasecmp(boolstr, "on", 2) ||
605 !g_ascii_strncasecmp(boolstr, "1", 1))
612 SR_API int sr_parse_period(const char *periodstr, uint64_t *p, uint64_t *q)
616 *p = strtoull(periodstr, &s, 10);
617 if (*p == 0 && s == periodstr)
618 /* No digits found. */
624 if (!strcmp(s, "fs"))
625 *q = 1000000000000000ULL;
626 else if (!strcmp(s, "ps"))
627 *q = 1000000000000ULL;
628 else if (!strcmp(s, "ns"))
630 else if (!strcmp(s, "us"))
632 else if (!strcmp(s, "ms"))
634 else if (!strcmp(s, "s"))
637 /* Must have a time suffix. */
645 SR_API int sr_parse_voltage(const char *voltstr, uint64_t *p, uint64_t *q)
649 *p = strtoull(voltstr, &s, 10);
650 if (*p == 0 && s == voltstr)
651 /* No digits found. */
657 if (!g_ascii_strcasecmp(s, "mv"))
659 else if (!g_ascii_strcasecmp(s, "v"))
662 /* Must have a base suffix. */