2 **********************************************************************
3 * Copyright (c) 2001-2016 International Business Machines
4 * Corporation and others. All Rights Reserved.
5 **********************************************************************
6 * Date Name Description
7 * 08/10/2001 aliu Creation.
8 **********************************************************************
11 #include "unicode/utypes.h"
13 #if !UCONFIG_NO_TRANSLITERATION
15 #include "unicode/translit.h"
16 #include "unicode/resbund.h"
17 #include "unicode/uniset.h"
18 #include "unicode/uscript.h"
30 // Enable the following symbol to add debugging code that tracks the
31 // allocation, deletion, and use of Entry objects. BoundsChecker has
32 // reported dangling pointer errors with these objects, but I have
33 // been unable to confirm them. I suspect BoundsChecker is getting
34 // confused with pointers going into and coming out of a UHashtable,
35 // despite the hinting code that is designed to help it.
42 static const UChar LOCALE_SEP
= 95; // '_'
43 //static const UChar ID_SEP = 0x002D; /*-*/
44 //static const UChar VARIANT_SEP = 0x002F; // '/'
47 static const UChar ANY
[] = { 0x41, 0x6E, 0x79, 0 }; // Any
48 static const UChar LAT
[] = { 0x4C, 0x61, 0x74, 0 }; // Lat
51 #define NO_VARIANT UnicodeString()
53 // initial estimate for specDAG size
54 #define SPECDAG_INIT_SIZE 134
56 // initial estimate for number of variant names
57 #define VARIANT_LIST_INIT_SIZE 11
58 #define VARIANT_LIST_MAX_SIZE 31
60 // initial estimate for availableIDs count (default estimate is 8 => multiple reallocs)
61 #define AVAILABLE_IDS_INIT_SIZE 493
63 // initial estimate for number of targets for source "Any", "Lat"
64 #define ANY_TARGETS_INIT_SIZE 102
65 #define LAT_TARGETS_INIT_SIZE 23
68 * Resource bundle key for the RuleBasedTransliterator rule.
70 //static const char RB_RULE[] = "Rule";
74 //------------------------------------------------------------------
76 //------------------------------------------------------------------
78 TransliteratorAlias::TransliteratorAlias(const UnicodeString
& theAliasID
,
79 const UnicodeSet
* cpdFilter
) :
81 aliasesOrRules(theAliasID
),
83 compoundFilter(cpdFilter
),
84 direction(UTRANS_FORWARD
),
85 type(TransliteratorAlias::SIMPLE
) {
88 TransliteratorAlias::TransliteratorAlias(const UnicodeString
& theID
,
89 const UnicodeString
& idBlocks
,
90 UVector
* adoptedTransliterators
,
91 const UnicodeSet
* cpdFilter
) :
93 aliasesOrRules(idBlocks
),
94 transes(adoptedTransliterators
),
95 compoundFilter(cpdFilter
),
96 direction(UTRANS_FORWARD
),
97 type(TransliteratorAlias::COMPOUND
) {
100 TransliteratorAlias::TransliteratorAlias(const UnicodeString
& theID
,
101 const UnicodeString
& rules
,
102 UTransDirection dir
) :
104 aliasesOrRules(rules
),
108 type(TransliteratorAlias::RULES
) {
111 TransliteratorAlias::~TransliteratorAlias() {
116 Transliterator
* TransliteratorAlias::create(UParseError
& pe
,
121 Transliterator
*t
= NULL
;
124 t
= Transliterator::createInstance(aliasesOrRules
, UTRANS_FORWARD
, pe
, ec
);
128 if (compoundFilter
!= 0)
129 t
->adoptFilter((UnicodeSet
*)compoundFilter
->clone());
133 // the total number of transliterators in the compound is the total number of anonymous transliterators
134 // plus the total number of ID blocks-- we start by assuming the list begins and ends with an ID
135 // block and that each pair anonymous transliterators has an ID block between them. Then we go back
136 // to see whether there really are ID blocks at the beginning and end (by looking for U+FFFF, which
137 // marks the position where an anonymous transliterator goes) and adjust accordingly
138 int32_t anonymousRBTs
= transes
->size();
139 int32_t transCount
= anonymousRBTs
* 2 + 1;
140 if (!aliasesOrRules
.isEmpty() && aliasesOrRules
[0] == (UChar
)(0xffff))
142 if (aliasesOrRules
.length() >= 2 && aliasesOrRules
[aliasesOrRules
.length() - 1] == (UChar
)(0xffff))
144 UnicodeString
noIDBlock((UChar
)(0xffff));
145 noIDBlock
+= ((UChar
)(0xffff));
146 int32_t pos
= aliasesOrRules
.indexOf(noIDBlock
);
149 pos
= aliasesOrRules
.indexOf(noIDBlock
, pos
+ 1);
152 UVector
transliterators(ec
);
153 UnicodeString idBlock
;
154 int32_t blockSeparatorPos
= aliasesOrRules
.indexOf((UChar
)(0xffff));
155 while (blockSeparatorPos
>= 0) {
156 aliasesOrRules
.extract(0, blockSeparatorPos
, idBlock
);
157 aliasesOrRules
.remove(0, blockSeparatorPos
+ 1);
158 if (!idBlock
.isEmpty())
159 transliterators
.addElement(Transliterator::createInstance(idBlock
, UTRANS_FORWARD
, pe
, ec
), ec
);
160 if (!transes
->isEmpty())
161 transliterators
.addElement(transes
->orphanElementAt(0), ec
);
162 blockSeparatorPos
= aliasesOrRules
.indexOf((UChar
)(0xffff));
164 if (!aliasesOrRules
.isEmpty())
165 transliterators
.addElement(Transliterator::createInstance(aliasesOrRules
, UTRANS_FORWARD
, pe
, ec
), ec
);
166 while (!transes
->isEmpty())
167 transliterators
.addElement(transes
->orphanElementAt(0), ec
);
170 t
= new CompoundTransliterator(ID
, transliterators
,
171 (compoundFilter
? (UnicodeSet
*)(compoundFilter
->clone()) : 0),
172 anonymousRBTs
, pe
, ec
);
174 ec
= U_MEMORY_ALLOCATION_ERROR
;
178 for (int32_t i
= 0; i
< transliterators
.size(); i
++)
179 delete (Transliterator
*)(transliterators
.elementAt(i
));
184 U_ASSERT(FALSE
); // don't call create() if isRuleBased() returns TRUE!
190 UBool
TransliteratorAlias::isRuleBased() const {
191 return type
== RULES
;
194 void TransliteratorAlias::parse(TransliteratorParser
& parser
,
195 UParseError
& pe
, UErrorCode
& ec
) const {
196 U_ASSERT(type
== RULES
);
201 parser
.parse(aliasesOrRules
, direction
, pe
, ec
);
204 //----------------------------------------------------------------------
205 // class TransliteratorSpec
206 //----------------------------------------------------------------------
209 * A TransliteratorSpec is a string specifying either a source or a target. In more
210 * general terms, it may also specify a variant, but we only use the
211 * Spec class for sources and targets.
213 * A Spec may be a locale or a script. If it is a locale, it has a
214 * fallback chain that goes xx_YY_ZZZ -> xx_YY -> xx -> ssss, where
215 * ssss is the script mapping of xx_YY_ZZZ. The Spec API methods
216 * hasFallback(), next(), and reset() iterate over this fallback
219 * The Spec class canonicalizes itself, so the locale is put into
220 * canonical form, or the script is transformed from an abbreviation
223 class TransliteratorSpec
: public UMemory
{
225 TransliteratorSpec(const UnicodeString
& spec
);
226 ~TransliteratorSpec();
228 const UnicodeString
& get() const;
229 UBool
hasFallback() const;
230 const UnicodeString
& next();
233 UBool
isLocale() const;
234 ResourceBundle
& getBundle() const;
236 operator const UnicodeString
&() const { return get(); }
237 const UnicodeString
& getTop() const { return top
; }
244 UnicodeString nextSpec
;
245 UnicodeString scriptName
;
246 UBool isSpecLocale
; // TRUE if spec is a locale
247 UBool isNextLocale
; // TRUE if nextSpec is a locale
250 TransliteratorSpec(const TransliteratorSpec
&other
); // forbid copying of this class
251 TransliteratorSpec
&operator=(const TransliteratorSpec
&other
); // forbid copying of this class
254 TransliteratorSpec::TransliteratorSpec(const UnicodeString
& theSpec
)
258 UErrorCode status
= U_ZERO_ERROR
;
260 LocaleUtility::initLocaleFromName(theSpec
, topLoc
);
261 if (!topLoc
.isBogus()) {
262 res
= new ResourceBundle(U_ICUDATA_TRANSLIT
, topLoc
, status
);
267 if (U_FAILURE(status
) || status
== U_USING_DEFAULT_WARNING
) {
273 // Canonicalize script name -or- do locale->script mapping
274 status
= U_ZERO_ERROR
;
275 static const int32_t capacity
= 10;
276 UScriptCode script
[capacity
]={USCRIPT_INVALID_CODE
};
277 int32_t num
= uscript_getCode(CharString().appendInvariantChars(theSpec
, status
).data(),
278 script
, capacity
, &status
);
279 if (num
> 0 && script
[0] != USCRIPT_INVALID_CODE
) {
280 scriptName
= UnicodeString(uscript_getName(script
[0]), -1, US_INV
);
285 // Canonicalize locale name
286 UnicodeString locStr
;
287 LocaleUtility::initNameFromLocale(topLoc
, locStr
);
288 if (!locStr
.isBogus()) {
291 } else if (scriptName
.length() != 0) {
292 // We are a script; use canonical name
296 // assert(spec != top);
300 TransliteratorSpec::~TransliteratorSpec() {
304 UBool
TransliteratorSpec::hasFallback() const {
305 return nextSpec
.length() != 0;
308 void TransliteratorSpec::reset() {
311 isSpecLocale
= (res
!= 0);
316 void TransliteratorSpec::setupNext() {
317 isNextLocale
= FALSE
;
320 int32_t i
= nextSpec
.lastIndexOf(LOCALE_SEP
);
321 // If i == 0 then we have _FOO, so we fall through
322 // to the scriptName.
324 nextSpec
.truncate(i
);
327 nextSpec
= scriptName
; // scriptName may be empty
330 // spec is a script, so we are at the end
331 nextSpec
.truncate(0);
336 // for(const UnicodeString& s(spec.get());
337 // spec.hasFallback(); s(spec.next())) { ...
339 const UnicodeString
& TransliteratorSpec::next() {
341 isSpecLocale
= isNextLocale
;
346 const UnicodeString
& TransliteratorSpec::get() const {
350 UBool
TransliteratorSpec::isLocale() const {
354 ResourceBundle
& TransliteratorSpec::getBundle() const {
358 //----------------------------------------------------------------------
362 // Vector of Entry pointers currently in use
363 static UVector
* DEBUG_entries
= NULL
;
365 static void DEBUG_setup() {
366 if (DEBUG_entries
== NULL
) {
367 UErrorCode ec
= U_ZERO_ERROR
;
368 DEBUG_entries
= new UVector(ec
);
372 // Caller must call DEBUG_setup first. Return index of given Entry,
373 // if it is in use (not deleted yet), or -1 if not found.
374 static int DEBUG_findEntry(TransliteratorEntry
* e
) {
375 for (int i
=0; i
<DEBUG_entries
->size(); ++i
) {
376 if (e
== (TransliteratorEntry
*) DEBUG_entries
->elementAt(i
)) {
383 // Track object creation
384 static void DEBUG_newEntry(TransliteratorEntry
* e
) {
386 if (DEBUG_findEntry(e
) >= 0) {
387 // This should really never happen unless the heap is broken
388 printf("ERROR DEBUG_newEntry duplicate new pointer %08X\n", e
);
391 UErrorCode ec
= U_ZERO_ERROR
;
392 DEBUG_entries
->addElement(e
, ec
);
395 // Track object deletion
396 static void DEBUG_delEntry(TransliteratorEntry
* e
) {
398 int i
= DEBUG_findEntry(e
);
400 printf("ERROR DEBUG_delEntry possible double deletion %08X\n", e
);
403 DEBUG_entries
->removeElementAt(i
);
406 // Track object usage
407 static void DEBUG_useEntry(TransliteratorEntry
* e
) {
408 if (e
== NULL
) return;
410 int i
= DEBUG_findEntry(e
);
412 printf("ERROR DEBUG_useEntry possible dangling pointer %08X\n", e
);
417 // If we're not debugging then make these macros into NOPs
418 #define DEBUG_newEntry(x)
419 #define DEBUG_delEntry(x)
420 #define DEBUG_useEntry(x)
423 //----------------------------------------------------------------------
425 //----------------------------------------------------------------------
428 * The Entry object stores objects of different types and
429 * singleton objects as placeholders for rule-based transliterators to
430 * be built as needed. Instances of this struct can be placeholders,
431 * can represent prototype transliterators to be cloned, or can
432 * represent TransliteratorData objects. We don't support storing
433 * classes in the registry because we don't have the rtti infrastructure
434 * for it. We could easily add this if there is a need for it in the
437 class TransliteratorEntry
: public UMemory
{
448 NONE
// Only used for uninitialized entries
450 // NOTE: stringArg cannot go inside the union because
451 // it has a copy constructor
452 UnicodeString stringArg
; // For RULES_*, ALIAS, COMPOUND_RBT
453 int32_t intArg
; // For COMPOUND_RBT, LOCALE_RULES
454 UnicodeSet
* compoundFilter
; // For COMPOUND_RBT
456 Transliterator
* prototype
; // For PROTOTYPE
457 TransliterationRuleData
* data
; // For RBT_DATA
458 UVector
* dataVector
; // For COMPOUND_RBT
460 Transliterator::Factory function
;
461 Transliterator::Token context
;
462 } factory
; // For FACTORY
464 TransliteratorEntry();
465 ~TransliteratorEntry();
466 void adoptPrototype(Transliterator
* adopted
);
467 void setFactory(Transliterator::Factory factory
,
468 Transliterator::Token context
);
472 TransliteratorEntry(const TransliteratorEntry
&other
); // forbid copying of this class
473 TransliteratorEntry
&operator=(const TransliteratorEntry
&other
); // forbid copying of this class
476 TransliteratorEntry::TransliteratorEntry() {
478 compoundFilter
= NULL
;
480 DEBUG_newEntry(this);
483 TransliteratorEntry::~TransliteratorEntry() {
484 DEBUG_delEntry(this);
485 if (entryType
== PROTOTYPE
) {
487 } else if (entryType
== RBT_DATA
) {
488 // The data object is shared between instances of RBT. The
489 // entry object owns it. It should only be deleted when the
490 // transliterator component is being cleaned up. Doing so
491 // invalidates any RBTs that the user has instantiated.
493 } else if (entryType
== COMPOUND_RBT
) {
494 while (u
.dataVector
!= NULL
&& !u
.dataVector
->isEmpty())
495 delete (TransliterationRuleData
*)u
.dataVector
->orphanElementAt(0);
498 delete compoundFilter
;
501 void TransliteratorEntry::adoptPrototype(Transliterator
* adopted
) {
502 if (entryType
== PROTOTYPE
) {
505 entryType
= PROTOTYPE
;
506 u
.prototype
= adopted
;
509 void TransliteratorEntry::setFactory(Transliterator::Factory factory
,
510 Transliterator::Token context
) {
511 if (entryType
== PROTOTYPE
) {
515 u
.factory
.function
= factory
;
516 u
.factory
.context
= context
;
519 // UObjectDeleter for Hashtable::setValueDeleter
521 static void U_CALLCONV
522 deleteEntry(void* obj
) {
523 delete (TransliteratorEntry
*) obj
;
527 //----------------------------------------------------------------------
528 // class TransliteratorRegistry: Basic public API
529 //----------------------------------------------------------------------
531 TransliteratorRegistry::TransliteratorRegistry(UErrorCode
& status
) :
532 registry(TRUE
, status
),
533 specDAG(TRUE
, SPECDAG_INIT_SIZE
, status
),
534 variantList(VARIANT_LIST_INIT_SIZE
, status
),
535 availableIDs(AVAILABLE_IDS_INIT_SIZE
, status
)
537 registry
.setValueDeleter(deleteEntry
);
538 variantList
.setDeleter(uprv_deleteUObject
);
539 variantList
.setComparer(uhash_compareCaselessUnicodeString
);
540 UnicodeString
*emptyString
= new UnicodeString();
541 if (emptyString
!= NULL
) {
542 variantList
.addElement(emptyString
, status
);
544 availableIDs
.setDeleter(uprv_deleteUObject
);
545 availableIDs
.setComparer(uhash_compareCaselessUnicodeString
);
546 specDAG
.setValueDeleter(uhash_deleteHashtable
);
549 TransliteratorRegistry::~TransliteratorRegistry() {
550 // Through the magic of C++, everything cleans itself up
553 Transliterator
* TransliteratorRegistry::get(const UnicodeString
& ID
,
554 TransliteratorAlias
*& aliasReturn
,
555 UErrorCode
& status
) {
556 U_ASSERT(aliasReturn
== NULL
);
557 TransliteratorEntry
*entry
= find(ID
);
558 return (entry
== 0) ? 0
559 : instantiateEntry(ID
, entry
, aliasReturn
, status
);
562 Transliterator
* TransliteratorRegistry::reget(const UnicodeString
& ID
,
563 TransliteratorParser
& parser
,
564 TransliteratorAlias
*& aliasReturn
,
565 UErrorCode
& status
) {
566 U_ASSERT(aliasReturn
== NULL
);
567 TransliteratorEntry
*entry
= find(ID
);
570 // We get to this point if there are two threads, one of which
571 // is instantiating an ID, and another of which is removing
572 // the same ID from the registry, and the timing is just right.
576 // The usage model for the caller is that they will first call
577 // reg->get() inside the mutex, they'll get back an alias, they call
578 // alias->isRuleBased(), and if they get TRUE, they call alias->parse()
579 // outside the mutex, then reg->reget() inside the mutex again. A real
580 // mess, but it gets things working for ICU 3.0. [alan].
582 // Note: It's possible that in between the caller calling
583 // alias->parse() and reg->reget(), that another thread will have
584 // called reg->reget(), and the entry will already have been fixed up.
585 // We have to detect this so we don't stomp over existing entry
586 // data members and potentially leak memory (u.data and compoundFilter).
588 if (entry
->entryType
== TransliteratorEntry::RULES_FORWARD
||
589 entry
->entryType
== TransliteratorEntry::RULES_REVERSE
||
590 entry
->entryType
== TransliteratorEntry::LOCALE_RULES
) {
592 if (parser
.idBlockVector
.isEmpty() && parser
.dataVector
.isEmpty()) {
594 entry
->entryType
= TransliteratorEntry::ALIAS
;
595 entry
->stringArg
= UNICODE_STRING_SIMPLE("Any-NULL");
597 else if (parser
.idBlockVector
.isEmpty() && parser
.dataVector
.size() == 1) {
598 entry
->u
.data
= (TransliterationRuleData
*)parser
.dataVector
.orphanElementAt(0);
599 entry
->entryType
= TransliteratorEntry::RBT_DATA
;
601 else if (parser
.idBlockVector
.size() == 1 && parser
.dataVector
.isEmpty()) {
602 entry
->stringArg
= *(UnicodeString
*)(parser
.idBlockVector
.elementAt(0));
603 entry
->compoundFilter
= parser
.orphanCompoundFilter();
604 entry
->entryType
= TransliteratorEntry::ALIAS
;
607 entry
->entryType
= TransliteratorEntry::COMPOUND_RBT
;
608 entry
->compoundFilter
= parser
.orphanCompoundFilter();
609 entry
->u
.dataVector
= new UVector(status
);
610 entry
->stringArg
.remove();
612 int32_t limit
= parser
.idBlockVector
.size();
613 if (parser
.dataVector
.size() > limit
)
614 limit
= parser
.dataVector
.size();
616 for (int32_t i
= 0; i
< limit
; i
++) {
617 if (i
< parser
.idBlockVector
.size()) {
618 UnicodeString
* idBlock
= (UnicodeString
*)parser
.idBlockVector
.elementAt(i
);
619 if (!idBlock
->isEmpty())
620 entry
->stringArg
+= *idBlock
;
622 if (!parser
.dataVector
.isEmpty()) {
623 TransliterationRuleData
* data
= (TransliterationRuleData
*)parser
.dataVector
.orphanElementAt(0);
624 entry
->u
.dataVector
->addElement(data
, status
);
625 entry
->stringArg
+= (UChar
)0xffff; // use U+FFFF to mark position of RBTs in ID block
632 instantiateEntry(ID
, entry
, aliasReturn
, status
);
636 void TransliteratorRegistry::put(Transliterator
* adoptedProto
,
640 TransliteratorEntry
*entry
= new TransliteratorEntry();
642 ec
= U_MEMORY_ALLOCATION_ERROR
;
645 entry
->adoptPrototype(adoptedProto
);
646 registerEntry(adoptedProto
->getID(), entry
, visible
);
649 void TransliteratorRegistry::put(const UnicodeString
& ID
,
650 Transliterator::Factory factory
,
651 Transliterator::Token context
,
654 TransliteratorEntry
*entry
= new TransliteratorEntry();
656 ec
= U_MEMORY_ALLOCATION_ERROR
;
659 entry
->setFactory(factory
, context
);
660 registerEntry(ID
, entry
, visible
);
663 void TransliteratorRegistry::put(const UnicodeString
& ID
,
664 const UnicodeString
& resourceName
,
666 UBool readonlyResourceAlias
,
669 TransliteratorEntry
*entry
= new TransliteratorEntry();
671 ec
= U_MEMORY_ALLOCATION_ERROR
;
674 entry
->entryType
= (dir
== UTRANS_FORWARD
) ? TransliteratorEntry::RULES_FORWARD
675 : TransliteratorEntry::RULES_REVERSE
;
676 if (readonlyResourceAlias
) {
677 entry
->stringArg
.setTo(TRUE
, resourceName
.getBuffer(), -1);
680 entry
->stringArg
= resourceName
;
682 registerEntry(ID
, entry
, visible
);
685 void TransliteratorRegistry::put(const UnicodeString
& ID
,
686 const UnicodeString
& alias
,
687 UBool readonlyAliasAlias
,
689 UErrorCode
& /*ec*/) {
690 TransliteratorEntry
*entry
= new TransliteratorEntry();
691 // Null pointer check
693 entry
->entryType
= TransliteratorEntry::ALIAS
;
694 if (readonlyAliasAlias
) {
695 entry
->stringArg
.setTo(TRUE
, alias
.getBuffer(), -1);
698 entry
->stringArg
= alias
;
700 registerEntry(ID
, entry
, visible
);
704 void TransliteratorRegistry::remove(const UnicodeString
& ID
) {
705 UnicodeString source
, target
, variant
;
707 TransliteratorIDParser::IDtoSTV(ID
, source
, target
, variant
, sawSource
);
708 // Only need to do this if ID.indexOf('-') < 0
710 TransliteratorIDParser::STVtoID(source
, target
, variant
, id
);
712 removeSTV(source
, target
, variant
);
713 availableIDs
.removeElement((void*) &id
);
716 //----------------------------------------------------------------------
717 // class TransliteratorRegistry: Public ID and spec management
718 //----------------------------------------------------------------------
721 * == OBSOLETE - remove in ICU 3.4 ==
722 * Return the number of IDs currently registered with the system.
723 * To retrieve the actual IDs, call getAvailableID(i) with
724 * i from 0 to countAvailableIDs() - 1.
726 int32_t TransliteratorRegistry::countAvailableIDs(void) const {
727 return availableIDs
.size();
731 * == OBSOLETE - remove in ICU 3.4 ==
732 * Return the index-th available ID. index must be between 0
733 * and countAvailableIDs() - 1, inclusive. If index is out of
734 * range, the result of getAvailableID(0) is returned.
736 const UnicodeString
& TransliteratorRegistry::getAvailableID(int32_t index
) const {
737 if (index
< 0 || index
>= availableIDs
.size()) {
740 return *(const UnicodeString
*) availableIDs
[index
];
743 StringEnumeration
* TransliteratorRegistry::getAvailableIDs() const {
744 return new Enumeration(*this);
747 int32_t TransliteratorRegistry::countAvailableSources(void) const {
748 return specDAG
.count();
751 UnicodeString
& TransliteratorRegistry::getAvailableSource(int32_t index
,
752 UnicodeString
& result
) const {
753 int32_t pos
= UHASH_FIRST
;
754 const UHashElement
*e
= 0;
755 while (index
-- >= 0) {
756 e
= specDAG
.nextElement(pos
);
764 result
= *(UnicodeString
*) e
->key
.pointer
;
769 int32_t TransliteratorRegistry::countAvailableTargets(const UnicodeString
& source
) const {
770 Hashtable
*targets
= (Hashtable
*) specDAG
.get(source
);
771 return (targets
== 0) ? 0 : targets
->count();
774 UnicodeString
& TransliteratorRegistry::getAvailableTarget(int32_t index
,
775 const UnicodeString
& source
,
776 UnicodeString
& result
) const {
777 Hashtable
*targets
= (Hashtable
*) specDAG
.get(source
);
779 result
.truncate(0); // invalid source
782 int32_t pos
= UHASH_FIRST
;
783 const UHashElement
*e
= 0;
784 while (index
-- >= 0) {
785 e
= targets
->nextElement(pos
);
791 result
.truncate(0); // invalid index
793 result
= *(UnicodeString
*) e
->key
.pointer
;
798 int32_t TransliteratorRegistry::countAvailableVariants(const UnicodeString
& source
,
799 const UnicodeString
& target
) const {
800 Hashtable
*targets
= (Hashtable
*) specDAG
.get(source
);
804 int32_t varMask
= targets
->geti(target
);
805 int32_t varCount
= 0;
806 while (varMask
> 0) {
815 UnicodeString
& TransliteratorRegistry::getAvailableVariant(int32_t index
,
816 const UnicodeString
& source
,
817 const UnicodeString
& target
,
818 UnicodeString
& result
) const {
819 Hashtable
*targets
= (Hashtable
*) specDAG
.get(source
);
821 result
.truncate(0); // invalid source
824 int32_t varMask
= targets
->geti(target
);
825 int32_t varCount
= 0;
826 int32_t varListIndex
= 0;
827 while (varMask
> 0) {
829 if (varCount
== index
) {
830 UnicodeString
*v
= (UnicodeString
*) variantList
.elementAt(varListIndex
);
842 result
.truncate(0); // invalid target or index
846 //----------------------------------------------------------------------
847 // class TransliteratorRegistry::Enumeration
848 //----------------------------------------------------------------------
850 TransliteratorRegistry::Enumeration::Enumeration(const TransliteratorRegistry
& _reg
) :
851 index(0), reg(_reg
) {
854 TransliteratorRegistry::Enumeration::~Enumeration() {
857 int32_t TransliteratorRegistry::Enumeration::count(UErrorCode
& /*status*/) const {
858 return reg
.availableIDs
.size();
861 const UnicodeString
* TransliteratorRegistry::Enumeration::snext(UErrorCode
& status
) {
862 // This is sloppy but safe -- if we get out of sync with the underlying
863 // registry, we will still return legal strings, but they might not
864 // correspond to the snapshot at construction time. So there could be
865 // duplicate IDs or omitted IDs if insertions or deletions occur in one
866 // thread while another is iterating. To be more rigorous, add a timestamp,
867 // which is incremented with any modification, and validate this iterator
868 // against the timestamp at construction time. This probably isn't worth
869 // doing as long as there is some possibility of removing this code in favor
870 // of some new code based on Doug's service framework.
871 if (U_FAILURE(status
)) {
874 int32_t n
= reg
.availableIDs
.size();
876 status
= U_ENUM_OUT_OF_SYNC_ERROR
;
878 // index == n is okay -- this means we've reached the end
880 // Copy the string! This avoids lifetime problems.
881 unistr
= *(const UnicodeString
*)reg
.availableIDs
[index
++];
888 void TransliteratorRegistry::Enumeration::reset(UErrorCode
& /*status*/) {
892 UOBJECT_DEFINE_RTTI_IMPLEMENTATION(TransliteratorRegistry::Enumeration
)
894 //----------------------------------------------------------------------
895 // class TransliteratorRegistry: internal
896 //----------------------------------------------------------------------
899 * Convenience method. Calls 6-arg registerEntry().
901 void TransliteratorRegistry::registerEntry(const UnicodeString
& source
,
902 const UnicodeString
& target
,
903 const UnicodeString
& variant
,
904 TransliteratorEntry
* adopted
,
907 UnicodeString
s(source
);
908 if (s
.length() == 0) {
909 s
.setTo(TRUE
, ANY
, 3);
911 TransliteratorIDParser::STVtoID(source
, target
, variant
, ID
);
912 registerEntry(ID
, s
, target
, variant
, adopted
, visible
);
916 * Convenience method. Calls 6-arg registerEntry().
918 void TransliteratorRegistry::registerEntry(const UnicodeString
& ID
,
919 TransliteratorEntry
* adopted
,
921 UnicodeString source
, target
, variant
;
923 TransliteratorIDParser::IDtoSTV(ID
, source
, target
, variant
, sawSource
);
924 // Only need to do this if ID.indexOf('-') < 0
926 TransliteratorIDParser::STVtoID(source
, target
, variant
, id
);
927 registerEntry(id
, source
, target
, variant
, adopted
, visible
);
931 * Register an entry object (adopted) with the given ID, source,
932 * target, and variant strings.
934 void TransliteratorRegistry::registerEntry(const UnicodeString
& ID
,
935 const UnicodeString
& source
,
936 const UnicodeString
& target
,
937 const UnicodeString
& variant
,
938 TransliteratorEntry
* adopted
,
940 UErrorCode status
= U_ZERO_ERROR
;
941 registry
.put(ID
, adopted
, status
);
943 registerSTV(source
, target
, variant
);
944 if (!availableIDs
.contains((void*) &ID
)) {
945 UnicodeString
*newID
= (UnicodeString
*)ID
.clone();
946 // Check to make sure newID was created.
948 // NUL-terminate the ID string
949 newID
->getTerminatedBuffer();
950 availableIDs
.addElement(newID
, status
);
954 removeSTV(source
, target
, variant
);
955 availableIDs
.removeElement((void*) &ID
);
960 * Register a source-target/variant in the specDAG. Variant may be
961 * empty, but source and target must not be.
963 void TransliteratorRegistry::registerSTV(const UnicodeString
& source
,
964 const UnicodeString
& target
,
965 const UnicodeString
& variant
) {
966 // assert(source.length() > 0);
967 // assert(target.length() > 0);
968 UErrorCode status
= U_ZERO_ERROR
;
969 Hashtable
*targets
= (Hashtable
*) specDAG
.get(source
);
972 if (source
.compare(ANY
,3) == 0) {
973 size
= ANY_TARGETS_INIT_SIZE
;
974 } else if (source
.compare(LAT
,3) == 0) {
975 size
= LAT_TARGETS_INIT_SIZE
;
977 targets
= new Hashtable(TRUE
, size
, status
);
978 if (U_FAILURE(status
) || targets
== NULL
) {
981 specDAG
.put(source
, targets
, status
);
983 int32_t variantListIndex
= variantList
.indexOf((void*) &variant
, 0);
984 if (variantListIndex
< 0) {
985 if (variantList
.size() >= VARIANT_LIST_MAX_SIZE
) {
986 // can't handle any more variants
989 UnicodeString
*variantEntry
= new UnicodeString(variant
);
990 if (variantEntry
!= NULL
) {
991 variantList
.addElement(variantEntry
, status
);
992 if (U_SUCCESS(status
)) {
993 variantListIndex
= variantList
.size() - 1;
996 if (variantListIndex
< 0) {
1000 int32_t addMask
= 1 << variantListIndex
;
1001 int32_t varMask
= targets
->geti(target
);
1002 targets
->puti(target
, varMask
| addMask
, status
);
1006 * Remove a source-target/variant from the specDAG.
1008 void TransliteratorRegistry::removeSTV(const UnicodeString
& source
,
1009 const UnicodeString
& target
,
1010 const UnicodeString
& variant
) {
1011 // assert(source.length() > 0);
1012 // assert(target.length() > 0);
1013 UErrorCode status
= U_ZERO_ERROR
;
1014 Hashtable
*targets
= (Hashtable
*) specDAG
.get(source
);
1015 if (targets
== NULL
) {
1016 return; // should never happen for valid s-t/v
1018 int32_t varMask
= targets
->geti(target
);
1020 return; // should never happen for valid s-t/v
1022 int32_t variantListIndex
= variantList
.indexOf((void*) &variant
, 0);
1023 if (variantListIndex
< 0) {
1024 return; // should never happen for valid s-t/v
1026 int32_t remMask
= 1 << variantListIndex
;
1027 varMask
&= (~remMask
);
1029 targets
->puti(target
, varMask
, status
);
1031 targets
->remove(target
); // should delete variants
1032 if (targets
->count() == 0) {
1033 specDAG
.remove(source
); // should delete targetss
1039 * Attempt to find a source-target/variant in the dynamic registry
1040 * store. Return 0 on failure.
1042 * Caller does NOT own returned object.
1044 TransliteratorEntry
* TransliteratorRegistry::findInDynamicStore(const TransliteratorSpec
& src
,
1045 const TransliteratorSpec
& trg
,
1046 const UnicodeString
& variant
) const {
1048 TransliteratorIDParser::STVtoID(src
, trg
, variant
, ID
);
1049 TransliteratorEntry
*e
= (TransliteratorEntry
*) registry
.get(ID
);
1055 * Attempt to find a source-target/variant in the static locale
1056 * resource store. Do not perform fallback. Return 0 on failure.
1058 * On success, create a new entry object, register it in the dynamic
1059 * store, and return a pointer to it, but do not make it public --
1060 * just because someone requested something, we do not expand the
1061 * available ID list (or spec DAG).
1063 * Caller does NOT own returned object.
1065 TransliteratorEntry
* TransliteratorRegistry::findInStaticStore(const TransliteratorSpec
& src
,
1066 const TransliteratorSpec
& trg
,
1067 const UnicodeString
& variant
) {
1068 TransliteratorEntry
* entry
= 0;
1069 if (src
.isLocale()) {
1070 entry
= findInBundle(src
, trg
, variant
, UTRANS_FORWARD
);
1071 } else if (trg
.isLocale()) {
1072 entry
= findInBundle(trg
, src
, variant
, UTRANS_REVERSE
);
1075 // If we found an entry, store it in the Hashtable for next
1078 registerEntry(src
.getTop(), trg
.getTop(), variant
, entry
, FALSE
);
1084 // As of 2.0, resource bundle keys cannot contain '_'
1085 static const UChar TRANSLITERATE_TO
[] = {84,114,97,110,115,108,105,116,101,114,97,116,101,84,111,0}; // "TransliterateTo"
1087 static const UChar TRANSLITERATE_FROM
[] = {84,114,97,110,115,108,105,116,101,114,97,116,101,70,114,111,109,0}; // "TransliterateFrom"
1089 static const UChar TRANSLITERATE
[] = {84,114,97,110,115,108,105,116,101,114,97,116,101,0}; // "Transliterate"
1092 * Attempt to find an entry in a single resource bundle. This is
1093 * a one-sided lookup. findInStaticStore() performs up to two such
1094 * lookups, one for the source, and one for the target.
1096 * Do not perform fallback. Return 0 on failure.
1098 * On success, create a new Entry object, populate it, and return it.
1099 * The caller owns the returned object.
1101 TransliteratorEntry
* TransliteratorRegistry::findInBundle(const TransliteratorSpec
& specToOpen
,
1102 const TransliteratorSpec
& specToFind
,
1103 const UnicodeString
& variant
,
1104 UTransDirection direction
)
1107 UnicodeString resStr
;
1110 for (pass
=0; pass
<2; ++pass
) {
1112 // First try either TransliteratorTo_xxx or
1113 // TransliterateFrom_xxx, then try the bidirectional
1114 // Transliterate_xxx. This precedence order is arbitrary
1115 // but must be consistent and documented.
1117 utag
.append(direction
== UTRANS_FORWARD
?
1118 TRANSLITERATE_TO
: TRANSLITERATE_FROM
, -1);
1120 utag
.append(TRANSLITERATE
, -1);
1122 UnicodeString
s(specToFind
.get());
1123 utag
.append(s
.toUpper(""));
1124 UErrorCode status
= U_ZERO_ERROR
;
1125 ResourceBundle
subres(specToOpen
.getBundle().get(
1126 CharString().appendInvariantChars(utag
, status
).data(), status
));
1127 if (U_FAILURE(status
) || status
== U_USING_DEFAULT_WARNING
) {
1132 if (specToOpen
.get() != LocaleUtility::initNameFromLocale(subres
.getLocale(), s
)) {
1136 if (variant
.length() != 0) {
1137 status
= U_ZERO_ERROR
;
1138 resStr
= subres
.getStringEx(
1139 CharString().appendInvariantChars(variant
, status
).data(), status
);
1140 if (U_SUCCESS(status
)) {
1141 // Exit loop successfully
1145 // Variant is empty, which means match the first variant listed.
1146 status
= U_ZERO_ERROR
;
1147 resStr
= subres
.getStringEx(1, status
);
1148 if (U_SUCCESS(status
)) {
1149 // Exit loop successfully
1160 // We have succeeded in loading a string from the locale
1161 // resources. Create a new registry entry to hold it and return it.
1162 TransliteratorEntry
*entry
= new TransliteratorEntry();
1164 // The direction is always forward for the
1165 // TransliterateTo_xxx and TransliterateFrom_xxx
1166 // items; those are unidirectional forward rules.
1167 // For the bidirectional Transliterate_xxx items,
1168 // the direction is the value passed in to this
1170 int32_t dir
= (pass
== 0) ? UTRANS_FORWARD
: direction
;
1171 entry
->entryType
= TransliteratorEntry::LOCALE_RULES
;
1172 entry
->stringArg
= resStr
;
1173 entry
->intArg
= dir
;
1180 * Convenience method. Calls 3-arg find().
1182 TransliteratorEntry
* TransliteratorRegistry::find(const UnicodeString
& ID
) {
1183 UnicodeString source
, target
, variant
;
1185 TransliteratorIDParser::IDtoSTV(ID
, source
, target
, variant
, sawSource
);
1186 return find(source
, target
, variant
);
1190 * Top-level find method. Attempt to find a source-target/variant in
1191 * either the dynamic or the static (locale resource) store. Perform
1194 * Lookup sequence for ss_SS_SSS-tt_TT_TTT/v:
1196 * ss_SS_SSS-tt_TT_TTT/v -- in hashtable
1197 * ss_SS_SSS-tt_TT_TTT/v -- in ss_SS_SSS (no fallback)
1199 * repeat with t = tt_TT_TTT, tt_TT, tt, and tscript
1206 * Here * matches the first variant listed.
1208 * Caller does NOT own returned object. Return 0 on failure.
1210 TransliteratorEntry
* TransliteratorRegistry::find(UnicodeString
& source
,
1211 UnicodeString
& target
,
1212 UnicodeString
& variant
) {
1214 TransliteratorSpec
src(source
);
1215 TransliteratorSpec
trg(target
);
1216 TransliteratorEntry
* entry
;
1218 // Seek exact match in hashtable. Temporary fix for ICU 4.6.
1219 // TODO: The general logic for finding a matching transliterator needs to be reviewed.
1222 TransliteratorIDParser::STVtoID(source
, target
, variant
, ID
);
1223 entry
= (TransliteratorEntry
*) registry
.get(ID
);
1226 // std::cout << ID.toUTF8String(ss) << std::endl;
1230 if (variant
.length() != 0) {
1232 // Seek exact match in hashtable
1233 entry
= findInDynamicStore(src
, trg
, variant
);
1238 // Seek exact match in locale resources
1239 entry
= findInStaticStore(src
, trg
, variant
);
1248 // Seek match in hashtable
1249 entry
= findInDynamicStore(src
, trg
, NO_VARIANT
);
1254 // Seek match in locale resources
1255 entry
= findInStaticStore(src
, trg
, NO_VARIANT
);
1259 if (!src
.hasFallback()) {
1264 if (!trg
.hasFallback()) {
1274 * Given an Entry object, instantiate it. Caller owns result. Return
1277 * Return a non-empty aliasReturn value if the ID points to an alias.
1278 * We cannot instantiate it ourselves because the alias may contain
1279 * filters or compounds, which we do not understand. Caller should
1280 * make aliasReturn empty before calling.
1282 * The entry object is assumed to reside in the dynamic store. It may be
1285 Transliterator
* TransliteratorRegistry::instantiateEntry(const UnicodeString
& ID
,
1286 TransliteratorEntry
*entry
,
1287 TransliteratorAlias
* &aliasReturn
,
1288 UErrorCode
& status
) {
1289 Transliterator
*t
= 0;
1290 U_ASSERT(aliasReturn
== 0);
1292 switch (entry
->entryType
) {
1293 case TransliteratorEntry::RBT_DATA
:
1294 t
= new RuleBasedTransliterator(ID
, entry
->u
.data
);
1296 status
= U_MEMORY_ALLOCATION_ERROR
;
1299 case TransliteratorEntry::PROTOTYPE
:
1300 t
= entry
->u
.prototype
->clone();
1302 status
= U_MEMORY_ALLOCATION_ERROR
;
1305 case TransliteratorEntry::ALIAS
:
1306 aliasReturn
= new TransliteratorAlias(entry
->stringArg
, entry
->compoundFilter
);
1307 if (aliasReturn
== 0) {
1308 status
= U_MEMORY_ALLOCATION_ERROR
;
1311 case TransliteratorEntry::FACTORY
:
1312 t
= entry
->u
.factory
.function(ID
, entry
->u
.factory
.context
);
1314 status
= U_MEMORY_ALLOCATION_ERROR
;
1317 case TransliteratorEntry::COMPOUND_RBT
:
1319 UVector
* rbts
= new UVector(entry
->u
.dataVector
->size(), status
);
1320 // Check for null pointer
1322 status
= U_MEMORY_ALLOCATION_ERROR
;
1325 int32_t passNumber
= 1;
1326 for (int32_t i
= 0; U_SUCCESS(status
) && i
< entry
->u
.dataVector
->size(); i
++) {
1327 // TODO: Should passNumber be turned into a decimal-string representation (1 -> "1")?
1328 Transliterator
* t
= new RuleBasedTransliterator(UnicodeString(CompoundTransliterator::PASS_STRING
) + UnicodeString(passNumber
++),
1329 (TransliterationRuleData
*)(entry
->u
.dataVector
->elementAt(i
)), FALSE
);
1331 status
= U_MEMORY_ALLOCATION_ERROR
;
1333 rbts
->addElement(t
, status
);
1335 if (U_FAILURE(status
)) {
1339 aliasReturn
= new TransliteratorAlias(ID
, entry
->stringArg
, rbts
, entry
->compoundFilter
);
1341 if (aliasReturn
== 0) {
1342 status
= U_MEMORY_ALLOCATION_ERROR
;
1345 case TransliteratorEntry::LOCALE_RULES
:
1346 aliasReturn
= new TransliteratorAlias(ID
, entry
->stringArg
,
1347 (UTransDirection
) entry
->intArg
);
1348 if (aliasReturn
== 0) {
1349 status
= U_MEMORY_ALLOCATION_ERROR
;
1352 case TransliteratorEntry::RULES_FORWARD
:
1353 case TransliteratorEntry::RULES_REVERSE
:
1354 // Process the rule data into a TransliteratorRuleData object,
1355 // and possibly also into an ::id header and/or footer. Then
1356 // we modify the registry with the parsed data and retry.
1358 TransliteratorParser
parser(status
);
1360 // We use the file name, taken from another resource bundle
1361 // 2-d array at static init time, as a locale language. We're
1362 // just using the locale mechanism to map through to a file
1363 // name; this in no way represents an actual locale.
1364 //CharString ch(entry->stringArg);
1365 //UResourceBundle *bundle = ures_openDirect(0, ch, &status);
1366 UnicodeString rules
= entry
->stringArg
;
1367 //ures_close(bundle);
1369 //if (U_FAILURE(status)) {
1370 // We have a failure of some kind. Remove the ID from the
1371 // registry so we don't keep trying. NOTE: This will throw off
1372 // anyone who is, at the moment, trying to iterate over the
1373 // available IDs. That's acceptable since we should never
1374 // really get here except under installation, configuration,
1375 // or unrecoverable run time memory failures.
1379 // If the status indicates a failure, then we don't have any
1380 // rules -- there is probably an installation error. The list
1381 // in the root locale should correspond to all the installed
1382 // transliterators; if it lists something that's not
1383 // installed, we'll get an error from ResourceBundle.
1384 aliasReturn
= new TransliteratorAlias(ID
, rules
,
1385 ((entry
->entryType
== TransliteratorEntry::RULES_REVERSE
) ?
1386 UTRANS_REVERSE
: UTRANS_FORWARD
));
1387 if (aliasReturn
== 0) {
1388 status
= U_MEMORY_ALLOCATION_ERROR
;
1394 U_ASSERT(FALSE
); // can't get here
1400 #endif /* #if !UCONFIG_NO_TRANSLITERATION */