From db78689015b2eab47a56bc8c0cbffb2146c08380 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nils=20O=2E=20Sel=C3=A5sdal?= Date: Thu, 10 Dec 2015 19:13:16 +0100 Subject: [PATCH] Add uc_strv_reverse --- include/ucore/strvec.h | 5 +++++ src/strvec.c | 11 +++++++++++ test/test_strv.c | 39 +++++++++++++++++++++++++++++++++++++++ 3 files changed, 55 insertions(+) diff --git a/include/ucore/strvec.h b/include/ucore/strvec.h index 4e2c174..d4cf7f9 100644 --- a/include/ucore/strvec.h +++ b/include/ucore/strvec.h @@ -101,6 +101,11 @@ void uc_strv_destroy(struct UCStrv *strv); */ int uc_strv_append_all(struct UCStrv *restrict a, struct UCStrv *restrict b, int copy); +/** Reverse the order of strings in a UCStrv + * + * @param strv strv to reverse. + */ +void uc_strv_reverse(struct UCStrv *strv); #ifdef __cplusplus } #endif diff --git a/src/strvec.c b/src/strvec.c index 1e9f00a..3ed3d8e 100644 --- a/src/strvec.c +++ b/src/strvec.c @@ -130,3 +130,14 @@ int uc_strv_append_all(struct UCStrv *restrict a, struct UCStrv *restrict b, int return 0; } +void uc_strv_reverse(struct UCStrv *strv) +{ + for (size_t i = 0; i < strv->cnt / 2; i++) { + + size_t k = strv->cnt - i - 1; + char *tmp = strv->strings[i]; + + strv->strings[i] = strv->strings[k]; + strv->strings[k] = tmp; + } +} diff --git a/test/test_strv.c b/test/test_strv.c index b9100b4..311665c 100644 --- a/test/test_strv.c +++ b/test/test_strv.c @@ -123,6 +123,44 @@ START_TEST (test_strv_append_all_nocopy) END_TEST +START_TEST (test_strv_reverse) + struct UCStrv strv; + + uc_strv_init(&strv); + + uc_strv_append(&strv, "string1"); + + uc_strv_reverse(&strv); + ck_assert_str_eq("string1", strv.strings[0]); + + uc_strv_destroy(&strv); + + uc_strv_init(&strv); + + uc_strv_append(&strv, "string1"); + uc_strv_append(&strv, "string2"); + + uc_strv_reverse(&strv); + ck_assert_str_eq("string2", strv.strings[0]); + ck_assert_str_eq("string1", strv.strings[1]); + + uc_strv_destroy(&strv); + + uc_strv_init(&strv); + + uc_strv_append(&strv, "string1"); + uc_strv_append(&strv, "string2"); + uc_strv_append(&strv, "string3"); + + uc_strv_reverse(&strv); + ck_assert_str_eq("string3", strv.strings[0]); + ck_assert_str_eq("string2", strv.strings[1]); + ck_assert_str_eq("string1", strv.strings[2]); + + uc_strv_destroy(&strv); + + +END_TEST Suite *strv_suite(void) { @@ -135,6 +173,7 @@ Suite *strv_suite(void) tcase_add_test(tc, test_strv_null_terminate); tcase_add_test(tc, test_strv_append_all_copy); tcase_add_test(tc, test_strv_append_all_nocopy); + tcase_add_test(tc, test_strv_reverse); suite_add_tcase(s, tc);