From 9388b5d4464d13117bcaad1fda1a1b7ebd8d0264 Mon Sep 17 00:00:00 2001 From: jcid Date: Mon, 7 Apr 2008 18:55:14 +0200 Subject: - Added dStr_printable() to dlib. --- dlib/dlib.c | 34 ++++++++++++++++++++++++++++++++++ dlib/dlib.h | 1 + 2 files changed, 35 insertions(+) (limited to 'dlib') diff --git a/dlib/dlib.c b/dlib/dlib.c index 862e642f..f01314eb 100644 --- a/dlib/dlib.c +++ b/dlib/dlib.c @@ -434,6 +434,40 @@ char *dStr_memmem(Dstr *haystack, Dstr *needle) return NULL; } +/* + * Return a printable representation of the provided Dstr, limited to a length + * of roughly maxlen. + * + * This is NOT threadsafe. + */ +const char *dStr_printable(Dstr *in, int maxlen) +{ + int i; + static const char *const HEX = "0123456789ABCDEF"; + static Dstr *out = NULL; + + if (in == NULL) + return NULL; + + if (out) + dStr_truncate(out, 0); + else + out = dStr_sized_new(in->len); + + for (i = 0; (i < in->len) && (out->len < maxlen); ++i) { + if (isprint(in->str[i]) || (in->str[i] == '\n')) { + dStr_append_c(out, in->str[i]); + } else { + dStr_append_l(out, "\\x", 2); + dStr_append_c(out, HEX[(in->str[i] >> 4) & 15]); + dStr_append_c(out, HEX[in->str[i] & 15]); + } + } + if (out->len >= maxlen) + dStr_append(out, "..."); + return out->str; +} + /* *- dList --------------------------------------------------------------------- */ diff --git a/dlib/dlib.h b/dlib/dlib.h index 7bcac739..cd3b9fc5 100644 --- a/dlib/dlib.h +++ b/dlib/dlib.h @@ -108,6 +108,7 @@ void dStr_sprintf (Dstr *ds, const char *format, ...); void dStr_sprintfa (Dstr *ds, const char *format, ...); int dStr_cmp(Dstr *ds1, Dstr *ds2); char *dStr_memmem(Dstr *haystack, Dstr *needle); +const char *dStr_printable(Dstr *in, int maxlen); /* *-- dList -------------------------------------------------------------------- -- cgit v1.2.3