From 4682328ced5f3d71b80b993a2fd3feeca0ffd250 Mon Sep 17 00:00:00 2001 From: Bruno Haible Date: Sun, 2 Apr 2023 21:03:55 +0200 Subject: [PATCH] trim: Fix trim_trailing result in multibyte locales. * lib/trim.c (trim2): Simplify algorithm for trim_trailing in multibyte locales, to use 2 instead of 3 states. --- ChangeLog | 4 ++++ lib/trim.c | 43 +++++++++++-------------------------------- 2 files changed, 15 insertions(+), 32 deletions(-) diff --git a/ChangeLog b/ChangeLog index a559f3dd71..30e39d757a 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,5 +1,9 @@ 2023-04-02 Bruno Haible + trim: Fix trim_trailing result in multibyte locales. + * lib/trim.c (trim2): Simplify algorithm for trim_trailing in multibyte + locales, to use 2 instead of 3 states. + trim: Add tests. * tests/test-trim.c: New file. * tests/test-trim1.sh: New file. diff --git a/lib/trim.c b/lib/trim.c index 162c43e1de..ed643cd20c 100644 --- a/lib/trim.c +++ b/lib/trim.c @@ -65,42 +65,21 @@ trim2 (const char *s, int how) /* Trim trailing whitespaces. */ if (how != TRIM_LEADING) { - unsigned int state = 0; - char *r IF_LINT (= NULL); /* used only while state = 2 */ + char *start_of_spaces = NULL; mbi_init (i, d, strlen (d)); for (; mbi_avail (i); mbi_advance (i)) - { - if (state == 0 && mb_isspace (mbi_cur (i))) - continue; - - if (state == 0 && !mb_isspace (mbi_cur (i))) - { - state = 1; - continue; - } - - if (state == 1 && !mb_isspace (mbi_cur (i))) - continue; - - if (state == 1 && mb_isspace (mbi_cur (i))) - { - state = 2; - r = (char *) mbi_cur_ptr (i); - } - else if (state == 2 && mb_isspace (mbi_cur (i))) - { - /* empty */ - } - else - { - state = 1; - } - } - - if (state == 2) - *r = '\0'; + if (mb_isspace (mbi_cur (i))) + { + if (start_of_spaces == NULL) + start_of_spaces = (char *) mbi_cur_ptr (i); + } + else + start_of_spaces = NULL; + + if (start_of_spaces != NULL) + *start_of_spaces = '\0'; } } else -- 2.39.5