forked from sigrokproject/libsigrok
-
Notifications
You must be signed in to change notification settings - Fork 2
/
strutil.c
1927 lines (1738 loc) · 48.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
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* 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/>.
*/
/* Needed for POSIX.1-2008 locale functions */
/** @cond PRIVATE */
#define _XOPEN_SOURCE 700
/** @endcond */
#include <config.h>
#include <ctype.h>
#include <locale.h>
#if defined(__FreeBSD__) || defined(__APPLE__)
#include <xlocale.h>
#endif
#if defined(__FreeBSD__)
#include <sys/param.h>
#endif
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <errno.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.
*
* @{
*/
/**
* 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.
*
* @private
*/
SR_PRIV int sr_atol(const char *str, long *ret)
{
long tmp;
char *endptr = NULL;
errno = 0;
tmp = strtol(str, &endptr, 10);
while (endptr && isspace(*endptr))
endptr++;
if (!endptr || *endptr || errno) {
if (!errno)
errno = EINVAL;
return SR_ERR;
}
*ret = tmp;
return SR_OK;
}
/**
* Convert a text to a number including support for non-decimal bases.
* Also optionally returns the position after the number, where callers
* can either error out, or support application specific suffixes.
*
* @param[in] str The input text to convert.
* @param[out] ret The conversion result.
* @param[out] end The position after the number.
* @param[in] base The number format's base, can be 0.
*
* @retval SR_OK Conversion successful.
* @retval SR_ERR Conversion failed.
*
* @private
*
* This routine is more general than @ref sr_atol(), which strictly
* expects the input text to contain just a decimal number, and nothing
* else in addition. The @ref sr_atol_base() routine accepts trailing
* text after the number, and supports non-decimal numbers (bin, hex),
* including automatic detection from prefix text.
*/
SR_PRIV int sr_atol_base(const char *str, long *ret, char **end, int base)
{
long num;
char *endptr;
/* Add "0b" prefix support which strtol(3) may be missing. */
while (str && isspace(*str))
str++;
if (!base && strncmp(str, "0b", strlen("0b")) == 0) {
str += strlen("0b");
base = 2;
}
/* Run the number conversion. Quick bail out if that fails. */
errno = 0;
endptr = NULL;
num = strtol(str, &endptr, base);
if (!endptr || errno) {
if (!errno)
errno = EINVAL;
return SR_ERR;
}
*ret = num;
/* Advance to optional non-space trailing suffix. */
while (endptr && isspace(*endptr))
endptr++;
if (end)
*end = endptr;
return SR_OK;
}
/**
* Convert a text to a number including support for non-decimal bases.
* Also optionally returns the position after the number, where callers
* can either error out, or support application specific suffixes.
*
* @param[in] str The input text to convert.
* @param[out] ret The conversion result.
* @param[out] end The position after the number.
* @param[in] base The number format's base, can be 0.
*
* @retval SR_OK Conversion successful.
* @retval SR_ERR Conversion failed.
*
* @private
*
* This routine is more general than @ref sr_atol(), which strictly
* expects the input text to contain just a decimal number, and nothing
* else in addition. The @ref sr_atoul_base() routine accepts trailing
* text after the number, and supports non-decimal numbers (bin, hex),
* including automatic detection from prefix text.
*/
SR_PRIV int sr_atoul_base(const char *str, unsigned long *ret, char **end, int base)
{
unsigned long num;
char *endptr;
/* Add "0b" prefix support which strtol(3) may be missing. */
while (str && isspace(*str))
str++;
if ((!base || base == 2) && strncmp(str, "0b", strlen("0b")) == 0) {
str += strlen("0b");
base = 2;
}
/* Run the number conversion. Quick bail out if that fails. */
errno = 0;
endptr = NULL;
num = strtoul(str, &endptr, base);
if (!endptr || errno) {
if (!errno)
errno = EINVAL;
return SR_ERR;
}
*ret = num;
/* Advance to optional non-space trailing suffix. */
while (endptr && isspace(*endptr))
endptr++;
if (end)
*end = endptr;
return SR_OK;
}
/**
* 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.
*
* @private
*/
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;
}
/**
* 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.
*
* @private
*/
SR_PRIV int sr_atod(const char *str, double *ret)
{
double tmp;
char *endptr = NULL;
errno = 0;
tmp = strtof(str, &endptr);
while (endptr && isspace(*endptr))
endptr++;
if (!endptr || *endptr || errno) {
if (!errno)
errno = EINVAL;
return SR_ERR;
}
*ret = tmp;
return SR_OK;
}
/**
* 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.
*
* @private
*/
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;
}
/**
* 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. This version ignores the locale.
*
* @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.
*
* @private
*/
SR_PRIV int sr_atod_ascii(const char *str, double *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;
}
*ret = tmp;
return SR_OK;
}
/**
* Convert text to a floating point value, and get its precision.
*
* @param[in] str The input text to convert.
* @param[out] ret The conversion result, a double precision float number.
* @param[out] digits The number of significant decimals.
*
* @returns SR_OK in case of successful text to number conversion.
* @returns SR_ERR when conversion fails.
*
* @since 0.6.0
*/
SR_PRIV int sr_atod_ascii_digits(const char *str, double *ret, int *digits)
{
int d;
double f;
if (sr_count_digits(str, &d) != SR_OK || sr_atod_ascii(str, &f) != SR_OK)
return SR_ERR;
if (ret)
*ret = f;
if (digits)
*digits = d;
return SR_OK;
}
/**
* 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.
*
* @private
*/
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 text to a floating point value, and get its precision.
*
* @param[in] str The input text to convert.
* @param[out] ret The conversion result, a double precision float number.
* @param[out] digits The number of significant decimals.
*
* @returns SR_OK in case of successful text to number conversion.
* @returns SR_ERR when conversion fails.
*/
SR_PRIV int sr_atof_ascii_digits(const char *str, float *ret, int *digits)
{
int d;
float f;
if (sr_count_digits(str, &d) != SR_OK || sr_atof_ascii(str, &f) != SR_OK)
return SR_ERR;
if (ret)
*ret = f;
if (digits)
*digits = d;
return SR_OK;
}
/**
* Get the precision of a floating point number.
*
* @param[in] str The input text to convert.
* @param[out] digits The number of significant decimals.
*
* @returns SR_OK in case of successful.
* @returns SR_ERR when conversion fails.
*
* @private
*/
SR_PRIV int sr_count_digits(const char *str, int *digits)
{
const char *p = str;
char *exp_end;
int d_int = 0;
int d_dec = 0;
int exp = 0;
/* Skip leading spaces */
while ((*p) && isspace(*p))
p++;
/* Skip the integer part */
if ((*p == '-') || (*p == '+'))
p++;
while (isdigit(*p)) {
d_int++;
p++;
}
/* Count decimal digits. */
if (*p == '.') {
p++;
while (isdigit(*p)) {
p++;
d_dec++;
}
}
/* Parse the exponent */
if (toupper(*p) == 'E') {
p++;
errno = 0;
exp = strtol(p, &exp_end, 10);
if (errno) {
sr_spew("Failed to parse exponent: txt \"%s\", e \"%s\"",
str, p);
return SR_ERR;
}
p = exp_end;
}
sr_spew("count digits: txt \"%s\" -> d_int %d, d_dec %d, e %d "
"-> digits %d\n",
str, d_int, d_dec, exp, d_dec - exp);
/* We should have parsed the whole string by now. Return an
* error if not. */
if ((*p) || (d_dec == 0 && d_int == 0)) {
return SR_ERR;
}
*digits = d_dec - exp;
return SR_OK;
}
/**
* Compose a string with a format string in the buffer pointed to by buf.
*
* It is up to the caller to ensure that the allocated buffer is large enough
* to hold the formatted result.
*
* A terminating NUL character is automatically appended after the content
* written.
*
* After the format parameter, the function expects at least as many additional
* arguments as needed for format.
*
* This version ignores the current locale and uses the locale "C" for Linux,
* FreeBSD, OSX and Android.
*
* @param buf Pointer to a buffer where the resulting C string is stored.
* @param format C string that contains a format string (see printf).
* @param ... A sequence of additional arguments, each containing a value to be
* used to replace a format specifier in the format string.
*
* @return On success, the number of characters that would have been written,
* not counting the terminating NUL character.
*
* @since 0.6.0
*/
SR_API int sr_sprintf_ascii(char *buf, const char *format, ...)
{
int ret;
va_list args;
va_start(args, format);
ret = sr_vsprintf_ascii(buf, format, args);
va_end(args);
return ret;
}
/**
* Compose a string with a format string in the buffer pointed to by buf.
*
* It is up to the caller to ensure that the allocated buffer is large enough
* to hold the formatted result.
*
* Internally, the function retrieves arguments from the list identified by
* args as if va_arg was used on it, and thus the state of args is likely to
* be altered by the call.
*
* In any case, args should have been initialized by va_start at some point
* before the call, and it is expected to be released by va_end at some point
* after the call.
*
* This version ignores the current locale and uses the locale "C" for Linux,
* FreeBSD, OSX and Android.
*
* @param buf Pointer to a buffer where the resulting C string is stored.
* @param format C string that contains a format string (see printf).
* @param args A value identifying a variable arguments list initialized with
* va_start.
*
* @return On success, the number of characters that would have been written,
* not counting the terminating NUL character.
*
* @since 0.6.0
*/
SR_API int sr_vsprintf_ascii(char *buf, const char *format, va_list args)
{
#if defined(_WIN32)
int ret;
#if 0
/*
* TODO: This part compiles with mingw-w64 but doesn't run with Win7.
* Doesn't start because of "Procedure entry point _create_locale
* not found in msvcrt.dll".
* mingw-w64 should link to msvcr100.dll not msvcrt.dll!
* See: https://msdn.microsoft.com/en-us/en-en/library/1kt27hek.aspx
*/
_locale_t locale;
locale = _create_locale(LC_NUMERIC, "C");
ret = _vsprintf_l(buf, format, locale, args);
_free_locale(locale);
#endif
/* vsprintf() uses the current locale, may not work correctly for floats. */
ret = vsprintf(buf, format, args);
return ret;
#elif defined(__APPLE__)
/*
* See:
* https://developer.apple.com/legacy/library/documentation/Darwin/Reference/ManPages/man3/printf_l.3.html
* https://developer.apple.com/legacy/library/documentation/Darwin/Reference/ManPages/man3/xlocale.3.html
*/
int ret;
locale_t locale;
locale = newlocale(LC_NUMERIC_MASK, "C", NULL);
ret = vsprintf_l(buf, locale, format, args);
freelocale(locale);
return ret;
#elif defined(__FreeBSD__) && __FreeBSD_version >= 901000
/*
* See:
* https://www.freebsd.org/cgi/man.cgi?query=printf_l&apropos=0&sektion=3&manpath=FreeBSD+9.1-RELEASE
* https://www.freebsd.org/cgi/man.cgi?query=xlocale&apropos=0&sektion=3&manpath=FreeBSD+9.1-RELEASE
*/
int ret;
locale_t locale;
locale = newlocale(LC_NUMERIC_MASK, "C", NULL);
ret = vsprintf_l(buf, locale, format, args);
freelocale(locale);
return ret;
#elif defined(__ANDROID__)
/*
* The Bionic libc only has two locales ("C" aka "POSIX" and "C.UTF-8"
* aka "en_US.UTF-8"). The decimal point is hard coded as "."
* See: https://android.googlesource.com/platform/bionic/+/master/libc/bionic/locale.cpp
*/
int ret;
ret = vsprintf(buf, format, args);
return ret;
#elif defined(__linux__)
int ret;
locale_t old_locale, temp_locale;
/* Switch to C locale for proper float/double conversion. */
temp_locale = newlocale(LC_NUMERIC, "C", NULL);
old_locale = uselocale(temp_locale);
ret = vsprintf(buf, format, args);
/* Switch back to original locale. */
uselocale(old_locale);
freelocale(temp_locale);
return ret;
#elif defined(__unix__) || defined(__unix)
/*
* This is a fallback for all other BSDs, *nix and FreeBSD <= 9.0, by
* using the current locale for snprintf(). This may not work correctly
* for floats!
*/
int ret;
ret = vsprintf(buf, format, args);
return ret;
#else
/* No implementation for unknown systems! */
return -1;
#endif
}
/**
* Composes a string with a format string (like printf) in the buffer pointed
* by buf (taking buf_size as the maximum buffer capacity to fill).
* If the resulting string would be longer than n - 1 characters, the remaining
* characters are discarded and not stored, but counted for the value returned
* by the function.
* A terminating NUL character is automatically appended after the content
* written.
* After the format parameter, the function expects at least as many additional
* arguments as needed for format.
*
* This version ignores the current locale and uses the locale "C" for Linux,
* FreeBSD, OSX and Android.
*
* @param buf Pointer to a buffer where the resulting C string is stored.
* @param buf_size Maximum number of bytes to be used in the buffer. The
* generated string has a length of at most buf_size - 1, leaving space
* for the additional terminating NUL character.
* @param format C string that contains a format string (see printf).
* @param ... A sequence of additional arguments, each containing a value to be
* used to replace a format specifier in the format string.
*
* @return On success, the number of characters that would have been written if
* buf_size had been sufficiently large, not counting the terminating
* NUL character. On failure, a negative number is returned.
* Notice that only when this returned value is non-negative and less
* than buf_size, the string has been completely written.
*
* @since 0.6.0
*/
SR_API int sr_snprintf_ascii(char *buf, size_t buf_size,
const char *format, ...)
{
int ret;
va_list args;
va_start(args, format);
ret = sr_vsnprintf_ascii(buf, buf_size, format, args);
va_end(args);
return ret;
}
/**
* Composes a string with a format string (like printf) in the buffer pointed
* by buf (taking buf_size as the maximum buffer capacity to fill).
* If the resulting string would be longer than n - 1 characters, the remaining
* characters are discarded and not stored, but counted for the value returned
* by the function.
* A terminating NUL character is automatically appended after the content
* written.
* Internally, the function retrieves arguments from the list identified by
* args as if va_arg was used on it, and thus the state of args is likely to
* be altered by the call.
* In any case, arg should have been initialized by va_start at some point
* before the call, and it is expected to be released by va_end at some point
* after the call.
*
* This version ignores the current locale and uses the locale "C" for Linux,
* FreeBSD, OSX and Android.
*
* @param buf Pointer to a buffer where the resulting C string is stored.
* @param buf_size Maximum number of bytes to be used in the buffer. The
* generated string has a length of at most buf_size - 1, leaving space
* for the additional terminating NUL character.
* @param format C string that contains a format string (see printf).
* @param args A value identifying a variable arguments list initialized with
* va_start.
*
* @return On success, the number of characters that would have been written if
* buf_size had been sufficiently large, not counting the terminating
* NUL character. On failure, a negative number is returned.
* Notice that only when this returned value is non-negative and less
* than buf_size, the string has been completely written.
*
* @since 0.6.0
*/
SR_API int sr_vsnprintf_ascii(char *buf, size_t buf_size,
const char *format, va_list args)
{
#if defined(_WIN32)
int ret;
#if 0
/*
* TODO: This part compiles with mingw-w64 but doesn't run with Win7.
* Doesn't start because of "Procedure entry point _create_locale
* not found in msvcrt.dll".
* mingw-w64 should link to msvcr100.dll not msvcrt.dll!.
* See: https://msdn.microsoft.com/en-us/en-en/library/1kt27hek.aspx
*/
_locale_t locale;
locale = _create_locale(LC_NUMERIC, "C");
ret = _vsnprintf_l(buf, buf_size, format, locale, args);
_free_locale(locale);
#endif
/* vsprintf uses the current locale, may cause issues for floats. */
ret = vsnprintf(buf, buf_size, format, args);
return ret;
#elif defined(__APPLE__)
/*
* See:
* https://developer.apple.com/legacy/library/documentation/Darwin/Reference/ManPages/man3/printf_l.3.html
* https://developer.apple.com/legacy/library/documentation/Darwin/Reference/ManPages/man3/xlocale.3.html
*/
int ret;
locale_t locale;
locale = newlocale(LC_NUMERIC_MASK, "C", NULL);
ret = vsnprintf_l(buf, buf_size, locale, format, args);
freelocale(locale);
return ret;
#elif defined(__FreeBSD__) && __FreeBSD_version >= 901000
/*
* See:
* https://www.freebsd.org/cgi/man.cgi?query=printf_l&apropos=0&sektion=3&manpath=FreeBSD+9.1-RELEASE
* https://www.freebsd.org/cgi/man.cgi?query=xlocale&apropos=0&sektion=3&manpath=FreeBSD+9.1-RELEASE
*/
int ret;
locale_t locale;
locale = newlocale(LC_NUMERIC_MASK, "C", NULL);
ret = vsnprintf_l(buf, buf_size, locale, format, args);
freelocale(locale);
return ret;
#elif defined(__ANDROID__)
/*
* The Bionic libc only has two locales ("C" aka "POSIX" and "C.UTF-8"
* aka "en_US.UTF-8"). The decimal point is hard coded as ".".
* See: https://android.googlesource.com/platform/bionic/+/master/libc/bionic/locale.cpp
*/
int ret;
ret = vsnprintf(buf, buf_size, format, args);
return ret;
#elif defined(__linux__)
int ret;
locale_t old_locale, temp_locale;
/* Switch to C locale for proper float/double conversion. */
temp_locale = newlocale(LC_NUMERIC, "C", NULL);
old_locale = uselocale(temp_locale);
ret = vsnprintf(buf, buf_size, format, args);
/* Switch back to original locale. */
uselocale(old_locale);
freelocale(temp_locale);
return ret;
#elif defined(__unix__) || defined(__unix)
/*
* This is a fallback for all other BSDs, *nix and FreeBSD <= 9.0, by
* using the current locale for snprintf(). This may not work correctly
* for floats!
*/
int ret;
ret = vsnprintf(buf, buf_size, format, args);
return ret;
#else
/* No implementation for unknown systems! */
return -1;
#endif
}
/**
* Convert a sequence of bytes to its textual representation ("hex dump").
*
* Callers should free the allocated GString. See sr_hexdump_free().
*
* @param[in] data Pointer to the byte sequence to print.
* @param[in] len Number of bytes to print.
*
* @return NULL upon error, newly allocated GString pointer otherwise.
*
* @private
*/
SR_PRIV GString *sr_hexdump_new(const uint8_t *data, const size_t len)
{
GString *s;
size_t i;
i = 3 * len;
i += len / 8;
i += len / 16;
s = g_string_sized_new(i);
for (i = 0; i < len; i++) {
if (i)
g_string_append_c(s, ' ');
if (i && (i % 8) == 0)
g_string_append_c(s, ' ');
if (i && (i % 16) == 0)
g_string_append_c(s, ' ');
g_string_append_printf(s, "%02x", data[i]);
}
return s;
}
/**
* Free a hex dump text that was created by sr_hexdump_new().
*
* @param[in] s Pointer to the GString to release.
*
* @private
*/
SR_PRIV void sr_hexdump_free(GString *s)
{
if (s)
g_string_free(s, TRUE);
}
/**
* 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)
{
const char *readptr;
char *endptr;
gboolean is_negative, empty_integral, empty_fractional, exp_negative;
int64_t integral;
int64_t fractional;
int64_t denominator;
uint32_t fractional_len;
int32_t exponent;
/*
* Implementor's note: This routine tries hard to avoid calling
* glib's or the platform's conversion routines with input that
* cannot get converted *at all* (see bug #1093). It also takes
* care to return with non-zero errno values for any failed
* conversion attempt. It's assumed that correctness and robustness
* are more important than performance, which is why code paths
* are not optimized at all. Maintainability took priority.
*/
readptr = str;
/* Skip leading whitespace. */
while (isspace(*readptr))
readptr++;
/* Determine the sign, default to non-negative. */
is_negative = FALSE;
if (*readptr == '-') {
is_negative = TRUE;
readptr++;
} else if (*readptr == '+') {
is_negative = FALSE;
readptr++;
}
/* Get the (optional) integral part. */
empty_integral = TRUE;
integral = 0;
endptr = (char *)readptr;
errno = 0;
if (isdigit(*readptr)) {
empty_integral = FALSE;
integral = g_ascii_strtoll(readptr, &endptr, 10);
if (errno)
return SR_ERR;
if (endptr == str) {
errno = -EINVAL;
return SR_ERR;
}
readptr = endptr;
}
/* Get the optional fractional part. */
empty_fractional = TRUE;
fractional = 0;
fractional_len = 0;
if (*readptr == '.') {
readptr++;
endptr++;
errno = 0;
if (isdigit(*readptr)) {
empty_fractional = FALSE;
fractional = g_ascii_strtoll(readptr, &endptr, 10);
if (errno)
return SR_ERR;
if (endptr == readptr) {
errno = -EINVAL;
return SR_ERR;
}
fractional_len = endptr - readptr;
readptr = endptr;
}
}
/* At least one of integral or fractional is required. */
if (empty_integral && empty_fractional) {
errno = -EINVAL;
return SR_ERR;
}
/* Get the (optional) exponent. */
exponent = 0;
if ((*readptr == 'E') || (*readptr == 'e')) {
readptr++;
endptr++;
exp_negative = FALSE;
if (*readptr == '+') {
exp_negative = FALSE;
readptr++;
endptr++;
} else if (*readptr == '-') {
exp_negative = TRUE;
readptr++;
endptr++;
}
if (!isdigit(*readptr)) {
errno = -EINVAL;
return SR_ERR;
}
errno = 0;
exponent = g_ascii_strtoll(readptr, &endptr, 10);
if (errno)
return SR_ERR;
if (endptr == readptr) {
errno = -EINVAL;
return SR_ERR;
}
readptr = endptr;
if (exp_negative)
exponent = -exponent;
}