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