e88a91143fb2cef3f931448551cf6581b64a6a59
[dcpomatic.git] / src / lib / collator.cc
1 /*
2     Copyright (C) 2022 Carl Hetherington <cth@carlh.net>
3
4     This file is part of DCP-o-matic.
5
6     DCP-o-matic is free software; you can redistribute it and/or modify
7     it under the terms of the GNU General Public License as published by
8     the Free Software Foundation; either version 2 of the License, or
9     (at your option) any later version.
10
11     DCP-o-matic is distributed in the hope that it will be useful,
12     but WITHOUT ANY WARRANTY; without even the implied warranty of
13     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14     GNU General Public License for more details.
15
16     You should have received a copy of the GNU General Public License
17     along with DCP-o-matic.  If not, see <http://www.gnu.org/licenses/>.
18
19 */
20
21
22 #include "collator.h"
23 #include "dcpomatic_assert.h"
24 #include <unicode/putil.h>
25 #include <unicode/ucol.h>
26 #include <unicode/uiter.h>
27 #include <unicode/utypes.h>
28 #include <unicode/ustring.h>
29 #include <boost/scoped_array.hpp>
30 #include <cstring>
31 #include <vector>
32
33
34 using std::string;
35 using std::vector;
36
37
38 Collator::Collator()
39 {
40         UErrorCode status = U_ZERO_ERROR;
41         _collator = ucol_open(nullptr, &status);
42         if (_collator) {
43                 ucol_setAttribute(_collator, UCOL_NORMALIZATION_MODE, UCOL_ON, &status);
44                 ucol_setAttribute(_collator, UCOL_STRENGTH, UCOL_PRIMARY, &status);
45                 ucol_setAttribute(_collator, UCOL_ALTERNATE_HANDLING, UCOL_SHIFTED, &status);
46         }
47 }
48
49
50 Collator::~Collator()
51 {
52         if (_collator) {
53                 ucol_close (_collator);
54         }
55 }
56
57
58 vector<UChar>
59 utf8_to_utf16(string const& utf8)
60 {
61         vector<UChar> utf16(utf8.size() + 1);
62         UErrorCode error = U_ZERO_ERROR;
63         u_strFromUTF8(utf16.data(), utf8.size() + 1, nullptr, utf8.c_str(), -1, &error);
64         DCPOMATIC_ASSERT(error == U_ZERO_ERROR);
65         return utf16;
66 }
67
68
69 int
70 Collator::compare (string const& utf8_a, string const& utf8_b) const
71 {
72         if (_collator) {
73                 auto utf16_a = utf8_to_utf16(utf8_a);
74                 auto utf16_b = utf8_to_utf16(utf8_b);
75                 return ucol_strcoll(_collator, utf16_a.data(), -1, utf16_b.data(), -1);
76         } else {
77                 return strcoll(utf8_a.c_str(), utf8_b.c_str());
78         }
79 }
80