comparison th_printf1.c @ 310:11cba47777ec

Split some things to a template file th_printf1.c
author Matti Hamalainen <ccr@tnsp.org>
date Mon, 22 Feb 2016 21:56:23 +0200
parents
children 7bce1e9fa397
comparison
equal deleted inserted replaced
309:2c87abec62db 310:11cba47777ec
1 /*
2 * printf() helper implementation
3 * Programmed and designed by Matti 'ccr' Hamalainen
4 * (C) Copyright 2016 Tecnic Software productions (TNSP)
5 *
6 * Please read file 'COPYING' for information on license and distribution.
7 */
8
9 static int TH_PFUNC_NAME (th_printf_ctx *ctx, th_printf_vputch vputch,
10 #ifdef TH_PFUNC_SIGNED
11 TH_PFUNC_TYPE_S pval,
12 #else
13 TH_PFUNC_TYPE_U val,
14 #endif
15 const int radix, const int f_flags,
16 const int f_width, const BOOL unsig, const BOOL upcase)
17 {
18 char buf[64];
19 size_t pos = 0;
20 int ret = 0;
21 #ifdef TH_PFUNC_SIGNED
22 BOOL neg = FALSE;
23 #else
24 (void) unsig;
25 #endif
26
27 if (radix > 16)
28 return EOF;
29
30 #ifdef TH_PFUNC_SIGNED
31 // Check for negative value
32 if (!unsig && pval < 0)
33 {
34 neg = TRUE;
35 pval = -pval;
36 }
37
38 // Render the value to a string in buf (reversed)
39 TH_PFUNC_TYPE_U val = pval;
40 #endif
41 do
42 {
43 TH_PFUNC_TYPE_U digit = val % radix;
44 if (digit < 10)
45 buf[pos] = '0' + digit;
46 else
47 buf[pos] = (upcase ? 'A' : 'a') + digit - 10;
48 val /= radix;
49 pos++;
50 }
51 while (val > 0 && pos < sizeof(buf) - 1);
52 buf[pos] = 0;
53
54 // Oops, the value did not fit in the buffer!
55 if (val > 0)
56 return EOF;
57
58 // Do we want a sign prefix? Not for unsigned values
59 #ifdef TH_PFUNC_SIGNED
60 if (!unsig)
61 {
62 char ch = (f_flags & TH_PF_SIGN) ? (neg ? '-' : '+') : (neg ? '-' : ((f_flags & TH_PF_SPACE) ? ' ' : 0));
63 if (ch && (ret = vputch(ctx, ch)) == EOF)
64 goto out;
65 }
66 #endif
67
68 // Output the data
69 return th_printf_vput_intstr(ctx, vputch, buf, f_width, pos, f_flags);
70
71 #ifdef TH_PFUNC_SIGNED
72 out:
73 #endif
74 return ret;
75 }
76
77
78 #undef TH_PFUNC_NAME
79 #undef TH_PFUNC_SIGNED
80 #undef TH_PFUNC_TYPE_S
81 #undef TH_PFUNC_TYPE_U