forked from symisc/sod
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sod.c
13961 lines (13321 loc) · 399 KB
/
sod.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
/*
* SOD - An Embedded Computer Vision & Machine Learning Library.
* Copyright (C) 2018 - 2019 PixLab| Symisc Systems. https://sod.pixlab.io
* Version 1.1.8
*
* Symisc Systems employs a dual licensing model that offers customers
* a choice of either our open source license (GPLv3) or a commercial
* license.
*
* For information on licensing, redistribution of the SOD library, and for a DISCLAIMER OF ALL WARRANTIES
* please visit:
* https://pixlab.io/sod
* or contact:
*/
/*
* This file is part of Symisc SOD - Open Source Release (GPLv3)
*
* SOD 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 3 of the License, or
* (at your option) any later version.
*
* SOD 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 SOD. If not, see <http://www.gnu.org/licenses/>.
*/
/* $SymiscID: sod.c v1.1.8 Win10 2018-02-02 05:34 stable <[email protected]> $ */
#ifdef _MSC_VER
#ifndef _CRT_SECURE_NO_WARNINGS
/*
* Ignore Microsoft compilers warnings on fopen() which is used only
* by the CNN layer for reading SOD models or saving Realnets models to disk.
*/
#define _CRT_SECURE_NO_WARNINGS
#endif /*_CRT_SECURE_NO_WARNINGS*/
/* Disable the double to float warning */
#pragma warning(disable:4244)
#pragma warning(disable:4305)
#endif /* _MSC_VER */
/* Standard C library includes */
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <stdint.h>
#include <ctype.h>
#ifdef SOD_MEM_DEBUG
/* Memory leak detection which is done under Visual Studio only */
#define _CRTDBG_MAP_ALLOC
#include <crtdbg.h>
#endif /* SOD_MEM_DEBUG */
#include <float.h>
#ifndef _USE_MATH_DEFINES
#define _USE_MATH_DEFINES
#endif /* _USE_MATH_DEFINES */
#include <math.h>
#include <string.h>
#include <limits.h>
/* Local includes */
#include "sod.h"
/* Forward declaration */
typedef struct SySet SySet;
typedef struct SyBlob SyBlob;
typedef struct SyString SyString;
typedef struct sod_vfs sod_vfs;
/*
* A generic dynamic set.
*/
struct SySet
{
void *pBase; /* Base pointer */
size_t nUsed; /* Total number of used slots */
size_t nSize; /* Total number of available slots */
size_t eSize; /* Size of a single slot */
void *pUserData; /* User private data associated with this container */
};
#define SySetBasePtr(S) ((S)->pBase)
#define SySetBasePtrJump(S, OFFT) (&((char *)(S)->pBase)[OFFT*(S)->eSize])
#define SySetUsed(S) ((S)->nUsed)
#define SySetSize(S) ((S)->nSize)
#define SySetElemSize(S) ((S)->eSize)
#define SySetSetUserData(S, DATA) ((S)->pUserData = DATA)
#define SySetGetUserData(S) ((S)->pUserData)
/*
* A variable length containers for generic data (Mostly dynamic string).
*/
struct SyBlob
{
void *pBlob; /* Base pointer */
size_t nByte; /* Total number of used bytes */
size_t mByte; /* Total number of available bytes */
int nFlags; /* Blob internal flags, see below */
};
/*
* Container for non null terminated strings.
*/
struct SyString
{
const char *zString; /* Raw string (May not be null terminated) */
size_t nByte; /* Raw string length */
};
#define SXBLOB_LOCKED 0x01 /* Blob is locked [i.e: Cannot auto grow] */
#define SXBLOB_STATIC 0x02 /* Not allocated from heap */
#define SXBLOB_RDONLY 0x04 /* Read-Only data */
#define SyBlobFreeSpace(BLOB) ((BLOB)->mByte - (BLOB)->nByte)
#define SyBlobLength(BLOB) ((BLOB)->nByte)
#define SyBlobData(BLOB) ((BLOB)->pBlob)
#define SyBlobCurData(BLOB) ((void*)(&((char*)(BLOB)->pBlob)[(BLOB)->nByte]))
#define SyBlobDataAt(BLOB, OFFT) ((void *)(&((char *)(BLOB)->pBlob)[OFFT]))
#define SyBlobGetAllocator(BLOB) ((BLOB)->pAllocator)
#define SyStringData(RAW) ((RAW)->zString)
#define SyStringLength(RAW) ((RAW)->nByte)
#define SyStringInitFromBuf(RAW, ZBUF, NLEN){\
(RAW)->zString = (const char *)ZBUF;\
(RAW)->nByte = (size_t)(NLEN);\
}
#define SyStringDupPtr(RAW1, RAW2)\
(RAW1)->zString = (RAW2)->zString;\
(RAW1)->nByte = (RAW2)->nByte;
#define SyStringTrimLeadingChar(RAW, CHAR)\
while((RAW)->nByte > 0 && (RAW)->zString[0] == CHAR ){\
(RAW)->zString++;\
(RAW)->nByte--;\
}
#define SyStringTrimTrailingChar(RAW, CHAR)\
while((RAW)->nByte > 0 && (RAW)->zString[(RAW)->nByte - 1] == CHAR){\
(RAW)->nByte--;\
}
#define SyStringCmp(RAW1, RAW2, xCMP)\
(((RAW1)->nByte == (RAW2)->nByte) ? xCMP((RAW1)->zString, (RAW2)->zString, (RAW2)->nByte) : (int)((RAW1)->nByte - (RAW2)->nByte))
/*
* value pathinfo(string $path [,int $options = PATHINFO_DIRNAME | PATHINFO_BASENAME | PATHINFO_EXTENSION | PATHINFO_FILENAME ])
* Returns information about a file path.
* Taken from the Symisc PH7 source tree, http://ph7.symisc.net
*/
typedef struct sod_path_info sod_path_info;
struct sod_path_info
{
SyString sDir; /* Directory [i.e: /var/www] */
SyString sBasename; /* Basename [i.e httpd.conf] */
SyString sExtension; /* File extension [i.e xml,pdf..] */
SyString sFilename; /* Filename */
};
#ifndef MAX
#define MAX(a, b) ((a)>(b)?(a):(b))
#endif /* MAX */
#ifndef MIN
#define MIN(a, b) ((a)<(b)?(a):(b))
#endif /* MIN */
/*
* CAPIREF: OS Interface Object
*
* An instance of the sod_vfs object defines the interface between
* the sod core and the underlying operating system. The "vfs"
* in the name of the object stands for "Virtual File System".
*
* Only a single vfs can be registered within the sod core.
* Vfs registration is done using the [sod_lib_config()] interface
* with a configuration verb set to LIBCOX_LIB_CONFIG_VFS.
* Note that Windows and UNIX (Linux, FreeBSD, Solaris, Mac OS X, etc.) users
* does not have to worry about registering and installing a vfs since sod
* come with a built-in vfs for these platforms that implements most the methods
* defined below.
*
* Clients running on exotic systems (ie: Other than Windows and UNIX systems)
* must register their own vfs in order to be able to use the sod library.
*
* The value of the iVersion field is initially 1 but may be larger in
* future versions of sod.
*
* The szOsFile field is the size of the subclassed [sod_file] structure
* used by this VFS. mxPathname is the maximum length of a pathname in this VFS.
*
* At least szOsFile bytes of memory are allocated by sod to hold the [sod_file]
* structure passed as the third argument to xOpen. The xOpen method does not have to
* allocate the structure; it should just fill it in. Note that the xOpen method must
* set the sod_file.pMethods to either a valid [sod_io_methods] object or to NULL.
* xOpen must do this even if the open fails. sod expects that the sod_file.pMethods
* element will be valid after xOpen returns regardless of the success or failure of the
* xOpen call.
*/
#define LIBCOX_VFS_VERSION 2900 /* 2.9 */
struct sod_vfs {
const char *zName; /* Name of this virtual file system [i.e: Windows, UNIX, etc.] */
int iVersion; /* Structure version number (currently 2.6) */
int szOsFile;
int mxPathname; /* Maximum file pathname length */
/* Directory functions */
int(*xChdir)(const char *); /* Change directory */
int(*xGetcwd)(SyBlob *); /* Get the current working directory */
int(*xMkdir)(const char *, int, int); /* Make directory */
int(*xRmdir)(const char *); /* Remove directory */
int(*xIsdir)(const char *); /* Tells whether the filename is a directory */
int(*xRename)(const char *, const char *); /* Renames a file or directory */
int(*xRealpath)(const char *, SyBlob *); /* Return canonicalized absolute pathname*/
/* Dir handle */
int(*xOpenDir)(const char *, void **); /* Open directory handle */
void(*xCloseDir)(void *pHandle); /* Close directory handle */
int(*xDirRead)(void *pHandle, SyBlob *); /* Read the next entry from the directory handle */
void(*xDirRewind)(void *pHandle); /* Rewind the cursor */
/* Systems functions */
int(*xUnlink)(const char *); /* Deletes a file */
int(*xFileExists)(const char *); /* Checks whether a file or directory exists */
int64_t(*xFreeSpace)(const char *); /* Available space on filesystem or disk partition */
int64_t(*xTotalSpace)(const char *); /* Total space on filesystem or disk partition */
int64_t(*xFileSize)(const char *); /* Gets file size */
int(*xIsfile)(const char *); /* Tells whether the filename is a regular file */
int(*xReadable)(const char *); /* Tells whether a file exists and is readable */
int(*xWritable)(const char *); /* Tells whether the filename is writable */
int(*xExecutable)(const char *); /* Tells whether the filename is executable */
int(*xGetenv)(const char *, SyBlob *); /* Gets the value of an environment variable */
int(*xSetenv)(const char *, const char *); /* Sets the value of an environment variable */
int(*xMmap)(const char *, void **, size_t *); /* Read-only memory map of the whole file */
void(*xUnmap)(void *, size_t); /* Unmap a memory view */
void(*xTempDir)(SyBlob *); /* Get path of the temporary directory */
float(*xTicks)(); /* High precision timer */
};
/* @Implementation */
static int SyBlobInit(SyBlob *pBlob)
{
pBlob->pBlob = 0;
pBlob->mByte = pBlob->nByte = 0;
pBlob->nFlags = 0;
return SOD_OK;
}
#ifndef SXBLOB_MIN_GROWTH
#define SXBLOB_MIN_GROWTH 16
#endif
static int BlobPrepareGrow(SyBlob *pBlob, size_t *pByte)
{
size_t nByte;
void *pNew;
nByte = *pByte;
if (pBlob->nFlags & (SXBLOB_LOCKED | SXBLOB_STATIC)) {
if (SyBlobFreeSpace(pBlob) < nByte) {
*pByte = SyBlobFreeSpace(pBlob);
if ((*pByte) == 0) {
return -1;
}
}
return SOD_OK;
}
if (pBlob->nFlags & SXBLOB_RDONLY) {
/* Make a copy of the read-only item */
if (pBlob->nByte > 0) {
pNew = realloc(pBlob->pBlob, pBlob->nByte);
if (pNew == 0) {
return SOD_OUTOFMEM;
}
pBlob->pBlob = pNew;
pBlob->mByte = pBlob->nByte;
}
else {
pBlob->pBlob = 0;
pBlob->mByte = 0;
}
/* Remove the read-only flag */
pBlob->nFlags &= ~SXBLOB_RDONLY;
}
if (SyBlobFreeSpace(pBlob) >= nByte) {
return SOD_OK;
}
if (pBlob->mByte > 0) {
nByte = nByte + pBlob->mByte * 2 + SXBLOB_MIN_GROWTH;
}
else if (nByte < SXBLOB_MIN_GROWTH) {
nByte = SXBLOB_MIN_GROWTH;
}
pNew = realloc(pBlob->pBlob, nByte);
if (pNew == 0) {
return SOD_OUTOFMEM;
}
pBlob->pBlob = pNew;
pBlob->mByte = nByte;
return SOD_OK;
}
static int SyBlobAppend(SyBlob *pBlob, const void *pData, size_t nSize)
{
uint8_t *zBlob;
int rc;
if (nSize < 1) {
return SOD_OK;
}
rc = BlobPrepareGrow(&(*pBlob), &nSize);
if (SOD_OK != rc) {
return rc;
}
if (pData) {
zBlob = (uint8_t *)pBlob->pBlob;
zBlob = &zBlob[pBlob->nByte];
pBlob->nByte += nSize;
memcpy(zBlob, pData, nSize);
}
return SOD_OK;
}
#define SyBlobStrAppend(pBlob,STR) SyBlobAppend(&(*pBlob), (const void *)STR,strlen(STR))
#define SyBlobNullAppend(pBlob) if( SOD_OK == SyBlobAppend(&(*pBlob), (const void *)"\0", sizeof(char)) ){(pBlob)->nByte--;}
static inline int SyBlobReset(SyBlob *pBlob)
{
pBlob->nByte = 0;
if (pBlob->nFlags & SXBLOB_RDONLY) {
/* Read-only (Not malloced chunk) */
pBlob->pBlob = 0;
pBlob->mByte = 0;
pBlob->nFlags &= ~SXBLOB_RDONLY;
}
return SOD_OK;
}
static int SyBlobRelease(SyBlob *pBlob)
{
if ((pBlob->nFlags & (SXBLOB_STATIC | SXBLOB_RDONLY)) == 0 && pBlob->mByte > 0) {
free(pBlob->pBlob);
}
pBlob->pBlob = 0;
pBlob->nByte = pBlob->mByte = 0;
pBlob->nFlags = 0;
return SOD_OK;
}
#ifdef SOD_ENABLE_NET_TRAIN
/* SyRunTimeApi: sxfmt.c */
#define SXFMT_BUFSIZ 1024 /* Conversion buffer size */
/* Signature of the consumer routine */
typedef int(*ProcConsumer)(const void *, unsigned int, void *);
/*
** Conversion types fall into various categories as defined by the
** following enumeration.
*/
#define SXFMT_RADIX 1 /* Integer types.%d, %x, %o, and so forth */
#define SXFMT_FLOAT 2 /* Floating point.%f */
#define SXFMT_EXP 3 /* Exponentional notation.%e and %E */
#define SXFMT_GENERIC 4 /* Floating or exponential, depending on exponent.%g */
#define SXFMT_SIZE 5 /* Total number of characters processed so far.%n */
#define SXFMT_STRING 6 /* Strings.%s */
#define SXFMT_PERCENT 7 /* Percent symbol.%% */
#define SXFMT_CHARX 8 /* Characters.%c */
#define SXFMT_ERROR 9 /* Used to indicate no such conversion type */
/* Extension by Symisc Systems */
#define SXFMT_RAWSTR 13 /* %z Pointer to raw string (SyString *) */
#define SXFMT_UNUSED 15
/*
** Allowed values for SyFmtInfo.flags
*/
#define SXFLAG_SIGNED 0x01
#define SXFLAG_UNSIGNED 0x02
/* Allowed values for SyFmtConsumer.nType */
#define SXFMT_CONS_PROC 1 /* Consumer is a procedure */
#define SXFMT_CONS_STR 2 /* Consumer is a managed string */
#define SXFMT_CONS_FILE 5 /* Consumer is an open File */
#define SXFMT_CONS_BLOB 6 /* Consumer is a BLOB */
/*
** Each built-in conversion character (ex: the 'd' in "%d") is described
** by an instance of the following structure
*/
typedef struct SyFmtInfo SyFmtInfo;
struct SyFmtInfo
{
char fmttype; /* The format field code letter [i.e: 'd', 's', 'x'] */
uint8_t base; /* The base for radix conversion */
int flags; /* One or more of SXFLAG_ constants below */
uint8_t type; /* Conversion paradigm */
char *charset; /* The character set for conversion */
char *prefix; /* Prefix on non-zero values in alt format */
};
typedef struct SyFmtConsumer SyFmtConsumer;
struct SyFmtConsumer
{
size_t nLen; /* Total output length */
int nType; /* Type of the consumer see below */
int rc; /* Consumer return value;Abort processing if rc != SOD_OK */
union {
struct {
ProcConsumer xUserConsumer;
void *pUserData;
}sFunc;
SyBlob *pBlob;
}uConsumer;
};
static int getdigit(long double *val, int *cnt)
{
long double d;
int digit;
if ((*cnt)++ >= 16) {
return '0';
}
digit = (int)*val;
d = digit;
*val = (*val - d)*10.0;
return digit + '0';
}
/*
* The following routine was taken from the SQLITE2 source tree and was
* extended by Symisc Systems to fit its need.
* Status: Public Domain
*/
static int InternFormat(ProcConsumer xConsumer, void *pUserData, const char *zFormat, va_list ap)
{
/*
* The following table is searched linearly, so it is good to put the most frequently
* used conversion types first.
*/
static const SyFmtInfo aFmt[] = {
{ 'd', 10, SXFLAG_SIGNED, SXFMT_RADIX, "0123456789", 0 },
{ 's', 0, 0, SXFMT_STRING, 0, 0 },
{ 'c', 0, 0, SXFMT_CHARX, 0, 0 },
{ 'x', 16, 0, SXFMT_RADIX, "0123456789abcdef", "x0" },
{ 'X', 16, 0, SXFMT_RADIX, "0123456789ABCDEF", "X0" },
/* -- Extensions by Symisc Systems -- */
{ 'z', 0, 0, SXFMT_RAWSTR, 0, 0 }, /* Pointer to a raw string (SyString *) */
{ 'B', 2, 0, SXFMT_RADIX, "01", "b0" },
/* -- End of Extensions -- */
{ 'o', 8, 0, SXFMT_RADIX, "01234567", "0" },
{ 'u', 10, 0, SXFMT_RADIX, "0123456789", 0 },
{ 'f', 0, SXFLAG_SIGNED, SXFMT_FLOAT, 0, 0 },
{ 'e', 0, SXFLAG_SIGNED, SXFMT_EXP, "e", 0 },
{ 'E', 0, SXFLAG_SIGNED, SXFMT_EXP, "E", 0 },
{ 'g', 0, SXFLAG_SIGNED, SXFMT_GENERIC, "e", 0 },
{ 'G', 0, SXFLAG_SIGNED, SXFMT_GENERIC, "E", 0 },
{ 'i', 10, SXFLAG_SIGNED, SXFMT_RADIX, "0123456789", 0 },
{ 'n', 0, 0, SXFMT_SIZE, 0, 0 },
{ '%', 0, 0, SXFMT_PERCENT, 0, 0 },
{ 'p', 10, 0, SXFMT_RADIX, "0123456789", 0 }
};
int c; /* Next character in the format string */
char *bufpt; /* Pointer to the conversion buffer */
int precision; /* Precision of the current field */
int length; /* Length of the field */
int idx; /* A general purpose loop counter */
int width; /* Width of the current field */
uint8_t flag_leftjustify; /* True if "-" flag is present */
uint8_t flag_plussign; /* True if "+" flag is present */
uint8_t flag_blanksign; /* True if " " flag is present */
uint8_t flag_alternateform; /* True if "#" flag is present */
uint8_t flag_zeropad; /* True if field width constant starts with zero */
uint8_t flag_long; /* True if "l" flag is present */
int64_t longvalue; /* Value for integer types */
const SyFmtInfo *infop; /* Pointer to the appropriate info structure */
char buf[SXFMT_BUFSIZ]; /* Conversion buffer */
char prefix; /* Prefix character."+" or "-" or " " or '\0'.*/
uint8_t errorflag = 0; /* True if an error is encountered */
uint8_t xtype; /* Conversion paradigm */
static char spaces[] = " ";
#define etSPACESIZE ((int)sizeof(spaces)-1)
long double realvalue; /* Value for real types */
int exp; /* exponent of real numbers */
double rounder; /* Used for rounding floating point values */
uint8_t flag_dp; /* True if decimal point should be shown */
uint8_t flag_rtz; /* True if trailing zeros should be removed */
uint8_t flag_exp; /* True to force display of the exponent */
int nsd; /* Number of significant digits returned */
int rc;
length = 0;
bufpt = 0;
for (; (c = (*zFormat)) != 0; ++zFormat) {
if (c != '%') {
unsigned int amt;
bufpt = (char *)zFormat;
amt = 1;
while ((c = (*++zFormat)) != '%' && c != 0) amt++;
rc = xConsumer((const void *)bufpt, amt, pUserData);
if (rc != SOD_OK) {
return SOD_ABORT; /* Consumer routine request an operation abort */
}
if (c == 0) {
return errorflag > 0 ? -1 : SOD_OK;
}
}
if ((c = (*++zFormat)) == 0) {
errorflag = 1;
rc = xConsumer("%", sizeof("%") - 1, pUserData);
if (rc != SOD_OK) {
return SOD_ABORT; /* Consumer routine request an operation abort */
}
return errorflag > 0 ? -1 : SOD_OK;
}
/* Find out what flags are present */
flag_leftjustify = flag_plussign = flag_blanksign =
flag_alternateform = flag_zeropad = 0;
do {
switch (c) {
case '-': flag_leftjustify = 1; c = 0; break;
case '+': flag_plussign = 1; c = 0; break;
case ' ': flag_blanksign = 1; c = 0; break;
case '#': flag_alternateform = 1; c = 0; break;
case '0': flag_zeropad = 1; c = 0; break;
default: break;
}
} while (c == 0 && (c = (*++zFormat)) != 0);
/* Get the field width */
width = 0;
if (c == '*') {
width = va_arg(ap, int);
if (width<0) {
flag_leftjustify = 1;
width = -width;
}
c = *++zFormat;
}
else {
while (c >= '0' && c <= '9') {
width = width * 10 + c - '0';
c = *++zFormat;
}
}
if (width > SXFMT_BUFSIZ - 10) {
width = SXFMT_BUFSIZ - 10;
}
/* Get the precision */
precision = -1;
if (c == '.') {
precision = 0;
c = *++zFormat;
if (c == '*') {
precision = va_arg(ap, int);
if (precision<0) precision = -precision;
c = *++zFormat;
}
else {
while (c >= '0' && c <= '9') {
precision = precision * 10 + c - '0';
c = *++zFormat;
}
}
}
/* Get the conversion type modifier */
flag_long = 0;
if (c == 'l' || c == 'q' /* BSD quad (expect a 64-bit integer) */) {
flag_long = (c == 'q') ? 2 : 1;
c = *++zFormat;
if (c == 'l') {
/* Standard printf emulation 'lld' (expect a 64bit integer) */
flag_long = 2;
}
}
/* Fetch the info entry for the field */
infop = 0;
xtype = SXFMT_ERROR;
for (idx = 0; idx< (int)sizeof(aFmt) / sizeof(aFmt[0]); idx++) {
if (c == aFmt[idx].fmttype) {
infop = &aFmt[idx];
xtype = infop->type;
break;
}
}
/*
** At this point, variables are initialized as follows:
**
** flag_alternateform TRUE if a '#' is present.
** flag_plussign TRUE if a '+' is present.
** flag_leftjustify TRUE if a '-' is present or if the
** field width was negative.
** flag_zeropad TRUE if the width began with 0.
** flag_long TRUE if the letter 'l' (ell) or 'q'(BSD quad) prefixed
** the conversion character.
** flag_blanksign TRUE if a ' ' is present.
** width The specified field width.This is
** always non-negative.Zero is the default.
** precision The specified precision.The default
** is -1.
** xtype The object of the conversion.
** infop Pointer to the appropriate info struct.
*/
switch (xtype) {
case SXFMT_RADIX:
if (flag_long > 0) {
if (flag_long > 1) {
/* BSD quad: expect a 64-bit integer */
longvalue = va_arg(ap, int64_t);
}
else {
longvalue = va_arg(ap, long double);
}
}
else {
if (infop->flags & SXFLAG_SIGNED) {
longvalue = va_arg(ap, int);
}
else {
longvalue = va_arg(ap, unsigned int);
}
}
/* Limit the precision to prevent overflowing buf[] during conversion */
if (precision>SXFMT_BUFSIZ - 40) precision = SXFMT_BUFSIZ - 40;
#if 1
/* For the format %#x, the value zero is printed "0" not "0x0".
** I think this is stupid.*/
if (longvalue == 0) flag_alternateform = 0;
#else
/* More sensible: turn off the prefix for octal (to prevent "00"),
** but leave the prefix for hex.*/
if (longvalue == 0 && infop->base == 8) flag_alternateform = 0;
#endif
if (infop->flags & SXFLAG_SIGNED) {
if (longvalue<0) {
longvalue = -longvalue;
/* Ticket 1433-003 */
if (longvalue < 0) {
/* Overflow */
longvalue = 0x7FFFFFFFFFFFFFFF;
}
prefix = '-';
}
else if (flag_plussign) prefix = '+';
else if (flag_blanksign) prefix = ' ';
else prefix = 0;
}
else {
if (longvalue<0) {
longvalue = -longvalue;
/* Ticket 1433-003 */
if (longvalue < 0) {
/* Overflow */
longvalue = 0x7FFFFFFFFFFFFFFF;
}
}
prefix = 0;
}
if (flag_zeropad && precision<width - (prefix != 0)) {
precision = width - (prefix != 0);
}
bufpt = &buf[SXFMT_BUFSIZ - 1];
{
register char *cset; /* Use registers for speed */
register int base;
cset = infop->charset;
base = infop->base;
do { /* Convert to ascii */
*(--bufpt) = cset[longvalue%base];
longvalue = longvalue / base;
} while (longvalue>0);
}
length = &buf[SXFMT_BUFSIZ - 1] - bufpt;
for (idx = precision - length; idx>0; idx--) {
*(--bufpt) = '0'; /* Zero pad */
}
if (prefix) *(--bufpt) = prefix; /* Add sign */
if (flag_alternateform && infop->prefix) { /* Add "0" or "0x" */
char *pre, x;
pre = infop->prefix;
if (*bufpt != pre[0]) {
for (pre = infop->prefix; (x = (*pre)) != 0; pre++) *(--bufpt) = x;
}
}
length = &buf[SXFMT_BUFSIZ - 1] - bufpt;
break;
case SXFMT_FLOAT:
case SXFMT_EXP:
case SXFMT_GENERIC:
realvalue = va_arg(ap, double);
if (precision<0) precision = 6; /* Set default precision */
if (precision>SXFMT_BUFSIZ - 40) precision = SXFMT_BUFSIZ - 40;
if (realvalue<0.0) {
realvalue = -realvalue;
prefix = '-';
}
else {
if (flag_plussign) prefix = '+';
else if (flag_blanksign) prefix = ' ';
else prefix = 0;
}
if (infop->type == SXFMT_GENERIC && precision>0) precision--;
rounder = 0.0;
#if 0
/* Rounding works like BSD when the constant 0.4999 is used.Wierd! */
for (idx = precision, rounder = 0.4999; idx>0; idx--, rounder *= 0.1);
#else
/* It makes more sense to use 0.5 */
for (idx = precision, rounder = 0.5; idx>0; idx--, rounder *= 0.1);
#endif
if (infop->type == SXFMT_FLOAT) realvalue += rounder;
/* Normalize realvalue to within 10.0 > realvalue >= 1.0 */
exp = 0;
if (realvalue>0.0) {
while (realvalue >= 1e8 && exp <= 350) { realvalue *= 1e-8; exp += 8; }
while (realvalue >= 10.0 && exp <= 350) { realvalue *= 0.1; exp++; }
while (realvalue<1e-8 && exp >= -350) { realvalue *= 1e8; exp -= 8; }
while (realvalue<1.0 && exp >= -350) { realvalue *= 10.0; exp--; }
if (exp>350 || exp<-350) {
bufpt = "NaN";
length = 3;
break;
}
}
bufpt = buf;
/*
** If the field type is etGENERIC, then convert to either etEXP
** or etFLOAT, as appropriate.
*/
flag_exp = xtype == SXFMT_EXP;
if (xtype != SXFMT_FLOAT) {
realvalue += rounder;
if (realvalue >= 10.0) { realvalue *= 0.1; exp++; }
}
if (xtype == SXFMT_GENERIC) {
flag_rtz = !flag_alternateform;
if (exp<-4 || exp>precision) {
xtype = SXFMT_EXP;
}
else {
precision = precision - exp;
xtype = SXFMT_FLOAT;
}
}
else {
flag_rtz = 0;
}
/*
** The "exp+precision" test causes output to be of type etEXP if
** the precision is too large to fit in buf[].
*/
nsd = 0;
if (xtype == SXFMT_FLOAT && exp + precision<SXFMT_BUFSIZ - 30) {
flag_dp = (precision>0 || flag_alternateform);
if (prefix) *(bufpt++) = prefix; /* Sign */
if (exp<0) *(bufpt++) = '0'; /* Digits before "." */
else for (; exp >= 0; exp--) *(bufpt++) = (char)getdigit(&realvalue, &nsd);
if (flag_dp) *(bufpt++) = '.'; /* The decimal point */
for (exp++; exp<0 && precision>0; precision--, exp++) {
*(bufpt++) = '0';
}
while ((precision--)>0) *(bufpt++) = (char)getdigit(&realvalue, &nsd);
*(bufpt--) = 0; /* Null terminate */
if (flag_rtz && flag_dp) { /* Remove trailing zeros and "." */
while (bufpt >= buf && *bufpt == '0') *(bufpt--) = 0;
if (bufpt >= buf && *bufpt == '.') *(bufpt--) = 0;
}
bufpt++; /* point to next free slot */
}
else { /* etEXP or etGENERIC */
flag_dp = (precision>0 || flag_alternateform);
if (prefix) *(bufpt++) = prefix; /* Sign */
*(bufpt++) = (char)getdigit(&realvalue, &nsd); /* First digit */
if (flag_dp) *(bufpt++) = '.'; /* Decimal point */
while ((precision--)>0) *(bufpt++) = (char)getdigit(&realvalue, &nsd);
bufpt--; /* point to last digit */
if (flag_rtz && flag_dp) { /* Remove tail zeros */
while (bufpt >= buf && *bufpt == '0') *(bufpt--) = 0;
if (bufpt >= buf && *bufpt == '.') *(bufpt--) = 0;
}
bufpt++; /* point to next free slot */
if (exp || flag_exp) {
*(bufpt++) = infop->charset[0];
if (exp<0) { *(bufpt++) = '-'; exp = -exp; } /* sign of exp */
else { *(bufpt++) = '+'; }
if (exp >= 100) {
*(bufpt++) = (char)((exp / 100) + '0'); /* 100's digit */
exp %= 100;
}
*(bufpt++) = (char)(exp / 10 + '0'); /* 10's digit */
*(bufpt++) = (char)(exp % 10 + '0'); /* 1's digit */
}
}
/* The converted number is in buf[] and zero terminated.Output it.
** Note that the number is in the usual order, not reversed as with
** integer conversions.*/
length = bufpt - buf;
bufpt = buf;
/* Special case: Add leading zeros if the flag_zeropad flag is
** set and we are not left justified */
if (flag_zeropad && !flag_leftjustify && length < width) {
int i;
int nPad = width - length;
for (i = width; i >= nPad; i--) {
bufpt[i] = bufpt[i - nPad];
}
i = prefix != 0;
while (nPad--) bufpt[i++] = '0';
length = width;
}
break;
case SXFMT_SIZE: {
size_t *pSize = va_arg(ap, size_t *);
*pSize = ((SyFmtConsumer *)pUserData)->nLen;
length = width = 0;
}
break;
case SXFMT_PERCENT:
buf[0] = '%';
bufpt = buf;
length = 1;
break;
case SXFMT_CHARX:
c = va_arg(ap, int);
buf[0] = (char)c;
/* Limit the precision to prevent overflowing buf[] during conversion */
if (precision>SXFMT_BUFSIZ - 40) precision = SXFMT_BUFSIZ - 40;
if (precision >= 0) {
for (idx = 1; idx<precision; idx++) buf[idx] = (char)c;
length = precision;
}
else {
length = 1;
}
bufpt = buf;
break;
case SXFMT_STRING:
bufpt = va_arg(ap, char*);
if (bufpt == 0) {
bufpt = " ";
length = (int)sizeof(" ") - 1;
break;
}
length = precision;
if (precision < 0) {
/* Symisc extension */
length = (int)strlen(bufpt);
}
if (precision >= 0 && precision<length) length = precision;
break;
case SXFMT_RAWSTR: {
/* Symisc extension */
SyString *pStr = va_arg(ap, SyString *);
if (pStr == 0 || pStr->zString == 0) {
bufpt = " ";
length = (int)sizeof(char);
break;
}
bufpt = (char *)pStr->zString;
length = (int)pStr->nByte;
break;
}
case SXFMT_ERROR:
buf[0] = '?';
bufpt = buf;
length = (int)sizeof(char);
if (c == 0) zFormat--;
break;
}/* End switch over the format type */
/*
** The text of the conversion is pointed to by "bufpt" and is
** "length" characters long.The field width is "width".Do
** the output.
*/
if (!flag_leftjustify) {
register int nspace;
nspace = width - length;
if (nspace>0) {
while (nspace >= etSPACESIZE) {
rc = xConsumer(spaces, etSPACESIZE, pUserData);
if (rc != SOD_OK) {
return SOD_ABORT; /* Consumer routine request an operation abort */
}
nspace -= etSPACESIZE;
}
if (nspace>0) {
rc = xConsumer(spaces, (unsigned int)nspace, pUserData);
if (rc != SOD_OK) {
return SOD_ABORT; /* Consumer routine request an operation abort */
}
}
}
}
if (length>0) {
rc = xConsumer(bufpt, (unsigned int)length, pUserData);
if (rc != SOD_OK) {
return SOD_ABORT; /* Consumer routine request an operation abort */
}
}
if (flag_leftjustify) {
register int nspace;
nspace = width - length;
if (nspace>0) {
while (nspace >= etSPACESIZE) {
rc = xConsumer(spaces, etSPACESIZE, pUserData);
if (rc != SOD_OK) {
return SOD_ABORT; /* Consumer routine request an operation abort */
}
nspace -= etSPACESIZE;
}
if (nspace>0) {
rc = xConsumer(spaces, (unsigned int)nspace, pUserData);
if (rc != SOD_OK) {
return SOD_ABORT; /* Consumer routine request an operation abort */
}
}
}
}
}/* End for loop over the format string */
return errorflag ? -1 : SOD_OK;
}
static int FormatConsumer(const void *pSrc, unsigned int nLen, void *pData)
{
SyFmtConsumer *pConsumer = (SyFmtConsumer *)pData;
int rc = SOD_ABORT;
switch (pConsumer->nType) {
case SXFMT_CONS_PROC:
/* User callback */
rc = pConsumer->uConsumer.sFunc.xUserConsumer(pSrc, nLen, pConsumer->uConsumer.sFunc.pUserData);
break;
case SXFMT_CONS_BLOB:
/* Blob consumer */
rc = SyBlobAppend(pConsumer->uConsumer.pBlob, pSrc, (unsigned int)nLen);
break;
default:
/* Unknown consumer */
break;
}
/* Update total number of bytes consumed so far */
pConsumer->nLen += nLen;
pConsumer->rc = rc;
return rc;
}
static int32_t FormatMount(int32_t nType, void *pConsumer, ProcConsumer xUserCons, void *pUserData, size_t *pOutLen, const char *zFormat, va_list ap)
{
SyFmtConsumer sCons;
sCons.nType = nType;
sCons.rc = SOD_OK;
sCons.nLen = 0;
if (pOutLen) {
*pOutLen = 0;
}
switch (nType) {
case SXFMT_CONS_PROC:
sCons.uConsumer.sFunc.xUserConsumer = xUserCons;
sCons.uConsumer.sFunc.pUserData = pUserData;
break;
case SXFMT_CONS_BLOB:
sCons.uConsumer.pBlob = (SyBlob *)pConsumer;
break;
default:
return -1; /* Unknown */
}
InternFormat(FormatConsumer, &sCons, zFormat, ap);
if (pOutLen) {
*pOutLen = sCons.nLen;
}
return sCons.rc;
}
static size_t SyBlobFormatAp(SyBlob *pBlob, const char *zFormat, va_list ap)
{
size_t n = 0; /* cc warning */
FormatMount(SXFMT_CONS_BLOB, &(*pBlob), 0, 0, &n, zFormat, ap);
SyBlobNullAppend(pBlob);
return n;
}
#endif /* SOD_ENABLE_NET_TRAIN */
/*
* Dynamic Set Implementation.
*/
static int SySetInit(SySet *pSet, size_t ElemSize)
{
pSet->nSize = 0;
pSet->nUsed = 0;
pSet->eSize = ElemSize;
pSet->pBase = 0;
pSet->pUserData = 0;
return 0;
}
static int SySetPut(SySet *pSet, const void *pItem)
{
unsigned char *zbase;
if (pSet->nUsed >= pSet->nSize) {
void *pNew;
if (pSet->nSize < 1) {
pSet->nSize = 8;
}
pNew = realloc(pSet->pBase, pSet->eSize * pSet->nSize * 2);
if (pNew == 0) {
return SOD_OUTOFMEM;
}
pSet->pBase = pNew;
pSet->nSize <<= 1;
}
if (pItem) {
zbase = (unsigned char *)pSet->pBase;
memcpy((void *)&zbase[pSet->nUsed * pSet->eSize], pItem, pSet->eSize);
pSet->nUsed++;
}
return SOD_OK;
}
static inline void SySetReset(SySet *pSet)
{
pSet->nUsed = 0;
}
#ifdef SOD_ENABLE_NET_TRAIN
static void * SySetPeek(SySet *pSet)
{
const char *zBase;
if (pSet->nUsed <= 0) {
return 0;
}
zBase = (const char *)pSet->pBase;
return (void *)&zBase[(pSet->nUsed - 1) * pSet->eSize];
}
#endif /* SOD_ENABLE_NET_TRAIN */
static void * SySetFetch(SySet *pSet, size_t idx)
{
const char *zBase;
if (idx >= pSet->nUsed) {
return 0;
}