[v2 2/6] misc: add xstrrtrim and xstrnrtrim - right-trim a string

Daniel Martin consume.noise at gmail.com
Tue Dec 17 14:35:55 PST 2013


Add xstrrtrim() and xstrnrtrim() to right-trim a string and a test for
both functions to test/xstr.c.

Signed-off-by: Daniel Martin <consume.noise at gmail.com>
---
v2: Prefixed functions with "xstr" and added tests.

 include/misc.h |  2 ++
 os/utils.c     | 32 ++++++++++++++++++++++++++++++++
 test/xstr.c    | 28 ++++++++++++++++++++++++++++
 3 files changed, 62 insertions(+)

diff --git a/include/misc.h b/include/misc.h
index 165d42e..dd7243f 100644
--- a/include/misc.h
+++ b/include/misc.h
@@ -246,6 +246,8 @@ padding_for_int32(const int bytes)
 }
 
 
+extern int xstrrtrim(char *str);
+extern int xstrnrtrim(char *str, int len);
 extern const char **xstrtokenize(const char *str, const char *separators);
 extern void FormatInt64(int64_t num, char *string);
 extern void FormatUInt64(uint64_t num, char *string);
diff --git a/os/utils.c b/os/utils.c
index 6f83a08..ff56f2d 100644
--- a/os/utils.c
+++ b/os/utils.c
@@ -1943,6 +1943,38 @@ CheckUserAuthorization(void)
 }
 
 /*
+ * Right-trim a string. Returns the string length after trimming.
+ */
+int
+xstrrtrim(char *str)
+{
+    if (!str)
+        return 0;
+
+    return xstrnrtrim(str, strlen(str));
+}
+
+/*
+ * Right-trim a string of a specific length. Returns the string length
+ * after trimming.
+ */
+int
+xstrnrtrim(char *str, int len)
+{
+    int i = len;
+
+    if (!str || (len <= 0))
+        return 0;
+
+    while (i > 0 && !isgraph(str[i - 1]))
+        i--;
+
+    str[i] = '\0';
+
+    return i - 1;
+}
+
+/*
  * Tokenize a string into a NULL terminated array of strings. Always returns
  * an allocated array unless an error occurs.
  */
diff --git a/test/xstr.c b/test/xstr.c
index aba3e86..1ed7e7a 100644
--- a/test/xstr.c
+++ b/test/xstr.c
@@ -4,6 +4,32 @@
 
 #include "misc.h"
 
+static void test_xstrnrtrim(void)
+{
+    char trim[] = "trim\n\n\n";
+
+    assert(xstrnrtrim(trim, 6) == 3);
+    assert(strcmp(trim, "trim") == 0);
+
+    /* An additional trim shouldn't change the result. */
+    assert(xstrnrtrim(trim, 6) == 3);
+
+    assert(xstrnrtrim(NULL, 0) == 0);
+}
+
+static void test_xstrrtrim(void)
+{
+    char trim[] = "trim\n\n\n";
+
+    assert(xstrrtrim(trim) == 3);
+    assert(strcmp(trim, "trim") == 0);
+
+    /* An additional trim shouldn't change the result. */
+    assert(xstrrtrim(trim) == 3);
+
+    assert(xstrrtrim(NULL) == 0);
+}
+
 static void test_xstrtokenize(void)
 {
     char tokenstr[] = "123|456|789";
@@ -30,6 +56,8 @@ static void test_xstrtokenize(void)
 int
 main(int argc, char **argv)
 {
+    test_xstrnrtrim();
+    test_xstrrtrim();
     test_xstrtokenize();
 
     return 0;
-- 
1.8.5.1



More information about the xorg-devel mailing list