]> sigrok.org Git - libsigrok.git/blob - strutil.c
40ffc4dc7ccce2895fd1413640f8054e34fb7177
[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  * 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
48  * failure.
49  *
50  * @param str The string representation to convert.
51  * @param ret Pointer to long where the result of the conversion will be stored.
52  *
53  * @return SR_OK if conversion is successful, otherwise SR_ERR.
54  *
55  * @since 0.3.0
56  */
57 SR_PRIV int sr_atol(const char *str, long *ret)
58 {
59         long tmp;
60         char *endptr = NULL;
61
62         errno = 0;
63         tmp = strtol(str, &endptr, 0);
64
65         if (!endptr || *endptr || errno) {
66                 if (!errno)
67                         errno = EINVAL;
68                 return SR_ERR;
69         }
70
71         *ret = tmp;
72         return SR_OK;
73 }
74
75 /**
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
79  * failure.
80  *
81  * @param str The string representation to convert.
82  * @param ret Pointer to int where the result of the conversion will be stored.
83  *
84  * @return SR_OK if conversion is successful, otherwise SR_ERR.
85  *
86  * @since 0.3.0
87  */
88 SR_PRIV int sr_atoi(const char *str, int *ret)
89 {
90         long tmp;
91
92         if (sr_atol(str, &tmp) != SR_OK)
93                 return SR_ERR;
94
95         if ((int) tmp != tmp) {
96                 errno = ERANGE;
97                 return SR_ERR;
98         }
99
100         *ret = (int) tmp;
101         return SR_OK;
102 }
103
104 /**
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
108  * failure.
109  *
110  * @param str The string representation to convert.
111  * @param ret Pointer to double where the result of the conversion will be stored.
112  *
113  * @return SR_OK if conversion is successful, otherwise SR_ERR.
114  *
115  * @since 0.3.0
116  */
117 SR_PRIV int sr_atod(const char *str, double *ret)
118 {
119         double tmp;
120         char *endptr = NULL;
121
122         errno = 0;
123         tmp = strtof(str, &endptr);
124
125         if (!endptr || *endptr || errno) {
126                 if (!errno)
127                         errno = EINVAL;
128                 return SR_ERR;
129         }
130
131         *ret = tmp;
132         return SR_OK;
133 }
134
135 /**
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
139  * failure.
140  *
141  * @param str The string representation to convert.
142  * @param ret Pointer to float where the result of the conversion will be stored.
143  *
144  * @return SR_OK if conversion is successful, otherwise SR_ERR.
145  *
146  * @since 0.3.0
147  */
148 SR_PRIV int sr_atof(const char *str, float *ret)
149 {
150         double tmp;
151
152         if (sr_atod(str, &tmp) != SR_OK)
153                 return SR_ERR;
154
155         if ((float) tmp != tmp) {
156                 errno = ERANGE;
157                 return SR_ERR;
158         }
159
160         *ret = (float) tmp;
161         return SR_OK;
162 }
163
164 /**
165  * Convert a numeric value value to its "natural" string representation
166  * in SI units.
167  *
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".
170  *
171  * @param x The value to convert.
172  * @param unit The unit to append to the string, or NULL if the string
173  *             has no units.
174  *
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
177  *         memory.
178  */
179 SR_API char *sr_si_string_u64(uint64_t x, const char *unit)
180 {
181         uint8_t i;
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),
185         };
186         const char *p, prefix[] = "\0kMGTPE";
187         char fmt[8], fract[20] = "", *f;
188
189         if (unit == NULL)
190                 unit = "";
191
192         for (i = 0; (quot = x / divisor[i]) >= 1000; i++);
193
194         if (i) {
195                 sprintf(fmt, ".%%0%dlu", i * 3);
196                 f = fract + sprintf(fract, fmt, x % divisor[i]) - 1;
197
198                 while (f >= fract && strchr("0.", *f))
199                         *f-- = 0;
200         }
201
202         p = prefix + i;
203
204         return g_strdup_printf("%" PRIu64 "%s %.1s%s", quot, fract, p, unit);
205 }
206
207 /**
208  * Convert a numeric samplerate value to its "natural" string representation.
209  *
210  * E.g. a value of 3000000 would be converted to "3 MHz", 20000 to "20 kHz",
211  * 31500 would become "31.5 kHz".
212  *
213  * @param samplerate The samplerate in Hz.
214  *
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
217  *         memory.
218  */
219 SR_API char *sr_samplerate_string(uint64_t samplerate)
220 {
221         return sr_si_string_u64(samplerate, "Hz");
222 }
223
224 /**
225  * Convert a numeric frequency value to the "natural" string representation
226  * of its period.
227  *
228  * E.g. a value of 3000000 would be converted to "3 us", 20000 to "50 ms".
229  *
230  * @param frequency The frequency in Hz.
231  *
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
234  *         memory.
235  */
236 SR_API char *sr_period_string(uint64_t frequency)
237 {
238         char *o;
239         int r;
240
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__);
244                 return NULL;
245         }
246
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);
253         else
254                 r = snprintf(o, 30, "%" PRIu64 " s", frequency);
255
256         if (r < 0) {
257                 /* Something went wrong... */
258                 g_free(o);
259                 return NULL;
260         }
261
262         return o;
263 }
264
265 /**
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.
269  *
270  * E.g. a value of 300000 would be converted to "300mV", 2 to "2V".
271  *
272  * @param v_p The voltage numerator.
273  * @param v_q The voltage denominator.
274  *
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
277  *         memory.
278  */
279 SR_API char *sr_voltage_string(uint64_t v_p, uint64_t v_q)
280 {
281         int r;
282         char *o;
283
284         if (!(o = g_try_malloc0(30 + 1))) {
285                 sr_err("%s: o malloc failed", __func__);
286                 return NULL;
287         }
288
289         if (v_q == 1000)
290                 r = snprintf(o, 30, "%" PRIu64 "mV", v_p);
291         else if (v_q == 1)
292                 r = snprintf(o, 30, "%" PRIu64 "V", v_p);
293         else
294                 r = snprintf(o, 30, "%gV", (float)v_p / (float)v_q);
295
296         if (r < 0) {
297                 /* Something went wrong... */
298                 g_free(o);
299                 return NULL;
300         }
301
302         return o;
303 }
304
305 /**
306  * Parse a trigger specification string.
307  *
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"
319  *
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).
327  */
328 SR_API char **sr_parse_triggerstring(const struct sr_dev_inst *sdi,
329                                      const char *triggerstring)
330 {
331         GSList *l;
332         GVariant *gvar;
333         struct sr_probe *probe;
334         int max_probes, probenum, i;
335         char **tokens, **triggerlist, *trigger, *tc;
336         const char *trigger_types;
337         gboolean error;
338
339         max_probes = g_slist_length(sdi->probes);
340         error = FALSE;
341
342         if (!(triggerlist = g_try_malloc0(max_probes * sizeof(char *)))) {
343                 sr_err("%s: triggerlist malloc failed", __func__);
344                 return NULL;
345         }
346
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__);
350                 return NULL;
351         }
352         trigger_types = g_variant_get_string(gvar, NULL);
353
354         tokens = g_strsplit(triggerstring, ",", max_probes);
355         for (i = 0; tokens[i]; i++) {
356                 probenum = -1;
357                 for (l = sdi->probes; l; l = l->next) {
358                         probe = (struct sr_probe *)l->data;
359                         if (probe->enabled
360                                 && !strncmp(probe->name, tokens[i],
361                                         strlen(probe->name))) {
362                                 probenum = probe->index;
363                                 break;
364                         }
365                 }
366
367                 if (probenum < 0 || probenum >= max_probes) {
368                         sr_err("Invalid probe.");
369                         error = TRUE;
370                         break;
371                 }
372
373                 if ((trigger = strchr(tokens[i], '='))) {
374                         for (tc = ++trigger; *tc; tc++) {
375                                 if (strchr(trigger_types, *tc) == NULL) {
376                                         sr_err("Unsupported trigger "
377                                                "type '%c'.", *tc);
378                                         error = TRUE;
379                                         break;
380                                 }
381                         }
382                         if (!error)
383                                 triggerlist[probenum] = g_strdup(trigger);
384                 }
385         }
386         g_strfreev(tokens);
387         g_variant_unref(gvar);
388
389         if (error) {
390                 for (i = 0; i < max_probes; i++)
391                         g_free(triggerlist[i]);
392                 g_free(triggerlist);
393                 triggerlist = NULL;
394         }
395
396         return triggerlist;
397 }
398
399 /**
400  * Convert a "natural" string representation of a size value to uint64_t.
401  *
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.
404  *
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.
408  *
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.
411  *
412  * @return SR_OK upon success, SR_ERR upon errors.
413  */
414 SR_API int sr_parse_sizestring(const char *sizestring, uint64_t *size)
415 {
416         int multiplier, done;
417         char *s;
418
419         *size = strtoull(sizestring, &s, 10);
420         multiplier = 0;
421         done = FALSE;
422         while (s && *s && multiplier == 0 && !done) {
423                 switch (*s) {
424                 case ' ':
425                         break;
426                 case 'k':
427                 case 'K':
428                         multiplier = SR_KHZ(1);
429                         break;
430                 case 'm':
431                 case 'M':
432                         multiplier = SR_MHZ(1);
433                         break;
434                 case 'g':
435                 case 'G':
436                         multiplier = SR_GHZ(1);
437                         break;
438                 default:
439                         done = TRUE;
440                         s--;
441                 }
442                 s++;
443         }
444         if (multiplier > 0)
445                 *size *= multiplier;
446
447         if (*s && strcasecmp(s, "Hz"))
448                 return SR_ERR;
449
450         return SR_OK;
451 }
452
453 /**
454  * Convert a "natural" string representation of a time value to an
455  * uint64_t value in milliseconds.
456  *
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.
459  *
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.
463  *
464  * @param timestring A string containing a (decimal) time value.
465  * @return The string's time value as uint64_t, in milliseconds.
466  *
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.
470  */
471 SR_API uint64_t sr_parse_timestring(const char *timestring)
472 {
473         uint64_t time_msec;
474         char *s;
475
476         /* TODO: Error handling, logging. */
477
478         time_msec = strtoull(timestring, &s, 10);
479         if (time_msec == 0 && s == timestring)
480                 return 0;
481
482         if (s && *s) {
483                 while (*s == ' ')
484                         s++;
485                 if (!strcmp(s, "s"))
486                         time_msec *= 1000;
487                 else if (!strcmp(s, "ms"))
488                         ; /* redundant */
489                 else
490                         return 0;
491         }
492
493         return time_msec;
494 }
495
496 SR_API gboolean sr_parse_boolstring(const char *boolstr)
497 {
498         if (!boolstr)
499                 return FALSE;
500
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))
505                 return TRUE;
506
507         return FALSE;
508 }
509
510 SR_API int sr_parse_period(const char *periodstr, uint64_t *p, uint64_t *q)
511 {
512         char *s;
513
514         *p = strtoull(periodstr, &s, 10);
515         if (*p == 0 && s == periodstr)
516                 /* No digits found. */
517                 return SR_ERR_ARG;
518
519         if (s && *s) {
520                 while (*s == ' ')
521                         s++;
522                 if (!strcmp(s, "fs"))
523                         *q = 1000000000000000ULL;
524                 else if (!strcmp(s, "ps"))
525                         *q = 1000000000000ULL;
526                 else if (!strcmp(s, "ns"))
527                         *q = 1000000000ULL;
528                 else if (!strcmp(s, "us"))
529                         *q = 1000000;
530                 else if (!strcmp(s, "ms"))
531                         *q = 1000;
532                 else if (!strcmp(s, "s"))
533                         *q = 1;
534                 else
535                         /* Must have a time suffix. */
536                         return SR_ERR_ARG;
537         }
538
539         return SR_OK;
540 }
541
542
543 SR_API int sr_parse_voltage(const char *voltstr, uint64_t *p, uint64_t *q)
544 {
545         char *s;
546
547         *p = strtoull(voltstr, &s, 10);
548         if (*p == 0 && s == voltstr)
549                 /* No digits found. */
550                 return SR_ERR_ARG;
551
552         if (s && *s) {
553                 while (*s == ' ')
554                         s++;
555                 if (!strcasecmp(s, "mv"))
556                         *q = 1000L;
557                 else if (!strcasecmp(s, "v"))
558                         *q = 1;
559                 else
560                         /* Must have a base suffix. */
561                         return SR_ERR_ARG;
562         }
563
564         return SR_OK;
565 }
566
567 /** @} */