Cleanup: const correctness.
[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 <unicode/putil.h>
24 #include <unicode/ucol.h>
25 #include <unicode/uiter.h>
26 #include <unicode/utypes.h>
27 #include <unicode/ustring.h>
28 #include <boost/scoped_array.hpp>
29 #include <cstring>
30
31
32 using std::string;
33
34
35 Collator::Collator()
36 {
37         UErrorCode status = U_ZERO_ERROR;
38         _collator = ucol_open(nullptr, &status);
39         if (_collator) {
40                 ucol_setAttribute(_collator, UCOL_NORMALIZATION_MODE, UCOL_ON, &status);
41                 ucol_setAttribute(_collator, UCOL_STRENGTH, UCOL_PRIMARY, &status);
42                 ucol_setAttribute(_collator, UCOL_ALTERNATE_HANDLING, UCOL_SHIFTED, &status);
43         }
44 }
45
46
47 Collator::~Collator()
48 {
49         if (_collator) {
50                 ucol_close (_collator);
51         }
52 }
53
54
55 int
56 Collator::compare (string const& utf8_a, string const& utf8_b) const
57 {
58         if (_collator) {
59                 UErrorCode error = U_ZERO_ERROR;
60                 boost::scoped_array<uint16_t> utf16_a(new uint16_t[utf8_a.size() + 1]);
61                 u_strFromUTF8(reinterpret_cast<UChar*>(utf16_a.get()), utf8_a.size() + 1, nullptr, utf8_a.c_str(), -1, &error);
62                 boost::scoped_array<uint16_t> utf16_b(new uint16_t[utf8_b.size() + 1]);
63                 u_strFromUTF8(reinterpret_cast<UChar*>(utf16_b.get()), utf8_b.size() + 1, nullptr, utf8_b.c_str(), -1, &error);
64                 return ucol_strcoll(_collator, reinterpret_cast<UChar*>(utf16_a.get()), -1, reinterpret_cast<UChar*>(utf16_b.get()), -1);
65         } else {
66                 return strcoll(utf8_a.c_str(), utf8_b.c_str());
67         }
68 }
69