Skip to content

Instantly share code, notes, and snippets.

@imasahiro
Created October 3, 2014 02:44
Show Gist options
  • Save imasahiro/c491892bc18ac5ccc914 to your computer and use it in GitHub Desktop.
Save imasahiro/c491892bc18ac5ccc914 to your computer and use it in GitHub Desktop.
diff --git a/qrintf.h b/qrintf.h
index 6e6c7d8..35af13e 100644
--- a/qrintf.h
+++ b/qrintf.h
@@ -73,26 +73,37 @@ static inline qrintf_t _qrintf_s_len(qrintf_t ctx, const char *s, size_t l)
return ctx;
}
+static inline void _qprintf_reverse(char *start, char *end)
+{
+ char *s = start;
+ char *e = end - 1;
+ char *middle = s + (end - s) / 2;
+ char tmp;
+ while (s < middle) {
+ tmp = *s;
+ *s++ = *e;
+ *e-- = tmp;
+ }
+}
+
#define _QP_SIGNED_F(type, suffix, min, max) \
static inline qrintf_t _qrintf_ ## suffix (qrintf_t ctx, type v) \
{ \
- char tmp[sizeof(type) * 3]; \
- size_t i = 0; \
+ size_t off = ctx.off; \
if (v < 0) { \
ctx.str[ctx.off++] = '-'; \
+ off = ctx.off; \
if (v == min) { \
- tmp[i++] = '1' + max % 10; \
+ ctx.str[ctx.off++] = '1' + max % 10; \
v = max / 10; \
} else { \
v = -v; \
} \
} \
do { \
- tmp[i++] = '0' + v % 10; \
+ ctx.str[ctx.off++] = '0' + v % 10; \
} while ((v /= 10) != 0); \
- do { \
- ctx.str[ctx.off++] = tmp[--i]; \
- } while (i != 0); \
+ _qprintf_reverse(ctx.str + off, ctx.str + ctx.off);\
return ctx; \
}
@@ -104,14 +115,11 @@ _QP_SIGNED_F(long long, lld, LLONG_MIN, LLONG_MAX)
#define _QP_UNSIGNED_F(type, suffix, max) \
static inline qrintf_t _qrintf_ ## suffix (qrintf_t ctx, type v) \
{ \
- char tmp[sizeof(type) * 3]; \
- size_t i = 0; \
+ size_t off = ctx.off; \
do { \
- tmp[i++] = '0' + v % 10; \
+ ctx.str[ctx.off++] = '0' + v % 10; \
} while ((v /= 10) != 0); \
- do { \
- ctx.str[ctx.off++] = tmp[--i]; \
- } while (i != 0); \
+ _qprintf_reverse(ctx.str + off, ctx.str + ctx.off);\
return ctx; \
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment