]> sigrok.org Git - libsigrok.git/blob - strutil.c
c147b961eb94a6c1aeb2dc4468aa97f388771950
[libsigrok.git] / strutil.c
1 /*
2  * This file is part of the sigrok 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 "libsigrok.h"
25 #include "libsigrok-internal.h"
26
27 /**
28  * @defgroup grp_strutil String utilities
29  *
30  * Helper functions for handling or converting libsigrok-related strings.
31  *
32  * @{
33  */
34
35 /**
36  * Convert a numeric value value to its "natural" string representation.
37  * in SI units
38  *
39  * E.g. a value of 3000000, with units set to "W", would be converted
40  * to "3 MW", 20000 to "20 kW", 31500 would become "31.5 kW".
41  *
42  * @param x The value to convert.
43  * @param unit The unit to append to the string, or NULL if the string
44  *             has no units.
45  *
46  * @return A g_try_malloc()ed string representation of the samplerate value,
47  *         or NULL upon errors. The caller is responsible to g_free() the
48  *         memory.
49  */
50 SR_API char *sr_si_string_u64(uint64_t x, const char *unit)
51 {
52         if(unit == NULL)
53                 unit = "";
54
55         if ((x >= SR_GHZ(1)) && (x % SR_GHZ(1) == 0)) {
56                 return g_strdup_printf("%" PRIu64 " G%s", x / SR_GHZ(1), unit);
57         } else if ((x >= SR_GHZ(1)) && (x % SR_GHZ(1) != 0)) {
58                 return g_strdup_printf("%" PRIu64 ".%" PRIu64 " G%s",
59                                        x / SR_GHZ(1), x % SR_GHZ(1), unit);
60         } else if ((x >= SR_MHZ(1)) && (x % SR_MHZ(1) == 0)) {
61                 return g_strdup_printf("%" PRIu64 " M%s",
62                                        x / SR_MHZ(1), unit);
63         } else if ((x >= SR_MHZ(1)) && (x % SR_MHZ(1) != 0)) {
64                 return g_strdup_printf("%" PRIu64 ".%" PRIu64 " M%s",
65                                     x / SR_MHZ(1), x % SR_MHZ(1), unit);
66         } else if ((x >= SR_KHZ(1)) && (x % SR_KHZ(1) == 0)) {
67                 return g_strdup_printf("%" PRIu64 " k%s",
68                                     x / SR_KHZ(1), unit);
69         } else if ((x >= SR_KHZ(1)) && (x % SR_KHZ(1) != 0)) {
70                 return g_strdup_printf("%" PRIu64 ".%" PRIu64 " k%s",
71                                     x / SR_KHZ(1), x % SR_KHZ(1), unit);
72         } else {
73                 return g_strdup_printf("%" PRIu64 " %s", x, unit);
74         }
75
76         sr_err("strutil: %s: Error creating SI units string.",
77                 __func__);
78         return NULL;
79 }
80
81 /**
82  * Convert a numeric samplerate value to its "natural" string representation.
83  *
84  * E.g. a value of 3000000 would be converted to "3 MHz", 20000 to "20 kHz",
85  * 31500 would become "31.5 kHz".
86  *
87  * @param samplerate The samplerate in Hz.
88  *
89  * @return A g_try_malloc()ed string representation of the samplerate value,
90  *         or NULL upon errors. The caller is responsible to g_free() the
91  *         memory.
92  */
93 SR_API char *sr_samplerate_string(uint64_t samplerate)
94 {
95         return sr_si_string_u64(samplerate, "Hz");
96 }
97
98 /**
99  * Convert a numeric frequency value to the "natural" string representation
100  * of its period.
101  *
102  * E.g. a value of 3000000 would be converted to "3 us", 20000 to "50 ms".
103  *
104  * @param frequency The frequency in Hz.
105  *
106  * @return A g_try_malloc()ed string representation of the frequency value,
107  *         or NULL upon errors. The caller is responsible to g_free() the
108  *         memory.
109  */
110 SR_API char *sr_period_string(uint64_t frequency)
111 {
112         char *o;
113         int r;
114
115         /* Allocate enough for a uint64_t as string + " ms". */
116         if (!(o = g_try_malloc0(30 + 1))) {
117                 sr_err("strutil: %s: o malloc failed", __func__);
118                 return NULL;
119         }
120
121         if (frequency >= SR_GHZ(1))
122                 r = snprintf(o, 30, "%" PRIu64 " ns", frequency / 1000000000);
123         else if (frequency >= SR_MHZ(1))
124                 r = snprintf(o, 30, "%" PRIu64 " us", frequency / 1000000);
125         else if (frequency >= SR_KHZ(1))
126                 r = snprintf(o, 30, "%" PRIu64 " ms", frequency / 1000);
127         else
128                 r = snprintf(o, 30, "%" PRIu64 " s", frequency);
129
130         if (r < 0) {
131                 /* Something went wrong... */
132                 g_free(o);
133                 return NULL;
134         }
135
136         return o;
137 }
138
139 /**
140  * Convert a numeric frequency value to the "natural" string representation
141  * of its voltage value.
142  *
143  * E.g. a value of 300000 would be converted to "300mV", 2 to "2V".
144  *
145  * @param voltage The voltage represented as a rational number, with the
146  *                denominator a divisor of 1V.
147  *
148  * @return A g_try_malloc()ed string representation of the voltage value,
149  *         or NULL upon errors. The caller is responsible to g_free() the
150  *         memory.
151  */
152 SR_API char *sr_voltage_string(struct sr_rational *voltage)
153 {
154         char *o;
155         int r;
156
157         if (!(o = g_try_malloc0(30 + 1))) {
158                 sr_err("strutil: %s: o malloc failed", __func__);
159                 return NULL;
160         }
161
162         if (voltage->q == 1000)
163                 r = snprintf(o, 30, "%" PRIu64 "mV", voltage->p);
164         else if (voltage->q == 1)
165                 r = snprintf(o, 30, "%" PRIu64 "V", voltage->p);
166         else
167                 r = -1;
168
169         if (r < 0) {
170                 /* Something went wrong... */
171                 g_free(o);
172                 return NULL;
173         }
174
175         return o;
176 }
177
178 /**
179  * Parse a trigger specification string.
180  *
181  * @param sdi The device instance for which the trigger specification is
182  *            intended. Must not be NULL. Also, sdi->driver and
183  *            sdi->driver->info_get must not be NULL.
184  * @param triggerstring The string containing the trigger specification for
185  *        one or more probes of this device. Entries for multiple probes are
186  *        comma-separated. Triggers are specified in the form key=value,
187  *        where the key is a probe number (or probe name) and the value is
188  *        the requested trigger type. Valid trigger types currently
189  *        include 'r' (rising edge), 'f' (falling edge), 'c' (any pin value
190  *        change), '0' (low value), or '1' (high value).
191  *        Example: "1=r,sck=f,miso=0,7=c"
192  *
193  * @return Pointer to a list of trigger types (strings), or NULL upon errors.
194  *         The pointer list (if non-NULL) has as many entries as the
195  *         respective device has probes (all physically available probes,
196  *         not just enabled ones). Entries of the list which don't have
197  *         a trigger value set in 'triggerstring' are NULL, the other entries
198  *         contain the respective trigger type which is requested for the
199  *         respective probe (e.g. "r", "c", and so on).
200  */
201 SR_API char **sr_parse_triggerstring(const struct sr_dev_inst *sdi,
202                                      const char *triggerstring)
203 {
204         GSList *l;
205         struct sr_probe *probe;
206         int max_probes, probenum, i;
207         char **tokens, **triggerlist, *trigger, *tc;
208         const char *trigger_types;
209         gboolean error;
210
211         max_probes = g_slist_length(sdi->probes);
212         error = FALSE;
213
214         if (!(triggerlist = g_try_malloc0(max_probes * sizeof(char *)))) {
215                 sr_err("strutil: %s: triggerlist malloc failed", __func__);
216                 return NULL;
217         }
218
219         if (sdi->driver->info_get(SR_DI_TRIGGER_TYPES,
220                         (const void **)&trigger_types, sdi) != SR_OK) {
221                 sr_err("strutil: %s: Device doesn't support any triggers.", __func__);
222                 return NULL;
223         }
224
225         tokens = g_strsplit(triggerstring, ",", max_probes);
226         for (i = 0; tokens[i]; i++) {
227                 probenum = -1;
228                 for (l = sdi->probes; l; l = l->next) {
229                         probe = (struct sr_probe *)l->data;
230                         if (probe->enabled
231                                 && !strncmp(probe->name, tokens[i],
232                                         strlen(probe->name))) {
233                                 probenum = probe->index;
234                                 break;
235                         }
236                 }
237
238                 if (probenum < 0 || probenum >= max_probes) {
239                         sr_err("strutil: Invalid probe.");
240                         error = TRUE;
241                         break;
242                 }
243
244                 if ((trigger = strchr(tokens[i], '='))) {
245                         for (tc = ++trigger; *tc; tc++) {
246                                 if (strchr(trigger_types, *tc) == NULL) {
247                                         sr_err("strutil: Unsupported trigger "
248                                                "type '%c'.", *tc);
249                                         error = TRUE;
250                                         break;
251                                 }
252                         }
253                         if (!error)
254                                 triggerlist[probenum] = g_strdup(trigger);
255                 }
256         }
257         g_strfreev(tokens);
258
259         if (error) {
260                 for (i = 0; i < max_probes; i++)
261                         g_free(triggerlist[i]);
262                 g_free(triggerlist);
263                 triggerlist = NULL;
264         }
265
266         return triggerlist;
267 }
268
269 /**
270  * Convert a "natural" string representation of a size value to uint64_t.
271  *
272  * E.g. a value of "3k" or "3 K" would be converted to 3000, a value
273  * of "15M" would be converted to 15000000.
274  *
275  * Value representations other than decimal (such as hex or octal) are not
276  * supported. Only 'k' (kilo), 'm' (mega), 'g' (giga) suffixes are supported.
277  * Spaces (but not other whitespace) between value and suffix are allowed.
278  *
279  * @param sizestring A string containing a (decimal) size value.
280  * @param size Pointer to uint64_t which will contain the string's size value.
281  *
282  * @return SR_OK upon success, SR_ERR upon errors.
283  */
284 SR_API int sr_parse_sizestring(const char *sizestring, uint64_t *size)
285 {
286         int multiplier, done;
287         char *s;
288
289         *size = strtoull(sizestring, &s, 10);
290         multiplier = 0;
291         done = FALSE;
292         while (s && *s && multiplier == 0 && !done) {
293                 switch (*s) {
294                 case ' ':
295                         break;
296                 case 'k':
297                 case 'K':
298                         multiplier = SR_KHZ(1);
299                         break;
300                 case 'm':
301                 case 'M':
302                         multiplier = SR_MHZ(1);
303                         break;
304                 case 'g':
305                 case 'G':
306                         multiplier = SR_GHZ(1);
307                         break;
308                 default:
309                         done = TRUE;
310                         s--;
311                 }
312                 s++;
313         }
314         if (multiplier > 0)
315                 *size *= multiplier;
316
317         if (*s && strcasecmp(s, "Hz"))
318                 return SR_ERR;
319
320         return SR_OK;
321 }
322
323 /**
324  * Convert a "natural" string representation of a time value to an
325  * uint64_t value in milliseconds.
326  *
327  * E.g. a value of "3s" or "3 s" would be converted to 3000, a value
328  * of "15ms" would be converted to 15.
329  *
330  * Value representations other than decimal (such as hex or octal) are not
331  * supported. Only lower-case "s" and "ms" time suffixes are supported.
332  * Spaces (but not other whitespace) between value and suffix are allowed.
333  *
334  * @param timestring A string containing a (decimal) time value.
335  * @return The string's time value as uint64_t, in milliseconds.
336  *
337  * @todo Add support for "m" (minutes) and others.
338  * @todo Add support for picoseconds?
339  * @todo Allow both lower-case and upper-case? If no, document it.
340  */
341 SR_API uint64_t sr_parse_timestring(const char *timestring)
342 {
343         uint64_t time_msec;
344         char *s;
345
346         /* TODO: Error handling, logging. */
347
348         time_msec = strtoull(timestring, &s, 10);
349         if (time_msec == 0 && s == timestring)
350                 return 0;
351
352         if (s && *s) {
353                 while (*s == ' ')
354                         s++;
355                 if (!strcmp(s, "s"))
356                         time_msec *= 1000;
357                 else if (!strcmp(s, "ms"))
358                         ; /* redundant */
359                 else
360                         return 0;
361         }
362
363         return time_msec;
364 }
365
366 SR_API gboolean sr_parse_boolstring(const char *boolstr)
367 {
368         if (!boolstr)
369                 return FALSE;
370
371         if (!g_ascii_strncasecmp(boolstr, "true", 4) ||
372             !g_ascii_strncasecmp(boolstr, "yes", 3) ||
373             !g_ascii_strncasecmp(boolstr, "on", 2) ||
374             !g_ascii_strncasecmp(boolstr, "1", 1))
375                 return TRUE;
376
377         return FALSE;
378 }
379
380 SR_API int sr_parse_period(const char *periodstr, struct sr_rational *r)
381 {
382         char *s;
383
384         r->p = strtoull(periodstr, &s, 10);
385         if (r->p == 0 && s == periodstr)
386                 /* No digits found. */
387                 return SR_ERR_ARG;
388
389         if (s && *s) {
390                 while (*s == ' ')
391                         s++;
392                 if (!strcmp(s, "ns"))
393                         r->q = 1000000000L;
394                 else if (!strcmp(s, "us"))
395                         r->q = 1000000;
396                 else if (!strcmp(s, "ms"))
397                         r->q = 1000;
398                 else if (!strcmp(s, "s"))
399                         r->q = 1;
400                 else
401                         /* Must have a time suffix. */
402                         return SR_ERR_ARG;
403         }
404
405         return SR_OK;
406 }
407
408
409 SR_API int sr_parse_voltage(const char *voltstr, struct sr_rational *r)
410 {
411         char *s;
412
413         r->p = strtoull(voltstr, &s, 10);
414         if (r->p == 0 && s == voltstr)
415                 /* No digits found. */
416                 return SR_ERR_ARG;
417
418         if (s && *s) {
419                 while (*s == ' ')
420                         s++;
421                 if (!strcasecmp(s, "mv"))
422                         r->q = 1000L;
423                 else if (!strcasecmp(s, "v"))
424                         r->q = 1;
425                 else
426                         /* Must have a base suffix. */
427                         return SR_ERR_ARG;
428         }
429
430         return SR_OK;
431 }
432
433 /** @} */