From f5df65b0a1476cc281c2505455d8c0bde74588c9 Mon Sep 17 00:00:00 2001 From: Christian Thaeter Date: Thu, 7 Aug 2008 05:02:08 +0200 Subject: [PATCH] add a translation function to tmpbuf tmpbuf_tr takes an input string and 2 sets of characters plus a default character. It produces a output string with all characters from the first set translated to the correspondending character in the 2nd set, similar to the shell 'tr' util. --- src/lib/safeclib.c | 35 +++++++++++++++++++++++++++++++++++ src/lib/safeclib.h | 14 ++++++++++++++ tests/15safeclib.tests | 31 +++++++++++++++++++++++++++++-- tests/library/test-safeclib.c | 20 ++++++++++++++++++++ 4 files changed, 98 insertions(+), 2 deletions(-) diff --git a/src/lib/safeclib.c b/src/lib/safeclib.c index 4a19477c1..c7c4f6e10 100644 --- a/src/lib/safeclib.c +++ b/src/lib/safeclib.c @@ -25,6 +25,7 @@ #include #include #include +#include LUMIERA_ERROR_DEFINE (NO_MEMORY, "Out of Memory!"); @@ -171,3 +172,37 @@ lumiera_tmpbuf_snprintf (size_t size, const char* fmt, ...) return buf; } + + +char* +lumiera_tmpbuf_tr (const char* in, const char* from, const char* to, const char* def) +{ + REQUIRE (strlen (from) == strlen (to), "from and to character set must have equal length"); + + char* ret = lumiera_tmpbuf_strndup (in, SIZE_MAX); + + char* wpos; + char* rpos; + for (wpos = rpos = ret; *rpos; ++rpos, ++wpos) + { + char* found = strchr (from, *rpos); + if (found) + *wpos = to[found-from]; + else if (def) + { + if (*def) + *wpos = *def; + else + { + ++rpos; + if (!*rpos) + break; + } + } + else + return NULL; + } + *wpos = '\0'; + + return ret; +} diff --git a/src/lib/safeclib.h b/src/lib/safeclib.h index 6fc532239..793bd1368 100644 --- a/src/lib/safeclib.h +++ b/src/lib/safeclib.h @@ -123,3 +123,17 @@ lumiera_tmpbuf_strndup (const char* src, size_t size); char* lumiera_tmpbuf_snprintf (size_t size, const char* fmt, ...); +/** + * Translates characters in a string, similar to the shell 'tr' utility + * @param in input string to be translated + * @param from source character set + * @param to destination character set + * @param def default destination character when a character is not in the source set, + * when NULL then translation will abort on unknown characters and return NULL, + * when "" then unknown characters will be removed + * when set to a single character string, unknown characters will be replaced with this string + * @return temporary buffer containing the constructed of the string + */ +char* +lumiera_tmpbuf_tr (const char* in, const char* from, const char* to, const char* def); + diff --git a/tests/15safeclib.tests b/tests/15safeclib.tests index 7e4039ead..560c0ee0a 100644 --- a/tests/15safeclib.tests +++ b/tests/15safeclib.tests @@ -9,9 +9,10 @@ TEST "Allocating some memory" allocation1024 <