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/>.
20 /* Needed for POSIX.1-2008 locale functions */
21 #define _XOPEN_SOURCE 700
25 #if defined(__FreeBSD__) || defined(__APPLE__)
28 #if defined(__FreeBSD__)
29 #include <sys/param.h>
37 #include <libsigrok/libsigrok.h>
38 #include "libsigrok-internal.h"
41 #define LOG_PREFIX "strutil"
47 * Helper functions for handling or converting libsigrok-related strings.
51 * @defgroup grp_strutil String utilities
53 * Helper functions for handling or converting libsigrok-related strings.
61 * Convert a string representation of a numeric value (base 10) to a long integer. The
62 * conversion is strict and will fail if the complete string does not represent
63 * a valid long integer. The function sets errno according to the details of the
66 * @param str The string representation to convert.
67 * @param ret Pointer to long where the result of the conversion will be stored.
69 * @retval SR_OK Conversion successful.
70 * @retval SR_ERR Failure.
72 SR_PRIV int sr_atol(const char *str, long *ret)
78 tmp = strtol(str, &endptr, 10);
80 while (endptr && isspace(*endptr))
83 if (!endptr || *endptr || errno) {
96 * Convert a string representation of a numeric value (base 10) to an integer. The
97 * conversion is strict and will fail if the complete string does not represent
98 * a valid integer. The function sets errno according to the details of the
101 * @param str The string representation to convert.
102 * @param ret Pointer to int where the result of the conversion will be stored.
104 * @retval SR_OK Conversion successful.
105 * @retval SR_ERR Failure.
107 SR_PRIV int sr_atoi(const char *str, int *ret)
111 if (sr_atol(str, &tmp) != SR_OK)
114 if ((int) tmp != tmp) {
126 * Convert a string representation of a numeric value to a double. The
127 * conversion is strict and will fail if the complete string does not represent
128 * a valid double. The function sets errno according to the details of the
131 * @param str The string representation to convert.
132 * @param ret Pointer to double where the result of the conversion will be stored.
134 * @retval SR_OK Conversion successful.
135 * @retval SR_ERR Failure.
137 SR_PRIV int sr_atod(const char *str, double *ret)
143 tmp = strtof(str, &endptr);
145 while (endptr && isspace(*endptr))
148 if (!endptr || *endptr || errno) {
161 * Convert a string representation of a numeric value to a float. The
162 * conversion is strict and will fail if the complete string does not represent
163 * a valid float. The function sets errno according to the details of the
166 * @param str The string representation to convert.
167 * @param ret Pointer to float where the result of the conversion will be stored.
169 * @retval SR_OK Conversion successful.
170 * @retval SR_ERR Failure.
172 SR_PRIV int sr_atof(const char *str, float *ret)
176 if (sr_atod(str, &tmp) != SR_OK)
179 if ((float) tmp != tmp) {
191 * Convert a string representation of a numeric value to a double. The
192 * conversion is strict and will fail if the complete string does not represent
193 * a valid double. The function sets errno according to the details of the
194 * failure. This version ignores the locale.
196 * @param str The string representation to convert.
197 * @param ret Pointer to double where the result of the conversion will be stored.
199 * @retval SR_OK Conversion successful.
200 * @retval SR_ERR Failure.
202 SR_PRIV int sr_atod_ascii(const char *str, double *ret)
208 tmp = g_ascii_strtod(str, &endptr);
210 if (!endptr || *endptr || errno) {
223 * Convert a string representation of a numeric value to a float. The
224 * conversion is strict and will fail if the complete string does not represent
225 * a valid float. The function sets errno according to the details of the
226 * failure. This version ignores the locale.
228 * @param str The string representation to convert.
229 * @param ret Pointer to float where the result of the conversion will be stored.
231 * @retval SR_OK Conversion successful.
232 * @retval SR_ERR Failure.
234 SR_PRIV int sr_atof_ascii(const char *str, float *ret)
240 tmp = g_ascii_strtod(str, &endptr);
242 if (!endptr || *endptr || errno) {
248 /* FIXME This fails unexpectedly. Some other method to safel downcast
249 * needs to be found. Checking against FLT_MAX doesn't work as well. */
251 if ((float) tmp != tmp) {
253 sr_dbg("ERANGEEEE %e != %e", (float) tmp, tmp);
263 * Compose a string with a format string in the buffer pointed to by buf.
265 * It is up to the caller to ensure that the allocated buffer is large enough
266 * to hold the formatted result.
268 * A terminating NUL character is automatically appended after the content
271 * After the format parameter, the function expects at least as many additional
272 * arguments as needed for format.
274 * This version ignores the current locale and uses the locale "C" for Linux,
275 * FreeBSD, OSX and Android.
277 * @param buf Pointer to a buffer where the resulting C string is stored.
278 * @param format C string that contains a format string (see printf).
279 * @param ... A sequence of additional arguments, each containing a value to be
280 * used to replace a format specifier in the format string.
282 * @return On success, the number of characters that would have been written,
283 * not counting the terminating NUL character.
287 SR_API int sr_sprintf_ascii(char *buf, const char *format, ...)
292 va_start(args, format);
293 ret = sr_vsprintf_ascii(buf, format, args);
300 * Compose a string with a format string in the buffer pointed to by buf.
302 * It is up to the caller to ensure that the allocated buffer is large enough
303 * to hold the formatted result.
305 * Internally, the function retrieves arguments from the list identified by
306 * args as if va_arg was used on it, and thus the state of args is likely to
307 * be altered by the call.
309 * In any case, args should have been initialized by va_start at some point
310 * before the call, and it is expected to be released by va_end at some point
313 * This version ignores the current locale and uses the locale "C" for Linux,
314 * FreeBSD, OSX and Android.
316 * @param buf Pointer to a buffer where the resulting C string is stored.
317 * @param format C string that contains a format string (see printf).
318 * @param args A value identifying a variable arguments list initialized with
321 * @return On success, the number of characters that would have been written,
322 * not counting the terminating NUL character.
326 SR_API int sr_vsprintf_ascii(char *buf, const char *format, va_list args)
333 * TODO: This part compiles with mingw-w64 but doesn't run with Win7.
334 * Doesn't start because of "Procedure entry point _create_locale
335 * not found in msvcrt.dll".
336 * mingw-w64 should link to msvcr100.dll not msvcrt.dll!
337 * See: https://msdn.microsoft.com/en-us/en-en/library/1kt27hek.aspx
341 locale = _create_locale(LC_NUMERIC, "C");
342 ret = _vsprintf_l(buf, format, locale, args);
343 _free_locale(locale);
346 /* vsprintf() uses the current locale, may not work correctly for floats. */
347 ret = vsprintf(buf, format, args);
350 #elif defined(__APPLE__)
353 * https://developer.apple.com/legacy/library/documentation/Darwin/Reference/ManPages/man3/printf_l.3.html
354 * https://developer.apple.com/legacy/library/documentation/Darwin/Reference/ManPages/man3/xlocale.3.html
359 locale = newlocale(LC_NUMERIC_MASK, "C", NULL);
360 ret = vsprintf_l(buf, locale, format, args);
364 #elif defined(__FreeBSD__) && __FreeBSD_version >= 901000
367 * https://www.freebsd.org/cgi/man.cgi?query=printf_l&apropos=0&sektion=3&manpath=FreeBSD+9.1-RELEASE
368 * https://www.freebsd.org/cgi/man.cgi?query=xlocale&apropos=0&sektion=3&manpath=FreeBSD+9.1-RELEASE
373 locale = newlocale(LC_NUMERIC_MASK, "C", NULL);
374 ret = vsprintf_l(buf, locale, format, args);
378 #elif defined(__ANDROID__)
380 * The Bionic libc only has two locales ("C" aka "POSIX" and "C.UTF-8"
381 * aka "en_US.UTF-8"). The decimal point is hard coded as "."
382 * See: https://android.googlesource.com/platform/bionic/+/master/libc/bionic/locale.cpp
386 ret = vsprintf(buf, format, args);
389 #elif defined(__linux__)
391 locale_t old_locale, temp_locale;
393 /* Switch to C locale for proper float/double conversion. */
394 temp_locale = newlocale(LC_NUMERIC, "C", NULL);
395 old_locale = uselocale(temp_locale);
397 ret = vsprintf(buf, format, args);
399 /* Switch back to original locale. */
400 uselocale(old_locale);
401 freelocale(temp_locale);
404 #elif defined(__unix__) || defined(__unix)
406 * This is a fallback for all other BSDs, *nix and FreeBSD <= 9.0, by
407 * using the current locale for snprintf(). This may not work correctly
412 ret = vsprintf(buf, format, args);
416 /* No implementation for unknown systems! */
422 * Composes a string with a format string (like printf) in the buffer pointed
423 * by buf (taking buf_size as the maximum buffer capacity to fill).
424 * If the resulting string would be longer than n - 1 characters, the remaining
425 * characters are discarded and not stored, but counted for the value returned
427 * A terminating NUL character is automatically appended after the content
429 * After the format parameter, the function expects at least as many additional
430 * arguments as needed for format.
432 * This version ignores the current locale and uses the locale "C" for Linux,
433 * FreeBSD, OSX and Android.
435 * @param buf Pointer to a buffer where the resulting C string is stored.
436 * @param buf_size Maximum number of bytes to be used in the buffer. The
437 * generated string has a length of at most buf_size - 1, leaving space
438 * for the additional terminating NUL character.
439 * @param format C string that contains a format string (see printf).
440 * @param ... A sequence of additional arguments, each containing a value to be
441 * used to replace a format specifier in the format string.
443 * @return On success, the number of characters that would have been written if
444 * buf_size had been sufficiently large, not counting the terminating
445 * NUL character. On failure, a negative number is returned.
446 * Notice that only when this returned value is non-negative and less
447 * than buf_size, the string has been completely written.
451 SR_API int sr_snprintf_ascii(char *buf, size_t buf_size,
452 const char *format, ...)
457 va_start(args, format);
458 ret = sr_vsnprintf_ascii(buf, buf_size, format, args);
465 * Composes a string with a format string (like printf) in the buffer pointed
466 * by buf (taking buf_size as the maximum buffer capacity to fill).
467 * If the resulting string would be longer than n - 1 characters, the remaining
468 * characters are discarded and not stored, but counted for the value returned
470 * A terminating NUL character is automatically appended after the content
472 * Internally, the function retrieves arguments from the list identified by
473 * args as if va_arg was used on it, and thus the state of args is likely to
474 * be altered by the call.
475 * In any case, arg should have been initialized by va_start at some point
476 * before the call, and it is expected to be released by va_end at some point
479 * This version ignores the current locale and uses the locale "C" for Linux,
480 * FreeBSD, OSX and Android.
482 * @param buf Pointer to a buffer where the resulting C string is stored.
483 * @param buf_size Maximum number of bytes to be used in the buffer. The
484 * generated string has a length of at most buf_size - 1, leaving space
485 * for the additional terminating NUL character.
486 * @param format C string that contains a format string (see printf).
487 * @param args A value identifying a variable arguments list initialized with
490 * @return On success, the number of characters that would have been written if
491 * buf_size had been sufficiently large, not counting the terminating
492 * NUL character. On failure, a negative number is returned.
493 * Notice that only when this returned value is non-negative and less
494 * than buf_size, the string has been completely written.
498 SR_API int sr_vsnprintf_ascii(char *buf, size_t buf_size,
499 const char *format, va_list args)
506 * TODO: This part compiles with mingw-w64 but doesn't run with Win7.
507 * Doesn't start because of "Procedure entry point _create_locale
508 * not found in msvcrt.dll".
509 * mingw-w64 should link to msvcr100.dll not msvcrt.dll!.
510 * See: https://msdn.microsoft.com/en-us/en-en/library/1kt27hek.aspx
514 locale = _create_locale(LC_NUMERIC, "C");
515 ret = _vsnprintf_l(buf, buf_size, format, locale, args);
516 _free_locale(locale);
519 /* vsprintf uses the current locale, may cause issues for floats. */
520 ret = vsnprintf(buf, buf_size, format, args);
523 #elif defined(__APPLE__)
526 * https://developer.apple.com/legacy/library/documentation/Darwin/Reference/ManPages/man3/printf_l.3.html
527 * https://developer.apple.com/legacy/library/documentation/Darwin/Reference/ManPages/man3/xlocale.3.html
532 locale = newlocale(LC_NUMERIC_MASK, "C", NULL);
533 ret = vsnprintf_l(buf, buf_size, locale, format, args);
537 #elif defined(__FreeBSD__) && __FreeBSD_version >= 901000
540 * https://www.freebsd.org/cgi/man.cgi?query=printf_l&apropos=0&sektion=3&manpath=FreeBSD+9.1-RELEASE
541 * https://www.freebsd.org/cgi/man.cgi?query=xlocale&apropos=0&sektion=3&manpath=FreeBSD+9.1-RELEASE
546 locale = newlocale(LC_NUMERIC_MASK, "C", NULL);
547 ret = vsnprintf_l(buf, buf_size, locale, format, args);
551 #elif defined(__ANDROID__)
553 * The Bionic libc only has two locales ("C" aka "POSIX" and "C.UTF-8"
554 * aka "en_US.UTF-8"). The decimal point is hard coded as ".".
555 * See: https://android.googlesource.com/platform/bionic/+/master/libc/bionic/locale.cpp
559 ret = vsnprintf(buf, buf_size, format, args);
562 #elif defined(__linux__)
564 locale_t old_locale, temp_locale;
566 /* Switch to C locale for proper float/double conversion. */
567 temp_locale = newlocale(LC_NUMERIC, "C", NULL);
568 old_locale = uselocale(temp_locale);
570 ret = vsnprintf(buf, buf_size, format, args);
572 /* Switch back to original locale. */
573 uselocale(old_locale);
574 freelocale(temp_locale);
577 #elif defined(__unix__) || defined(__unix)
579 * This is a fallback for all other BSDs, *nix and FreeBSD <= 9.0, by
580 * using the current locale for snprintf(). This may not work correctly
585 ret = vsnprintf(buf, buf_size, format, args);
589 /* No implementation for unknown systems! */
595 * Convert a string representation of a numeric value to a sr_rational.
597 * The conversion is strict and will fail if the complete string does not
598 * represent a valid number. The function sets errno according to the details
599 * of the failure. This version ignores the locale.
601 * @param str The string representation to convert.
602 * @param ret Pointer to sr_rational where the result of the conversion will be stored.
604 * @retval SR_OK Conversion successful.
605 * @retval SR_ERR Failure.
609 SR_API int sr_parse_rational(const char *str, struct sr_rational *ret)
613 int64_t fractional = 0;
614 int64_t denominator = 1;
615 int32_t fractional_len = 0;
616 int32_t exponent = 0;
617 bool is_negative = false;
620 integral = g_ascii_strtoll(str, &endptr, 10);
622 if (str == endptr && (str[0] == '-' || str[0] == '+') && str[1] == '.')
627 if (integral < 0 || str[0] == '-')
630 if (*endptr == '.') {
631 const char* start = endptr + 1;
632 fractional = g_ascii_strtoll(start, &endptr, 10);
635 fractional_len = endptr - start;
638 if ((*endptr == 'E') || (*endptr == 'e')) {
639 exponent = g_ascii_strtoll(endptr + 1, &endptr, 10);
647 for (int i = 0; i < fractional_len; i++)
649 exponent -= fractional_len;
652 integral += fractional;
654 integral -= fractional;
656 while (exponent > 0) {
661 while (exponent < 0) {
667 ret->q = denominator;
673 * Convert a numeric value value to its "natural" string representation
676 * E.g. a value of 3000000, with units set to "W", would be converted
677 * to "3 MW", 20000 to "20 kW", 31500 would become "31.5 kW".
679 * @param x The value to convert.
680 * @param unit The unit to append to the string, or NULL if the string
683 * @return A newly allocated string representation of the samplerate value,
684 * or NULL upon errors. The caller is responsible to g_free() the
689 SR_API char *sr_si_string_u64(uint64_t x, const char *unit)
692 uint64_t quot, divisor[] = {
693 SR_HZ(1), SR_KHZ(1), SR_MHZ(1), SR_GHZ(1),
694 SR_GHZ(1000), SR_GHZ(1000 * 1000), SR_GHZ(1000 * 1000 * 1000),
696 const char *p, prefix[] = "\0kMGTPE";
697 char fmt[16], fract[20] = "", *f;
702 for (i = 0; (quot = x / divisor[i]) >= 1000; i++);
705 sprintf(fmt, ".%%0%d"PRIu64, i * 3);
706 f = fract + sprintf(fract, fmt, x % divisor[i]) - 1;
708 while (f >= fract && strchr("0.", *f))
714 return g_strdup_printf("%" PRIu64 "%s %.1s%s", quot, fract, p, unit);
718 * Convert a numeric samplerate value to its "natural" string representation.
720 * E.g. a value of 3000000 would be converted to "3 MHz", 20000 to "20 kHz",
721 * 31500 would become "31.5 kHz".
723 * @param samplerate The samplerate in Hz.
725 * @return A newly allocated string representation of the samplerate value,
726 * or NULL upon errors. The caller is responsible to g_free() the
731 SR_API char *sr_samplerate_string(uint64_t samplerate)
733 return sr_si_string_u64(samplerate, "Hz");
737 * Convert a numeric period value to the "natural" string representation
738 * of its period value.
740 * The period is specified as a rational number's numerator and denominator.
742 * E.g. a pair of (1, 5) would be converted to "200 ms", (10, 100) to "100 ms".
744 * @param v_p The period numerator.
745 * @param v_q The period denominator.
747 * @return A newly allocated string representation of the period value,
748 * or NULL upon errors. The caller is responsible to g_free() the
753 SR_API char *sr_period_string(uint64_t v_p, uint64_t v_q)
758 freq = 1 / ((double)v_p / v_q);
760 if (freq > SR_GHZ(1)) {
761 v = (double)v_p / v_q * 1000000000000.0;
762 prec = ((v - (uint64_t)v) < FLT_MIN) ? 0 : 3;
763 return g_strdup_printf("%.*f ps", prec, v);
764 } else if (freq > SR_MHZ(1)) {
765 v = (double)v_p / v_q * 1000000000.0;
766 prec = ((v - (uint64_t)v) < FLT_MIN) ? 0 : 3;
767 return g_strdup_printf("%.*f ns", prec, v);
768 } else if (freq > SR_KHZ(1)) {
769 v = (double)v_p / v_q * 1000000.0;
770 prec = ((v - (uint64_t)v) < FLT_MIN) ? 0 : 3;
771 return g_strdup_printf("%.*f us", prec, v);
772 } else if (freq > 1) {
773 v = (double)v_p / v_q * 1000.0;
774 prec = ((v - (uint64_t)v) < FLT_MIN) ? 0 : 3;
775 return g_strdup_printf("%.*f ms", prec, v);
777 v = (double)v_p / v_q;
778 prec = ((v - (uint64_t)v) < FLT_MIN) ? 0 : 3;
779 return g_strdup_printf("%.*f s", prec, v);
784 * Convert a numeric voltage value to the "natural" string representation
785 * of its voltage value. The voltage is specified as a rational number's
786 * numerator and denominator.
788 * E.g. a value of 300000 would be converted to "300mV", 2 to "2V".
790 * @param v_p The voltage numerator.
791 * @param v_q The voltage denominator.
793 * @return A newly allocated string representation of the voltage value,
794 * or NULL upon errors. The caller is responsible to g_free() the
799 SR_API char *sr_voltage_string(uint64_t v_p, uint64_t v_q)
802 return g_strdup_printf("%" PRIu64 " mV", v_p);
804 return g_strdup_printf("%" PRIu64 " V", v_p);
806 return g_strdup_printf("%g V", (float)v_p / (float)v_q);
810 * Convert a "natural" string representation of a size value to uint64_t.
812 * E.g. a value of "3k" or "3 K" would be converted to 3000, a value
813 * of "15M" would be converted to 15000000.
815 * Value representations other than decimal (such as hex or octal) are not
816 * supported. Only 'k' (kilo), 'm' (mega), 'g' (giga) suffixes are supported.
817 * Spaces (but not other whitespace) between value and suffix are allowed.
819 * @param sizestring A string containing a (decimal) size value.
820 * @param size Pointer to uint64_t which will contain the string's size value.
822 * @return SR_OK upon success, SR_ERR upon errors.
826 SR_API int sr_parse_sizestring(const char *sizestring, uint64_t *size)
833 *size = strtoull(sizestring, &s, 10);
837 while (s && *s && multiplier == 0 && !done) {
842 frac_part = g_ascii_strtod(s, &s);
846 multiplier = SR_KHZ(1);
850 multiplier = SR_MHZ(1);
854 multiplier = SR_GHZ(1);
858 multiplier = SR_GHZ(1000);
862 multiplier = SR_GHZ(1000 * 1000);
866 multiplier = SR_GHZ(1000 * 1000 * 1000);
874 if (multiplier > 0) {
876 *size += frac_part * multiplier;
881 if (s && *s && g_ascii_strcasecmp(s, "Hz"))
888 * Convert a "natural" string representation of a time value to an
889 * uint64_t value in milliseconds.
891 * E.g. a value of "3s" or "3 s" would be converted to 3000, a value
892 * of "15ms" would be converted to 15.
894 * Value representations other than decimal (such as hex or octal) are not
895 * supported. Only lower-case "s" and "ms" time suffixes are supported.
896 * Spaces (but not other whitespace) between value and suffix are allowed.
898 * @param timestring A string containing a (decimal) time value.
899 * @return The string's time value as uint64_t, in milliseconds.
901 * @todo Add support for "m" (minutes) and others.
902 * @todo Add support for picoseconds?
903 * @todo Allow both lower-case and upper-case? If no, document it.
907 SR_API uint64_t sr_parse_timestring(const char *timestring)
912 /* TODO: Error handling, logging. */
914 time_msec = strtoull(timestring, &s, 10);
915 if (time_msec == 0 && s == timestring)
923 else if (!strcmp(s, "ms"))
933 SR_API gboolean sr_parse_boolstring(const char *boolstr)
936 * Complete absence of an input spec is assumed to mean TRUE,
937 * as in command line option strings like this:
938 * ...:samplerate=100k:header:numchannels=4:...
940 if (!boolstr || !*boolstr)
943 if (!g_ascii_strncasecmp(boolstr, "true", 4) ||
944 !g_ascii_strncasecmp(boolstr, "yes", 3) ||
945 !g_ascii_strncasecmp(boolstr, "on", 2) ||
946 !g_ascii_strncasecmp(boolstr, "1", 1))
953 SR_API int sr_parse_period(const char *periodstr, uint64_t *p, uint64_t *q)
957 *p = strtoull(periodstr, &s, 10);
958 if (*p == 0 && s == periodstr)
959 /* No digits found. */
965 if (!strcmp(s, "fs"))
966 *q = UINT64_C(1000000000000000);
967 else if (!strcmp(s, "ps"))
968 *q = UINT64_C(1000000000000);
969 else if (!strcmp(s, "ns"))
970 *q = UINT64_C(1000000000);
971 else if (!strcmp(s, "us"))
973 else if (!strcmp(s, "ms"))
975 else if (!strcmp(s, "s"))
978 /* Must have a time suffix. */
986 SR_API int sr_parse_voltage(const char *voltstr, uint64_t *p, uint64_t *q)
990 *p = strtoull(voltstr, &s, 10);
991 if (*p == 0 && s == voltstr)
992 /* No digits found. */
998 if (!g_ascii_strcasecmp(s, "mv"))
1000 else if (!g_ascii_strcasecmp(s, "v"))
1003 /* Must have a base suffix. */