]> git.ipfire.org Git - pakfire.git/commitdiff
strings: Add function to truncate strings
authorMichael Tremer <michael.tremer@ipfire.org>
Tue, 4 Feb 2025 17:13:15 +0000 (17:13 +0000)
committerMichael Tremer <michael.tremer@ipfire.org>
Tue, 4 Feb 2025 17:13:15 +0000 (17:13 +0000)
Signed-off-by: Michael Tremer <michael.tremer@ipfire.org>
src/pakfire/string.c
src/pakfire/string.h
tests/libpakfire/string.c

index 6ebec1c7c989926cade4927772adde52245dd48d..edd4211dc38a19cb2b86687b62581e59d07e8dc9 100644 (file)
@@ -175,6 +175,18 @@ int pakfire_string_matches(const char* s, const char* pattern) {
        return !!strstr(s, pattern);
 }
 
+void pakfire_string_truncate(char* s, const size_t l) {
+       // Determine the length of the string
+       size_t length = strlen(s);
+
+       // Return if the string isn't long enough
+       if (length < l)
+               return;
+
+       // Truncate
+       s[l] = '\0';
+}
+
 int pakfire_string_partition(const char* s, const char* delim, char** s1, char** s2) {
        char* p = strstr(s, delim);
 
index 0e7f10913c59e3eaf464027b9e0ce44062a32a91..b7fd8d65b74178f32fa4d36c444a15baf9ac108b 100644 (file)
@@ -56,6 +56,8 @@ int pakfire_string_startswith(const char* s, const char* prefix);
 int pakfire_string_endswith(const char* s, const char* suffix);
 int pakfire_string_matches(const char* s, const char* pattern);
 
+void pakfire_string_truncate(char* s, const size_t l);
+
 // Strip
 void pakfire_string_lstrip(char* s);
 void pakfire_string_rstrip(char* s);
index a4a56ff450ea960a6c855463ddddd26b16a149e6..56e01a96bffbf111313f4005344e4deddd02ac17 100644 (file)
@@ -413,6 +413,31 @@ FAIL:
        return r;
 }
 
+static int test_truncate(const struct test* t) {
+       char s[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
+       int r = EXIT_FAILURE;
+
+       // Truncate the string bit by bit
+
+       pakfire_string_truncate(s, 24);
+       ASSERT_STRING_EQUALS(s, "ABCDEFGHIJKLMNOPQRSTUVWX");
+
+       pakfire_string_truncate(s, 3);
+       ASSERT_STRING_EQUALS(s, "ABC");
+
+       pakfire_string_truncate(s, 4);
+       ASSERT_STRING_EQUALS(s, "ABC");
+
+       pakfire_string_truncate(s, 0);
+       ASSERT_STRING_EQUALS(s, "");
+
+       // Everything passed
+       r = EXIT_SUCCESS;
+
+FAIL:
+       return r;
+}
+
 int main(int argc, const char* argv[]) {
        testsuite_add_test(test_string_set, 0);
        testsuite_add_test(test_string_setn, 0);
@@ -428,6 +453,7 @@ int main(int argc, const char* argv[]) {
        testsuite_add_test(test_intervals, 0);
        testsuite_add_test(test_string_contains_whitespace, 0);
        testsuite_add_test(test_string_search, 0);
+       testsuite_add_test(test_truncate, 0);
 
        return testsuite_run(argc, argv);
 }