1 // © 2019 and later: Unicode, Inc. and others.
2 // License & terms of use: http://www.unicode.org/copyright.html
3
4 // localematcher.cpp
5 // created: 2019may08 Markus W. Scherer
6
7 #include "unicode/utypes.h"
8 #include "unicode/localebuilder.h"
9 #include "unicode/localematcher.h"
10 #include "unicode/locid.h"
11 #include "unicode/stringpiece.h"
12 #include "unicode/uloc.h"
13 #include "unicode/uobject.h"
14 #include "cstring.h"
15 #include "localeprioritylist.h"
16 #include "loclikelysubtags.h"
17 #include "locdistance.h"
18 #include "lsr.h"
19 #include "uassert.h"
20 #include "uhash.h"
21 #include "ustr_imp.h"
22 #include "uvector.h"
23
24 #define UND_LSR LSR("und", "", "", LSR::EXPLICIT_LSR)
25
26 /**
27 * Indicator for the lifetime of desired-locale objects passed into the LocaleMatcher.
28 *
29 * @draft ICU 65
30 */
31 enum ULocMatchLifetime {
32 /**
33 * Locale objects are temporary.
34 * The matcher will make a copy of a locale that will be used beyond one function call.
35 *
36 * @draft ICU 65
37 */
38 ULOCMATCH_TEMPORARY_LOCALES,
39 /**
40 * Locale objects are stored at least as long as the matcher is used.
41 * The matcher will keep only a pointer to a locale that will be used beyond one function call,
42 * avoiding a copy.
43 *
44 * @draft ICU 65
45 */
46 ULOCMATCH_STORED_LOCALES // TODO: permanent? cached? clone?
47 };
48 #ifndef U_IN_DOXYGEN
49 typedef enum ULocMatchLifetime ULocMatchLifetime;
50 #endif
51
52 U_NAMESPACE_BEGIN
53
Result(LocaleMatcher::Result && src)54 LocaleMatcher::Result::Result(LocaleMatcher::Result &&src) U_NOEXCEPT :
55 desiredLocale(src.desiredLocale),
56 supportedLocale(src.supportedLocale),
57 desiredIndex(src.desiredIndex),
58 supportedIndex(src.supportedIndex),
59 desiredIsOwned(src.desiredIsOwned) {
60 if (desiredIsOwned) {
61 src.desiredLocale = nullptr;
62 src.desiredIndex = -1;
63 src.desiredIsOwned = FALSE;
64 }
65 }
66
~Result()67 LocaleMatcher::Result::~Result() {
68 if (desiredIsOwned) {
69 delete desiredLocale;
70 }
71 }
72
operator =(LocaleMatcher::Result && src)73 LocaleMatcher::Result &LocaleMatcher::Result::operator=(LocaleMatcher::Result &&src) U_NOEXCEPT {
74 this->~Result();
75
76 desiredLocale = src.desiredLocale;
77 supportedLocale = src.supportedLocale;
78 desiredIndex = src.desiredIndex;
79 supportedIndex = src.supportedIndex;
80 desiredIsOwned = src.desiredIsOwned;
81
82 if (desiredIsOwned) {
83 src.desiredLocale = nullptr;
84 src.desiredIndex = -1;
85 src.desiredIsOwned = FALSE;
86 }
87 return *this;
88 }
89
makeResolvedLocale(UErrorCode & errorCode) const90 Locale LocaleMatcher::Result::makeResolvedLocale(UErrorCode &errorCode) const {
91 if (U_FAILURE(errorCode) || supportedLocale == nullptr) {
92 return Locale::getRoot();
93 }
94 const Locale *bestDesired = getDesiredLocale();
95 if (bestDesired == nullptr || *supportedLocale == *bestDesired) {
96 return *supportedLocale;
97 }
98 LocaleBuilder b;
99 b.setLocale(*supportedLocale);
100
101 // Copy the region from bestDesired, if there is one.
102 const char *region = bestDesired->getCountry();
103 if (*region != 0) {
104 b.setRegion(region);
105 }
106
107 // Copy the variants from bestDesired, if there are any.
108 // Note that this will override any supportedLocale variants.
109 // For example, "sco-ulster-fonipa" + "...-fonupa" => "sco-fonupa" (replacing ulster).
110 const char *variants = bestDesired->getVariant();
111 if (*variants != 0) {
112 b.setVariant(variants);
113 }
114
115 // Copy the extensions from bestDesired, if there are any.
116 // C++ note: The following note, copied from Java, may not be true,
117 // as long as C++ copies by legacy ICU keyword, not by extension singleton.
118 // Note that this will override any supportedLocale extensions.
119 // For example, "th-u-nu-latn-ca-buddhist" + "...-u-nu-native" => "th-u-nu-native"
120 // (replacing calendar).
121 b.copyExtensionsFrom(*bestDesired, errorCode);
122 return b.build(errorCode);
123 }
124
Builder(LocaleMatcher::Builder && src)125 LocaleMatcher::Builder::Builder(LocaleMatcher::Builder &&src) U_NOEXCEPT :
126 errorCode_(src.errorCode_),
127 supportedLocales_(src.supportedLocales_),
128 thresholdDistance_(src.thresholdDistance_),
129 demotion_(src.demotion_),
130 defaultLocale_(src.defaultLocale_),
131 withDefault_(src.withDefault_),
132 favor_(src.favor_),
133 direction_(src.direction_) {
134 src.supportedLocales_ = nullptr;
135 src.defaultLocale_ = nullptr;
136 }
137
~Builder()138 LocaleMatcher::Builder::~Builder() {
139 delete supportedLocales_;
140 delete defaultLocale_;
141 delete maxDistanceDesired_;
142 delete maxDistanceSupported_;
143 }
144
operator =(LocaleMatcher::Builder && src)145 LocaleMatcher::Builder &LocaleMatcher::Builder::operator=(LocaleMatcher::Builder &&src) U_NOEXCEPT {
146 this->~Builder();
147
148 errorCode_ = src.errorCode_;
149 supportedLocales_ = src.supportedLocales_;
150 thresholdDistance_ = src.thresholdDistance_;
151 demotion_ = src.demotion_;
152 defaultLocale_ = src.defaultLocale_;
153 withDefault_ = src.withDefault_,
154 favor_ = src.favor_;
155 direction_ = src.direction_;
156
157 src.supportedLocales_ = nullptr;
158 src.defaultLocale_ = nullptr;
159 return *this;
160 }
161
clearSupportedLocales()162 void LocaleMatcher::Builder::clearSupportedLocales() {
163 if (supportedLocales_ != nullptr) {
164 supportedLocales_->removeAllElements();
165 }
166 }
167
ensureSupportedLocaleVector()168 bool LocaleMatcher::Builder::ensureSupportedLocaleVector() {
169 if (U_FAILURE(errorCode_)) { return false; }
170 if (supportedLocales_ != nullptr) { return true; }
171 supportedLocales_ = new UVector(uprv_deleteUObject, nullptr, errorCode_);
172 if (U_FAILURE(errorCode_)) { return false; }
173 if (supportedLocales_ == nullptr) {
174 errorCode_ = U_MEMORY_ALLOCATION_ERROR;
175 return false;
176 }
177 return true;
178 }
179
setSupportedLocalesFromListString(StringPiece locales)180 LocaleMatcher::Builder &LocaleMatcher::Builder::setSupportedLocalesFromListString(
181 StringPiece locales) {
182 LocalePriorityList list(locales, errorCode_);
183 if (U_FAILURE(errorCode_)) { return *this; }
184 clearSupportedLocales();
185 if (!ensureSupportedLocaleVector()) { return *this; }
186 int32_t length = list.getLengthIncludingRemoved();
187 for (int32_t i = 0; i < length; ++i) {
188 Locale *locale = list.orphanLocaleAt(i);
189 if (locale == nullptr) { continue; }
190 supportedLocales_->addElement(locale, errorCode_);
191 if (U_FAILURE(errorCode_)) {
192 delete locale;
193 break;
194 }
195 }
196 return *this;
197 }
198
setSupportedLocales(Locale::Iterator & locales)199 LocaleMatcher::Builder &LocaleMatcher::Builder::setSupportedLocales(Locale::Iterator &locales) {
200 if (U_FAILURE(errorCode_)) { return *this; }
201 clearSupportedLocales();
202 if (!ensureSupportedLocaleVector()) { return *this; }
203 while (locales.hasNext()) {
204 const Locale &locale = locales.next();
205 Locale *clone = locale.clone();
206 if (clone == nullptr) {
207 errorCode_ = U_MEMORY_ALLOCATION_ERROR;
208 break;
209 }
210 supportedLocales_->addElement(clone, errorCode_);
211 if (U_FAILURE(errorCode_)) {
212 delete clone;
213 break;
214 }
215 }
216 return *this;
217 }
218
addSupportedLocale(const Locale & locale)219 LocaleMatcher::Builder &LocaleMatcher::Builder::addSupportedLocale(const Locale &locale) {
220 if (!ensureSupportedLocaleVector()) { return *this; }
221 Locale *clone = locale.clone();
222 if (clone == nullptr) {
223 errorCode_ = U_MEMORY_ALLOCATION_ERROR;
224 return *this;
225 }
226 supportedLocales_->addElement(clone, errorCode_);
227 if (U_FAILURE(errorCode_)) {
228 delete clone;
229 }
230 return *this;
231 }
232
setNoDefaultLocale()233 LocaleMatcher::Builder &LocaleMatcher::Builder::setNoDefaultLocale() {
234 if (U_FAILURE(errorCode_)) { return *this; }
235 delete defaultLocale_;
236 defaultLocale_ = nullptr;
237 withDefault_ = false;
238 return *this;
239 }
240
setDefaultLocale(const Locale * defaultLocale)241 LocaleMatcher::Builder &LocaleMatcher::Builder::setDefaultLocale(const Locale *defaultLocale) {
242 if (U_FAILURE(errorCode_)) { return *this; }
243 Locale *clone = nullptr;
244 if (defaultLocale != nullptr) {
245 clone = defaultLocale->clone();
246 if (clone == nullptr) {
247 errorCode_ = U_MEMORY_ALLOCATION_ERROR;
248 return *this;
249 }
250 }
251 delete defaultLocale_;
252 defaultLocale_ = clone;
253 withDefault_ = true;
254 return *this;
255 }
256
setFavorSubtag(ULocMatchFavorSubtag subtag)257 LocaleMatcher::Builder &LocaleMatcher::Builder::setFavorSubtag(ULocMatchFavorSubtag subtag) {
258 if (U_FAILURE(errorCode_)) { return *this; }
259 favor_ = subtag;
260 return *this;
261 }
262
setDemotionPerDesiredLocale(ULocMatchDemotion demotion)263 LocaleMatcher::Builder &LocaleMatcher::Builder::setDemotionPerDesiredLocale(ULocMatchDemotion demotion) {
264 if (U_FAILURE(errorCode_)) { return *this; }
265 demotion_ = demotion;
266 return *this;
267 }
268
setMaxDistance(const Locale & desired,const Locale & supported)269 LocaleMatcher::Builder &LocaleMatcher::Builder::setMaxDistance(const Locale &desired,
270 const Locale &supported) {
271 if (U_FAILURE(errorCode_)) { return *this; }
272 Locale *desiredClone = desired.clone();
273 Locale *supportedClone = supported.clone();
274 if (desiredClone == nullptr || supportedClone == nullptr) {
275 delete desiredClone; // in case only one could not be allocated
276 delete supportedClone;
277 errorCode_ = U_MEMORY_ALLOCATION_ERROR;
278 return *this;
279 }
280 delete maxDistanceDesired_;
281 delete maxDistanceSupported_;
282 maxDistanceDesired_ = desiredClone;
283 maxDistanceSupported_ = supportedClone;
284 return *this;
285 }
286
287 #if 0
288 /**
289 * <i>Internal only!</i>
290 *
291 * @param thresholdDistance the thresholdDistance to set, with -1 = default
292 * @return this Builder object
293 * @internal
294 * @deprecated This API is ICU internal only.
295 */
296 @Deprecated
297 LocaleMatcher::Builder &LocaleMatcher::Builder::internalSetThresholdDistance(int32_t thresholdDistance) {
298 if (U_FAILURE(errorCode_)) { return *this; }
299 if (thresholdDistance > 100) {
300 thresholdDistance = 100;
301 }
302 thresholdDistance_ = thresholdDistance;
303 return *this;
304 }
305 #endif
306
copyErrorTo(UErrorCode & outErrorCode) const307 UBool LocaleMatcher::Builder::copyErrorTo(UErrorCode &outErrorCode) const {
308 if (U_FAILURE(outErrorCode)) { return TRUE; }
309 if (U_SUCCESS(errorCode_)) { return FALSE; }
310 outErrorCode = errorCode_;
311 return TRUE;
312 }
313
build(UErrorCode & errorCode) const314 LocaleMatcher LocaleMatcher::Builder::build(UErrorCode &errorCode) const {
315 if (U_SUCCESS(errorCode) && U_FAILURE(errorCode_)) {
316 errorCode = errorCode_;
317 }
318 return LocaleMatcher(*this, errorCode);
319 }
320
321 namespace {
322
getMaximalLsrOrUnd(const XLikelySubtags & likelySubtags,const Locale & locale,UErrorCode & errorCode)323 LSR getMaximalLsrOrUnd(const XLikelySubtags &likelySubtags, const Locale &locale,
324 UErrorCode &errorCode) {
325 if (U_FAILURE(errorCode) || locale.isBogus() || *locale.getName() == 0 /* "und" */) {
326 return UND_LSR;
327 } else {
328 return likelySubtags.makeMaximizedLsrFrom(locale, errorCode);
329 }
330 }
331
hashLSR(const UHashTok token)332 int32_t hashLSR(const UHashTok token) {
333 const LSR *lsr = static_cast<const LSR *>(token.pointer);
334 return lsr->hashCode;
335 }
336
compareLSRs(const UHashTok t1,const UHashTok t2)337 UBool compareLSRs(const UHashTok t1, const UHashTok t2) {
338 const LSR *lsr1 = static_cast<const LSR *>(t1.pointer);
339 const LSR *lsr2 = static_cast<const LSR *>(t2.pointer);
340 return *lsr1 == *lsr2;
341 }
342
343 } // namespace
344
putIfAbsent(const LSR & lsr,int32_t i,int32_t suppLength,UErrorCode & errorCode)345 int32_t LocaleMatcher::putIfAbsent(const LSR &lsr, int32_t i, int32_t suppLength,
346 UErrorCode &errorCode) {
347 if (U_FAILURE(errorCode)) { return suppLength; }
348 if (!uhash_containsKey(supportedLsrToIndex, &lsr)) {
349 uhash_putiAllowZero(supportedLsrToIndex, const_cast<LSR *>(&lsr), i, &errorCode);
350 if (U_SUCCESS(errorCode)) {
351 supportedLSRs[suppLength] = &lsr;
352 supportedIndexes[suppLength++] = i;
353 }
354 }
355 return suppLength;
356 }
357
LocaleMatcher(const Builder & builder,UErrorCode & errorCode)358 LocaleMatcher::LocaleMatcher(const Builder &builder, UErrorCode &errorCode) :
359 likelySubtags(*XLikelySubtags::getSingleton(errorCode)),
360 localeDistance(*LocaleDistance::getSingleton(errorCode)),
361 thresholdDistance(builder.thresholdDistance_),
362 demotionPerDesiredLocale(0),
363 favorSubtag(builder.favor_),
364 direction(builder.direction_),
365 supportedLocales(nullptr), lsrs(nullptr), supportedLocalesLength(0),
366 supportedLsrToIndex(nullptr),
367 supportedLSRs(nullptr), supportedIndexes(nullptr), supportedLSRsLength(0),
368 ownedDefaultLocale(nullptr), defaultLocale(nullptr) {
369 if (U_FAILURE(errorCode)) { return; }
370 const Locale *def = builder.defaultLocale_;
371 LSR builderDefaultLSR;
372 const LSR *defLSR = nullptr;
373 if (def != nullptr) {
374 ownedDefaultLocale = def->clone();
375 if (ownedDefaultLocale == nullptr) {
376 errorCode = U_MEMORY_ALLOCATION_ERROR;
377 return;
378 }
379 def = ownedDefaultLocale;
380 builderDefaultLSR = getMaximalLsrOrUnd(likelySubtags, *def, errorCode);
381 if (U_FAILURE(errorCode)) { return; }
382 defLSR = &builderDefaultLSR;
383 }
384 supportedLocalesLength = builder.supportedLocales_ != nullptr ?
385 builder.supportedLocales_->size() : 0;
386 if (supportedLocalesLength > 0) {
387 // Store the supported locales in input order,
388 // so that when different types are used (e.g., language tag strings)
389 // we can return those by parallel index.
390 supportedLocales = static_cast<const Locale **>(
391 uprv_malloc(supportedLocalesLength * sizeof(const Locale *)));
392 // Supported LRSs in input order.
393 // In C++, we store these permanently to simplify ownership management
394 // in the hash tables. Duplicate LSRs (if any) are unused overhead.
395 lsrs = new LSR[supportedLocalesLength];
396 if (supportedLocales == nullptr || lsrs == nullptr) {
397 errorCode = U_MEMORY_ALLOCATION_ERROR;
398 return;
399 }
400 // If the constructor fails partway, we need null pointers for destructibility.
401 uprv_memset(supportedLocales, 0, supportedLocalesLength * sizeof(const Locale *));
402 for (int32_t i = 0; i < supportedLocalesLength; ++i) {
403 const Locale &locale = *static_cast<Locale *>(builder.supportedLocales_->elementAt(i));
404 supportedLocales[i] = locale.clone();
405 if (supportedLocales[i] == nullptr) {
406 errorCode = U_MEMORY_ALLOCATION_ERROR;
407 return;
408 }
409 const Locale &supportedLocale = *supportedLocales[i];
410 LSR &lsr = lsrs[i] = getMaximalLsrOrUnd(likelySubtags, supportedLocale, errorCode);
411 lsr.setHashCode();
412 if (U_FAILURE(errorCode)) { return; }
413 }
414
415 // We need an unordered map from LSR to first supported locale with that LSR,
416 // and an ordered list of (LSR, supported index) for
417 // the supported locales in the following order:
418 // 1. Default locale, if it is supported.
419 // 2. Priority locales (aka "paradigm locales") in builder order.
420 // 3. Remaining locales in builder order.
421 supportedLsrToIndex = uhash_openSize(hashLSR, compareLSRs, uhash_compareLong,
422 supportedLocalesLength, &errorCode);
423 if (U_FAILURE(errorCode)) { return; }
424 supportedLSRs = static_cast<const LSR **>(
425 uprv_malloc(supportedLocalesLength * sizeof(const LSR *)));
426 supportedIndexes = static_cast<int32_t *>(
427 uprv_malloc(supportedLocalesLength * sizeof(int32_t)));
428 if (supportedLSRs == nullptr || supportedIndexes == nullptr) {
429 errorCode = U_MEMORY_ALLOCATION_ERROR;
430 return;
431 }
432 int32_t suppLength = 0;
433 // Determine insertion order.
434 // Add locales immediately that are equivalent to the default.
435 MaybeStackArray<int8_t, 100> order(supportedLocalesLength, errorCode);
436 if (U_FAILURE(errorCode)) { return; }
437 int32_t numParadigms = 0;
438 for (int32_t i = 0; i < supportedLocalesLength; ++i) {
439 const Locale &locale = *supportedLocales[i];
440 const LSR &lsr = lsrs[i];
441 if (defLSR == nullptr && builder.withDefault_) {
442 // Implicit default locale = first supported locale, if not turned off.
443 U_ASSERT(i == 0);
444 def = &locale;
445 defLSR = &lsr;
446 order[i] = 1;
447 suppLength = putIfAbsent(lsr, 0, suppLength, errorCode);
448 } else if (defLSR != nullptr && lsr.isEquivalentTo(*defLSR)) {
449 order[i] = 1;
450 suppLength = putIfAbsent(lsr, i, suppLength, errorCode);
451 } else if (localeDistance.isParadigmLSR(lsr)) {
452 order[i] = 2;
453 ++numParadigms;
454 } else {
455 order[i] = 3;
456 }
457 if (U_FAILURE(errorCode)) { return; }
458 }
459 // Add supported paradigm locales.
460 int32_t paradigmLimit = suppLength + numParadigms;
461 for (int32_t i = 0; i < supportedLocalesLength && suppLength < paradigmLimit; ++i) {
462 if (order[i] == 2) {
463 suppLength = putIfAbsent(lsrs[i], i, suppLength, errorCode);
464 }
465 }
466 // Add remaining supported locales.
467 for (int32_t i = 0; i < supportedLocalesLength; ++i) {
468 if (order[i] == 3) {
469 suppLength = putIfAbsent(lsrs[i], i, suppLength, errorCode);
470 }
471 }
472 supportedLSRsLength = suppLength;
473 // If supportedLSRsLength < supportedLocalesLength then
474 // we waste as many array slots as there are duplicate supported LSRs,
475 // but the amount of wasted space is small as long as there are few duplicates.
476 }
477
478 defaultLocale = def;
479
480 if (builder.demotion_ == ULOCMATCH_DEMOTION_REGION) {
481 demotionPerDesiredLocale = localeDistance.getDefaultDemotionPerDesiredLocale();
482 }
483
484 if (thresholdDistance >= 0) {
485 // already copied
486 } else if (builder.maxDistanceDesired_ != nullptr) {
487 LSR suppLSR = getMaximalLsrOrUnd(likelySubtags, *builder.maxDistanceSupported_, errorCode);
488 const LSR *pSuppLSR = &suppLSR;
489 int32_t indexAndDistance = localeDistance.getBestIndexAndDistance(
490 getMaximalLsrOrUnd(likelySubtags, *builder.maxDistanceDesired_, errorCode),
491 &pSuppLSR, 1,
492 LocaleDistance::shiftDistance(100), favorSubtag, direction);
493 if (U_SUCCESS(errorCode)) {
494 // +1 for an exclusive threshold from an inclusive max.
495 thresholdDistance = LocaleDistance::getDistanceFloor(indexAndDistance) + 1;
496 } else {
497 thresholdDistance = 0;
498 }
499 } else {
500 thresholdDistance = localeDistance.getDefaultScriptDistance();
501 }
502 }
503
LocaleMatcher(LocaleMatcher && src)504 LocaleMatcher::LocaleMatcher(LocaleMatcher &&src) U_NOEXCEPT :
505 likelySubtags(src.likelySubtags),
506 localeDistance(src.localeDistance),
507 thresholdDistance(src.thresholdDistance),
508 demotionPerDesiredLocale(src.demotionPerDesiredLocale),
509 favorSubtag(src.favorSubtag),
510 direction(src.direction),
511 supportedLocales(src.supportedLocales), lsrs(src.lsrs),
512 supportedLocalesLength(src.supportedLocalesLength),
513 supportedLsrToIndex(src.supportedLsrToIndex),
514 supportedLSRs(src.supportedLSRs),
515 supportedIndexes(src.supportedIndexes),
516 supportedLSRsLength(src.supportedLSRsLength),
517 ownedDefaultLocale(src.ownedDefaultLocale), defaultLocale(src.defaultLocale) {
518 src.supportedLocales = nullptr;
519 src.lsrs = nullptr;
520 src.supportedLocalesLength = 0;
521 src.supportedLsrToIndex = nullptr;
522 src.supportedLSRs = nullptr;
523 src.supportedIndexes = nullptr;
524 src.supportedLSRsLength = 0;
525 src.ownedDefaultLocale = nullptr;
526 src.defaultLocale = nullptr;
527 }
528
~LocaleMatcher()529 LocaleMatcher::~LocaleMatcher() {
530 for (int32_t i = 0; i < supportedLocalesLength; ++i) {
531 delete supportedLocales[i];
532 }
533 uprv_free(supportedLocales);
534 delete[] lsrs;
535 uhash_close(supportedLsrToIndex);
536 uprv_free(supportedLSRs);
537 uprv_free(supportedIndexes);
538 delete ownedDefaultLocale;
539 }
540
operator =(LocaleMatcher && src)541 LocaleMatcher &LocaleMatcher::operator=(LocaleMatcher &&src) U_NOEXCEPT {
542 this->~LocaleMatcher();
543
544 thresholdDistance = src.thresholdDistance;
545 demotionPerDesiredLocale = src.demotionPerDesiredLocale;
546 favorSubtag = src.favorSubtag;
547 direction = src.direction;
548 supportedLocales = src.supportedLocales;
549 lsrs = src.lsrs;
550 supportedLocalesLength = src.supportedLocalesLength;
551 supportedLsrToIndex = src.supportedLsrToIndex;
552 supportedLSRs = src.supportedLSRs;
553 supportedIndexes = src.supportedIndexes;
554 supportedLSRsLength = src.supportedLSRsLength;
555 ownedDefaultLocale = src.ownedDefaultLocale;
556 defaultLocale = src.defaultLocale;
557
558 src.supportedLocales = nullptr;
559 src.lsrs = nullptr;
560 src.supportedLocalesLength = 0;
561 src.supportedLsrToIndex = nullptr;
562 src.supportedLSRs = nullptr;
563 src.supportedIndexes = nullptr;
564 src.supportedLSRsLength = 0;
565 src.ownedDefaultLocale = nullptr;
566 src.defaultLocale = nullptr;
567 return *this;
568 }
569
570 class LocaleLsrIterator {
571 public:
LocaleLsrIterator(const XLikelySubtags & likelySubtags,Locale::Iterator & locales,ULocMatchLifetime lifetime)572 LocaleLsrIterator(const XLikelySubtags &likelySubtags, Locale::Iterator &locales,
573 ULocMatchLifetime lifetime) :
574 likelySubtags(likelySubtags), locales(locales), lifetime(lifetime) {}
575
~LocaleLsrIterator()576 ~LocaleLsrIterator() {
577 if (lifetime == ULOCMATCH_TEMPORARY_LOCALES) {
578 delete remembered;
579 }
580 }
581
hasNext() const582 bool hasNext() const {
583 return locales.hasNext();
584 }
585
next(UErrorCode & errorCode)586 LSR next(UErrorCode &errorCode) {
587 current = &locales.next();
588 return getMaximalLsrOrUnd(likelySubtags, *current, errorCode);
589 }
590
rememberCurrent(int32_t desiredIndex,UErrorCode & errorCode)591 void rememberCurrent(int32_t desiredIndex, UErrorCode &errorCode) {
592 if (U_FAILURE(errorCode)) { return; }
593 bestDesiredIndex = desiredIndex;
594 if (lifetime == ULOCMATCH_STORED_LOCALES) {
595 remembered = current;
596 } else {
597 // ULOCMATCH_TEMPORARY_LOCALES
598 delete remembered;
599 remembered = new Locale(*current);
600 if (remembered == nullptr) {
601 errorCode = U_MEMORY_ALLOCATION_ERROR;
602 }
603 }
604 }
605
orphanRemembered()606 const Locale *orphanRemembered() {
607 const Locale *rem = remembered;
608 remembered = nullptr;
609 return rem;
610 }
611
getBestDesiredIndex() const612 int32_t getBestDesiredIndex() const {
613 return bestDesiredIndex;
614 }
615
616 private:
617 const XLikelySubtags &likelySubtags;
618 Locale::Iterator &locales;
619 ULocMatchLifetime lifetime;
620 const Locale *current = nullptr, *remembered = nullptr;
621 int32_t bestDesiredIndex = -1;
622 };
623
getBestMatch(const Locale & desiredLocale,UErrorCode & errorCode) const624 const Locale *LocaleMatcher::getBestMatch(const Locale &desiredLocale, UErrorCode &errorCode) const {
625 if (U_FAILURE(errorCode)) { return nullptr; }
626 int32_t suppIndex = getBestSuppIndex(
627 getMaximalLsrOrUnd(likelySubtags, desiredLocale, errorCode),
628 nullptr, errorCode);
629 return U_SUCCESS(errorCode) && suppIndex >= 0 ? supportedLocales[suppIndex] : defaultLocale;
630 }
631
getBestMatch(Locale::Iterator & desiredLocales,UErrorCode & errorCode) const632 const Locale *LocaleMatcher::getBestMatch(Locale::Iterator &desiredLocales,
633 UErrorCode &errorCode) const {
634 if (U_FAILURE(errorCode)) { return nullptr; }
635 if (!desiredLocales.hasNext()) {
636 return defaultLocale;
637 }
638 LocaleLsrIterator lsrIter(likelySubtags, desiredLocales, ULOCMATCH_TEMPORARY_LOCALES);
639 int32_t suppIndex = getBestSuppIndex(lsrIter.next(errorCode), &lsrIter, errorCode);
640 return U_SUCCESS(errorCode) && suppIndex >= 0 ? supportedLocales[suppIndex] : defaultLocale;
641 }
642
getBestMatchForListString(StringPiece desiredLocaleList,UErrorCode & errorCode) const643 const Locale *LocaleMatcher::getBestMatchForListString(
644 StringPiece desiredLocaleList, UErrorCode &errorCode) const {
645 LocalePriorityList list(desiredLocaleList, errorCode);
646 LocalePriorityList::Iterator iter = list.iterator();
647 return getBestMatch(iter, errorCode);
648 }
649
getBestMatchResult(const Locale & desiredLocale,UErrorCode & errorCode) const650 LocaleMatcher::Result LocaleMatcher::getBestMatchResult(
651 const Locale &desiredLocale, UErrorCode &errorCode) const {
652 if (U_FAILURE(errorCode)) {
653 return Result(nullptr, defaultLocale, -1, -1, FALSE);
654 }
655 int32_t suppIndex = getBestSuppIndex(
656 getMaximalLsrOrUnd(likelySubtags, desiredLocale, errorCode),
657 nullptr, errorCode);
658 if (U_FAILURE(errorCode) || suppIndex < 0) {
659 return Result(nullptr, defaultLocale, -1, -1, FALSE);
660 } else {
661 return Result(&desiredLocale, supportedLocales[suppIndex], 0, suppIndex, FALSE);
662 }
663 }
664
getBestMatchResult(Locale::Iterator & desiredLocales,UErrorCode & errorCode) const665 LocaleMatcher::Result LocaleMatcher::getBestMatchResult(
666 Locale::Iterator &desiredLocales, UErrorCode &errorCode) const {
667 if (U_FAILURE(errorCode) || !desiredLocales.hasNext()) {
668 return Result(nullptr, defaultLocale, -1, -1, FALSE);
669 }
670 LocaleLsrIterator lsrIter(likelySubtags, desiredLocales, ULOCMATCH_TEMPORARY_LOCALES);
671 int32_t suppIndex = getBestSuppIndex(lsrIter.next(errorCode), &lsrIter, errorCode);
672 if (U_FAILURE(errorCode) || suppIndex < 0) {
673 return Result(nullptr, defaultLocale, -1, -1, FALSE);
674 } else {
675 return Result(lsrIter.orphanRemembered(), supportedLocales[suppIndex],
676 lsrIter.getBestDesiredIndex(), suppIndex, TRUE);
677 }
678 }
679
getBestSuppIndex(LSR desiredLSR,LocaleLsrIterator * remainingIter,UErrorCode & errorCode) const680 int32_t LocaleMatcher::getBestSuppIndex(LSR desiredLSR, LocaleLsrIterator *remainingIter,
681 UErrorCode &errorCode) const {
682 if (U_FAILURE(errorCode)) { return -1; }
683 int32_t desiredIndex = 0;
684 int32_t bestSupportedLsrIndex = -1;
685 for (int32_t bestShiftedDistance = LocaleDistance::shiftDistance(thresholdDistance);;) {
686 // Quick check for exact maximized LSR.
687 if (supportedLsrToIndex != nullptr) {
688 desiredLSR.setHashCode();
689 UBool found = false;
690 int32_t suppIndex = uhash_getiAndFound(supportedLsrToIndex, &desiredLSR, &found);
691 if (found) {
692 if (remainingIter != nullptr) {
693 remainingIter->rememberCurrent(desiredIndex, errorCode);
694 }
695 return suppIndex;
696 }
697 }
698 int32_t bestIndexAndDistance = localeDistance.getBestIndexAndDistance(
699 desiredLSR, supportedLSRs, supportedLSRsLength,
700 bestShiftedDistance, favorSubtag, direction);
701 if (bestIndexAndDistance >= 0) {
702 bestShiftedDistance = LocaleDistance::getShiftedDistance(bestIndexAndDistance);
703 if (remainingIter != nullptr) {
704 remainingIter->rememberCurrent(desiredIndex, errorCode);
705 if (U_FAILURE(errorCode)) { return -1; }
706 }
707 bestSupportedLsrIndex = LocaleDistance::getIndex(bestIndexAndDistance);
708 }
709 if ((bestShiftedDistance -= LocaleDistance::shiftDistance(demotionPerDesiredLocale)) <= 0) {
710 break;
711 }
712 if (remainingIter == nullptr || !remainingIter->hasNext()) {
713 break;
714 }
715 desiredLSR = remainingIter->next(errorCode);
716 if (U_FAILURE(errorCode)) { return -1; }
717 ++desiredIndex;
718 }
719 if (bestSupportedLsrIndex < 0) {
720 // no good match
721 return -1;
722 }
723 return supportedIndexes[bestSupportedLsrIndex];
724 }
725
isMatch(const Locale & desired,const Locale & supported,UErrorCode & errorCode) const726 UBool LocaleMatcher::isMatch(const Locale &desired, const Locale &supported,
727 UErrorCode &errorCode) const {
728 LSR suppLSR = getMaximalLsrOrUnd(likelySubtags, supported, errorCode);
729 if (U_FAILURE(errorCode)) { return 0; }
730 const LSR *pSuppLSR = &suppLSR;
731 int32_t indexAndDistance = localeDistance.getBestIndexAndDistance(
732 getMaximalLsrOrUnd(likelySubtags, desired, errorCode),
733 &pSuppLSR, 1,
734 LocaleDistance::shiftDistance(thresholdDistance), favorSubtag, direction);
735 return indexAndDistance >= 0;
736 }
737
internalMatch(const Locale & desired,const Locale & supported,UErrorCode & errorCode) const738 double LocaleMatcher::internalMatch(const Locale &desired, const Locale &supported, UErrorCode &errorCode) const {
739 // Returns the inverse of the distance: That is, 1-distance(desired, supported).
740 LSR suppLSR = getMaximalLsrOrUnd(likelySubtags, supported, errorCode);
741 if (U_FAILURE(errorCode)) { return 0; }
742 const LSR *pSuppLSR = &suppLSR;
743 int32_t indexAndDistance = localeDistance.getBestIndexAndDistance(
744 getMaximalLsrOrUnd(likelySubtags, desired, errorCode),
745 &pSuppLSR, 1,
746 LocaleDistance::shiftDistance(thresholdDistance), favorSubtag, direction);
747 double distance = LocaleDistance::getDistanceDouble(indexAndDistance);
748 return (100.0 - distance) / 100.0;
749 }
750
751 U_NAMESPACE_END
752
753 // uloc_acceptLanguage() --------------------------------------------------- ***
754
755 U_NAMESPACE_USE
756
757 namespace {
758
759 class LocaleFromTag {
760 public:
LocaleFromTag()761 LocaleFromTag() : locale(Locale::getRoot()) {}
operator ()(const char * tag)762 const Locale &operator()(const char *tag) { return locale = Locale(tag); }
763
764 private:
765 // Store the locale in the converter, rather than return a reference to a temporary,
766 // or a value which could go out of scope with the caller's reference to it.
767 Locale locale;
768 };
769
acceptLanguage(UEnumeration & supportedLocales,Locale::Iterator & desiredLocales,char * dest,int32_t capacity,UAcceptResult * acceptResult,UErrorCode & errorCode)770 int32_t acceptLanguage(UEnumeration &supportedLocales, Locale::Iterator &desiredLocales,
771 char *dest, int32_t capacity, UAcceptResult *acceptResult,
772 UErrorCode &errorCode) {
773 if (U_FAILURE(errorCode)) { return 0; }
774 LocaleMatcher::Builder builder;
775 const char *locString;
776 while ((locString = uenum_next(&supportedLocales, nullptr, &errorCode)) != nullptr) {
777 Locale loc(locString);
778 if (loc.isBogus()) {
779 errorCode = U_ILLEGAL_ARGUMENT_ERROR;
780 return 0;
781 }
782 builder.addSupportedLocale(loc);
783 }
784 LocaleMatcher matcher = builder.build(errorCode);
785 LocaleMatcher::Result result = matcher.getBestMatchResult(desiredLocales, errorCode);
786 if (U_FAILURE(errorCode)) { return 0; }
787 if (result.getDesiredIndex() >= 0) {
788 if (acceptResult != nullptr) {
789 *acceptResult = *result.getDesiredLocale() == *result.getSupportedLocale() ?
790 ULOC_ACCEPT_VALID : ULOC_ACCEPT_FALLBACK;
791 }
792 const char *bestStr = result.getSupportedLocale()->getName();
793 int32_t bestLength = (int32_t)uprv_strlen(bestStr);
794 if (bestLength <= capacity) {
795 uprv_memcpy(dest, bestStr, bestLength);
796 }
797 return u_terminateChars(dest, capacity, bestLength, &errorCode);
798 } else {
799 if (acceptResult != nullptr) {
800 *acceptResult = ULOC_ACCEPT_FAILED;
801 }
802 return u_terminateChars(dest, capacity, 0, &errorCode);
803 }
804 }
805
806 } // namespace
807
808 U_CAPI int32_t U_EXPORT2
uloc_acceptLanguage(char * result,int32_t resultAvailable,UAcceptResult * outResult,const char ** acceptList,int32_t acceptListCount,UEnumeration * availableLocales,UErrorCode * status)809 uloc_acceptLanguage(char *result, int32_t resultAvailable,
810 UAcceptResult *outResult,
811 const char **acceptList, int32_t acceptListCount,
812 UEnumeration *availableLocales,
813 UErrorCode *status) {
814 if (U_FAILURE(*status)) { return 0; }
815 if ((result == nullptr ? resultAvailable != 0 : resultAvailable < 0) ||
816 (acceptList == nullptr ? acceptListCount != 0 : acceptListCount < 0) ||
817 availableLocales == nullptr) {
818 *status = U_ILLEGAL_ARGUMENT_ERROR;
819 return 0;
820 }
821 LocaleFromTag converter;
822 Locale::ConvertingIterator<const char **, LocaleFromTag> desiredLocales(
823 acceptList, acceptList + acceptListCount, converter);
824 return acceptLanguage(*availableLocales, desiredLocales,
825 result, resultAvailable, outResult, *status);
826 }
827
828 U_CAPI int32_t U_EXPORT2
uloc_acceptLanguageFromHTTP(char * result,int32_t resultAvailable,UAcceptResult * outResult,const char * httpAcceptLanguage,UEnumeration * availableLocales,UErrorCode * status)829 uloc_acceptLanguageFromHTTP(char *result, int32_t resultAvailable,
830 UAcceptResult *outResult,
831 const char *httpAcceptLanguage,
832 UEnumeration *availableLocales,
833 UErrorCode *status) {
834 if (U_FAILURE(*status)) { return 0; }
835 if ((result == nullptr ? resultAvailable != 0 : resultAvailable < 0) ||
836 httpAcceptLanguage == nullptr || availableLocales == nullptr) {
837 *status = U_ILLEGAL_ARGUMENT_ERROR;
838 return 0;
839 }
840 LocalePriorityList list(httpAcceptLanguage, *status);
841 LocalePriorityList::Iterator desiredLocales = list.iterator();
842 return acceptLanguage(*availableLocales, desiredLocales,
843 result, resultAvailable, outResult, *status);
844 }
845