1 // © 2016 and later: Unicode, Inc. and others.
2 // License & terms of use: http://www.unicode.org/copyright.html
4 **********************************************************************
5 * Copyright (c) 2001-2014, International Business Machines
6 * Corporation and others. All Rights Reserved.
7 **********************************************************************
8 * Date Name Description
9 * 08/10/2001 aliu Creation.
10 **********************************************************************
13 #include "unicode/utypes.h"
15 #if !UCONFIG_NO_TRANSLITERATION
17 #include "unicode/translit.h"
18 #include "unicode/resbund.h"
19 #include "unicode/uniset.h"
20 #include "unicode/uscript.h"
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.
44 static const UChar LOCALE_SEP
= 95; // '_'
45 //static const UChar ID_SEP = 0x002D; /*-*/
46 //static const UChar VARIANT_SEP = 0x002F; // '/'
49 static const UChar ANY
[] = { 0x41, 0x6E, 0x79, 0 }; // Any
50 static const UChar LAT
[] = { 0x4C, 0x61, 0x74, 0 }; // Lat
53 #define NO_VARIANT UnicodeString()
55 // initial estimate for specDAG size
56 // ICU 60 Transliterator::countAvailableSources()
57 //#define SPECDAG_INIT_SIZE 149
59 #define SPECDAG_INIT_SIZE 134
61 // initial estimate for number of variant names
62 #define VARIANT_LIST_INIT_SIZE 11
63 #define VARIANT_LIST_MAX_SIZE 31
65 // initial estimate for availableIDs count (default estimate is 8 => multiple reallocs)
66 // ICU 60 Transliterator::countAvailableIDs()
67 //#define AVAILABLE_IDS_INIT_SIZE 641
69 #define AVAILABLE_IDS_INIT_SIZE 493
71 // initial estimate for number of targets for source "Any", "Lat"
72 // ICU 60 Transliterator::countAvailableTargets("Any")/("Latn")
73 //#define ANY_TARGETS_INIT_SIZE 125
75 #define ANY_TARGETS_INIT_SIZE 102
76 #define LAT_TARGETS_INIT_SIZE 23
79 * Resource bundle key for the RuleBasedTransliterator rule.
81 //static const char RB_RULE[] = "Rule";
85 //------------------------------------------------------------------
87 //------------------------------------------------------------------
89 TransliteratorAlias::TransliteratorAlias(const UnicodeString
& theAliasID
,
90 const UnicodeSet
* cpdFilter
) :
92 aliasesOrRules(theAliasID
),
94 compoundFilter(cpdFilter
),
95 direction(UTRANS_FORWARD
),
96 type(TransliteratorAlias::SIMPLE
) {
99 TransliteratorAlias::TransliteratorAlias(const UnicodeString
& theID
,
100 const UnicodeString
& idBlocks
,
101 UVector
* adoptedTransliterators
,
102 const UnicodeSet
* cpdFilter
) :
104 aliasesOrRules(idBlocks
),
105 transes(adoptedTransliterators
),
106 compoundFilter(cpdFilter
),
107 direction(UTRANS_FORWARD
),
108 type(TransliteratorAlias::COMPOUND
) {
111 TransliteratorAlias::TransliteratorAlias(const UnicodeString
& theID
,
112 const UnicodeString
& rules
,
113 UTransDirection dir
) :
115 aliasesOrRules(rules
),
119 type(TransliteratorAlias::RULES
) {
122 TransliteratorAlias::~TransliteratorAlias() {
127 Transliterator
* TransliteratorAlias::create(UParseError
& pe
,
132 Transliterator
*t
= NULL
;
135 t
= Transliterator::createInstance(aliasesOrRules
, UTRANS_FORWARD
, pe
, ec
);
139 if (compoundFilter
!= 0)
140 t
->adoptFilter((UnicodeSet
*)compoundFilter
->clone());
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))
153 if (aliasesOrRules
.length() >= 2 && aliasesOrRules
[aliasesOrRules
.length() - 1] == (UChar
)(0xffff))
155 UnicodeString
noIDBlock((UChar
)(0xffff));
156 noIDBlock
+= ((UChar
)(0xffff));
157 int32_t pos
= aliasesOrRules
.indexOf(noIDBlock
);
160 pos
= aliasesOrRules
.indexOf(noIDBlock
, pos
+ 1);
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));
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
);
181 t
= new CompoundTransliterator(ID
, transliterators
,
182 (compoundFilter
? (UnicodeSet
*)(compoundFilter
->clone()) : 0),
183 anonymousRBTs
, pe
, ec
);
185 ec
= U_MEMORY_ALLOCATION_ERROR
;
189 for (int32_t i
= 0; i
< transliterators
.size(); i
++)
190 delete (Transliterator
*)(transliterators
.elementAt(i
));
195 U_ASSERT(FALSE
); // don't call create() if isRuleBased() returns TRUE!
201 UBool
TransliteratorAlias::isRuleBased() const {
202 return type
== RULES
;
205 void TransliteratorAlias::parse(TransliteratorParser
& parser
,
206 UParseError
& pe
, UErrorCode
& ec
) const {
207 U_ASSERT(type
== RULES
);
212 parser
.parse(aliasesOrRules
, direction
, pe
, ec
);
215 //----------------------------------------------------------------------
216 // class TransliteratorSpec
217 //----------------------------------------------------------------------
220 * A TransliteratorSpec is a string specifying either a source or a target. In more
221 * general terms, it may also specify a variant, but we only use the
222 * Spec class for sources and targets.
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
230 * The Spec class canonicalizes itself, so the locale is put into
231 * canonical form, or the script is transformed from an abbreviation
234 class TransliteratorSpec
: public UMemory
{
236 TransliteratorSpec(const UnicodeString
& spec
);
237 ~TransliteratorSpec();
239 const UnicodeString
& get() const;
240 UBool
hasFallback() const;
241 const UnicodeString
& next();
244 UBool
isLocale() const;
245 ResourceBundle
& getBundle() const;
247 operator const UnicodeString
&() const { return get(); }
248 const UnicodeString
& getTop() const { return top
; }
255 UnicodeString nextSpec
;
256 UnicodeString scriptName
;
257 UBool isSpecLocale
; // TRUE if spec is a locale
258 UBool isNextLocale
; // TRUE if nextSpec is a locale
261 TransliteratorSpec(const TransliteratorSpec
&other
); // forbid copying of this class
262 TransliteratorSpec
&operator=(const TransliteratorSpec
&other
); // forbid copying of this class
265 TransliteratorSpec::TransliteratorSpec(const UnicodeString
& theSpec
)
269 UErrorCode status
= U_ZERO_ERROR
;
271 LocaleUtility::initLocaleFromName(theSpec
, topLoc
);
272 if (!topLoc
.isBogus()) {
273 res
= new ResourceBundle(U_ICUDATA_TRANSLIT
, topLoc
, status
);
278 if (U_FAILURE(status
) || status
== U_USING_DEFAULT_WARNING
) {
284 // Canonicalize script name -or- do locale->script mapping
285 status
= U_ZERO_ERROR
;
286 static const int32_t capacity
= 10;
287 UScriptCode script
[capacity
]={USCRIPT_INVALID_CODE
};
288 int32_t num
= uscript_getCode(CharString().appendInvariantChars(theSpec
, status
).data(),
289 script
, capacity
, &status
);
290 if (num
> 0 && script
[0] != USCRIPT_INVALID_CODE
) {
291 scriptName
= UnicodeString(uscript_getName(script
[0]), -1, US_INV
);
296 // Canonicalize locale name
297 UnicodeString locStr
;
298 LocaleUtility::initNameFromLocale(topLoc
, locStr
);
299 if (!locStr
.isBogus()) {
302 } else if (scriptName
.length() != 0) {
303 // We are a script; use canonical name
307 // assert(spec != top);
311 TransliteratorSpec::~TransliteratorSpec() {
315 UBool
TransliteratorSpec::hasFallback() const {
316 return nextSpec
.length() != 0;
319 void TransliteratorSpec::reset() {
322 isSpecLocale
= (res
!= 0);
327 void TransliteratorSpec::setupNext() {
328 isNextLocale
= FALSE
;
331 int32_t i
= nextSpec
.lastIndexOf(LOCALE_SEP
);
332 // If i == 0 then we have _FOO, so we fall through
333 // to the scriptName.
335 nextSpec
.truncate(i
);
338 nextSpec
= scriptName
; // scriptName may be empty
341 // spec is a script, so we are at the end
342 nextSpec
.truncate(0);
347 // for(const UnicodeString& s(spec.get());
348 // spec.hasFallback(); s(spec.next())) { ...
350 const UnicodeString
& TransliteratorSpec::next() {
352 isSpecLocale
= isNextLocale
;
357 const UnicodeString
& TransliteratorSpec::get() const {
361 UBool
TransliteratorSpec::isLocale() const {
365 ResourceBundle
& TransliteratorSpec::getBundle() const {
369 //----------------------------------------------------------------------
373 // Vector of Entry pointers currently in use
374 static UVector
* DEBUG_entries
= NULL
;
376 static void DEBUG_setup() {
377 if (DEBUG_entries
== NULL
) {
378 UErrorCode ec
= U_ZERO_ERROR
;
379 DEBUG_entries
= new UVector(ec
);
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.
385 static int DEBUG_findEntry(TransliteratorEntry
* e
) {
386 for (int i
=0; i
<DEBUG_entries
->size(); ++i
) {
387 if (e
== (TransliteratorEntry
*) DEBUG_entries
->elementAt(i
)) {
394 // Track object creation
395 static void DEBUG_newEntry(TransliteratorEntry
* e
) {
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
);
402 UErrorCode ec
= U_ZERO_ERROR
;
403 DEBUG_entries
->addElement(e
, ec
);
406 // Track object deletion
407 static void DEBUG_delEntry(TransliteratorEntry
* e
) {
409 int i
= DEBUG_findEntry(e
);
411 printf("ERROR DEBUG_delEntry possible double deletion %08X\n", e
);
414 DEBUG_entries
->removeElementAt(i
);
417 // Track object usage
418 static void DEBUG_useEntry(TransliteratorEntry
* e
) {
419 if (e
== NULL
) return;
421 int i
= DEBUG_findEntry(e
);
423 printf("ERROR DEBUG_useEntry possible dangling pointer %08X\n", e
);
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)
434 //----------------------------------------------------------------------
436 //----------------------------------------------------------------------
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
448 class TransliteratorEntry
: public UMemory
{
459 NONE
// Only used for uninitialized entries
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
467 Transliterator
* prototype
; // For PROTOTYPE
468 TransliterationRuleData
* data
; // For RBT_DATA
469 UVector
* dataVector
; // For COMPOUND_RBT
471 Transliterator::Factory function
;
472 Transliterator::Token context
;
473 } factory
; // For FACTORY
475 TransliteratorEntry();
476 ~TransliteratorEntry();
477 void adoptPrototype(Transliterator
* adopted
);
478 void setFactory(Transliterator::Factory factory
,
479 Transliterator::Token context
);
483 TransliteratorEntry(const TransliteratorEntry
&other
); // forbid copying of this class
484 TransliteratorEntry
&operator=(const TransliteratorEntry
&other
); // forbid copying of this class
487 TransliteratorEntry::TransliteratorEntry() {
489 compoundFilter
= NULL
;
491 DEBUG_newEntry(this);
494 TransliteratorEntry::~TransliteratorEntry() {
495 DEBUG_delEntry(this);
496 if (entryType
== PROTOTYPE
) {
498 } else if (entryType
== RBT_DATA
) {
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.
504 } else if (entryType
== COMPOUND_RBT
) {
505 while (u
.dataVector
!= NULL
&& !u
.dataVector
->isEmpty())
506 delete (TransliterationRuleData
*)u
.dataVector
->orphanElementAt(0);
509 delete compoundFilter
;
512 void TransliteratorEntry::adoptPrototype(Transliterator
* adopted
) {
513 if (entryType
== PROTOTYPE
) {
516 entryType
= PROTOTYPE
;
517 u
.prototype
= adopted
;
520 void TransliteratorEntry::setFactory(Transliterator::Factory factory
,
521 Transliterator::Token context
) {
522 if (entryType
== PROTOTYPE
) {
526 u
.factory
.function
= factory
;
527 u
.factory
.context
= context
;
530 // UObjectDeleter for Hashtable::setValueDeleter
532 static void U_CALLCONV
533 deleteEntry(void* obj
) {
534 delete (TransliteratorEntry
*) obj
;
538 //----------------------------------------------------------------------
539 // class TransliteratorRegistry: Basic public API
540 //----------------------------------------------------------------------
542 TransliteratorRegistry::TransliteratorRegistry(UErrorCode
& status
) :
543 registry(TRUE
, status
),
544 specDAG(TRUE
, SPECDAG_INIT_SIZE
, status
),
545 variantList(VARIANT_LIST_INIT_SIZE
, status
),
546 availableIDs(AVAILABLE_IDS_INIT_SIZE
, status
)
548 registry
.setValueDeleter(deleteEntry
);
549 variantList
.setDeleter(uprv_deleteUObject
);
550 variantList
.setComparer(uhash_compareCaselessUnicodeString
);
551 UnicodeString
*emptyString
= new UnicodeString();
552 if (emptyString
!= NULL
) {
553 variantList
.addElement(emptyString
, status
);
555 availableIDs
.setDeleter(uprv_deleteUObject
);
556 availableIDs
.setComparer(uhash_compareCaselessUnicodeString
);
557 specDAG
.setValueDeleter(uhash_deleteHashtable
);
560 TransliteratorRegistry::~TransliteratorRegistry() {
561 // Through the magic of C++, everything cleans itself up
564 Transliterator
* TransliteratorRegistry::get(const UnicodeString
& ID
,
565 TransliteratorAlias
*& aliasReturn
,
566 UErrorCode
& status
) {
567 U_ASSERT(aliasReturn
== NULL
);
568 TransliteratorEntry
*entry
= find(ID
);
569 return (entry
== 0) ? 0
570 : instantiateEntry(ID
, entry
, aliasReturn
, status
);
573 Transliterator
* TransliteratorRegistry::reget(const UnicodeString
& ID
,
574 TransliteratorParser
& parser
,
575 TransliteratorAlias
*& aliasReturn
,
576 UErrorCode
& status
) {
577 U_ASSERT(aliasReturn
== NULL
);
578 TransliteratorEntry
*entry
= find(ID
);
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.
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].
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).
599 if (entry
->entryType
== TransliteratorEntry::RULES_FORWARD
||
600 entry
->entryType
== TransliteratorEntry::RULES_REVERSE
||
601 entry
->entryType
== TransliteratorEntry::LOCALE_RULES
) {
603 if (parser
.idBlockVector
.isEmpty() && parser
.dataVector
.isEmpty()) {
605 entry
->entryType
= TransliteratorEntry::ALIAS
;
606 entry
->stringArg
= UNICODE_STRING_SIMPLE("Any-NULL");
608 else if (parser
.idBlockVector
.isEmpty() && parser
.dataVector
.size() == 1) {
609 entry
->u
.data
= (TransliterationRuleData
*)parser
.dataVector
.orphanElementAt(0);
610 entry
->entryType
= TransliteratorEntry::RBT_DATA
;
612 else if (parser
.idBlockVector
.size() == 1 && parser
.dataVector
.isEmpty()) {
613 entry
->stringArg
= *(UnicodeString
*)(parser
.idBlockVector
.elementAt(0));
614 entry
->compoundFilter
= parser
.orphanCompoundFilter();
615 entry
->entryType
= TransliteratorEntry::ALIAS
;
618 entry
->entryType
= TransliteratorEntry::COMPOUND_RBT
;
619 entry
->compoundFilter
= parser
.orphanCompoundFilter();
620 entry
->u
.dataVector
= new UVector(status
);
621 entry
->stringArg
.remove();
623 int32_t limit
= parser
.idBlockVector
.size();
624 if (parser
.dataVector
.size() > limit
)
625 limit
= parser
.dataVector
.size();
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
;
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
643 instantiateEntry(ID
, entry
, aliasReturn
, status
);
647 void TransliteratorRegistry::put(Transliterator
* adoptedProto
,
651 TransliteratorEntry
*entry
= new TransliteratorEntry();
653 ec
= U_MEMORY_ALLOCATION_ERROR
;
656 entry
->adoptPrototype(adoptedProto
);
657 registerEntry(adoptedProto
->getID(), entry
, visible
);
660 void TransliteratorRegistry::put(const UnicodeString
& ID
,
661 Transliterator::Factory factory
,
662 Transliterator::Token context
,
665 TransliteratorEntry
*entry
= new TransliteratorEntry();
667 ec
= U_MEMORY_ALLOCATION_ERROR
;
670 entry
->setFactory(factory
, context
);
671 registerEntry(ID
, entry
, visible
);
674 void TransliteratorRegistry::put(const UnicodeString
& ID
,
675 const UnicodeString
& resourceName
,
677 UBool readonlyResourceAlias
,
680 TransliteratorEntry
*entry
= new TransliteratorEntry();
682 ec
= U_MEMORY_ALLOCATION_ERROR
;
685 entry
->entryType
= (dir
== UTRANS_FORWARD
) ? TransliteratorEntry::RULES_FORWARD
686 : TransliteratorEntry::RULES_REVERSE
;
687 if (readonlyResourceAlias
) {
688 entry
->stringArg
.setTo(TRUE
, resourceName
.getBuffer(), -1);
691 entry
->stringArg
= resourceName
;
693 registerEntry(ID
, entry
, visible
);
696 void TransliteratorRegistry::put(const UnicodeString
& ID
,
697 const UnicodeString
& alias
,
698 UBool readonlyAliasAlias
,
700 UErrorCode
& /*ec*/) {
701 TransliteratorEntry
*entry
= new TransliteratorEntry();
702 // Null pointer check
704 entry
->entryType
= TransliteratorEntry::ALIAS
;
705 if (readonlyAliasAlias
) {
706 entry
->stringArg
.setTo(TRUE
, alias
.getBuffer(), -1);
709 entry
->stringArg
= alias
;
711 registerEntry(ID
, entry
, visible
);
715 void TransliteratorRegistry::remove(const UnicodeString
& ID
) {
716 UnicodeString source
, target
, variant
;
718 TransliteratorIDParser::IDtoSTV(ID
, source
, target
, variant
, sawSource
);
719 // Only need to do this if ID.indexOf('-') < 0
721 TransliteratorIDParser::STVtoID(source
, target
, variant
, id
);
723 removeSTV(source
, target
, variant
);
724 availableIDs
.removeElement((void*) &id
);
727 //----------------------------------------------------------------------
728 // class TransliteratorRegistry: Public ID and spec management
729 //----------------------------------------------------------------------
732 * == OBSOLETE - remove in ICU 3.4 ==
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.
737 int32_t TransliteratorRegistry::countAvailableIDs(void) const {
738 return availableIDs
.size();
742 * == OBSOLETE - remove in ICU 3.4 ==
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.
747 const UnicodeString
& TransliteratorRegistry::getAvailableID(int32_t index
) const {
748 if (index
< 0 || index
>= availableIDs
.size()) {
751 return *(const UnicodeString
*) availableIDs
[index
];
754 StringEnumeration
* TransliteratorRegistry::getAvailableIDs() const {
755 return new Enumeration(*this);
758 int32_t TransliteratorRegistry::countAvailableSources(void) const {
759 return specDAG
.count();
762 UnicodeString
& TransliteratorRegistry::getAvailableSource(int32_t index
,
763 UnicodeString
& result
) const {
764 int32_t pos
= UHASH_FIRST
;
765 const UHashElement
*e
= 0;
766 while (index
-- >= 0) {
767 e
= specDAG
.nextElement(pos
);
775 result
= *(UnicodeString
*) e
->key
.pointer
;
780 int32_t TransliteratorRegistry::countAvailableTargets(const UnicodeString
& source
) const {
781 Hashtable
*targets
= (Hashtable
*) specDAG
.get(source
);
782 return (targets
== 0) ? 0 : targets
->count();
785 UnicodeString
& TransliteratorRegistry::getAvailableTarget(int32_t index
,
786 const UnicodeString
& source
,
787 UnicodeString
& result
) const {
788 Hashtable
*targets
= (Hashtable
*) specDAG
.get(source
);
790 result
.truncate(0); // invalid source
793 int32_t pos
= UHASH_FIRST
;
794 const UHashElement
*e
= 0;
795 while (index
-- >= 0) {
796 e
= targets
->nextElement(pos
);
802 result
.truncate(0); // invalid index
804 result
= *(UnicodeString
*) e
->key
.pointer
;
809 int32_t TransliteratorRegistry::countAvailableVariants(const UnicodeString
& source
,
810 const UnicodeString
& target
) const {
811 Hashtable
*targets
= (Hashtable
*) specDAG
.get(source
);
815 uint32_t varMask
= targets
->geti(target
);
816 int32_t varCount
= 0;
817 while (varMask
> 0) {
826 UnicodeString
& TransliteratorRegistry::getAvailableVariant(int32_t index
,
827 const UnicodeString
& source
,
828 const UnicodeString
& target
,
829 UnicodeString
& result
) const {
830 Hashtable
*targets
= (Hashtable
*) specDAG
.get(source
);
832 result
.truncate(0); // invalid source
835 uint32_t varMask
= targets
->geti(target
);
836 int32_t varCount
= 0;
837 int32_t varListIndex
= 0;
838 while (varMask
> 0) {
840 if (varCount
== index
) {
841 UnicodeString
*v
= (UnicodeString
*) variantList
.elementAt(varListIndex
);
853 result
.truncate(0); // invalid target or index
857 //----------------------------------------------------------------------
858 // class TransliteratorRegistry::Enumeration
859 //----------------------------------------------------------------------
861 TransliteratorRegistry::Enumeration::Enumeration(const TransliteratorRegistry
& _reg
) :
862 index(0), reg(_reg
) {
865 TransliteratorRegistry::Enumeration::~Enumeration() {
868 int32_t TransliteratorRegistry::Enumeration::count(UErrorCode
& /*status*/) const {
869 return reg
.availableIDs
.size();
872 const 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
)) {
885 int32_t n
= reg
.availableIDs
.size();
887 status
= U_ENUM_OUT_OF_SYNC_ERROR
;
889 // index == n is okay -- this means we've reached the end
891 // Copy the string! This avoids lifetime problems.
892 unistr
= *(const UnicodeString
*)reg
.availableIDs
[index
++];
899 void TransliteratorRegistry::Enumeration::reset(UErrorCode
& /*status*/) {
903 UOBJECT_DEFINE_RTTI_IMPLEMENTATION(TransliteratorRegistry::Enumeration
)
905 //----------------------------------------------------------------------
906 // class TransliteratorRegistry: internal
907 //----------------------------------------------------------------------
910 * Convenience method. Calls 6-arg registerEntry().
912 void TransliteratorRegistry::registerEntry(const UnicodeString
& source
,
913 const UnicodeString
& target
,
914 const UnicodeString
& variant
,
915 TransliteratorEntry
* adopted
,
918 UnicodeString
s(source
);
919 if (s
.length() == 0) {
920 s
.setTo(TRUE
, ANY
, 3);
922 TransliteratorIDParser::STVtoID(source
, target
, variant
, ID
);
923 registerEntry(ID
, s
, target
, variant
, adopted
, visible
);
927 * Convenience method. Calls 6-arg registerEntry().
929 void TransliteratorRegistry::registerEntry(const UnicodeString
& ID
,
930 TransliteratorEntry
* adopted
,
932 UnicodeString source
, target
, variant
;
934 TransliteratorIDParser::IDtoSTV(ID
, source
, target
, variant
, sawSource
);
935 // Only need to do this if ID.indexOf('-') < 0
937 TransliteratorIDParser::STVtoID(source
, target
, variant
, id
);
938 registerEntry(id
, source
, target
, variant
, adopted
, visible
);
942 * Register an entry object (adopted) with the given ID, source,
943 * target, and variant strings.
945 void TransliteratorRegistry::registerEntry(const UnicodeString
& ID
,
946 const UnicodeString
& source
,
947 const UnicodeString
& target
,
948 const UnicodeString
& variant
,
949 TransliteratorEntry
* adopted
,
951 UErrorCode status
= U_ZERO_ERROR
;
952 registry
.put(ID
, adopted
, status
);
954 registerSTV(source
, target
, variant
);
955 if (!availableIDs
.contains((void*) &ID
)) {
956 UnicodeString
*newID
= (UnicodeString
*)ID
.clone();
957 // Check to make sure newID was created.
959 // NUL-terminate the ID string
960 newID
->getTerminatedBuffer();
961 availableIDs
.addElement(newID
, status
);
965 removeSTV(source
, target
, variant
);
966 availableIDs
.removeElement((void*) &ID
);
971 * Register a source-target/variant in the specDAG. Variant may be
972 * empty, but source and target must not be.
974 void 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
);
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
;
988 targets
= new Hashtable(TRUE
, size
, status
);
989 if (U_FAILURE(status
) || targets
== NULL
) {
992 specDAG
.put(source
, targets
, status
);
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
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;
1007 if (variantListIndex
< 0) {
1011 uint32_t addMask
= 1 << variantListIndex
;
1012 uint32_t varMask
= targets
->geti(target
);
1013 targets
->puti(target
, varMask
| addMask
, status
);
1017 * Remove a source-target/variant from the specDAG.
1019 void TransliteratorRegistry::removeSTV(const UnicodeString
& source
,
1020 const UnicodeString
& target
,
1021 const UnicodeString
& variant
) {
1022 // assert(source.length() > 0);
1023 // assert(target.length() > 0);
1024 UErrorCode status
= U_ZERO_ERROR
;
1025 Hashtable
*targets
= (Hashtable
*) specDAG
.get(source
);
1026 if (targets
== NULL
) {
1027 return; // should never happen for valid s-t/v
1029 uint32_t varMask
= targets
->geti(target
);
1031 return; // should never happen for valid s-t/v
1033 int32_t variantListIndex
= variantList
.indexOf((void*) &variant
, 0);
1034 if (variantListIndex
< 0) {
1035 return; // should never happen for valid s-t/v
1037 int32_t remMask
= 1 << variantListIndex
;
1038 varMask
&= (~remMask
);
1040 targets
->puti(target
, varMask
, status
);
1042 targets
->remove(target
); // should delete variants
1043 if (targets
->count() == 0) {
1044 specDAG
.remove(source
); // should delete targets
1050 * Attempt to find a source-target/variant in the dynamic registry
1051 * store. Return 0 on failure.
1053 * Caller does NOT own returned object.
1055 TransliteratorEntry
* TransliteratorRegistry::findInDynamicStore(const TransliteratorSpec
& src
,
1056 const TransliteratorSpec
& trg
,
1057 const UnicodeString
& variant
) const {
1059 TransliteratorIDParser::STVtoID(src
, trg
, variant
, ID
);
1060 TransliteratorEntry
*e
= (TransliteratorEntry
*) registry
.get(ID
);
1066 * Attempt to find a source-target/variant in the static locale
1067 * resource store. Do not perform fallback. Return 0 on failure.
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).
1074 * Caller does NOT own returned object.
1076 TransliteratorEntry
* TransliteratorRegistry::findInStaticStore(const TransliteratorSpec
& src
,
1077 const TransliteratorSpec
& trg
,
1078 const UnicodeString
& variant
) {
1079 TransliteratorEntry
* entry
= 0;
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
);
1086 // If we found an entry, store it in the Hashtable for next
1089 registerEntry(src
.getTop(), trg
.getTop(), variant
, entry
, FALSE
);
1095 // As of 2.0, resource bundle keys cannot contain '_'
1096 static const UChar TRANSLITERATE_TO
[] = {84,114,97,110,115,108,105,116,101,114,97,116,101,84,111,0}; // "TransliterateTo"
1098 static const UChar TRANSLITERATE_FROM
[] = {84,114,97,110,115,108,105,116,101,114,97,116,101,70,114,111,109,0}; // "TransliterateFrom"
1100 static const UChar TRANSLITERATE
[] = {84,114,97,110,115,108,105,116,101,114,97,116,101,0}; // "Transliterate"
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.
1107 * Do not perform fallback. Return 0 on failure.
1109 * On success, create a new Entry object, populate it, and return it.
1110 * The caller owns the returned object.
1112 TransliteratorEntry
* TransliteratorRegistry::findInBundle(const TransliteratorSpec
& specToOpen
,
1113 const TransliteratorSpec
& specToFind
,
1114 const UnicodeString
& variant
,
1115 UTransDirection direction
)
1118 UnicodeString resStr
;
1121 for (pass
=0; pass
<2; ++pass
) {
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.
1128 utag
.append(direction
== UTRANS_FORWARD
?
1129 TRANSLITERATE_TO
: TRANSLITERATE_FROM
, -1);
1131 utag
.append(TRANSLITERATE
, -1);
1133 UnicodeString
s(specToFind
.get());
1134 utag
.append(s
.toUpper(""));
1135 UErrorCode status
= U_ZERO_ERROR
;
1136 ResourceBundle
subres(specToOpen
.getBundle().get(
1137 CharString().appendInvariantChars(utag
, status
).data(), status
));
1138 if (U_FAILURE(status
) || status
== U_USING_DEFAULT_WARNING
) {
1143 if (specToOpen
.get() != LocaleUtility::initNameFromLocale(subres
.getLocale(), s
)) {
1147 if (variant
.length() != 0) {
1148 status
= U_ZERO_ERROR
;
1149 resStr
= subres
.getStringEx(
1150 CharString().appendInvariantChars(variant
, status
).data(), status
);
1151 if (U_SUCCESS(status
)) {
1152 // Exit loop successfully
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
1171 // We have succeeded in loading a string from the locale
1172 // resources. Create a new registry entry to hold it and return it.
1173 TransliteratorEntry
*entry
= new TransliteratorEntry();
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
1181 int32_t dir
= (pass
== 0) ? UTRANS_FORWARD
: direction
;
1182 entry
->entryType
= TransliteratorEntry::LOCALE_RULES
;
1183 entry
->stringArg
= resStr
;
1184 entry
->intArg
= dir
;
1191 * Convenience method. Calls 3-arg find().
1193 TransliteratorEntry
* TransliteratorRegistry::find(const UnicodeString
& ID
) {
1194 UnicodeString source
, target
, variant
;
1196 TransliteratorIDParser::IDtoSTV(ID
, source
, target
, variant
, sawSource
);
1197 return find(source
, target
, variant
);
1201 * Top-level find method. Attempt to find a source-target/variant in
1202 * either the dynamic or the static (locale resource) store. Perform
1205 * Lookup sequence for ss_SS_SSS-tt_TT_TTT/v:
1207 * ss_SS_SSS-tt_TT_TTT/v -- in hashtable
1208 * ss_SS_SSS-tt_TT_TTT/v -- in ss_SS_SSS (no fallback)
1210 * repeat with t = tt_TT_TTT, tt_TT, tt, and tscript
1217 * Here * matches the first variant listed.
1219 * Caller does NOT own returned object. Return 0 on failure.
1221 TransliteratorEntry
* TransliteratorRegistry::find(UnicodeString
& source
,
1222 UnicodeString
& target
,
1223 UnicodeString
& variant
) {
1225 TransliteratorSpec
src(source
);
1226 TransliteratorSpec
trg(target
);
1227 TransliteratorEntry
* entry
;
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.
1233 TransliteratorIDParser::STVtoID(source
, target
, variant
, ID
);
1234 entry
= (TransliteratorEntry
*) registry
.get(ID
);
1237 // std::cout << ID.toUTF8String(ss) << std::endl;
1241 if (variant
.length() != 0) {
1243 // Seek exact match in hashtable
1244 entry
= findInDynamicStore(src
, trg
, variant
);
1249 // Seek exact match in locale resources
1250 entry
= findInStaticStore(src
, trg
, variant
);
1259 // Seek match in hashtable
1260 entry
= findInDynamicStore(src
, trg
, NO_VARIANT
);
1265 // Seek match in locale resources
1266 entry
= findInStaticStore(src
, trg
, NO_VARIANT
);
1270 if (!src
.hasFallback()) {
1275 if (!trg
.hasFallback()) {
1285 * Given an Entry object, instantiate it. Caller owns result. Return
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.
1293 * The entry object is assumed to reside in the dynamic store. It may be
1296 Transliterator
* TransliteratorRegistry::instantiateEntry(const UnicodeString
& ID
,
1297 TransliteratorEntry
*entry
,
1298 TransliteratorAlias
* &aliasReturn
,
1299 UErrorCode
& status
) {
1300 Transliterator
*t
= 0;
1301 U_ASSERT(aliasReturn
== 0);
1303 switch (entry
->entryType
) {
1304 case TransliteratorEntry::RBT_DATA
:
1305 t
= new RuleBasedTransliterator(ID
, entry
->u
.data
);
1307 status
= U_MEMORY_ALLOCATION_ERROR
;
1310 case TransliteratorEntry::PROTOTYPE
:
1311 t
= entry
->u
.prototype
->clone();
1313 status
= U_MEMORY_ALLOCATION_ERROR
;
1316 case TransliteratorEntry::ALIAS
:
1317 aliasReturn
= new TransliteratorAlias(entry
->stringArg
, entry
->compoundFilter
);
1318 if (aliasReturn
== 0) {
1319 status
= U_MEMORY_ALLOCATION_ERROR
;
1322 case TransliteratorEntry::FACTORY
:
1323 t
= entry
->u
.factory
.function(ID
, entry
->u
.factory
.context
);
1325 status
= U_MEMORY_ALLOCATION_ERROR
;
1328 case TransliteratorEntry::COMPOUND_RBT
:
1330 UVector
* rbts
= new UVector(entry
->u
.dataVector
->size(), status
);
1331 // Check for null pointer
1333 status
= U_MEMORY_ALLOCATION_ERROR
;
1336 int32_t passNumber
= 1;
1337 for (int32_t i
= 0; U_SUCCESS(status
) && i
< entry
->u
.dataVector
->size(); i
++) {
1338 // TODO: Should passNumber be turned into a decimal-string representation (1 -> "1")?
1339 Transliterator
* t
= new RuleBasedTransliterator(UnicodeString(CompoundTransliterator::PASS_STRING
) + UnicodeString(passNumber
++),
1340 (TransliterationRuleData
*)(entry
->u
.dataVector
->elementAt(i
)), FALSE
);
1342 status
= U_MEMORY_ALLOCATION_ERROR
;
1344 rbts
->addElement(t
, status
);
1346 if (U_FAILURE(status
)) {
1350 aliasReturn
= new TransliteratorAlias(ID
, entry
->stringArg
, rbts
, entry
->compoundFilter
);
1352 if (aliasReturn
== 0) {
1353 status
= U_MEMORY_ALLOCATION_ERROR
;
1356 case TransliteratorEntry::LOCALE_RULES
:
1357 aliasReturn
= new TransliteratorAlias(ID
, entry
->stringArg
,
1358 (UTransDirection
) entry
->intArg
);
1359 if (aliasReturn
== 0) {
1360 status
= U_MEMORY_ALLOCATION_ERROR
;
1363 case TransliteratorEntry::RULES_FORWARD
:
1364 case TransliteratorEntry::RULES_REVERSE
:
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.
1369 TransliteratorParser
parser(status
);
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.
1375 //CharString ch(entry->stringArg);
1376 //UResourceBundle *bundle = ures_openDirect(0, ch, &status);
1377 UnicodeString rules
= entry
->stringArg
;
1378 //ures_close(bundle);
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.
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
,
1396 ((entry
->entryType
== TransliteratorEntry::RULES_REVERSE
) ?
1397 UTRANS_REVERSE
: UTRANS_FORWARD
));
1398 if (aliasReturn
== 0) {
1399 status
= U_MEMORY_ALLOCATION_ERROR
;
1405 U_ASSERT(FALSE
); // can't get here
1411 #endif /* #if !UCONFIG_NO_TRANSLITERATION */