Skip to content

Commit

Permalink
Optimize UnicodeICU localeCompare
Browse files Browse the repository at this point in the history
  • Loading branch information
sujankh committed Nov 10, 2023
1 parent 84732b3 commit d9adb66
Showing 1 changed file with 21 additions and 6 deletions.
27 changes: 21 additions & 6 deletions lib/Platform/Unicode/PlatformUnicodeICU.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,21 @@

#include <time.h>

#include <memory>

namespace hermes {
namespace platform_unicode {

int localeCompare(
llvh::ArrayRef<char16_t> left,
llvh::ArrayRef<char16_t> right) {
namespace {
struct UCollatorDeleter {
void operator()(UCollator *coll) {
if (coll) {
ucol_close(coll);
}
}
};

std::unique_ptr<UCollator, UCollatorDeleter> openUCollator() {
UErrorCode err{U_ZERO_ERROR};
UCollator *coll = ucol_open(uloc_getDefault(), &err);
if (U_FAILURE(err)) {
Expand All @@ -32,16 +41,22 @@ int localeCompare(
// in two different ways to compare as equal.
ucol_setAttribute(coll, UCOL_NORMALIZATION_MODE, UCOL_ON, &err);
assert(U_SUCCESS(err) && "failed to set collator attribute");
return std::unique_ptr<UCollator, UCollatorDeleter>(coll, UCollatorDeleter());
}
} // namespace

int localeCompare(
llvh::ArrayRef<char16_t> left,
llvh::ArrayRef<char16_t> right) {
static auto coll = openUCollator();

auto result = ucol_strcoll(
coll,
coll.get(),
(const UChar *)left.data(),
left.size(),
(const UChar *)right.data(),
right.size());

ucol_close(coll);

switch (result) {
case UCOL_LESS:
return -1;
Expand Down

0 comments on commit d9adb66

Please sign in to comment.