diff 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
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/th_printf1.c	Mon Feb 22 21:56:23 2016 +0200
@@ -0,0 +1,81 @@
+/*
+ * printf() helper implementation
+ * Programmed and designed by Matti 'ccr' Hamalainen
+ * (C) Copyright 2016 Tecnic Software productions (TNSP)
+ *
+ * Please read file 'COPYING' for information on license and distribution.
+ */
+
+static int TH_PFUNC_NAME (th_printf_ctx *ctx, th_printf_vputch vputch,
+#ifdef TH_PFUNC_SIGNED
+    TH_PFUNC_TYPE_S pval,
+#else
+    TH_PFUNC_TYPE_U val,
+#endif
+    const int radix, const int f_flags,
+    const int f_width, const BOOL unsig, const BOOL upcase)
+{
+    char buf[64];
+    size_t pos = 0;
+    int ret = 0;
+#ifdef TH_PFUNC_SIGNED
+    BOOL neg = FALSE;
+#else
+    (void) unsig;
+#endif
+
+    if (radix > 16)
+        return EOF;
+
+#ifdef TH_PFUNC_SIGNED
+    // Check for negative value
+    if (!unsig && pval < 0)
+    {
+        neg = TRUE;
+        pval = -pval;
+    }
+
+    // Render the value to a string in buf (reversed)
+    TH_PFUNC_TYPE_U val = pval;
+#endif
+    do
+    {
+        TH_PFUNC_TYPE_U digit = val % radix;
+        if (digit < 10)
+            buf[pos] = '0' + digit;
+        else
+            buf[pos] = (upcase ? 'A' : 'a') + digit - 10;
+        val /= radix;
+        pos++;
+    }
+    while (val > 0 && pos < sizeof(buf) - 1);
+    buf[pos] = 0;
+
+    // Oops, the value did not fit in the buffer!
+    if (val > 0)
+        return EOF;
+
+    // Do we want a sign prefix? Not for unsigned values
+#ifdef TH_PFUNC_SIGNED
+    if (!unsig)
+    {
+        char ch = (f_flags & TH_PF_SIGN) ? (neg ? '-' : '+') : (neg ? '-' : ((f_flags & TH_PF_SPACE) ? ' ' : 0));
+        if (ch && (ret = vputch(ctx, ch)) == EOF)
+            goto out;
+    }
+#endif
+
+    // Output the data
+    return th_printf_vput_intstr(ctx, vputch, buf, f_width, pos, f_flags);
+    
+#ifdef TH_PFUNC_SIGNED
+out:
+#endif
+    return ret;
+}
+
+
+#undef TH_PFUNC_NAME
+#undef TH_PFUNC_SIGNED
+#undef TH_PFUNC_TYPE_S
+#undef TH_PFUNC_TYPE_U