From 69a635412d4787ccb96f6641f3b4d35b77d25072 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?S=C3=A9bastien=20Helleu?= Date: Mon, 30 Jan 2023 20:54:37 +0100 Subject: [PATCH] core: add function string_get_common_bytes_count (issue #1877) --- src/core/wee-string.c | 25 +++++++++++++++++++++++++ src/core/wee-string.h | 2 ++ tests/unit/core/test-core-string.cpp | 24 +++++++++++++++++++++++- 3 files changed, 50 insertions(+), 1 deletion(-) diff --git a/src/core/wee-string.c b/src/core/wee-string.c index abe7ccd17..a6634ba7c 100644 --- a/src/core/wee-string.c +++ b/src/core/wee-string.c @@ -3960,6 +3960,31 @@ string_input_for_buffer (const char *string) return NULL; } +/* + * Returns the number of bytes in common between two strings (this function + * works with bytes and not UTF-8 chars). + */ + +int +string_get_common_bytes_count (const char *string1, const char *string2) +{ + const char *ptr_str1; + int found; + + if (!string1 || !string2) + return 0; + + found = 0; + ptr_str1 = string1; + while (ptr_str1[0]) + { + if (strchr (string2, ptr_str1[0])) + found++; + ptr_str1++; + } + return found; +} + /* * Returns the distance between two strings using the Levenshtein algorithm. * See: https://en.wikipedia.org/wiki/Levenshtein_distance diff --git a/src/core/wee-string.h b/src/core/wee-string.h index 641855f7f..19c616e5e 100644 --- a/src/core/wee-string.h +++ b/src/core/wee-string.h @@ -134,6 +134,8 @@ extern char *string_hex_dump (const char *data, int data_size, const char *prefix, const char *suffix); extern int string_is_command_char (const char *string); extern const char *string_input_for_buffer (const char *string); +extern int string_get_common_bytes_count (const char *string1, + const char *string2); extern int string_levenshtein (const char *string1, const char *string2, int case_sensitive); extern char *string_replace_with_callback (const char *string, diff --git a/tests/unit/core/test-core-string.cpp b/tests/unit/core/test-core-string.cpp index 671a1327c..ce1468336 100644 --- a/tests/unit/core/test-core-string.cpp +++ b/tests/unit/core/test-core-string.cpp @@ -2542,7 +2542,29 @@ TEST(CoreString, InputForBuffer) /* * Tests functions: - * string_levenshtein + * string_get_common_bytes_count + */ + +TEST(CoreString, GetCommonBytesCount) +{ + LONGS_EQUAL(0, string_get_common_bytes_count (NULL, NULL)); + LONGS_EQUAL(0, string_get_common_bytes_count ("", NULL)); + LONGS_EQUAL(0, string_get_common_bytes_count (NULL, "")); + LONGS_EQUAL(0, string_get_common_bytes_count ("", "")); + + LONGS_EQUAL(1, string_get_common_bytes_count ("a", "a")); + LONGS_EQUAL(0, string_get_common_bytes_count ("a", "b")); + + LONGS_EQUAL(3, string_get_common_bytes_count ("abc", "abc")); + + LONGS_EQUAL(3, string_get_common_bytes_count ("abcdef", "fac")); + + LONGS_EQUAL(4, string_get_common_bytes_count ("noël", "noïl")); +} + +/* + * Tests functions: + * string_levenshtein */ TEST(CoreString, Levenshtein)