]> sigrok.org Git - libsigrok.git/blob - src/strutil.c
Fix sr_period_string() Doxygen comments.
[libsigrok.git] / src / strutil.c
1 /*
2  * This file is part of the libsigrok project.
3  *
4  * Copyright (C) 2010 Uwe Hermann <uwe@hermann-uwe.de>
5  *
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.
10  *
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.
15  *
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/>.
18  */
19
20 #include <config.h>
21 #include <stdint.h>
22 #include <stdlib.h>
23 #include <string.h>
24 #include <strings.h>
25 #include <errno.h>
26 #include <libsigrok/libsigrok.h>
27 #include "libsigrok-internal.h"
28
29 /** @cond PRIVATE */
30 #define LOG_PREFIX "strutil"
31 /** @endcond */
32
33 /**
34  * @file
35  *
36  * Helper functions for handling or converting libsigrok-related strings.
37  */
38
39 /**
40  * @defgroup grp_strutil String utilities
41  *
42  * Helper functions for handling or converting libsigrok-related strings.
43  *
44  * @{
45  */
46
47 /**
48  * @private
49  *
50  * Convert a string representation of a numeric value (base 10) to a long integer. The
51  * conversion is strict and will fail if the complete string does not represent
52  * a valid long integer. The function sets errno according to the details of the
53  * failure.
54  *
55  * @param str The string representation to convert.
56  * @param ret Pointer to long where the result of the conversion will be stored.
57  *
58  * @retval SR_OK Conversion successful.
59  * @retval SR_ERR Failure.
60  */
61 SR_PRIV int sr_atol(const char *str, long *ret)
62 {
63         long tmp;
64         char *endptr = NULL;
65
66         errno = 0;
67         tmp = strtol(str, &endptr, 10);
68
69         if (!endptr || *endptr || errno) {
70                 if (!errno)
71                         errno = EINVAL;
72                 return SR_ERR;
73         }
74
75         *ret = tmp;
76         return SR_OK;
77 }
78
79 /**
80  * @private
81  *
82  * Convert a string representation of a numeric value (base 10) to an integer. The
83  * conversion is strict and will fail if the complete string does not represent
84  * a valid integer. The function sets errno according to the details of the
85  * failure.
86  *
87  * @param str The string representation to convert.
88  * @param ret Pointer to int where the result of the conversion will be stored.
89  *
90  * @retval SR_OK Conversion successful.
91  * @retval SR_ERR Failure.
92  */
93 SR_PRIV int sr_atoi(const char *str, int *ret)
94 {
95         long tmp;
96
97         if (sr_atol(str, &tmp) != SR_OK)
98                 return SR_ERR;
99
100         if ((int) tmp != tmp) {
101                 errno = ERANGE;
102                 return SR_ERR;
103         }
104
105         *ret = (int) tmp;
106         return SR_OK;
107 }
108
109 /**
110  * @private
111  *
112  * Convert a string representation of a numeric value to a double. The
113  * conversion is strict and will fail if the complete string does not represent
114  * a valid double. The function sets errno according to the details of the
115  * failure.
116  *
117  * @param str The string representation to convert.
118  * @param ret Pointer to double where the result of the conversion will be stored.
119  *
120  * @retval SR_OK Conversion successful.
121  * @retval SR_ERR Failure.
122  */
123 SR_PRIV int sr_atod(const char *str, double *ret)
124 {
125         double tmp;
126         char *endptr = NULL;
127
128         errno = 0;
129         tmp = strtof(str, &endptr);
130
131         if (!endptr || *endptr || errno) {
132                 if (!errno)
133                         errno = EINVAL;
134                 return SR_ERR;
135         }
136
137         *ret = tmp;
138         return SR_OK;
139 }
140
141 /**
142  * @private
143  *
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
147  * failure.
148  *
149  * @param str The string representation to convert.
150  * @param ret Pointer to float where the result of the conversion will be stored.
151  *
152  * @retval SR_OK Conversion successful.
153  * @retval SR_ERR Failure.
154  */
155 SR_PRIV int sr_atof(const char *str, float *ret)
156 {
157         double tmp;
158
159         if (sr_atod(str, &tmp) != SR_OK)
160                 return SR_ERR;
161
162         if ((float) tmp != tmp) {
163                 errno = ERANGE;
164                 return SR_ERR;
165         }
166
167         *ret = (float) tmp;
168         return SR_OK;
169 }
170
171 /**
172  * @private
173  *
174  * Convert a string representation of a numeric value to a float. The
175  * conversion is strict and will fail if the complete string does not represent
176  * a valid float. The function sets errno according to the details of the
177  * failure. This version ignores the locale.
178  *
179  * @param str The string representation to convert.
180  * @param ret Pointer to float where the result of the conversion will be stored.
181  *
182  * @retval SR_OK Conversion successful.
183  * @retval SR_ERR Failure.
184  */
185 SR_PRIV int sr_atof_ascii(const char *str, float *ret)
186 {
187         double tmp;
188         char *endptr = NULL;
189
190         errno = 0;
191         tmp = g_ascii_strtod(str, &endptr);
192
193         if (!endptr || *endptr || errno) {
194                 if (!errno)
195                         errno = EINVAL;
196                 return SR_ERR;
197         }
198
199         /* FIXME This fails unexpectedly. Some other method to safel downcast
200          * needs to be found. Checking against FLT_MAX doesn't work as well. */
201         /*
202         if ((float) tmp != tmp) {
203                 errno = ERANGE;
204                 sr_dbg("ERANGEEEE %e != %e", (float) tmp, tmp);
205                 return SR_ERR;
206         }
207         */
208
209         *ret = (float) tmp;
210         return SR_OK;
211 }
212
213 /**
214  * Convert a string representation of a numeric value to a sr_rational.
215  *
216  * The conversion is strict and will fail if the complete string does not
217  * represent a valid number. The function sets errno according to the details
218  * of the failure. This version ignores the locale.
219  *
220  * @param str The string representation to convert.
221  * @param ret Pointer to sr_rational where the result of the conversion will be stored.
222  *
223  * @retval SR_OK Conversion successful.
224  * @retval SR_ERR Failure.
225  *
226  * @since 0.5.0
227  */
228 SR_API int sr_parse_rational(const char *str, struct sr_rational *ret)
229 {
230         char *endptr = NULL;
231         int64_t integral;
232         int64_t fractional = 0;
233         int64_t denominator = 1;
234         int32_t fractional_len = 0;
235         int32_t exponent = 0;
236
237         errno = 0;
238         integral = g_ascii_strtoll(str, &endptr, 10);
239
240         if (errno)
241                 return SR_ERR;
242
243         if (*endptr == '.') {
244                 const char* start = endptr + 1;
245                 fractional = g_ascii_strtoll(start, &endptr, 10);
246                 if (errno)
247                         return SR_ERR;
248                 fractional_len = endptr - start;
249         }
250
251         if ((*endptr == 'E') || (*endptr == 'e')) {
252                 exponent = g_ascii_strtoll(endptr + 1, &endptr, 10);
253                 if (errno)
254                         return SR_ERR;
255         }
256
257         if (*endptr != '\0')
258                 return SR_ERR;
259
260         for (int i = 0; i < fractional_len; i++)
261                 integral *= 10;
262         exponent -= fractional_len;
263
264         if (integral >= 0)
265                 integral += fractional;
266         else
267                 integral -= fractional;
268
269         while (exponent > 0) {
270                 integral *= 10;
271                 exponent--;
272         }
273
274         while (exponent < 0) {
275                 denominator *= 10;
276                 exponent++;
277         }
278
279         ret->p = integral;
280         ret->q = denominator;
281
282         return SR_OK;
283 }
284
285 /**
286  * Convert a numeric value value to its "natural" string representation
287  * in SI units.
288  *
289  * E.g. a value of 3000000, with units set to "W", would be converted
290  * to "3 MW", 20000 to "20 kW", 31500 would become "31.5 kW".
291  *
292  * @param x The value to convert.
293  * @param unit The unit to append to the string, or NULL if the string
294  *             has no units.
295  *
296  * @return A newly allocated string representation of the samplerate value,
297  *         or NULL upon errors. The caller is responsible to g_free() the
298  *         memory.
299  *
300  * @since 0.2.0
301  */
302 SR_API char *sr_si_string_u64(uint64_t x, const char *unit)
303 {
304         uint8_t i;
305         uint64_t quot, divisor[] = {
306                 SR_HZ(1), SR_KHZ(1), SR_MHZ(1), SR_GHZ(1),
307                 SR_GHZ(1000), SR_GHZ(1000 * 1000), SR_GHZ(1000 * 1000 * 1000),
308         };
309         const char *p, prefix[] = "\0kMGTPE";
310         char fmt[16], fract[20] = "", *f;
311
312         if (!unit)
313                 unit = "";
314
315         for (i = 0; (quot = x / divisor[i]) >= 1000; i++);
316
317         if (i) {
318                 sprintf(fmt, ".%%0%d"PRIu64, i * 3);
319                 f = fract + sprintf(fract, fmt, x % divisor[i]) - 1;
320
321                 while (f >= fract && strchr("0.", *f))
322                         *f-- = 0;
323         }
324
325         p = prefix + i;
326
327         return g_strdup_printf("%" PRIu64 "%s %.1s%s", quot, fract, p, unit);
328 }
329
330 /**
331  * Convert a numeric samplerate value to its "natural" string representation.
332  *
333  * E.g. a value of 3000000 would be converted to "3 MHz", 20000 to "20 kHz",
334  * 31500 would become "31.5 kHz".
335  *
336  * @param samplerate The samplerate in Hz.
337  *
338  * @return A newly allocated string representation of the samplerate value,
339  *         or NULL upon errors. The caller is responsible to g_free() the
340  *         memory.
341  *
342  * @since 0.1.0
343  */
344 SR_API char *sr_samplerate_string(uint64_t samplerate)
345 {
346         return sr_si_string_u64(samplerate, "Hz");
347 }
348
349 /**
350  * Convert a numeric period value to the "natural" string representation
351  * of its period value.
352  *
353  * The period is specified as a rational number's numerator and denominator.
354  *
355  * E.g. a pair of (1, 5) would be converted to "200 ms", (10, 100) to "100 ms".
356  *
357  * @param v_p The period numerator.
358  * @param v_q The period denominator.
359  *
360  * @return A newly allocated string representation of the period value,
361  *         or NULL upon errors. The caller is responsible to g_free() the
362  *         memory.
363  *
364  * @since 0.5.0
365  */
366 SR_API char *sr_period_string(uint64_t v_p, uint64_t v_q)
367 {
368         double freq, v;
369         char *o;
370         int prec, r;
371
372         freq = 1 / ((double)v_p / v_q);
373
374         o = g_malloc0(30 + 1);
375
376         if (freq > SR_GHZ(1)) {
377                 v = (double)v_p / v_q * 1000000000000.0;
378                 prec = ((v - (uint64_t)v) < FLT_MIN) ? 0 : 3;
379                 r = snprintf(o, 30, "%.*f ps", prec, v);
380         } else if (freq > SR_MHZ(1)) {
381                 v = (double)v_p / v_q * 1000000000.0;
382                 prec = ((v - (uint64_t)v) < FLT_MIN) ? 0 : 3;
383                 r = snprintf(o, 30, "%.*f ns", prec, v);
384         } else if (freq > SR_KHZ(1)) {
385                 v = (double)v_p / v_q * 1000000.0;
386                 prec = ((v - (uint64_t)v) < FLT_MIN) ? 0 : 3;
387                 r = snprintf(o, 30, "%.*f us", prec, v);
388         } else if (freq > 1) {
389                 v = (double)v_p / v_q * 1000.0;
390                 prec = ((v - (uint64_t)v) < FLT_MIN) ? 0 : 3;
391                 r = snprintf(o, 30, "%.*f ms", prec, v);
392         } else {
393                 v = (double)v_p / v_q;
394                 prec = ((v - (uint64_t)v) < FLT_MIN) ? 0 : 3;
395                 r = snprintf(o, 30, "%.*f s", prec, v);
396         }
397
398         if (r < 0) {
399                 /* Something went wrong... */
400                 g_free(o);
401                 return NULL;
402         }
403
404         return o;
405 }
406
407 /**
408  * Convert a numeric voltage value to the "natural" string representation
409  * of its voltage value. The voltage is specified as a rational number's
410  * numerator and denominator.
411  *
412  * E.g. a value of 300000 would be converted to "300mV", 2 to "2V".
413  *
414  * @param v_p The voltage numerator.
415  * @param v_q The voltage denominator.
416  *
417  * @return A newly allocated string representation of the voltage value,
418  *         or NULL upon errors. The caller is responsible to g_free() the
419  *         memory.
420  *
421  * @since 0.2.0
422  */
423 SR_API char *sr_voltage_string(uint64_t v_p, uint64_t v_q)
424 {
425         int r;
426         char *o;
427
428         o = g_malloc0(30 + 1);
429
430         if (v_q == 1000)
431                 r = snprintf(o, 30, "%" PRIu64 "mV", v_p);
432         else if (v_q == 1)
433                 r = snprintf(o, 30, "%" PRIu64 "V", v_p);
434         else
435                 r = snprintf(o, 30, "%gV", (float)v_p / (float)v_q);
436
437         if (r < 0) {
438                 /* Something went wrong... */
439                 g_free(o);
440                 return NULL;
441         }
442
443         return o;
444 }
445
446 /**
447  * Convert a "natural" string representation of a size value to uint64_t.
448  *
449  * E.g. a value of "3k" or "3 K" would be converted to 3000, a value
450  * of "15M" would be converted to 15000000.
451  *
452  * Value representations other than decimal (such as hex or octal) are not
453  * supported. Only 'k' (kilo), 'm' (mega), 'g' (giga) suffixes are supported.
454  * Spaces (but not other whitespace) between value and suffix are allowed.
455  *
456  * @param sizestring A string containing a (decimal) size value.
457  * @param size Pointer to uint64_t which will contain the string's size value.
458  *
459  * @return SR_OK upon success, SR_ERR upon errors.
460  *
461  * @since 0.1.0
462  */
463 SR_API int sr_parse_sizestring(const char *sizestring, uint64_t *size)
464 {
465         int multiplier, done;
466         double frac_part;
467         char *s;
468
469         *size = strtoull(sizestring, &s, 10);
470         multiplier = 0;
471         frac_part = 0;
472         done = FALSE;
473         while (s && *s && multiplier == 0 && !done) {
474                 switch (*s) {
475                 case ' ':
476                         break;
477                 case '.':
478                         frac_part = g_ascii_strtod(s, &s);
479                         break;
480                 case 'k':
481                 case 'K':
482                         multiplier = SR_KHZ(1);
483                         break;
484                 case 'm':
485                 case 'M':
486                         multiplier = SR_MHZ(1);
487                         break;
488                 case 'g':
489                 case 'G':
490                         multiplier = SR_GHZ(1);
491                         break;
492                 default:
493                         done = TRUE;
494                         s--;
495                 }
496                 s++;
497         }
498         if (multiplier > 0) {
499                 *size *= multiplier;
500                 *size += frac_part * multiplier;
501         } else
502                 *size += frac_part;
503
504         if (s && *s && g_ascii_strcasecmp(s, "Hz"))
505                 return SR_ERR;
506
507         return SR_OK;
508 }
509
510 /**
511  * Convert a "natural" string representation of a time value to an
512  * uint64_t value in milliseconds.
513  *
514  * E.g. a value of "3s" or "3 s" would be converted to 3000, a value
515  * of "15ms" would be converted to 15.
516  *
517  * Value representations other than decimal (such as hex or octal) are not
518  * supported. Only lower-case "s" and "ms" time suffixes are supported.
519  * Spaces (but not other whitespace) between value and suffix are allowed.
520  *
521  * @param timestring A string containing a (decimal) time value.
522  * @return The string's time value as uint64_t, in milliseconds.
523  *
524  * @todo Add support for "m" (minutes) and others.
525  * @todo Add support for picoseconds?
526  * @todo Allow both lower-case and upper-case? If no, document it.
527  *
528  * @since 0.1.0
529  */
530 SR_API uint64_t sr_parse_timestring(const char *timestring)
531 {
532         uint64_t time_msec;
533         char *s;
534
535         /* TODO: Error handling, logging. */
536
537         time_msec = strtoull(timestring, &s, 10);
538         if (time_msec == 0 && s == timestring)
539                 return 0;
540
541         if (s && *s) {
542                 while (*s == ' ')
543                         s++;
544                 if (!strcmp(s, "s"))
545                         time_msec *= 1000;
546                 else if (!strcmp(s, "ms"))
547                         ; /* redundant */
548                 else
549                         return 0;
550         }
551
552         return time_msec;
553 }
554
555 /** @since 0.1.0 */
556 SR_API gboolean sr_parse_boolstring(const char *boolstr)
557 {
558         if (!boolstr)
559                 return FALSE;
560
561         if (!g_ascii_strncasecmp(boolstr, "true", 4) ||
562             !g_ascii_strncasecmp(boolstr, "yes", 3) ||
563             !g_ascii_strncasecmp(boolstr, "on", 2) ||
564             !g_ascii_strncasecmp(boolstr, "1", 1))
565                 return TRUE;
566
567         return FALSE;
568 }
569
570 /** @since 0.2.0 */
571 SR_API int sr_parse_period(const char *periodstr, uint64_t *p, uint64_t *q)
572 {
573         char *s;
574
575         *p = strtoull(periodstr, &s, 10);
576         if (*p == 0 && s == periodstr)
577                 /* No digits found. */
578                 return SR_ERR_ARG;
579
580         if (s && *s) {
581                 while (*s == ' ')
582                         s++;
583                 if (!strcmp(s, "fs"))
584                         *q = 1000000000000000ULL;
585                 else if (!strcmp(s, "ps"))
586                         *q = 1000000000000ULL;
587                 else if (!strcmp(s, "ns"))
588                         *q = 1000000000ULL;
589                 else if (!strcmp(s, "us"))
590                         *q = 1000000;
591                 else if (!strcmp(s, "ms"))
592                         *q = 1000;
593                 else if (!strcmp(s, "s"))
594                         *q = 1;
595                 else
596                         /* Must have a time suffix. */
597                         return SR_ERR_ARG;
598         }
599
600         return SR_OK;
601 }
602
603 /** @since 0.2.0 */
604 SR_API int sr_parse_voltage(const char *voltstr, uint64_t *p, uint64_t *q)
605 {
606         char *s;
607
608         *p = strtoull(voltstr, &s, 10);
609         if (*p == 0 && s == voltstr)
610                 /* No digits found. */
611                 return SR_ERR_ARG;
612
613         if (s && *s) {
614                 while (*s == ' ')
615                         s++;
616                 if (!g_ascii_strcasecmp(s, "mv"))
617                         *q = 1000L;
618                 else if (!g_ascii_strcasecmp(s, "v"))
619                         *q = 1;
620                 else
621                         /* Must have a base suffix. */
622                         return SR_ERR_ARG;
623         }
624
625         return SR_OK;
626 }
627
628 /** @} */