Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 30 additions & 8 deletions libgnucash/core-utils/gnc-unicode.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
#include "gnc-unicode.h"

#include <memory>
#include <vector>
#include <unicode/stsearch.h>
#include <unicode/tblcoll.h>
#include <unicode/coll.h>
Expand Down Expand Up @@ -161,10 +162,15 @@ gnc_unicode_has_substring_identical(const char* needle,
return false;
}

static int
unicode_compare_internal(const char* one, const char* two,
CompareStrength strength)
static icu::Collator*
get_collator(CompareStrength strength)
{
thread_local std::vector<std::pair<CompareStrength, std::unique_ptr<icu::Collator>>> cache;

for (const auto& kvp : cache)
if (kvp.first == strength)
return kvp.second.get();

UErrorCode status{U_ZERO_ERROR};
auto locale{gnc_locale_name()};
std::unique_ptr<icu::Collator> coll(
Expand All @@ -179,21 +185,37 @@ unicode_compare_internal(const char* one, const char* two,
"Failed to create collator for locale %s: %s",
locale, u_errorName(status));
g_free(locale);
return -99;
cache.push_back ({strength, nullptr});
return nullptr;
}

auto* ptr = coll.get();
cache.push_back ({strength, std::move(coll)});

g_free(locale);
return ptr;
}


static int
unicode_compare_internal(const char* one, const char* two,
CompareStrength strength)
{
auto coll = get_collator (strength);
if (!coll)
return -99;

UErrorCode status{U_ZERO_ERROR};
auto result = coll->compare(one, two, status);

if (U_FAILURE(status))
{
g_log(logdomain, G_LOG_LEVEL_ERROR,
"Comparison of %s and %s in locale %s failed: %s",
one, two, locale, u_errorName(status));
g_free(locale);
"Comparison of %s and %s failed: %s",
one, two, u_errorName(status));
return -99;
}

g_free(locale);
return result == UCOL_LESS ? -1 : result == UCOL_EQUAL ? 0 : 1;
}

Expand Down
9 changes: 6 additions & 3 deletions libgnucash/core-utils/test/gtest-gnc-unicode.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,10 @@ TEST(GncUnicode, test_german_ss_decorated_accented_nocap)

TEST (GncUnicode, test_simple_identical)
{
EXPECT_EQ (gnc_unicode_compare_identical ("alice", "alice"), 0);
EXPECT_EQ (gnc_unicode_compare_identical ("alice", "bob"), -1);
EXPECT_EQ (gnc_unicode_compare_identical ("bob", "alice"), 1);
for (int i = 0; i < 5000000; ++i)
{
EXPECT_EQ (gnc_unicode_compare_identical ("alice", "alice"), 0);
EXPECT_EQ (gnc_unicode_compare_identical ("alice", "bob"), -1);
EXPECT_EQ (gnc_unicode_compare_identical ("bob", "alice"), 1);
}
}
Loading