]> git.saurik.com Git - apple/icu.git/blame - icuSources/i18n/transreg.cpp
ICU-62123.0.1.tar.gz
[apple/icu.git] / icuSources / i18n / transreg.cpp
CommitLineData
f3c0d7a5
A
1// © 2016 and later: Unicode, Inc. and others.
2// License & terms of use: http://www.unicode.org/copyright.html
b75a7d8f
A
3/*
4**********************************************************************
0f5d89e8 5* Copyright (c) 2001-2014, International Business Machines
b75a7d8f
A
6* Corporation and others. All Rights Reserved.
7**********************************************************************
8* Date Name Description
9* 08/10/2001 aliu Creation.
10**********************************************************************
11*/
12
13#include "unicode/utypes.h"
14
15#if !UCONFIG_NO_TRANSLITERATION
16
b75a7d8f 17#include "unicode/translit.h"
73c04bcf 18#include "unicode/resbund.h"
b75a7d8f
A
19#include "unicode/uniset.h"
20#include "unicode/uscript.h"
21#include "rbt.h"
22#include "cpdtrans.h"
23#include "nultrans.h"
24#include "transreg.h"
25#include "rbt_data.h"
26#include "rbt_pars.h"
27#include "tridpars.h"
28#include "charstr.h"
374ca955 29#include "uassert.h"
73c04bcf 30#include "locutil.h"
b75a7d8f
A
31
32// Enable the following symbol to add debugging code that tracks the
33// allocation, deletion, and use of Entry objects. BoundsChecker has
34// reported dangling pointer errors with these objects, but I have
35// been unable to confirm them. I suspect BoundsChecker is getting
36// confused with pointers going into and coming out of a UHashtable,
37// despite the hinting code that is designed to help it.
38// #define DEBUG_MEM
39#ifdef DEBUG_MEM
40#include <stdio.h>
41#endif
42
43// UChar constants
44static const UChar LOCALE_SEP = 95; // '_'
73c04bcf
A
45//static const UChar ID_SEP = 0x002D; /*-*/
46//static const UChar VARIANT_SEP = 0x002F; // '/'
b75a7d8f
A
47
48// String constants
2ca993e8
A
49static const UChar ANY[] = { 0x41, 0x6E, 0x79, 0 }; // Any
50static const UChar LAT[] = { 0x4C, 0x61, 0x74, 0 }; // Lat
b75a7d8f 51
4388f060
A
52// empty string
53#define NO_VARIANT UnicodeString()
54
2ca993e8 55// initial estimate for specDAG size
0f5d89e8
A
56// ICU 60 Transliterator::countAvailableSources()
57//#define SPECDAG_INIT_SIZE 149
58// Apple adjustment
2ca993e8
A
59#define SPECDAG_INIT_SIZE 134
60
61// initial estimate for number of variant names
62#define VARIANT_LIST_INIT_SIZE 11
63#define VARIANT_LIST_MAX_SIZE 31
64
65// initial estimate for availableIDs count (default estimate is 8 => multiple reallocs)
0f5d89e8
A
66// ICU 60 Transliterator::countAvailableIDs()
67//#define AVAILABLE_IDS_INIT_SIZE 641
68// Apple adjustment
2ca993e8
A
69#define AVAILABLE_IDS_INIT_SIZE 493
70
71// initial estimate for number of targets for source "Any", "Lat"
0f5d89e8
A
72// ICU 60 Transliterator::countAvailableTargets("Any")/("Latn")
73//#define ANY_TARGETS_INIT_SIZE 125
74// Apple adjustmennt
2ca993e8
A
75#define ANY_TARGETS_INIT_SIZE 102
76#define LAT_TARGETS_INIT_SIZE 23
77
b75a7d8f
A
78/**
79 * Resource bundle key for the RuleBasedTransliterator rule.
80 */
73c04bcf 81//static const char RB_RULE[] = "Rule";
b75a7d8f
A
82
83U_NAMESPACE_BEGIN
84
85//------------------------------------------------------------------
86// Alias
87//------------------------------------------------------------------
88
73c04bcf
A
89TransliteratorAlias::TransliteratorAlias(const UnicodeString& theAliasID,
90 const UnicodeSet* cpdFilter) :
b75a7d8f 91 ID(),
73c04bcf
A
92 aliasesOrRules(theAliasID),
93 transes(0),
94 compoundFilter(cpdFilter),
95 direction(UTRANS_FORWARD),
374ca955 96 type(TransliteratorAlias::SIMPLE) {
b75a7d8f
A
97}
98
99TransliteratorAlias::TransliteratorAlias(const UnicodeString& theID,
73c04bcf
A
100 const UnicodeString& idBlocks,
101 UVector* adoptedTransliterators,
b75a7d8f
A
102 const UnicodeSet* cpdFilter) :
103 ID(theID),
73c04bcf
A
104 aliasesOrRules(idBlocks),
105 transes(adoptedTransliterators),
b75a7d8f 106 compoundFilter(cpdFilter),
73c04bcf 107 direction(UTRANS_FORWARD),
374ca955
A
108 type(TransliteratorAlias::COMPOUND) {
109}
110
111TransliteratorAlias::TransliteratorAlias(const UnicodeString& theID,
112 const UnicodeString& rules,
113 UTransDirection dir) :
114 ID(theID),
73c04bcf
A
115 aliasesOrRules(rules),
116 transes(0),
374ca955 117 compoundFilter(0),
73c04bcf 118 direction(dir),
374ca955 119 type(TransliteratorAlias::RULES) {
b75a7d8f
A
120}
121
122TransliteratorAlias::~TransliteratorAlias() {
73c04bcf 123 delete transes;
b75a7d8f
A
124}
125
126
127Transliterator* TransliteratorAlias::create(UParseError& pe,
128 UErrorCode& ec) {
374ca955
A
129 if (U_FAILURE(ec)) {
130 return 0;
131 }
132 Transliterator *t = NULL;
133 switch (type) {
134 case SIMPLE:
73c04bcf
A
135 t = Transliterator::createInstance(aliasesOrRules, UTRANS_FORWARD, pe, ec);
136 if(U_FAILURE(ec)){
b75a7d8f
A
137 return 0;
138 }
73c04bcf
A
139 if (compoundFilter != 0)
140 t->adoptFilter((UnicodeSet*)compoundFilter->clone());
141 break;
142 case COMPOUND:
143 {
144 // the total number of transliterators in the compound is the total number of anonymous transliterators
145 // plus the total number of ID blocks-- we start by assuming the list begins and ends with an ID
146 // block and that each pair anonymous transliterators has an ID block between them. Then we go back
147 // to see whether there really are ID blocks at the beginning and end (by looking for U+FFFF, which
148 // marks the position where an anonymous transliterator goes) and adjust accordingly
149 int32_t anonymousRBTs = transes->size();
150 int32_t transCount = anonymousRBTs * 2 + 1;
151 if (!aliasesOrRules.isEmpty() && aliasesOrRules[0] == (UChar)(0xffff))
152 --transCount;
153 if (aliasesOrRules.length() >= 2 && aliasesOrRules[aliasesOrRules.length() - 1] == (UChar)(0xffff))
154 --transCount;
155 UnicodeString noIDBlock((UChar)(0xffff));
156 noIDBlock += ((UChar)(0xffff));
157 int32_t pos = aliasesOrRules.indexOf(noIDBlock);
158 while (pos >= 0) {
159 --transCount;
160 pos = aliasesOrRules.indexOf(noIDBlock, pos + 1);
161 }
162
163 UVector transliterators(ec);
164 UnicodeString idBlock;
165 int32_t blockSeparatorPos = aliasesOrRules.indexOf((UChar)(0xffff));
166 while (blockSeparatorPos >= 0) {
167 aliasesOrRules.extract(0, blockSeparatorPos, idBlock);
168 aliasesOrRules.remove(0, blockSeparatorPos + 1);
169 if (!idBlock.isEmpty())
170 transliterators.addElement(Transliterator::createInstance(idBlock, UTRANS_FORWARD, pe, ec), ec);
171 if (!transes->isEmpty())
172 transliterators.addElement(transes->orphanElementAt(0), ec);
173 blockSeparatorPos = aliasesOrRules.indexOf((UChar)(0xffff));
174 }
175 if (!aliasesOrRules.isEmpty())
176 transliterators.addElement(Transliterator::createInstance(aliasesOrRules, UTRANS_FORWARD, pe, ec), ec);
177 while (!transes->isEmpty())
178 transliterators.addElement(transes->orphanElementAt(0), ec);
179
180 if (U_SUCCESS(ec)) {
181 t = new CompoundTransliterator(ID, transliterators,
182 (compoundFilter ? (UnicodeSet*)(compoundFilter->clone()) : 0),
183 anonymousRBTs, pe, ec);
184 if (t == 0) {
185 ec = U_MEMORY_ALLOCATION_ERROR;
186 return 0;
187 }
188 } else {
189 for (int32_t i = 0; i < transliterators.size(); i++)
190 delete (Transliterator*)(transliterators.elementAt(i));
191 }
b75a7d8f 192 }
374ca955
A
193 break;
194 case RULES:
195 U_ASSERT(FALSE); // don't call create() if isRuleBased() returns TRUE!
196 break;
b75a7d8f
A
197 }
198 return t;
199}
200
374ca955
A
201UBool TransliteratorAlias::isRuleBased() const {
202 return type == RULES;
203}
204
205void TransliteratorAlias::parse(TransliteratorParser& parser,
206 UParseError& pe, UErrorCode& ec) const {
207 U_ASSERT(type == RULES);
208 if (U_FAILURE(ec)) {
209 return;
210 }
211
73c04bcf 212 parser.parse(aliasesOrRules, direction, pe, ec);
374ca955
A
213}
214
b75a7d8f 215//----------------------------------------------------------------------
729e4ab9 216// class TransliteratorSpec
b75a7d8f
A
217//----------------------------------------------------------------------
218
219/**
729e4ab9 220 * A TransliteratorSpec is a string specifying either a source or a target. In more
b75a7d8f
A
221 * general terms, it may also specify a variant, but we only use the
222 * Spec class for sources and targets.
223 *
224 * A Spec may be a locale or a script. If it is a locale, it has a
225 * fallback chain that goes xx_YY_ZZZ -> xx_YY -> xx -> ssss, where
226 * ssss is the script mapping of xx_YY_ZZZ. The Spec API methods
227 * hasFallback(), next(), and reset() iterate over this fallback
228 * sequence.
229 *
230 * The Spec class canonicalizes itself, so the locale is put into
231 * canonical form, or the script is transformed from an abbreviation
232 * to a full name.
233 */
729e4ab9 234class TransliteratorSpec : public UMemory {
b75a7d8f 235 public:
729e4ab9
A
236 TransliteratorSpec(const UnicodeString& spec);
237 ~TransliteratorSpec();
b75a7d8f
A
238
239 const UnicodeString& get() const;
240 UBool hasFallback() const;
241 const UnicodeString& next();
242 void reset();
243
244 UBool isLocale() const;
245 ResourceBundle& getBundle() const;
246
247 operator const UnicodeString&() const { return get(); }
248 const UnicodeString& getTop() const { return top; }
249
250 private:
251 void setupNext();
252
253 UnicodeString top;
254 UnicodeString spec;
255 UnicodeString nextSpec;
256 UnicodeString scriptName;
257 UBool isSpecLocale; // TRUE if spec is a locale
258 UBool isNextLocale; // TRUE if nextSpec is a locale
259 ResourceBundle* res;
260
729e4ab9
A
261 TransliteratorSpec(const TransliteratorSpec &other); // forbid copying of this class
262 TransliteratorSpec &operator=(const TransliteratorSpec &other); // forbid copying of this class
b75a7d8f
A
263};
264
729e4ab9 265TransliteratorSpec::TransliteratorSpec(const UnicodeString& theSpec)
73c04bcf
A
266: top(theSpec),
267 res(0)
268{
b75a7d8f 269 UErrorCode status = U_ZERO_ERROR;
73c04bcf
A
270 Locale topLoc("");
271 LocaleUtility::initLocaleFromName(theSpec, topLoc);
272 if (!topLoc.isBogus()) {
273 res = new ResourceBundle(U_ICUDATA_TRANSLIT, topLoc, status);
274 /* test for NULL */
275 if (res == 0) {
276 return;
277 }
278 if (U_FAILURE(status) || status == U_USING_DEFAULT_WARNING) {
279 delete res;
280 res = 0;
281 }
b75a7d8f
A
282 }
283
284 // Canonicalize script name -or- do locale->script mapping
285 status = U_ZERO_ERROR;
73c04bcf 286 static const int32_t capacity = 10;
b75a7d8f 287 UScriptCode script[capacity]={USCRIPT_INVALID_CODE};
729e4ab9
A
288 int32_t num = uscript_getCode(CharString().appendInvariantChars(theSpec, status).data(),
289 script, capacity, &status);
b75a7d8f 290 if (num > 0 && script[0] != USCRIPT_INVALID_CODE) {
73c04bcf 291 scriptName = UnicodeString(uscript_getName(script[0]), -1, US_INV);
b75a7d8f
A
292 }
293
294 // Canonicalize top
b75a7d8f
A
295 if (res != 0) {
296 // Canonicalize locale name
73c04bcf
A
297 UnicodeString locStr;
298 LocaleUtility::initNameFromLocale(topLoc, locStr);
299 if (!locStr.isBogus()) {
300 top = locStr;
b75a7d8f
A
301 }
302 } else if (scriptName.length() != 0) {
303 // We are a script; use canonical name
304 top = scriptName;
305 }
306
307 // assert(spec != top);
308 reset();
309}
310
729e4ab9 311TransliteratorSpec::~TransliteratorSpec() {
b75a7d8f
A
312 delete res;
313}
314
729e4ab9 315UBool TransliteratorSpec::hasFallback() const {
b75a7d8f
A
316 return nextSpec.length() != 0;
317}
318
729e4ab9 319void TransliteratorSpec::reset() {
b75a7d8f
A
320 if (spec != top) {
321 spec = top;
322 isSpecLocale = (res != 0);
323 setupNext();
324 }
325}
326
729e4ab9 327void TransliteratorSpec::setupNext() {
b75a7d8f
A
328 isNextLocale = FALSE;
329 if (isSpecLocale) {
330 nextSpec = spec;
331 int32_t i = nextSpec.lastIndexOf(LOCALE_SEP);
332 // If i == 0 then we have _FOO, so we fall through
333 // to the scriptName.
334 if (i > 0) {
335 nextSpec.truncate(i);
336 isNextLocale = TRUE;
337 } else {
338 nextSpec = scriptName; // scriptName may be empty
339 }
340 } else {
341 // spec is a script, so we are at the end
342 nextSpec.truncate(0);
343 }
344}
345
346// Protocol:
347// for(const UnicodeString& s(spec.get());
348// spec.hasFallback(); s(spec.next())) { ...
349
729e4ab9 350const UnicodeString& TransliteratorSpec::next() {
b75a7d8f
A
351 spec = nextSpec;
352 isSpecLocale = isNextLocale;
353 setupNext();
354 return spec;
355}
356
729e4ab9 357const UnicodeString& TransliteratorSpec::get() const {
b75a7d8f
A
358 return spec;
359}
360
729e4ab9 361UBool TransliteratorSpec::isLocale() const {
b75a7d8f
A
362 return isSpecLocale;
363}
364
729e4ab9 365ResourceBundle& TransliteratorSpec::getBundle() const {
b75a7d8f
A
366 return *res;
367}
368
369//----------------------------------------------------------------------
370
371#ifdef DEBUG_MEM
372
373// Vector of Entry pointers currently in use
374static UVector* DEBUG_entries = NULL;
375
376static void DEBUG_setup() {
377 if (DEBUG_entries == NULL) {
378 UErrorCode ec = U_ZERO_ERROR;
379 DEBUG_entries = new UVector(ec);
380 }
381}
382
383// Caller must call DEBUG_setup first. Return index of given Entry,
384// if it is in use (not deleted yet), or -1 if not found.
729e4ab9 385static int DEBUG_findEntry(TransliteratorEntry* e) {
b75a7d8f 386 for (int i=0; i<DEBUG_entries->size(); ++i) {
729e4ab9 387 if (e == (TransliteratorEntry*) DEBUG_entries->elementAt(i)) {
b75a7d8f
A
388 return i;
389 }
390 }
391 return -1;
392}
393
394// Track object creation
729e4ab9 395static void DEBUG_newEntry(TransliteratorEntry* e) {
b75a7d8f
A
396 DEBUG_setup();
397 if (DEBUG_findEntry(e) >= 0) {
398 // This should really never happen unless the heap is broken
399 printf("ERROR DEBUG_newEntry duplicate new pointer %08X\n", e);
400 return;
401 }
402 UErrorCode ec = U_ZERO_ERROR;
403 DEBUG_entries->addElement(e, ec);
404}
405
406// Track object deletion
729e4ab9 407static void DEBUG_delEntry(TransliteratorEntry* e) {
b75a7d8f
A
408 DEBUG_setup();
409 int i = DEBUG_findEntry(e);
410 if (i < 0) {
411 printf("ERROR DEBUG_delEntry possible double deletion %08X\n", e);
412 return;
413 }
414 DEBUG_entries->removeElementAt(i);
415}
416
417// Track object usage
729e4ab9 418static void DEBUG_useEntry(TransliteratorEntry* e) {
b75a7d8f
A
419 if (e == NULL) return;
420 DEBUG_setup();
421 int i = DEBUG_findEntry(e);
422 if (i < 0) {
423 printf("ERROR DEBUG_useEntry possible dangling pointer %08X\n", e);
424 }
425}
426
427#else
428// If we're not debugging then make these macros into NOPs
429#define DEBUG_newEntry(x)
430#define DEBUG_delEntry(x)
431#define DEBUG_useEntry(x)
432#endif
433
434//----------------------------------------------------------------------
435// class Entry
436//----------------------------------------------------------------------
437
438/**
439 * The Entry object stores objects of different types and
440 * singleton objects as placeholders for rule-based transliterators to
441 * be built as needed. Instances of this struct can be placeholders,
442 * can represent prototype transliterators to be cloned, or can
443 * represent TransliteratorData objects. We don't support storing
444 * classes in the registry because we don't have the rtti infrastructure
445 * for it. We could easily add this if there is a need for it in the
446 * future.
447 */
729e4ab9 448class TransliteratorEntry : public UMemory {
b75a7d8f
A
449public:
450 enum Type {
451 RULES_FORWARD,
452 RULES_REVERSE,
453 LOCALE_RULES,
454 PROTOTYPE,
455 RBT_DATA,
456 COMPOUND_RBT,
457 ALIAS,
458 FACTORY,
459 NONE // Only used for uninitialized entries
460 } entryType;
461 // NOTE: stringArg cannot go inside the union because
462 // it has a copy constructor
463 UnicodeString stringArg; // For RULES_*, ALIAS, COMPOUND_RBT
464 int32_t intArg; // For COMPOUND_RBT, LOCALE_RULES
465 UnicodeSet* compoundFilter; // For COMPOUND_RBT
466 union {
467 Transliterator* prototype; // For PROTOTYPE
73c04bcf
A
468 TransliterationRuleData* data; // For RBT_DATA
469 UVector* dataVector; // For COMPOUND_RBT
b75a7d8f
A
470 struct {
471 Transliterator::Factory function;
472 Transliterator::Token context;
473 } factory; // For FACTORY
474 } u;
729e4ab9
A
475 TransliteratorEntry();
476 ~TransliteratorEntry();
b75a7d8f
A
477 void adoptPrototype(Transliterator* adopted);
478 void setFactory(Transliterator::Factory factory,
479 Transliterator::Token context);
480
481private:
482
729e4ab9
A
483 TransliteratorEntry(const TransliteratorEntry &other); // forbid copying of this class
484 TransliteratorEntry &operator=(const TransliteratorEntry &other); // forbid copying of this class
b75a7d8f
A
485};
486
729e4ab9 487TransliteratorEntry::TransliteratorEntry() {
b75a7d8f
A
488 u.prototype = 0;
489 compoundFilter = NULL;
490 entryType = NONE;
491 DEBUG_newEntry(this);
492}
493
729e4ab9 494TransliteratorEntry::~TransliteratorEntry() {
b75a7d8f
A
495 DEBUG_delEntry(this);
496 if (entryType == PROTOTYPE) {
497 delete u.prototype;
73c04bcf 498 } else if (entryType == RBT_DATA) {
b75a7d8f
A
499 // The data object is shared between instances of RBT. The
500 // entry object owns it. It should only be deleted when the
501 // transliterator component is being cleaned up. Doing so
502 // invalidates any RBTs that the user has instantiated.
503 delete u.data;
73c04bcf
A
504 } else if (entryType == COMPOUND_RBT) {
505 while (u.dataVector != NULL && !u.dataVector->isEmpty())
506 delete (TransliterationRuleData*)u.dataVector->orphanElementAt(0);
507 delete u.dataVector;
b75a7d8f
A
508 }
509 delete compoundFilter;
510}
511
729e4ab9 512void TransliteratorEntry::adoptPrototype(Transliterator* adopted) {
b75a7d8f
A
513 if (entryType == PROTOTYPE) {
514 delete u.prototype;
515 }
516 entryType = PROTOTYPE;
517 u.prototype = adopted;
518}
519
729e4ab9 520void TransliteratorEntry::setFactory(Transliterator::Factory factory,
b75a7d8f
A
521 Transliterator::Token context) {
522 if (entryType == PROTOTYPE) {
523 delete u.prototype;
524 }
525 entryType = FACTORY;
526 u.factory.function = factory;
527 u.factory.context = context;
528}
529
530// UObjectDeleter for Hashtable::setValueDeleter
531U_CDECL_BEGIN
73c04bcf 532static void U_CALLCONV
b75a7d8f 533deleteEntry(void* obj) {
729e4ab9 534 delete (TransliteratorEntry*) obj;
b75a7d8f
A
535}
536U_CDECL_END
537
538//----------------------------------------------------------------------
539// class TransliteratorRegistry: Basic public API
540//----------------------------------------------------------------------
541
542TransliteratorRegistry::TransliteratorRegistry(UErrorCode& status) :
374ca955 543 registry(TRUE, status),
2ca993e8
A
544 specDAG(TRUE, SPECDAG_INIT_SIZE, status),
545 variantList(VARIANT_LIST_INIT_SIZE, status),
546 availableIDs(AVAILABLE_IDS_INIT_SIZE, status)
b75a7d8f
A
547{
548 registry.setValueDeleter(deleteEntry);
2ca993e8
A
549 variantList.setDeleter(uprv_deleteUObject);
550 variantList.setComparer(uhash_compareCaselessUnicodeString);
551 UnicodeString *emptyString = new UnicodeString();
552 if (emptyString != NULL) {
553 variantList.addElement(emptyString, status);
554 }
4388f060 555 availableIDs.setDeleter(uprv_deleteUObject);
b75a7d8f
A
556 availableIDs.setComparer(uhash_compareCaselessUnicodeString);
557 specDAG.setValueDeleter(uhash_deleteHashtable);
558}
559
560TransliteratorRegistry::~TransliteratorRegistry() {
561 // Through the magic of C++, everything cleans itself up
562}
563
564Transliterator* TransliteratorRegistry::get(const UnicodeString& ID,
565 TransliteratorAlias*& aliasReturn,
b75a7d8f 566 UErrorCode& status) {
374ca955 567 U_ASSERT(aliasReturn == NULL);
729e4ab9 568 TransliteratorEntry *entry = find(ID);
b75a7d8f 569 return (entry == 0) ? 0
374ca955
A
570 : instantiateEntry(ID, entry, aliasReturn, status);
571}
572
573Transliterator* TransliteratorRegistry::reget(const UnicodeString& ID,
574 TransliteratorParser& parser,
575 TransliteratorAlias*& aliasReturn,
576 UErrorCode& status) {
577 U_ASSERT(aliasReturn == NULL);
729e4ab9 578 TransliteratorEntry *entry = find(ID);
374ca955
A
579
580 if (entry == 0) {
581 // We get to this point if there are two threads, one of which
582 // is instantiating an ID, and another of which is removing
583 // the same ID from the registry, and the timing is just right.
584 return 0;
585 }
586
587 // The usage model for the caller is that they will first call
588 // reg->get() inside the mutex, they'll get back an alias, they call
589 // alias->isRuleBased(), and if they get TRUE, they call alias->parse()
590 // outside the mutex, then reg->reget() inside the mutex again. A real
591 // mess, but it gets things working for ICU 3.0. [alan].
592
593 // Note: It's possible that in between the caller calling
594 // alias->parse() and reg->reget(), that another thread will have
595 // called reg->reget(), and the entry will already have been fixed up.
596 // We have to detect this so we don't stomp over existing entry
597 // data members and potentially leak memory (u.data and compoundFilter).
598
729e4ab9
A
599 if (entry->entryType == TransliteratorEntry::RULES_FORWARD ||
600 entry->entryType == TransliteratorEntry::RULES_REVERSE ||
601 entry->entryType == TransliteratorEntry::LOCALE_RULES) {
374ca955 602
73c04bcf
A
603 if (parser.idBlockVector.isEmpty() && parser.dataVector.isEmpty()) {
604 entry->u.data = 0;
729e4ab9 605 entry->entryType = TransliteratorEntry::ALIAS;
73c04bcf
A
606 entry->stringArg = UNICODE_STRING_SIMPLE("Any-NULL");
607 }
608 else if (parser.idBlockVector.isEmpty() && parser.dataVector.size() == 1) {
609 entry->u.data = (TransliterationRuleData*)parser.dataVector.orphanElementAt(0);
729e4ab9 610 entry->entryType = TransliteratorEntry::RBT_DATA;
73c04bcf
A
611 }
612 else if (parser.idBlockVector.size() == 1 && parser.dataVector.isEmpty()) {
613 entry->stringArg = *(UnicodeString*)(parser.idBlockVector.elementAt(0));
614 entry->compoundFilter = parser.orphanCompoundFilter();
729e4ab9 615 entry->entryType = TransliteratorEntry::ALIAS;
73c04bcf
A
616 }
617 else {
729e4ab9 618 entry->entryType = TransliteratorEntry::COMPOUND_RBT;
73c04bcf
A
619 entry->compoundFilter = parser.orphanCompoundFilter();
620 entry->u.dataVector = new UVector(status);
621 entry->stringArg.remove();
622
623 int32_t limit = parser.idBlockVector.size();
624 if (parser.dataVector.size() > limit)
625 limit = parser.dataVector.size();
626
627 for (int32_t i = 0; i < limit; i++) {
628 if (i < parser.idBlockVector.size()) {
629 UnicodeString* idBlock = (UnicodeString*)parser.idBlockVector.elementAt(i);
630 if (!idBlock->isEmpty())
631 entry->stringArg += *idBlock;
632 }
633 if (!parser.dataVector.isEmpty()) {
634 TransliterationRuleData* data = (TransliterationRuleData*)parser.dataVector.orphanElementAt(0);
635 entry->u.dataVector->addElement(data, status);
636 entry->stringArg += (UChar)0xffff; // use U+FFFF to mark position of RBTs in ID block
637 }
374ca955
A
638 }
639 }
640 }
641
642 Transliterator *t =
643 instantiateEntry(ID, entry, aliasReturn, status);
644 return t;
b75a7d8f
A
645}
646
647void TransliteratorRegistry::put(Transliterator* adoptedProto,
46f4442e
A
648 UBool visible,
649 UErrorCode& ec)
650{
729e4ab9 651 TransliteratorEntry *entry = new TransliteratorEntry();
46f4442e
A
652 if (entry == NULL) {
653 ec = U_MEMORY_ALLOCATION_ERROR;
654 return;
655 }
b75a7d8f
A
656 entry->adoptPrototype(adoptedProto);
657 registerEntry(adoptedProto->getID(), entry, visible);
658}
659
660void TransliteratorRegistry::put(const UnicodeString& ID,
661 Transliterator::Factory factory,
662 Transliterator::Token context,
46f4442e
A
663 UBool visible,
664 UErrorCode& ec) {
729e4ab9 665 TransliteratorEntry *entry = new TransliteratorEntry();
46f4442e
A
666 if (entry == NULL) {
667 ec = U_MEMORY_ALLOCATION_ERROR;
668 return;
669 }
b75a7d8f
A
670 entry->setFactory(factory, context);
671 registerEntry(ID, entry, visible);
672}
673
674void TransliteratorRegistry::put(const UnicodeString& ID,
675 const UnicodeString& resourceName,
676 UTransDirection dir,
73c04bcf 677 UBool readonlyResourceAlias,
46f4442e
A
678 UBool visible,
679 UErrorCode& ec) {
729e4ab9 680 TransliteratorEntry *entry = new TransliteratorEntry();
46f4442e
A
681 if (entry == NULL) {
682 ec = U_MEMORY_ALLOCATION_ERROR;
683 return;
684 }
729e4ab9
A
685 entry->entryType = (dir == UTRANS_FORWARD) ? TransliteratorEntry::RULES_FORWARD
686 : TransliteratorEntry::RULES_REVERSE;
73c04bcf
A
687 if (readonlyResourceAlias) {
688 entry->stringArg.setTo(TRUE, resourceName.getBuffer(), -1);
689 }
690 else {
691 entry->stringArg = resourceName;
692 }
b75a7d8f
A
693 registerEntry(ID, entry, visible);
694}
695
696void TransliteratorRegistry::put(const UnicodeString& ID,
697 const UnicodeString& alias,
73c04bcf 698 UBool readonlyAliasAlias,
46f4442e
A
699 UBool visible,
700 UErrorCode& /*ec*/) {
729e4ab9 701 TransliteratorEntry *entry = new TransliteratorEntry();
46f4442e
A
702 // Null pointer check
703 if (entry != NULL) {
729e4ab9 704 entry->entryType = TransliteratorEntry::ALIAS;
46f4442e
A
705 if (readonlyAliasAlias) {
706 entry->stringArg.setTo(TRUE, alias.getBuffer(), -1);
707 }
708 else {
709 entry->stringArg = alias;
710 }
711 registerEntry(ID, entry, visible);
73c04bcf 712 }
b75a7d8f
A
713}
714
715void TransliteratorRegistry::remove(const UnicodeString& ID) {
716 UnicodeString source, target, variant;
717 UBool sawSource;
718 TransliteratorIDParser::IDtoSTV(ID, source, target, variant, sawSource);
719 // Only need to do this if ID.indexOf('-') < 0
720 UnicodeString id;
721 TransliteratorIDParser::STVtoID(source, target, variant, id);
722 registry.remove(id);
723 removeSTV(source, target, variant);
724 availableIDs.removeElement((void*) &id);
725}
726
727//----------------------------------------------------------------------
728// class TransliteratorRegistry: Public ID and spec management
729//----------------------------------------------------------------------
730
731/**
374ca955 732 * == OBSOLETE - remove in ICU 3.4 ==
b75a7d8f
A
733 * Return the number of IDs currently registered with the system.
734 * To retrieve the actual IDs, call getAvailableID(i) with
735 * i from 0 to countAvailableIDs() - 1.
736 */
374ca955 737int32_t TransliteratorRegistry::countAvailableIDs(void) const {
b75a7d8f
A
738 return availableIDs.size();
739}
740
741/**
374ca955 742 * == OBSOLETE - remove in ICU 3.4 ==
b75a7d8f
A
743 * Return the index-th available ID. index must be between 0
744 * and countAvailableIDs() - 1, inclusive. If index is out of
745 * range, the result of getAvailableID(0) is returned.
746 */
374ca955 747const UnicodeString& TransliteratorRegistry::getAvailableID(int32_t index) const {
b75a7d8f
A
748 if (index < 0 || index >= availableIDs.size()) {
749 index = 0;
750 }
751 return *(const UnicodeString*) availableIDs[index];
752}
753
374ca955
A
754StringEnumeration* TransliteratorRegistry::getAvailableIDs() const {
755 return new Enumeration(*this);
756}
757
758int32_t TransliteratorRegistry::countAvailableSources(void) const {
b75a7d8f
A
759 return specDAG.count();
760}
761
762UnicodeString& TransliteratorRegistry::getAvailableSource(int32_t index,
374ca955 763 UnicodeString& result) const {
b331163b 764 int32_t pos = UHASH_FIRST;
b75a7d8f
A
765 const UHashElement *e = 0;
766 while (index-- >= 0) {
767 e = specDAG.nextElement(pos);
768 if (e == 0) {
769 break;
770 }
771 }
772 if (e == 0) {
773 result.truncate(0);
774 } else {
775 result = *(UnicodeString*) e->key.pointer;
776 }
777 return result;
778}
779
374ca955 780int32_t TransliteratorRegistry::countAvailableTargets(const UnicodeString& source) const {
b75a7d8f
A
781 Hashtable *targets = (Hashtable*) specDAG.get(source);
782 return (targets == 0) ? 0 : targets->count();
783}
784
785UnicodeString& TransliteratorRegistry::getAvailableTarget(int32_t index,
786 const UnicodeString& source,
374ca955 787 UnicodeString& result) const {
b75a7d8f
A
788 Hashtable *targets = (Hashtable*) specDAG.get(source);
789 if (targets == 0) {
790 result.truncate(0); // invalid source
791 return result;
792 }
b331163b 793 int32_t pos = UHASH_FIRST;
b75a7d8f
A
794 const UHashElement *e = 0;
795 while (index-- >= 0) {
796 e = targets->nextElement(pos);
797 if (e == 0) {
798 break;
799 }
800 }
801 if (e == 0) {
802 result.truncate(0); // invalid index
803 } else {
804 result = *(UnicodeString*) e->key.pointer;
805 }
806 return result;
807}
808
809int32_t TransliteratorRegistry::countAvailableVariants(const UnicodeString& source,
374ca955 810 const UnicodeString& target) const {
b75a7d8f
A
811 Hashtable *targets = (Hashtable*) specDAG.get(source);
812 if (targets == 0) {
813 return 0;
814 }
0f5d89e8 815 uint32_t varMask = targets->geti(target);
2ca993e8
A
816 int32_t varCount = 0;
817 while (varMask > 0) {
818 if (varMask & 1) {
819 varCount++;
820 }
821 varMask >>= 1;
822 }
823 return varCount;
b75a7d8f
A
824}
825
826UnicodeString& TransliteratorRegistry::getAvailableVariant(int32_t index,
827 const UnicodeString& source,
828 const UnicodeString& target,
374ca955 829 UnicodeString& result) const {
b75a7d8f
A
830 Hashtable *targets = (Hashtable*) specDAG.get(source);
831 if (targets == 0) {
832 result.truncate(0); // invalid source
833 return result;
834 }
0f5d89e8 835 uint32_t varMask = targets->geti(target);
2ca993e8
A
836 int32_t varCount = 0;
837 int32_t varListIndex = 0;
838 while (varMask > 0) {
839 if (varMask & 1) {
840 if (varCount == index) {
841 UnicodeString *v = (UnicodeString*) variantList.elementAt(varListIndex);
842 if (v != NULL) {
843 result = *v;
844 return result;
845 }
846 break;
847 }
848 varCount++;
849 }
850 varMask >>= 1;
851 varListIndex++;
b75a7d8f 852 }
2ca993e8 853 result.truncate(0); // invalid target or index
b75a7d8f
A
854 return result;
855}
856
374ca955
A
857//----------------------------------------------------------------------
858// class TransliteratorRegistry::Enumeration
859//----------------------------------------------------------------------
860
861TransliteratorRegistry::Enumeration::Enumeration(const TransliteratorRegistry& _reg) :
862 index(0), reg(_reg) {
863}
864
865TransliteratorRegistry::Enumeration::~Enumeration() {
866}
867
868int32_t TransliteratorRegistry::Enumeration::count(UErrorCode& /*status*/) const {
869 return reg.availableIDs.size();
870}
871
872const UnicodeString* TransliteratorRegistry::Enumeration::snext(UErrorCode& status) {
873 // This is sloppy but safe -- if we get out of sync with the underlying
874 // registry, we will still return legal strings, but they might not
875 // correspond to the snapshot at construction time. So there could be
876 // duplicate IDs or omitted IDs if insertions or deletions occur in one
877 // thread while another is iterating. To be more rigorous, add a timestamp,
878 // which is incremented with any modification, and validate this iterator
879 // against the timestamp at construction time. This probably isn't worth
880 // doing as long as there is some possibility of removing this code in favor
881 // of some new code based on Doug's service framework.
882 if (U_FAILURE(status)) {
883 return NULL;
884 }
885 int32_t n = reg.availableIDs.size();
886 if (index > n) {
887 status = U_ENUM_OUT_OF_SYNC_ERROR;
888 }
889 // index == n is okay -- this means we've reached the end
890 if (index < n) {
891 // Copy the string! This avoids lifetime problems.
892 unistr = *(const UnicodeString*)reg.availableIDs[index++];
893 return &unistr;
894 } else {
895 return NULL;
896 }
897}
898
899void TransliteratorRegistry::Enumeration::reset(UErrorCode& /*status*/) {
900 index = 0;
901}
902
903UOBJECT_DEFINE_RTTI_IMPLEMENTATION(TransliteratorRegistry::Enumeration)
904
b75a7d8f
A
905//----------------------------------------------------------------------
906// class TransliteratorRegistry: internal
907//----------------------------------------------------------------------
908
909/**
910 * Convenience method. Calls 6-arg registerEntry().
911 */
912void TransliteratorRegistry::registerEntry(const UnicodeString& source,
913 const UnicodeString& target,
914 const UnicodeString& variant,
729e4ab9 915 TransliteratorEntry* adopted,
b75a7d8f
A
916 UBool visible) {
917 UnicodeString ID;
918 UnicodeString s(source);
919 if (s.length() == 0) {
4388f060 920 s.setTo(TRUE, ANY, 3);
b75a7d8f
A
921 }
922 TransliteratorIDParser::STVtoID(source, target, variant, ID);
923 registerEntry(ID, s, target, variant, adopted, visible);
924}
925
926/**
927 * Convenience method. Calls 6-arg registerEntry().
928 */
929void TransliteratorRegistry::registerEntry(const UnicodeString& ID,
729e4ab9 930 TransliteratorEntry* adopted,
b75a7d8f
A
931 UBool visible) {
932 UnicodeString source, target, variant;
933 UBool sawSource;
934 TransliteratorIDParser::IDtoSTV(ID, source, target, variant, sawSource);
935 // Only need to do this if ID.indexOf('-') < 0
936 UnicodeString id;
937 TransliteratorIDParser::STVtoID(source, target, variant, id);
938 registerEntry(id, source, target, variant, adopted, visible);
939}
940
941/**
942 * Register an entry object (adopted) with the given ID, source,
943 * target, and variant strings.
944 */
945void TransliteratorRegistry::registerEntry(const UnicodeString& ID,
946 const UnicodeString& source,
947 const UnicodeString& target,
948 const UnicodeString& variant,
729e4ab9 949 TransliteratorEntry* adopted,
b75a7d8f
A
950 UBool visible) {
951 UErrorCode status = U_ZERO_ERROR;
952 registry.put(ID, adopted, status);
953 if (visible) {
954 registerSTV(source, target, variant);
955 if (!availableIDs.contains((void*) &ID)) {
374ca955 956 UnicodeString *newID = (UnicodeString *)ID.clone();
46f4442e
A
957 // Check to make sure newID was created.
958 if (newID != NULL) {
2ca993e8
A
959 // NUL-terminate the ID string
960 newID->getTerminatedBuffer();
961 availableIDs.addElement(newID, status);
46f4442e 962 }
b75a7d8f
A
963 }
964 } else {
965 removeSTV(source, target, variant);
966 availableIDs.removeElement((void*) &ID);
967 }
968}
969
970/**
971 * Register a source-target/variant in the specDAG. Variant may be
2ca993e8 972 * empty, but source and target must not be.
b75a7d8f
A
973 */
974void TransliteratorRegistry::registerSTV(const UnicodeString& source,
975 const UnicodeString& target,
976 const UnicodeString& variant) {
977 // assert(source.length() > 0);
978 // assert(target.length() > 0);
979 UErrorCode status = U_ZERO_ERROR;
980 Hashtable *targets = (Hashtable*) specDAG.get(source);
981 if (targets == 0) {
2ca993e8
A
982 int32_t size = 3;
983 if (source.compare(ANY,3) == 0) {
984 size = ANY_TARGETS_INIT_SIZE;
985 } else if (source.compare(LAT,3) == 0) {
986 size = LAT_TARGETS_INIT_SIZE;
987 }
988 targets = new Hashtable(TRUE, size, status);
989 if (U_FAILURE(status) || targets == NULL) {
b75a7d8f
A
990 return;
991 }
b75a7d8f
A
992 specDAG.put(source, targets, status);
993 }
2ca993e8
A
994 int32_t variantListIndex = variantList.indexOf((void*) &variant, 0);
995 if (variantListIndex < 0) {
996 if (variantList.size() >= VARIANT_LIST_MAX_SIZE) {
997 // can't handle any more variants
b75a7d8f
A
998 return;
999 }
2ca993e8
A
1000 UnicodeString *variantEntry = new UnicodeString(variant);
1001 if (variantEntry != NULL) {
1002 variantList.addElement(variantEntry, status);
1003 if (U_SUCCESS(status)) {
1004 variantListIndex = variantList.size() - 1;
1005 }
1006 }
1007 if (variantListIndex < 0) {
1008 return;
b75a7d8f
A
1009 }
1010 }
0f5d89e8
A
1011 uint32_t addMask = 1 << variantListIndex;
1012 uint32_t varMask = targets->geti(target);
2ca993e8 1013 targets->puti(target, varMask | addMask, status);
b75a7d8f
A
1014}
1015
1016/**
1017 * Remove a source-target/variant from the specDAG.
1018 */
1019void TransliteratorRegistry::removeSTV(const UnicodeString& source,
1020 const UnicodeString& target,
1021 const UnicodeString& variant) {
1022 // assert(source.length() > 0);
1023 // assert(target.length() > 0);
2ca993e8 1024 UErrorCode status = U_ZERO_ERROR;
b75a7d8f 1025 Hashtable *targets = (Hashtable*) specDAG.get(source);
2ca993e8 1026 if (targets == NULL) {
b75a7d8f
A
1027 return; // should never happen for valid s-t/v
1028 }
0f5d89e8 1029 uint32_t varMask = targets->geti(target);
2ca993e8 1030 if (varMask == 0) {
b75a7d8f
A
1031 return; // should never happen for valid s-t/v
1032 }
2ca993e8
A
1033 int32_t variantListIndex = variantList.indexOf((void*) &variant, 0);
1034 if (variantListIndex < 0) {
1035 return; // should never happen for valid s-t/v
1036 }
1037 int32_t remMask = 1 << variantListIndex;
1038 varMask &= (~remMask);
1039 if (varMask != 0) {
1040 targets->puti(target, varMask, status);
1041 } else {
b75a7d8f
A
1042 targets->remove(target); // should delete variants
1043 if (targets->count() == 0) {
0f5d89e8 1044 specDAG.remove(source); // should delete targets
b75a7d8f
A
1045 }
1046 }
1047}
1048
1049/**
1050 * Attempt to find a source-target/variant in the dynamic registry
1051 * store. Return 0 on failure.
1052 *
1053 * Caller does NOT own returned object.
1054 */
729e4ab9
A
1055TransliteratorEntry* TransliteratorRegistry::findInDynamicStore(const TransliteratorSpec& src,
1056 const TransliteratorSpec& trg,
374ca955 1057 const UnicodeString& variant) const {
b75a7d8f
A
1058 UnicodeString ID;
1059 TransliteratorIDParser::STVtoID(src, trg, variant, ID);
729e4ab9 1060 TransliteratorEntry *e = (TransliteratorEntry*) registry.get(ID);
b75a7d8f
A
1061 DEBUG_useEntry(e);
1062 return e;
1063}
1064
1065/**
1066 * Attempt to find a source-target/variant in the static locale
1067 * resource store. Do not perform fallback. Return 0 on failure.
1068 *
1069 * On success, create a new entry object, register it in the dynamic
1070 * store, and return a pointer to it, but do not make it public --
1071 * just because someone requested something, we do not expand the
1072 * available ID list (or spec DAG).
1073 *
1074 * Caller does NOT own returned object.
1075 */
729e4ab9
A
1076TransliteratorEntry* TransliteratorRegistry::findInStaticStore(const TransliteratorSpec& src,
1077 const TransliteratorSpec& trg,
b75a7d8f 1078 const UnicodeString& variant) {
729e4ab9 1079 TransliteratorEntry* entry = 0;
b75a7d8f
A
1080 if (src.isLocale()) {
1081 entry = findInBundle(src, trg, variant, UTRANS_FORWARD);
1082 } else if (trg.isLocale()) {
1083 entry = findInBundle(trg, src, variant, UTRANS_REVERSE);
1084 }
1085
1086 // If we found an entry, store it in the Hashtable for next
1087 // time.
1088 if (entry != 0) {
1089 registerEntry(src.getTop(), trg.getTop(), variant, entry, FALSE);
1090 }
1091
1092 return entry;
1093}
1094
1095// As of 2.0, resource bundle keys cannot contain '_'
1096static const UChar TRANSLITERATE_TO[] = {84,114,97,110,115,108,105,116,101,114,97,116,101,84,111,0}; // "TransliterateTo"
1097
1098static const UChar TRANSLITERATE_FROM[] = {84,114,97,110,115,108,105,116,101,114,97,116,101,70,114,111,109,0}; // "TransliterateFrom"
1099
1100static const UChar TRANSLITERATE[] = {84,114,97,110,115,108,105,116,101,114,97,116,101,0}; // "Transliterate"
1101
1102/**
1103 * Attempt to find an entry in a single resource bundle. This is
1104 * a one-sided lookup. findInStaticStore() performs up to two such
1105 * lookups, one for the source, and one for the target.
1106 *
1107 * Do not perform fallback. Return 0 on failure.
1108 *
1109 * On success, create a new Entry object, populate it, and return it.
1110 * The caller owns the returned object.
1111 */
729e4ab9
A
1112TransliteratorEntry* TransliteratorRegistry::findInBundle(const TransliteratorSpec& specToOpen,
1113 const TransliteratorSpec& specToFind,
b75a7d8f
A
1114 const UnicodeString& variant,
1115 UTransDirection direction)
1116{
1117 UnicodeString utag;
1118 UnicodeString resStr;
1119 int32_t pass;
1120
1121 for (pass=0; pass<2; ++pass) {
1122 utag.truncate(0);
1123 // First try either TransliteratorTo_xxx or
1124 // TransliterateFrom_xxx, then try the bidirectional
1125 // Transliterate_xxx. This precedence order is arbitrary
1126 // but must be consistent and documented.
1127 if (pass == 0) {
1128 utag.append(direction == UTRANS_FORWARD ?
4388f060 1129 TRANSLITERATE_TO : TRANSLITERATE_FROM, -1);
b75a7d8f 1130 } else {
4388f060 1131 utag.append(TRANSLITERATE, -1);
b75a7d8f
A
1132 }
1133 UnicodeString s(specToFind.get());
73c04bcf 1134 utag.append(s.toUpper(""));
b75a7d8f 1135 UErrorCode status = U_ZERO_ERROR;
729e4ab9
A
1136 ResourceBundle subres(specToOpen.getBundle().get(
1137 CharString().appendInvariantChars(utag, status).data(), status));
b75a7d8f
A
1138 if (U_FAILURE(status) || status == U_USING_DEFAULT_WARNING) {
1139 continue;
1140 }
729e4ab9 1141
73c04bcf
A
1142 s.truncate(0);
1143 if (specToOpen.get() != LocaleUtility::initNameFromLocale(subres.getLocale(), s)) {
b75a7d8f
A
1144 continue;
1145 }
729e4ab9 1146
b75a7d8f 1147 if (variant.length() != 0) {
b75a7d8f 1148 status = U_ZERO_ERROR;
729e4ab9
A
1149 resStr = subres.getStringEx(
1150 CharString().appendInvariantChars(variant, status).data(), status);
b75a7d8f
A
1151 if (U_SUCCESS(status)) {
1152 // Exit loop successfully
1153 break;
1154 }
729e4ab9 1155 } else {
b75a7d8f
A
1156 // Variant is empty, which means match the first variant listed.
1157 status = U_ZERO_ERROR;
1158 resStr = subres.getStringEx(1, status);
1159 if (U_SUCCESS(status)) {
1160 // Exit loop successfully
1161 break;
1162 }
1163 }
1164 }
1165
1166 if (pass==2) {
1167 // Failed
1168 return NULL;
1169 }
1170
1171 // We have succeeded in loading a string from the locale
1172 // resources. Create a new registry entry to hold it and return it.
729e4ab9 1173 TransliteratorEntry *entry = new TransliteratorEntry();
b75a7d8f
A
1174 if (entry != 0) {
1175 // The direction is always forward for the
1176 // TransliterateTo_xxx and TransliterateFrom_xxx
1177 // items; those are unidirectional forward rules.
1178 // For the bidirectional Transliterate_xxx items,
1179 // the direction is the value passed in to this
1180 // function.
1181 int32_t dir = (pass == 0) ? UTRANS_FORWARD : direction;
729e4ab9 1182 entry->entryType = TransliteratorEntry::LOCALE_RULES;
b75a7d8f
A
1183 entry->stringArg = resStr;
1184 entry->intArg = dir;
1185 }
1186
1187 return entry;
1188}
1189
1190/**
1191 * Convenience method. Calls 3-arg find().
1192 */
729e4ab9 1193TransliteratorEntry* TransliteratorRegistry::find(const UnicodeString& ID) {
b75a7d8f
A
1194 UnicodeString source, target, variant;
1195 UBool sawSource;
1196 TransliteratorIDParser::IDtoSTV(ID, source, target, variant, sawSource);
1197 return find(source, target, variant);
1198}
1199
1200/**
1201 * Top-level find method. Attempt to find a source-target/variant in
1202 * either the dynamic or the static (locale resource) store. Perform
1203 * fallback.
1204 *
1205 * Lookup sequence for ss_SS_SSS-tt_TT_TTT/v:
1206 *
1207 * ss_SS_SSS-tt_TT_TTT/v -- in hashtable
1208 * ss_SS_SSS-tt_TT_TTT/v -- in ss_SS_SSS (no fallback)
1209 *
1210 * repeat with t = tt_TT_TTT, tt_TT, tt, and tscript
1211 *
1212 * ss_SS_SSS-t/ *
1213 * ss_SS-t/ *
1214 * ss-t/ *
1215 * sscript-t/ *
1216 *
1217 * Here * matches the first variant listed.
1218 *
1219 * Caller does NOT own returned object. Return 0 on failure.
1220 */
729e4ab9 1221TransliteratorEntry* TransliteratorRegistry::find(UnicodeString& source,
b75a7d8f
A
1222 UnicodeString& target,
1223 UnicodeString& variant) {
1224
729e4ab9
A
1225 TransliteratorSpec src(source);
1226 TransliteratorSpec trg(target);
1227 TransliteratorEntry* entry;
1228
1229 // Seek exact match in hashtable. Temporary fix for ICU 4.6.
1230 // TODO: The general logic for finding a matching transliterator needs to be reviewed.
1231 // ICU ticket #8089
1232 UnicodeString ID;
1233 TransliteratorIDParser::STVtoID(source, target, variant, ID);
1234 entry = (TransliteratorEntry*) registry.get(ID);
1235 if (entry != 0) {
1236 // std::string ss;
1237 // std::cout << ID.toUTF8String(ss) << std::endl;
1238 return entry;
1239 }
b75a7d8f
A
1240
1241 if (variant.length() != 0) {
1242
1243 // Seek exact match in hashtable
1244 entry = findInDynamicStore(src, trg, variant);
1245 if (entry != 0) {
1246 return entry;
1247 }
1248
1249 // Seek exact match in locale resources
1250 entry = findInStaticStore(src, trg, variant);
1251 if (entry != 0) {
1252 return entry;
1253 }
1254 }
1255
1256 for (;;) {
1257 src.reset();
1258 for (;;) {
1259 // Seek match in hashtable
1260 entry = findInDynamicStore(src, trg, NO_VARIANT);
1261 if (entry != 0) {
1262 return entry;
1263 }
1264
1265 // Seek match in locale resources
1266 entry = findInStaticStore(src, trg, NO_VARIANT);
1267 if (entry != 0) {
1268 return entry;
1269 }
1270 if (!src.hasFallback()) {
1271 break;
1272 }
1273 src.next();
1274 }
1275 if (!trg.hasFallback()) {
1276 break;
1277 }
1278 trg.next();
1279 }
1280
1281 return 0;
1282}
1283
1284/**
1285 * Given an Entry object, instantiate it. Caller owns result. Return
1286 * 0 on failure.
1287 *
1288 * Return a non-empty aliasReturn value if the ID points to an alias.
1289 * We cannot instantiate it ourselves because the alias may contain
1290 * filters or compounds, which we do not understand. Caller should
1291 * make aliasReturn empty before calling.
1292 *
1293 * The entry object is assumed to reside in the dynamic store. It may be
1294 * modified.
1295 */
1296Transliterator* TransliteratorRegistry::instantiateEntry(const UnicodeString& ID,
729e4ab9 1297 TransliteratorEntry *entry,
b75a7d8f 1298 TransliteratorAlias* &aliasReturn,
b75a7d8f 1299 UErrorCode& status) {
374ca955
A
1300 Transliterator *t = 0;
1301 U_ASSERT(aliasReturn == 0);
b75a7d8f 1302
374ca955 1303 switch (entry->entryType) {
729e4ab9 1304 case TransliteratorEntry::RBT_DATA:
374ca955
A
1305 t = new RuleBasedTransliterator(ID, entry->u.data);
1306 if (t == 0) {
1307 status = U_MEMORY_ALLOCATION_ERROR;
1308 }
1309 return t;
729e4ab9 1310 case TransliteratorEntry::PROTOTYPE:
374ca955
A
1311 t = entry->u.prototype->clone();
1312 if (t == 0) {
1313 status = U_MEMORY_ALLOCATION_ERROR;
1314 }
1315 return t;
729e4ab9 1316 case TransliteratorEntry::ALIAS:
73c04bcf 1317 aliasReturn = new TransliteratorAlias(entry->stringArg, entry->compoundFilter);
374ca955
A
1318 if (aliasReturn == 0) {
1319 status = U_MEMORY_ALLOCATION_ERROR;
1320 }
1321 return 0;
729e4ab9 1322 case TransliteratorEntry::FACTORY:
374ca955
A
1323 t = entry->u.factory.function(ID, entry->u.factory.context);
1324 if (t == 0) {
1325 status = U_MEMORY_ALLOCATION_ERROR;
1326 }
1327 return t;
729e4ab9 1328 case TransliteratorEntry::COMPOUND_RBT:
374ca955 1329 {
46f4442e
A
1330 UVector* rbts = new UVector(entry->u.dataVector->size(), status);
1331 // Check for null pointer
1332 if (rbts == NULL) {
2ca993e8
A
1333 status = U_MEMORY_ALLOCATION_ERROR;
1334 return NULL;
46f4442e 1335 }
73c04bcf
A
1336 int32_t passNumber = 1;
1337 for (int32_t i = 0; U_SUCCESS(status) && i < entry->u.dataVector->size(); i++) {
4388f060
A
1338 // TODO: Should passNumber be turned into a decimal-string representation (1 -> "1")?
1339 Transliterator* t = new RuleBasedTransliterator(UnicodeString(CompoundTransliterator::PASS_STRING) + UnicodeString(passNumber++),
73c04bcf
A
1340 (TransliterationRuleData*)(entry->u.dataVector->elementAt(i)), FALSE);
1341 if (t == 0)
1342 status = U_MEMORY_ALLOCATION_ERROR;
1343 else
1344 rbts->addElement(t, status);
b75a7d8f 1345 }
46f4442e
A
1346 if (U_FAILURE(status)) {
1347 delete rbts;
73c04bcf 1348 return 0;
46f4442e 1349 }
73c04bcf 1350 aliasReturn = new TransliteratorAlias(ID, entry->stringArg, rbts, entry->compoundFilter);
b75a7d8f 1351 }
374ca955
A
1352 if (aliasReturn == 0) {
1353 status = U_MEMORY_ALLOCATION_ERROR;
1354 }
1355 return 0;
729e4ab9 1356 case TransliteratorEntry::LOCALE_RULES:
374ca955
A
1357 aliasReturn = new TransliteratorAlias(ID, entry->stringArg,
1358 (UTransDirection) entry->intArg);
1359 if (aliasReturn == 0) {
1360 status = U_MEMORY_ALLOCATION_ERROR;
1361 }
1362 return 0;
729e4ab9
A
1363 case TransliteratorEntry::RULES_FORWARD:
1364 case TransliteratorEntry::RULES_REVERSE:
374ca955
A
1365 // Process the rule data into a TransliteratorRuleData object,
1366 // and possibly also into an ::id header and/or footer. Then
1367 // we modify the registry with the parsed data and retry.
1368 {
73c04bcf 1369 TransliteratorParser parser(status);
b75a7d8f
A
1370
1371 // We use the file name, taken from another resource bundle
1372 // 2-d array at static init time, as a locale language. We're
1373 // just using the locale mechanism to map through to a file
1374 // name; this in no way represents an actual locale.
374ca955
A
1375 //CharString ch(entry->stringArg);
1376 //UResourceBundle *bundle = ures_openDirect(0, ch, &status);
1377 UnicodeString rules = entry->stringArg;
1378 //ures_close(bundle);
b75a7d8f 1379
374ca955
A
1380 //if (U_FAILURE(status)) {
1381 // We have a failure of some kind. Remove the ID from the
1382 // registry so we don't keep trying. NOTE: This will throw off
1383 // anyone who is, at the moment, trying to iterate over the
1384 // available IDs. That's acceptable since we should never
1385 // really get here except under installation, configuration,
1386 // or unrecoverable run time memory failures.
1387 // remove(ID);
1388 //} else {
1389
1390 // If the status indicates a failure, then we don't have any
1391 // rules -- there is probably an installation error. The list
1392 // in the root locale should correspond to all the installed
1393 // transliterators; if it lists something that's not
1394 // installed, we'll get an error from ResourceBundle.
1395 aliasReturn = new TransliteratorAlias(ID, rules,
729e4ab9 1396 ((entry->entryType == TransliteratorEntry::RULES_REVERSE) ?
374ca955
A
1397 UTRANS_REVERSE : UTRANS_FORWARD));
1398 if (aliasReturn == 0) {
1399 status = U_MEMORY_ALLOCATION_ERROR;
1400 }
1401 //}
b75a7d8f 1402 }
374ca955
A
1403 return 0;
1404 default:
1405 U_ASSERT(FALSE); // can't get here
1406 return 0;
b75a7d8f 1407 }
b75a7d8f
A
1408}
1409U_NAMESPACE_END
1410
1411#endif /* #if !UCONFIG_NO_TRANSLITERATION */
1412
1413//eof