]> sigrok.org Git - libsigrok.git/blob - strutil.c
output/csv: use intermediate time_t var, silence compiler warning
[libsigrok.git] / 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, write to the Free Software
18  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
19  */
20
21 #include <stdint.h>
22 #include <stdlib.h>
23 #include <string.h>
24 #include <errno.h>
25 #include "libsigrok.h"
26 #include "libsigrok-internal.h"
27
28 #define LOG_PREFIX "strutil"
29
30 /**
31  * @file
32  *
33  * Helper functions for handling or converting libsigrok-related strings.
34  */
35
36 /**
37  * @defgroup grp_strutil String utilities
38  *
39  * Helper functions for handling or converting libsigrok-related strings.
40  *
41  * @{
42  */
43
44 /**
45  * @private
46  *
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
50  * failure.
51  *
52  * @param str The string representation to convert.
53  * @param ret Pointer to long where the result of the conversion will be stored.
54  *
55  * @return SR_OK if conversion is successful, otherwise SR_ERR.
56  *
57  * @since 0.3.0
58  */
59 SR_PRIV int sr_atol(const char *str, long *ret)
60 {
61         long tmp;
62         char *endptr = NULL;
63
64         errno = 0;
65         tmp = strtol(str, &endptr, 0);
66
67         if (!endptr || *endptr || errno) {
68                 if (!errno)
69                         errno = EINVAL;
70                 return SR_ERR;
71         }
72
73         *ret = tmp;
74         return SR_OK;
75 }
76
77 /**
78  * @private
79  *
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
83  * failure.
84  *
85  * @param str The string representation to convert.
86  * @param ret Pointer to int where the result of the conversion will be stored.
87  *
88  * @return SR_OK if conversion is successful, otherwise SR_ERR.
89  *
90  * @since 0.3.0
91  */
92 SR_PRIV int sr_atoi(const char *str, int *ret)
93 {
94         long tmp;
95
96         if (sr_atol(str, &tmp) != SR_OK)
97                 return SR_ERR;
98
99         if ((int) tmp != tmp) {
100                 errno = ERANGE;
101                 return SR_ERR;
102         }
103
104         *ret = (int) tmp;
105         return SR_OK;
106 }
107
108 /**
109  * @private
110  *
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
114  * failure.
115  *
116  * @param str The string representation to convert.
117  * @param ret Pointer to double where the result of the conversion will be stored.
118  *
119  * @return SR_OK if conversion is successful, otherwise SR_ERR.
120  *
121  * @since 0.3.0
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  * @return SR_OK if conversion is successful, otherwise SR_ERR.
153  *
154  * @since 0.3.0
155  */
156 SR_PRIV int sr_atof(const char *str, float *ret)
157 {
158         double tmp;
159
160         if (sr_atod(str, &tmp) != SR_OK)
161                 return SR_ERR;
162
163         if ((float) tmp != tmp) {
164                 errno = ERANGE;
165                 return SR_ERR;
166         }
167
168         *ret = (float) tmp;
169         return SR_OK;
170 }
171
172 /**
173  * @private
174  *
175  * Convert a string representation of a numeric value to a float. The
176  * conversion is strict and will fail if the complete string does not represent
177  * a valid float. The function sets errno according to the details of the
178  * failure. This version ignores the locale.
179  *
180  * @param str The string representation to convert.
181  * @param ret Pointer to float where the result of the conversion will be stored.
182  *
183  * @return SR_OK if conversion is successful, otherwise SR_ERR.
184  *
185  * @since 0.3.0
186  */
187 SR_PRIV int sr_atof_ascii(const char *str, float *ret)
188 {
189         double tmp;
190         char *endptr = NULL;
191
192         errno = 0;
193         tmp = g_ascii_strtod(str, &endptr);
194
195         if (!endptr || *endptr || errno) {
196                 if (!errno)
197                         errno = EINVAL;
198                 return SR_ERR;
199         }
200
201         /* FIXME This fails unexpectedly. Some other method to safel downcast
202          * needs to be found. Checking against FLT_MAX doesn't work as well. */
203         /*
204         if ((float) tmp != tmp) {
205                 errno = ERANGE;
206                 sr_dbg("ERANGEEEE %e != %e", (float) tmp, tmp);
207                 return SR_ERR;
208         }
209         */
210
211         *ret = (float) tmp;
212         return SR_OK;
213 }
214
215 /**
216  * Convert a numeric value value to its "natural" string representation
217  * in SI units.
218  *
219  * E.g. a value of 3000000, with units set to "W", would be converted
220  * to "3 MW", 20000 to "20 kW", 31500 would become "31.5 kW".
221  *
222  * @param x The value to convert.
223  * @param unit The unit to append to the string, or NULL if the string
224  *             has no units.
225  *
226  * @return A g_try_malloc()ed string representation of the samplerate value,
227  *         or NULL upon errors. The caller is responsible to g_free() the
228  *         memory.
229  */
230 SR_API char *sr_si_string_u64(uint64_t x, const char *unit)
231 {
232         uint8_t i;
233         uint64_t quot, divisor[] = {
234                 SR_HZ(1), SR_KHZ(1), SR_MHZ(1), SR_GHZ(1),
235                 SR_GHZ(1000), SR_GHZ(1000 * 1000), SR_GHZ(1000 * 1000 * 1000),
236         };
237         const char *p, prefix[] = "\0kMGTPE";
238         char fmt[16], fract[20] = "", *f;
239
240         if (unit == NULL)
241                 unit = "";
242
243         for (i = 0; (quot = x / divisor[i]) >= 1000; i++);
244
245         if (i) {
246                 sprintf(fmt, ".%%0%d"PRIu64, i * 3);
247                 f = fract + sprintf(fract, fmt, x % divisor[i]) - 1;
248
249                 while (f >= fract && strchr("0.", *f))
250                         *f-- = 0;
251         }
252
253         p = prefix + i;
254
255         return g_strdup_printf("%" PRIu64 "%s %.1s%s", quot, fract, p, unit);
256 }
257
258 /**
259  * Convert a numeric samplerate value to its "natural" string representation.
260  *
261  * E.g. a value of 3000000 would be converted to "3 MHz", 20000 to "20 kHz",
262  * 31500 would become "31.5 kHz".
263  *
264  * @param samplerate The samplerate in Hz.
265  *
266  * @return A g_try_malloc()ed string representation of the samplerate value,
267  *         or NULL upon errors. The caller is responsible to g_free() the
268  *         memory.
269  */
270 SR_API char *sr_samplerate_string(uint64_t samplerate)
271 {
272         return sr_si_string_u64(samplerate, "Hz");
273 }
274
275 /**
276  * Convert a numeric frequency value to the "natural" string representation
277  * of its period.
278  *
279  * E.g. a value of 3000000 would be converted to "3 us", 20000 to "50 ms".
280  *
281  * @param frequency The frequency in Hz.
282  *
283  * @return A g_try_malloc()ed string representation of the frequency value,
284  *         or NULL upon errors. The caller is responsible to g_free() the
285  *         memory.
286  */
287 SR_API char *sr_period_string(uint64_t frequency)
288 {
289         char *o;
290         int r;
291
292         /* Allocate enough for a uint64_t as string + " ms". */
293         if (!(o = g_try_malloc0(30 + 1))) {
294                 sr_err("%s: o malloc failed", __func__);
295                 return NULL;
296         }
297
298         if (frequency >= SR_GHZ(1))
299                 r = snprintf(o, 30, "%" PRIu64 " ns", frequency / 1000000000);
300         else if (frequency >= SR_MHZ(1))
301                 r = snprintf(o, 30, "%" PRIu64 " us", frequency / 1000000);
302         else if (frequency >= SR_KHZ(1))
303                 r = snprintf(o, 30, "%" PRIu64 " ms", frequency / 1000);
304         else
305                 r = snprintf(o, 30, "%" PRIu64 " s", frequency);
306
307         if (r < 0) {
308                 /* Something went wrong... */
309                 g_free(o);
310                 return NULL;
311         }
312
313         return o;
314 }
315
316 /**
317  * Convert a numeric voltage value to the "natural" string representation
318  * of its voltage value. The voltage is specified as a rational number's
319  * numerator and denominator.
320  *
321  * E.g. a value of 300000 would be converted to "300mV", 2 to "2V".
322  *
323  * @param v_p The voltage numerator.
324  * @param v_q The voltage denominator.
325  *
326  * @return A g_try_malloc()ed string representation of the voltage value,
327  *         or NULL upon errors. The caller is responsible to g_free() the
328  *         memory.
329  */
330 SR_API char *sr_voltage_string(uint64_t v_p, uint64_t v_q)
331 {
332         int r;
333         char *o;
334
335         if (!(o = g_try_malloc0(30 + 1))) {
336                 sr_err("%s: o malloc failed", __func__);
337                 return NULL;
338         }
339
340         if (v_q == 1000)
341                 r = snprintf(o, 30, "%" PRIu64 "mV", v_p);
342         else if (v_q == 1)
343                 r = snprintf(o, 30, "%" PRIu64 "V", v_p);
344         else
345                 r = snprintf(o, 30, "%gV", (float)v_p / (float)v_q);
346
347         if (r < 0) {
348                 /* Something went wrong... */
349                 g_free(o);
350                 return NULL;
351         }
352
353         return o;
354 }
355
356 /**
357  * Parse a trigger specification string.
358  *
359  * @param sdi The device instance for which the trigger specification is
360  *            intended. Must not be NULL. Also, sdi->driver and
361  *            sdi->driver->info_get must not be NULL.
362  * @param triggerstring The string containing the trigger specification for
363  *        one or more channels of this device. Entries for multiple channels are
364  *        comma-separated. Triggers are specified in the form key=value,
365  *        where the key is a channel number (or channel name) and the value is
366  *        the requested trigger type. Valid trigger types currently
367  *        include 'r' (rising edge), 'f' (falling edge), 'c' (any pin value
368  *        change), '0' (low value), or '1' (high value).
369  *        Example: "1=r,sck=f,miso=0,7=c"
370  *
371  * @return Pointer to a list of trigger types (strings), or NULL upon errors.
372  *         The pointer list (if non-NULL) has as many entries as the
373  *         respective device has channels (all physically available channels,
374  *         not just enabled ones). Entries of the list which don't have
375  *         a trigger value set in 'triggerstring' are NULL, the other entries
376  *         contain the respective trigger type which is requested for the
377  *         respective channel (e.g. "r", "c", and so on).
378  */
379 SR_API char **sr_parse_triggerstring(const struct sr_dev_inst *sdi,
380                                      const char *triggerstring)
381 {
382         GSList *l;
383         GVariant *gvar;
384         struct sr_channel *ch;
385         int max_channels, channelnum, i;
386         char **tokens, **triggerlist, *trigger, *tc;
387         const char *trigger_types;
388         gboolean error;
389
390         max_channels = g_slist_length(sdi->channels);
391         error = FALSE;
392
393         if (!(triggerlist = g_try_malloc0(max_channels * sizeof(char *)))) {
394                 sr_err("%s: triggerlist malloc failed", __func__);
395                 return NULL;
396         }
397
398         if (sdi->driver->config_list(SR_CONF_TRIGGER_TYPE,
399                                 &gvar, sdi, NULL) != SR_OK) {
400                 sr_err("%s: Device doesn't support any triggers.", __func__);
401                 return NULL;
402         }
403         trigger_types = g_variant_get_string(gvar, NULL);
404
405         tokens = g_strsplit(triggerstring, ",", max_channels);
406         for (i = 0; tokens[i]; i++) {
407                 channelnum = -1;
408                 for (l = sdi->channels; l; l = l->next) {
409                         ch = (struct sr_channel *)l->data;
410                         if (ch->enabled
411                                 && !strncmp(ch->name, tokens[i],
412                                         strlen(ch->name))) {
413                                 channelnum = ch->index;
414                                 break;
415                         }
416                 }
417
418                 if (channelnum < 0 || channelnum >= max_channels) {
419                         sr_err("Invalid channel.");
420                         error = TRUE;
421                         break;
422                 }
423
424                 if ((trigger = strchr(tokens[i], '='))) {
425                         for (tc = ++trigger; *tc; tc++) {
426                                 if (strchr(trigger_types, *tc) == NULL) {
427                                         sr_err("Unsupported trigger "
428                                                "type '%c'.", *tc);
429                                         error = TRUE;
430                                         break;
431                                 }
432                         }
433                         if (!error)
434                                 triggerlist[channelnum] = g_strdup(trigger);
435                 }
436         }
437         g_strfreev(tokens);
438         g_variant_unref(gvar);
439
440         if (error) {
441                 for (i = 0; i < max_channels; i++)
442                         g_free(triggerlist[i]);
443                 g_free(triggerlist);
444                 triggerlist = NULL;
445         }
446
447         return triggerlist;
448 }
449
450 /**
451  * Convert a "natural" string representation of a size value to uint64_t.
452  *
453  * E.g. a value of "3k" or "3 K" would be converted to 3000, a value
454  * of "15M" would be converted to 15000000.
455  *
456  * Value representations other than decimal (such as hex or octal) are not
457  * supported. Only 'k' (kilo), 'm' (mega), 'g' (giga) suffixes are supported.
458  * Spaces (but not other whitespace) between value and suffix are allowed.
459  *
460  * @param sizestring A string containing a (decimal) size value.
461  * @param size Pointer to uint64_t which will contain the string's size value.
462  *
463  * @return SR_OK upon success, SR_ERR upon errors.
464  */
465 SR_API int sr_parse_sizestring(const char *sizestring, uint64_t *size)
466 {
467         int multiplier, done;
468         double frac_part;
469         char *s;
470
471         *size = strtoull(sizestring, &s, 10);
472         multiplier = 0;
473         frac_part = 0;
474         done = FALSE;
475         while (s && *s && multiplier == 0 && !done) {
476                 switch (*s) {
477                 case ' ':
478                         break;
479                 case '.':
480                         frac_part = g_ascii_strtod(s, &s);
481                         break;
482                 case 'k':
483                 case 'K':
484                         multiplier = SR_KHZ(1);
485                         break;
486                 case 'm':
487                 case 'M':
488                         multiplier = SR_MHZ(1);
489                         break;
490                 case 'g':
491                 case 'G':
492                         multiplier = SR_GHZ(1);
493                         break;
494                 default:
495                         done = TRUE;
496                         s--;
497                 }
498                 s++;
499         }
500         if (multiplier > 0) {
501                 *size *= multiplier;
502                 *size += frac_part * multiplier;
503         } else
504                 *size += frac_part;
505
506         if (*s && strcasecmp(s, "Hz"))
507                 return SR_ERR;
508
509         return SR_OK;
510 }
511
512 /**
513  * Convert a "natural" string representation of a time value to an
514  * uint64_t value in milliseconds.
515  *
516  * E.g. a value of "3s" or "3 s" would be converted to 3000, a value
517  * of "15ms" would be converted to 15.
518  *
519  * Value representations other than decimal (such as hex or octal) are not
520  * supported. Only lower-case "s" and "ms" time suffixes are supported.
521  * Spaces (but not other whitespace) between value and suffix are allowed.
522  *
523  * @param timestring A string containing a (decimal) time value.
524  * @return The string's time value as uint64_t, in milliseconds.
525  *
526  * @todo Add support for "m" (minutes) and others.
527  * @todo Add support for picoseconds?
528  * @todo Allow both lower-case and upper-case? If no, document it.
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 SR_API gboolean sr_parse_boolstring(const char *boolstr)
556 {
557         if (!boolstr)
558                 return FALSE;
559
560         if (!g_ascii_strncasecmp(boolstr, "true", 4) ||
561             !g_ascii_strncasecmp(boolstr, "yes", 3) ||
562             !g_ascii_strncasecmp(boolstr, "on", 2) ||
563             !g_ascii_strncasecmp(boolstr, "1", 1))
564                 return TRUE;
565
566         return FALSE;
567 }
568
569 SR_API int sr_parse_period(const char *periodstr, uint64_t *p, uint64_t *q)
570 {
571         char *s;
572
573         *p = strtoull(periodstr, &s, 10);
574         if (*p == 0 && s == periodstr)
575                 /* No digits found. */
576                 return SR_ERR_ARG;
577
578         if (s && *s) {
579                 while (*s == ' ')
580                         s++;
581                 if (!strcmp(s, "fs"))
582                         *q = 1000000000000000ULL;
583                 else if (!strcmp(s, "ps"))
584                         *q = 1000000000000ULL;
585                 else if (!strcmp(s, "ns"))
586                         *q = 1000000000ULL;
587                 else if (!strcmp(s, "us"))
588                         *q = 1000000;
589                 else if (!strcmp(s, "ms"))
590                         *q = 1000;
591                 else if (!strcmp(s, "s"))
592                         *q = 1;
593                 else
594                         /* Must have a time suffix. */
595                         return SR_ERR_ARG;
596         }
597
598         return SR_OK;
599 }
600
601
602 SR_API int sr_parse_voltage(const char *voltstr, uint64_t *p, uint64_t *q)
603 {
604         char *s;
605
606         *p = strtoull(voltstr, &s, 10);
607         if (*p == 0 && s == voltstr)
608                 /* No digits found. */
609                 return SR_ERR_ARG;
610
611         if (s && *s) {
612                 while (*s == ' ')
613                         s++;
614                 if (!strcasecmp(s, "mv"))
615                         *q = 1000L;
616                 else if (!strcasecmp(s, "v"))
617                         *q = 1;
618                 else
619                         /* Must have a base suffix. */
620                         return SR_ERR_ARG;
621         }
622
623         return SR_OK;
624 }
625
626 /** @} */