]> git.ipfire.org Git - thirdparty/haproxy.git/commitdiff
MINOR: ist: define iststrip() new function
authorAmaury Denoyelle <adenoyelle@haproxy.com>
Fri, 26 Apr 2024 08:16:25 +0000 (10:16 +0200)
committerAmaury Denoyelle <adenoyelle@haproxy.com>
Fri, 26 Apr 2024 09:29:25 +0000 (11:29 +0200)
Implement iststrip(). This function removes any trailing newline
sequence if present from an ist.

include/import/ist.h
tests/unit/ist.c

index e4e1425d6fd984c58ff569327e308d34c723a979..962d63b802f4847cbb2bd21a88e72e7290edcc4d 100644 (file)
@@ -331,6 +331,25 @@ static inline struct ist istzero(const struct ist ist, size_t size)
        return ret;
 }
 
+/* Remove trailing newline characters if present in <ist> by reducing its
+ * length. Both '\n', '\r' and '\n\r' match. Return the modified ist.
+ */
+static inline struct ist iststrip(const struct ist ist)
+{
+       struct ist ret = ist;
+
+       if (ret.len) {
+               if (ret.ptr[ret.len - 1] == '\n')
+                       --ret.len;
+       }
+       if (ret.len) {
+               if (ret.ptr[ret.len - 1] == '\r')
+                       --ret.len;
+       }
+
+       return ret;
+}
+
 /* returns the ordinal difference between two strings :
  *    < 0 if ist1 < ist2
  *    = 0 if ist1 == ist2
index 43b34387af59f1f98d2ec487cba55803b9e2ac8f..e0d2b00c740be62ae040282cccfea7a621b233a2 100644 (file)
@@ -129,6 +129,30 @@ int test_istzero()
        return 0;
 }
 
+struct ist f_iststrip(struct ist ist) { return iststrip(ist); }
+int test_iststrip()
+{
+       if (iststrip(ist("foo")).len != 3)
+               return __LINE__;
+
+       if (iststrip(ist("foo\n")).len != 3)
+               return __LINE__;
+
+       if (iststrip(ist("foo\r")).len != 3)
+               return __LINE__;
+
+       if (iststrip(ist("foo\r\n")).len != 3)
+               return __LINE__;
+
+       if (iststrip(ist("")).len != 0)
+               return __LINE__;
+
+       if (iststrip(ist("\n")).len != 0)
+               return __LINE__;
+
+       return 0;
+}
+
 int f_istdiff(const struct ist ist1, const struct ist ist2) { return istdiff(ist1, ist2); }
 int test_istdiff()
 {
@@ -682,6 +706,7 @@ int main(void)
         printf("%4d istpad()\n", test_istpad());
         printf("%4d isttrim()\n", test_isttrim());
         printf("%4d istzero()\n", test_istzero());
+        printf("%4d iststrip()\n", test_iststrip());
         printf("%4d istdiff()\n", test_istdiff());
         printf("%4d istmatch()\n", test_istmatch());
         printf("%4d istnmatch()\n", test_istnmatch());