-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprintf-emb.c
1326 lines (1148 loc) · 50.1 KB
/
printf-emb.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
/******************************************************************************
(c) Copyright 2018 ee-quipment.com
printf-emb.c - printf type functions for an embedded environment.
int snprintf(char *s, size_t n, const char *fmt, ...)
int saprintf(char *s, size_t n, const char *fmt, ...)
void sfprintf(char *s)
What IS supported:
All integer conversion specifiers: d, i, o, u, x, and X.
The unsigned char specifier: c
The pointer specifier: p.
The string specifier: s.
The % escape specifier: %.
Length modifiers: hh, h, l, ll, z.
What is NOT supported:
Floating point conversion specifiers: e, E (see below), f, F, g, G, a, A.
The number-of-characters specifier: n.
Wide characters.
Any other specifier not explicitly supported.
Modifications / Extensions:
The conversion specifiers e, E are supported, but for integer
arguments in place of double. A length modifier may be associated
with the argument.
For e, the output is the same as if the argument as a double of the
same value as the integer argument, where there is one digit to the
left of the decimal point. The precision specifies the number of
digits to the right of the decimal point.
For E, the output is in engineering notation where there may be 1,
2, or 3 digits to the left of the decimal point, and the exponent
is always a multiple of three. The precision specifies the number
of significant digits. If the precision is zero it is
taken to be one. A decimal point appears only if it is followed
by at least one digit.
Passing a double as an argument to an e, E specifier will result
in undefined and most likely bad behavior.
For performance reasons no division operations (including modulo, etc) are performed.
This implementation is recursive, and is called for every conversion
specifier and string literal in the format string. For example, the
format string "There are %d months and %d days left this year" will result
in xprintf() being called 5 times. The recursion depth can be limited
by the MACRO RECURSION_LIMIT. If the recursion limit is reached
then the return string will be truncated at that point.
The recursive implementation analyzes the entire string and determines
the total length before writing to the output buffer. This allows buffer
memory to be allocated after the string length is known.
The implementation is targeted at a 32-bit ARM architecture that supports
long long (64 bit) data types, has a 32 x 32 = 32 multiplier and treats
int and long as the same data type.
*****************************************************************************/
/*
* Always optimize this file.
*/
#pragma GCC optimize ("O3")
#include <stddef.h>
#include <stdarg.h>
#include <stddef.h>
#include <stdint.h>
#include <stdbool.h>
#include "printf-emb.h"
/*
* Design by contract assertion macros are included as sanity checks in
* the function calls. To activate them supply an appropriate assert()
* function for your system.
*/
#define assert(test)
#define REQUIRE(test) assert(test)
#define ENSURE(test) assert(test)
#define RECURSION_LIMIT 14
#define ARG_OCT_DIGITS_MAX 22 // %llo 64-bit octal
#define ARG_DEC_DIGITS_MAX 20 // %lld 64-bit signed decimal including
#define ARG_STR_LEN_MAX (ARG_OCT_DIGITS_MAX + 1) // including '0' prefix
/*
* One global_variable_t is allocated per printf() call.
*/
typedef struct {
char * output_buf;
int output_buf_size;
int output_str_len;
int arg_str_pos;
int recursion_depth;
emb_printf_fn_alloc_t alloc;
va_list ap;
} global_variable_t;
/*
* One arg_token_t variable is allocated (on the stack) per token found
* in the format string, where a token is a converted argument or a
* string segment.
*/
typedef struct {
int16_t field_width;
int16_t precision;
int16_t arg_str_len;
union {
struct {
uint8_t alt_form :1;
uint8_t arg_signed :1;
uint8_t sign_indicator :1;
uint8_t space_before_pos :1;
uint8_t left_justify :1;
uint8_t zero_padded :1;
uint8_t string_const :1;
uint8_t caps :1;
} flag;
uint8_t flags;
};
union {
long long arg_LL;
unsigned long long arg_ULL;
};
union {
char arg_as_str[ARG_STR_LEN_MAX];
const char * p_fixed_str;
};
} arg_token_t;
#define PRECISION_UNDEFINED -1
#define PRECISION_MAX INT16_MAX
typedef enum { CONV_DECIMAL=0, CONV_OCTAL, CONV_HEX, CONV_EXP, CONV_CHAR, CONV_STRING, CONV_PERCENT } conversion_type_t;
typedef enum { ARG_CHAR=0, ARG_SHORT, ARG_INT, ARG_LONG, ARG_LONG_LONG, ARG_CHAR_POINTER, ARG_NUM_TYPES } arg_type_t;
#define SIZE_T_TYPE ((sizeof(size_t) == sizeof(unsigned int )) ? ARG_INT : \
(sizeof(size_t) == sizeof(unsigned long )) ? ARG_LONG : ARG_LONG_LONG)
/*
* Private functions
*/
static uint16_t _udiv_by_10(uint16_t *dividend);
static void _getVararg(global_variable_t *p_g_var, arg_token_t *token, arg_type_t arg_type);
static void _buildOutputString(global_variable_t *p_g_var, const arg_token_t *token);
static void _parse(global_variable_t * p_g_var, const char *fmt);
static void _flags(const char **p_fmt, arg_token_t *token);
static void _fieldWidth(global_variable_t *p_g_var, const char **p_fmt, arg_token_t *token);
static void _precision(global_variable_t *p_g_var, const char **p_fmt, arg_token_t *token);
static void _lengthModifier(const char **p_fmt, const arg_token_t *token, arg_type_t *arg_type);
static void _conversionSpecifier(const char **p_fmt, arg_token_t *token, conversion_type_t *conv_type);
static void _convertDec(arg_token_t *token);
static void _convertBin(arg_token_t *token, conversion_type_t radix);
static void _convertExp(arg_token_t *token);
static void _convertChar(arg_token_t *token);
static void _convertString(arg_token_t *token);
/******************************************************************************
*
* Write at most n bytes (including the terminating '0' to s. Return the
* number of characters printed, excluding the terminating nul. The
* return value will be the same regardless of the value of n.
*
* Values of 0 for n and NULL for s are permitted. No output will be generated.
*
*****************************************************************************/
int snprintf(char *s, size_t n, const char *fmt, ...) {
int n_chars;
va_list ap;
REQUIRE (fmt);
va_start(ap, fmt);
n_chars = vsnprintf(s, n, fmt, ap);
va_end(ap);
return (n_chars);
}
/******************************************************************************
*
* vsnprintf() is equivalent to snprintf(), except that it is called with
* a va_list instead of a variable number of arguments.
*
* This function does not call the va_end macro. Because it invokes the
* va_arg macro, the value of ap is undefined after the call.
*
*****************************************************************************/
int vsnprintf(char *s, size_t n, const char *fmt, va_list ap) {
global_variable_t g_var;
REQUIRE (fmt);
g_var.output_buf = s;
g_var.output_buf_size = (int) n;
g_var.output_str_len = 0;
g_var.recursion_depth = 0;
g_var.ap = ap;
g_var.alloc = NULL;
if (*fmt) {
_parse(&g_var, fmt);
}
return (g_var.output_str_len);
}
/******************************************************************************
*
* Determine the length of the output string and call fn_alloc() to allocate
* a buffer of that size. Assign the buffer pointer to *s. If a buffer
* cannot be allocated that will hold the entire output string then
* set **s to NULL.
*
* The caller is responsible for freeing any memory allocated by fn_alloc.
*
*****************************************************************************/
int saprintf(emb_printf_fn_alloc_t fn_alloc, char **s, const char *fmt, ...) {
int n_chars;
va_list ap;
REQUIRE (s);
REQUIRE (fmt);
va_start(ap, fmt);
n_chars = vsaprintf(fn_alloc, s, fmt, ap);
va_end(ap);
return (n_chars);
}
/******************************************************************************
*
* vsaprintf() is equivalent to saprintf(), except that it is called with
* a va_list instead of a variable number of arguments.
*
* This function does not call the va_end macro. Because it invokes the
* va_arg macro, the value of ap is undefined after the call.
*
*****************************************************************************/
int vsaprintf(emb_printf_fn_alloc_t fn_alloc, char **s, const char *fmt, va_list ap) {
global_variable_t g_var;
REQUIRE (s);
REQUIRE (fmt);
g_var.output_buf = (char *) s;
g_var.output_buf_size = INT32_MAX; // buf not allocated yet, assume it's plenty big
g_var.output_str_len = 0;
g_var.recursion_depth = 0;
g_var.ap = ap;
g_var.alloc = fn_alloc;
if (*fmt) {
_parse(&g_var, fmt);
}
return (g_var.output_str_len);
}
/******************************************************************************
*
* Unsigned integer divide by 10 using 16 x 16 = 32 multiplication. Modify the
* dividend in place (dividend = INT(dividend / 10) and return the remainder.
*
*****************************************************************************/
static uint16_t _udiv_by_10(uint16_t *dividend) {
const uint16_t recip_0pt8 = 0xcccd;
uint32_t q;
uint32_t d = (uint32_t) *dividend;
/* divide the dividend by 10 in-place and return the remainder */
q = (d * recip_0pt8) >> 19;
*dividend = (uint16_t) q;
return ((uint16_t) (d - (10 * q)));
}
/******************************************************************************
*
* Retrieve an argument from the variable argument list. The ... operator
* promotes all smaller parameters to int.
*
* If the argument is long or int, it is promoted (and sign extended) into the
* long long argument.
*
* If the argument is a pointer to a string, it is promoted to unsigned
* long long and stored in token->arg_ULL which is assumed large enough to
* hold a pointer.
*
*****************************************************************************/
static void _getVararg(global_variable_t *p_g_var, arg_token_t *token, arg_type_t arg_type) {
REQUIRE (p_g_var);
REQUIRE (token);
if (arg_type == ARG_LONG_LONG) {
token->arg_LL = va_arg(p_g_var->ap, long long); // works for signed or unsigned
}
else if (arg_type == ARG_CHAR_POINTER) {
token->arg_ULL = (unsigned long long) ((unsigned long) va_arg(p_g_var->ap, char *));
}
else {
if (token->flag.arg_signed) {
if (arg_type == ARG_LONG) { token->arg_LL = (long long) va_arg(p_g_var->ap, long); }
else { token->arg_LL = (long long) va_arg(p_g_var->ap, int); }
}
else {
if (arg_type == ARG_LONG) { token->arg_ULL = (unsigned long long) va_arg(p_g_var->ap, unsigned long); }
else { token->arg_ULL = (unsigned long long) va_arg(p_g_var->ap, unsigned int); }
}
}
}
/******************************************************************************
*
* Build up the final output string from individual token argument strings.
* The string is built right to left as the procedure calls are unwound.
* Truncate the string if the output buffer is insufficiently large.
*
* sob = pointer to location in output buffer to write token argument string
* eob = pointer to location of last char written to output buffer
*
* The pointers sob and eob may be out of range of the output buffer, but they
* are tested before dereferencing.
*
*****************************************************************************/
static void _buildOutputString(global_variable_t *p_g_var, const arg_token_t *token) {
char * sob;
char * eob;
const char * arg_str;
const char pad_char = (token->flag.zero_padded) ? '0' : ' ';
int i;
REQUIRE (p_g_var);
REQUIRE (token);
/*
* End of buffer is either the start of the previous token string or
* the terminating nul in the output buffer.
*/
eob = &(p_g_var->output_buf[p_g_var->arg_str_pos]);
if (&(p_g_var->output_buf[p_g_var->output_buf_size-1]) < eob) {
eob = &(p_g_var->output_buf[p_g_var->output_buf_size-1]);
}
// decrement position index and initialize pointer to the start of where this token argument string will be written
p_g_var->arg_str_pos -= (token->arg_str_len > token->field_width) ? token->arg_str_len : token->field_width;
ENSURE (p_g_var->arg_str_pos >= 0); // shouldn't ever exceed lower bound of output buffer
sob = &(p_g_var->output_buf[p_g_var->arg_str_pos]);
if (token->flag.string_const) { arg_str = token->p_fixed_str; }
else { arg_str = token->arg_as_str; }
/*
* If the string is right justified, left-pad if needed. If the pad char
* is '0', pad between the minus sign (if present) and the number.
* Truncate the string if it does not fit in the output buffer.
*/
if (!token->flag.left_justify) {
if (((token->field_width - token->arg_str_len) > 0) && (pad_char == '0') && (arg_str[0] == '-')) {
*sob++ = *arg_str++;
}
for (i=0; i<(token->field_width - token->arg_str_len) && (sob < eob); ++i) {
*sob++ = pad_char;
}
}
// output token argument string, truncate if needed
for (i=0; i<token->arg_str_len && (sob < eob); ++i) {
*sob++ = *arg_str++;
}
// pad the remaining field with spaces
while (sob < eob) { *sob++ = ' '; }
}
/******************************************************************************
*
* Parse the format string into tokens. A single token is generated every
* time _parse() is called, whenever there is a string literal or a conversion
* specifier.
*
*****************************************************************************/
static void _parse(global_variable_t *p_g_var, const char *fmt) {
arg_token_t token;
arg_type_t arg_type;
conversion_type_t conv_type;
REQUIRE (p_g_var);
REQUIRE (fmt);
token.flags = 0;
++p_g_var->recursion_depth;
/* Fixed string to be copied to output */
if (*fmt != '%') {
token.flag.string_const = 1;
token.p_fixed_str = fmt;
token.field_width = 0;
token.precision = PRECISION_MAX;
token.arg_str_len = 0;
while (*fmt && (*fmt != '%')) {
++token.arg_str_len;
++p_g_var->output_str_len;
++fmt;
}
}
/* Parse conversion specification % */
else {
_flags(&fmt, &token);
_fieldWidth(p_g_var, &fmt, &token);
_precision(p_g_var, &fmt, &token);
_lengthModifier(&fmt, &token, &arg_type);
_conversionSpecifier(&fmt, &token, &conv_type);
// reconcile conflicting flags
if (token.flag.zero_padded && token.flag.left_justify) { token.flag.zero_padded = 0; }
if (token.flag.space_before_pos && token.flag.sign_indicator) { token.flag.space_before_pos = 0; }
// convert the argument
switch (conv_type) {
case CONV_DECIMAL:
_getVararg(p_g_var, &token, arg_type);
_convertDec(&token);
break;
case CONV_OCTAL:
case CONV_HEX:
_getVararg(p_g_var, &token, arg_type);
_convertBin(&token, conv_type);
break;
case CONV_EXP:
_getVararg(p_g_var, &token, arg_type);
_convertExp(&token);
break;
case CONV_CHAR:
_getVararg(p_g_var, &token, arg_type);
_convertChar(&token);
break;
case CONV_STRING:
_getVararg(p_g_var, &token, ARG_CHAR_POINTER);
_convertString(&token);
break;
case CONV_PERCENT:
token.arg_str_len = 1;
token.arg_as_str[0] = '%';
break;
default:
assert (false);
}
// keep a running total of the length of the output string
p_g_var->output_str_len += (token.arg_str_len > token.field_width) ? token.arg_str_len : token.field_width;
}
/*
* Handle next portion of the format string by recursing, unless:
* The end of the format string has been reached, or
* The recursion depth limit has been reached, or
* The number of characters generated (incl trailing nul) has filled the output buffer
*/
if (*fmt && (p_g_var->recursion_depth < RECURSION_LIMIT) && ((p_g_var->output_str_len + 1) <= p_g_var->output_buf_size)) {
_parse(p_g_var, fmt);
}
// Recursion ended, prepare to unwind procedure calls. Allocate memory if needed
else {
if (p_g_var->alloc) {
*((char **) p_g_var->output_buf) = p_g_var->alloc((size_t) (p_g_var->output_str_len + 1)); // set user's pointer to output string
// dereference buf pointer and set size to look like a call to snprintf
p_g_var->output_buf = *((char **) p_g_var->output_buf);
p_g_var->output_buf_size = p_g_var->output_str_len + 1;
}
// return to caller if no output buffer is allocated
if (p_g_var->output_buf == NULL) { return; }
/*
* Maintain an index to where the next token string should be put
* in the output buffer. The pointer may exceed the bounds of the
* buffer, indicating that the token string must be truncated.
*
* Upon entry the pointer will point to the last char written.
*/
p_g_var->arg_str_pos = p_g_var->output_str_len; // terminating null goes here if buffer large enough
if (p_g_var->arg_str_pos <= (p_g_var->output_buf_size - 1)) {
p_g_var->output_buf[p_g_var->arg_str_pos] = '\0';
}
else { // otherwise terminate at the last buffer location
p_g_var->output_buf[p_g_var->output_buf_size-1] = '\0';
}
}
// as _parse() unwinds it returns here to construct string unless there is no buffer allocated
if (p_g_var->output_buf != NULL) {
_buildOutputString(p_g_var, &token);
}
}
/******************************************************************************
*
* Parse the flag characters and set the token flags. *fmt == '%' on entry
*
*****************************************************************************/
static void _flags(const char **p_fmt, arg_token_t *token) {
bool exit = false;
REQUIRE (token);
REQUIRE (p_fmt);
REQUIRE (*p_fmt);
REQUIRE (**p_fmt == '%');
do {
++*p_fmt;
switch (**p_fmt) {
case '#':
token->flag.alt_form = 1;
break;
case '0':
token->flag.zero_padded = 1;
break;
case '-':
token->flag.left_justify = 1;
break;
case ' ':
token->flag.space_before_pos = 1;
break;
case '+':
token->flag.sign_indicator = 1;
break;
default:
exit = true;
break;
}
} while (!exit);
}
/******************************************************************************
*
* Parse the field width. Zero cannot be the first field width numeral or it
* would have been interpreted as a flag. *fmt points to the (potential) first
* numeral of the field width on entry.
*
*****************************************************************************/
static void _fieldWidth(global_variable_t * p_g_var, const char **p_fmt, arg_token_t *token) {
int fw = 0;
REQUIRE (p_g_var);
REQUIRE (p_fmt);
REQUIRE (*p_fmt);
REQUIRE (token);
if (**p_fmt == '*') {
_getVararg(p_g_var, token, ARG_INT);
fw = (int) token->arg_LL;
if (fw < 0) { // a neg field width is taken as a '-' flag followed by a positive field width.
token->flag.left_justify = 1;
fw = -fw;
}
++*p_fmt;
}
else {
while ((**p_fmt >= '0') && **p_fmt <= '9') {
fw *= 10;
fw += **p_fmt - '0';
++*p_fmt;
}
}
token->field_width = (int16_t) fw;
}
/******************************************************************************
*
* Parse the precision. *fmt points to the precision field
* delimiter '.' (if present) on entry.
*
*****************************************************************************/
static void _precision(global_variable_t * p_g_var, const char **p_fmt, arg_token_t *token) {
int16_t prec;
bool neg = false;
REQUIRE (p_g_var);
REQUIRE (p_fmt);
REQUIRE (*p_fmt);
REQUIRE (token);
if (**p_fmt == '.') {
prec = 0;
++*p_fmt;
if (**p_fmt == '*') {
_getVararg(p_g_var, token, ARG_INT);
prec = (int16_t) token->arg_LL;
if (prec < 0) {
prec = PRECISION_UNDEFINED; // negative precision not allowed
}
++*p_fmt;
}
else {
if (**p_fmt == '-') {
neg = true;
++*p_fmt;
}
while ((**p_fmt >= '0') && **p_fmt <= '9') {
prec *= 10;
prec += **p_fmt - '0';
++*p_fmt;
}
if (neg) {
prec = PRECISION_UNDEFINED; // negative precision not allowed
}
}
}
else {
prec = PRECISION_UNDEFINED;
}
token->precision = prec;
}
/******************************************************************************
*
* Parse the length modifier and set the arg_type. *fmt points to the first
* character of the modifier (if present) on entry.
*
*****************************************************************************/
static void _lengthModifier(const char **p_fmt, const arg_token_t *token, arg_type_t *arg_type) {
REQUIRE (p_fmt);
REQUIRE (*p_fmt);
REQUIRE (token);
REQUIRE (arg_type);
*arg_type = ARG_INT;
if (**p_fmt == 'h') { // 'h'
*arg_type = ARG_SHORT;
++*p_fmt;
if (**p_fmt == 'h') { // 'hh'
*arg_type = ARG_CHAR;
++*p_fmt;
}
}
else if (**p_fmt == 'l') {
*arg_type = ARG_LONG; // 'l'
++*p_fmt;
if (**p_fmt == 'l') { // 'll'
*arg_type = ARG_LONG_LONG;
++*p_fmt;
}
}
else if (**p_fmt == 'z') {
*arg_type = SIZE_T_TYPE;
++*p_fmt;
}
}
/******************************************************************************
*
* Parse the conversion specifier and set the flag.arg_signed flag and the conversion
* type. *fmt points to the conversion specifier on entry.
*
*****************************************************************************/
static void _conversionSpecifier(const char **p_fmt, arg_token_t *token, conversion_type_t *conv_type) {
REQUIRE (p_fmt);
REQUIRE (*p_fmt);
REQUIRE (token);
REQUIRE (conv_type);
if ((**p_fmt == 'd') || (**p_fmt == 'i')) {
*conv_type = CONV_DECIMAL;
token->flag.arg_signed = 1;
}
else if (**p_fmt == 'c') {
*conv_type = CONV_CHAR;
}
else if (**p_fmt == 's') {
*conv_type = CONV_STRING;
if (token->precision == PRECISION_UNDEFINED) {
token->precision = PRECISION_MAX;
}
}
else if (**p_fmt == 'u') {
*conv_type = CONV_DECIMAL;
}
else if (**p_fmt == 'o') {
*conv_type = CONV_OCTAL;
}
else if ((**p_fmt == 'X') || (**p_fmt == 'x')) {
*conv_type = CONV_HEX;
if (**p_fmt == 'X') { token->flag.caps = 1; }
}
else if (**p_fmt == 'p') {
*conv_type = CONV_HEX;
token->flag.alt_form = 1;
}
else if ((**p_fmt == 'e') || (**p_fmt == 'E')) {
*conv_type = CONV_EXP;
token->flag.arg_signed = 1;
if (token->precision == PRECISION_UNDEFINED) { token->precision = 6; }
if (**p_fmt == 'E') { token->flag.caps = 1; }
}
else { // **p_fmt == '%' or any unrecognized conversion specifier
*conv_type = CONV_PERCENT;
}
/*
* If a precision is given with a numeric conversion, the '0' flag is
* ignored.
*/
if ((**p_fmt == 'd') || (**p_fmt == 'i') || (**p_fmt == 'o') || (**p_fmt == 'u') || (**p_fmt == 'x') || (**p_fmt == 'X')) {
if (token->precision != PRECISION_UNDEFINED) {
token->flag.zero_padded = 0;
}
}
/* Default precision for everything except s, e, E */
if (token->precision == PRECISION_UNDEFINED) { token->precision = 1; }
(*p_fmt)++;
}
/******************************************************************************
*
* The (optionally signed) value in token->arg_(U)LL is converted to a decimal string
* in token->arg_as_str.
*
* Algorithm derived from Douglas Jones
* http://homepage.cs.uiowa.edu/~jones/bcd/decimal.html
*
*****************************************************************************/
#define r_10000 ((((1LL << 32) << 13) / 10000) + 1) // (1 / 10000) << 45
static void _convertDec(arg_token_t *token) {
uint64_t n;
uint32_t d4, d3, d2, d1, d0, q;
int sign = 1;
REQUIRE (token);
/*
* If the precision == 0 and the argument == 0 then output an empty string
* or a single space if token->flag.space_before_pos is set and the
* conversion type is signed.
*/
if (token->precision == 0 && (token->arg_ULL == 0)) {
token->arg_str_len = 0;
token->field_width = 0;
if ((token->flag.arg_signed) && (token->flag.space_before_pos)) {
token->arg_str_len = 1;
token->arg_as_str[0] = ' ';
}
return;
}
n = token->arg_ULL;
if ((token->flag.arg_signed) && (token->arg_LL < 0)) {
n = (uint64_t) -((int64_t) n);
sign = -1;
}
d0 = n & 0xFFFF;
d1 = (n>>16) & 0xFFFF;
d2 = (n>>32) & 0xFFFF;
d3 = (n>>48) & 0xFFFF;
d0 = 656 * d3 + 7296 * d2 + 5536 * d1 + d0;
// q = d0 / 10000;
// d0 = d0 % 10000;
q = (d0 * r_10000) >> 45;
d0 = d0 - (q * 10000);
d1 = q + 7671 * d3 + 9496 * d2 + 6 * d1;
// q = d1 / 10000;
// d1 = d1 % 10000;
q = (d1 * r_10000) >> 45;
d1 = d1 - (q * 10000);
d2 = q + 4749 * d3 + 42 * d2;
// q = d2 / 10000;
// d2 = d2 % 10000;
q = (d2 * r_10000) >> 45;
d2 = d2 - (q * 10000);
d3 = q + 281 * d3;
// q = d3 / 10000;
// d3 = d3 % 10000;
q = (d3 * r_10000) >> 45;
d3 = d3 - (q * 10000);
d4 = q;
/*
* Create output string backwards, least significant digit first,
* creating all 20 digits. p_dec_str always points to a valid char.
*/
char * p_dec_str = &(token->arg_as_str[ARG_STR_LEN_MAX]);
uint16_t d0_16 = (uint16_t) d0;
uint16_t d1_16 = (uint16_t) d1;
uint16_t d2_16 = (uint16_t) d2;
uint16_t d3_16 = (uint16_t) d3;
uint16_t d4_16 = (uint16_t) d4;
for (int i=0; i<4; ++i) { *--p_dec_str = (char) ('0' + _udiv_by_10(&d0_16)); }
for (int i=0; i<4; ++i) { *--p_dec_str = (char) ('0' + _udiv_by_10(&d1_16)); }
for (int i=0; i<4; ++i) { *--p_dec_str = (char) ('0' + _udiv_by_10(&d2_16)); }
for (int i=0; i<4; ++i) { *--p_dec_str = (char) ('0' + _udiv_by_10(&d3_16)); }
for (int i=0; i<4; ++i) { *--p_dec_str = (char) ('0' + _udiv_by_10(&d4_16)); }
// trim string len to max of precision or sig digits
token->arg_str_len = ARG_DEC_DIGITS_MAX;
while (token->arg_str_len>token->precision && (*p_dec_str == '0')) {
--token->arg_str_len;
++p_dec_str;
}
/*
* Add the sign indicator (or space) for signed conversions if negative
* or required by the flags.
*/
if (token->flag.arg_signed) {
if (sign == -1) { *--p_dec_str = '-'; ++token->arg_str_len;}
else if (token->flag.sign_indicator) { *--p_dec_str = '+'; ++token->arg_str_len;}
else if (token->flag.space_before_pos) { *--p_dec_str = ' '; ++token->arg_str_len;}
}
// move characters from right justified to left justified
for (int i=0; i<token->arg_str_len; ++i) {
token->arg_as_str[i] = *p_dec_str++;
}
}
/******************************************************************************
*
* The value in token->arg_ULL is converted to an octal or hex string
* in token->arg_as_str.
*
*****************************************************************************/
static void _convertBin(arg_token_t *token, conversion_type_t radix) {
char * p_hex_str;
int shift_cnt;
uint8_t char_mask;
REQUIRE (token);
REQUIRE ((radix == CONV_OCTAL) || (radix == CONV_HEX));
token->arg_str_len = 0;
p_hex_str = &(token->arg_as_str[ARG_STR_LEN_MAX]); // create backwards, least significant digit first (pointer is predecremented in loop)
if (radix == CONV_OCTAL) {
shift_cnt = 3; // convert this many bits at a time
char_mask = 0x07; // 3 bits makes one octal char
}
else { // radix == CONV_HEX
shift_cnt = 4;
char_mask = 0x0f;
}
// precision == 0 and argument == 0 must output a null string
if (token->precision == 0 && (token->arg_ULL == 0)) {
token->arg_str_len = 0;
token->field_width = 0;
return;
}
// precision == 1 and argument == 0 output a '0' with no preceding '0x'
if (token->precision == 1 && (token->arg_ULL == 0)) {
token->arg_str_len = 1;
token->arg_as_str[0] = '0';
return;
}
// repeat until argument is exhausted and at least precision digits
int prec = token->precision;
while ((prec-- > 0) || token->arg_ULL) {
--p_hex_str; // decrement here so that it will point to valid char on exit
*p_hex_str = (char) ((token->arg_ULL & char_mask) + '0');
if (*p_hex_str > '9') {
if (token->flag.caps) { *p_hex_str += 'A' - ('9' + 1); }
else { *p_hex_str += 'a' - ('9' + 1); }
}
++token->arg_str_len;
token->arg_ULL >>= shift_cnt;
}
// add preceding zero (octal) or '0x' or '0X' if required
if (token->flag.alt_form) {
if (radix == CONV_HEX) {
if (token->flag.caps) { *--p_hex_str = 'X'; }
else { *--p_hex_str = 'x'; }
++token->arg_str_len;
}
if (*p_hex_str != '0') { // also takes care of alt form radix==CONV_OCTAL when first octal digit isn't a zero
*--p_hex_str = '0';
++token->arg_str_len;
}
}
// move characters from right justified to left justified
for (int i=0; i<token->arg_str_len; ++i) {
token->arg_as_str[i] = *p_hex_str++;
}
}
/******************************************************************************
*
* The signed integer value in token->arg_LL is converted to a
* decimal string in token->arg_as_str.
*
* The argument is rounded and converted in the style [-][d][d]d.ddde+dd.
*
* Because the input argument is an integer, the exponent will always be positive.
*
* If the conversion specifier is e, there will always be one and only one
* digit before the decimal point. The precision specifies the number of
* digits following the decimal point.
*
* If the conversion specifier is E, the exponent will be divisible by 3,
* there will be one, two, or three digits before the decimal point, and
* zero or more digits after the decimal point. The number of significant
* digits is equal to the precision. The least significant digit is rounded. If
* the precision is less than the number of digits to the left of the
* decimal point, the remaining digits will appear as zero.
*
*
*****************************************************************************/
#define EXP_MAX_STR_LEN (ARG_DEC_DIGITS_MAX + 6) // extra chars: sign, dec pt, e+dd
static void _convertExp(arg_token_t *token) {
char * p_dec_str;
uint32_t dec_chars_rem;
uint32_t exp;
uint32_t integer_digits;
char e_str[EXP_MAX_STR_LEN];
char * p_e_str = e_str;
REQUIRE (token);
/*
* Convert the integer argument to a decimal string with a precision of
* one in order to get all of the significant digits without any leading
* zeros, then massage the decimal string into e format.
*
* If the format is 'E' then the precision specifies the number of
* significant digits which must be at least one.
*/
int16_t e_precision = token->precision;
token->precision = 1;
_convertDec(token);
token->precision = e_precision;
if (token->precision == 0 && token->flag.caps) {
token->precision = 1;
}
/*
* If the argument is zero and the precision is zero, _convertDec will
* return "" or " ", but in e, E format this should be printed as "0".
*
* Fix up the output string and return.
*/
if (token->precision == 0 && (token->arg_ULL == 0)) {
token->arg_str_len = 1;
token->arg_as_str[0] = '0';
return;
}
p_dec_str = token->arg_as_str;
dec_chars_rem = (uint32_t) (int) (token->arg_str_len); // convoluted cast to silence lint
// preserve leading sign and spaces
if ((*p_dec_str == '+') || (*p_dec_str == '-') || (*p_dec_str == ' ')) {
*p_e_str++ = *p_dec_str++;
--dec_chars_rem;
}
/*
* All that's left in the string are digits. Based on the conversion
* specifier (e or E) determine the number of digits in the integer part
* and from that, the value of the exponent.
*/
if (!token->flag.caps) { // e conversion specifier - one digit in integer part