Skip to content

Commit

Permalink
Add localized_compare
Browse files Browse the repository at this point in the history
This is a helper to assist with sorting strings in a locale-aware
manner.
  • Loading branch information
jbytheway committed Apr 25, 2020
1 parent 842ba94 commit 7a6b2c8
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
5 changes: 5 additions & 0 deletions src/translations.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -686,3 +686,8 @@ std::string operator+( const translation &lhs, const translation &rhs )
{
return lhs.translated() + rhs.translated();
}

bool localized_comparator::operator()( const std::string &l, const std::string &r ) const
{
return std::locale()( l, r );
}
29 changes: 29 additions & 0 deletions src/translations.h
Original file line number Diff line number Diff line change
Expand Up @@ -244,4 +244,33 @@ std::string operator+( const translation &lhs, const std::string &rhs );
std::string operator+( const std::string &lhs, const translation &rhs );
std::string operator+( const translation &lhs, const translation &rhs );

// Localized comparison operator, intended for sorting strings when they should
// be sorted according to the user's locale.
//
// For convenience, it also sorts pairs recursively, because a common
// requirement is to sort some list of objects by their names, and this can be
// achieved by sorting a list of pairs where the first element of the pair is
// the translated name.
struct localized_comparator {
template<typename T, typename U>
bool operator()( const std::pair<T, U> &l, const std::pair<T, U> &r ) const {
if( ( *this )( l.first, r.first ) ) {
return true;
}
if( ( *this )( r.first, l.first ) ) {
return false;
}
return ( *this )( l.second, r.second );
}

template<typename T>
bool operator()( const T &l, const T &r ) const {
return l < r;
}

bool operator()( const std::string &, const std::string & ) const;
};

constexpr localized_comparator localized_compare;

#endif // CATA_SRC_TRANSLATIONS_H

0 comments on commit 7a6b2c8

Please sign in to comment.