Add a comment.
[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                 /* Ignore case and character encoding (and probably some other things) */
45                 ucol_setAttribute(_collator, UCOL_STRENGTH, UCOL_PRIMARY, &status);
46                 ucol_setAttribute(_collator, UCOL_ALTERNATE_HANDLING, UCOL_SHIFTED, &status);
47         }
48 }
49
50
51 Collator::~Collator()
52 {
53         if (_collator) {
54                 ucol_close (_collator);
55         }
56 }
57
58
59 vector<UChar>
60 utf8_to_utf16(string const& utf8)
61 {
62         vector<UChar> utf16(utf8.size() + 1);
63         UErrorCode error = U_ZERO_ERROR;
64         u_strFromUTF8(utf16.data(), utf8.size() + 1, nullptr, utf8.c_str(), -1, &error);
65         DCPOMATIC_ASSERT(error == U_ZERO_ERROR);
66         return utf16;
67 }
68
69
70 int
71 Collator::compare (string const& utf8_a, string const& utf8_b) const
72 {
73         if (_collator) {
74                 auto utf16_a = utf8_to_utf16(utf8_a);
75                 auto utf16_b = utf8_to_utf16(utf8_b);
76                 return ucol_strcoll(_collator, utf16_a.data(), -1, utf16_b.data(), -1);
77         } else {
78                 return strcoll(utf8_a.c_str(), utf8_b.c_str());
79         }
80 }
81