2 **********************************************************************
3 * Copyright (c) 2001-2004, 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/utypes.h"
16 #include "unicode/uobject.h"
17 #include "unicode/parseerr.h"
18 #include "unicode/resbund.h"
19 #include "unicode/translit.h"
20 #include "unicode/uniset.h"
21 #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 NO_VARIANT
[] = { 0 }; // empty string
50 static const UChar ANY
[] = { 65, 110, 121, 0 }; // Any
53 * Resource bundle key for the RuleBasedTransliterator rule.
55 static const char RB_RULE
[] = "Rule";
59 //------------------------------------------------------------------
61 //------------------------------------------------------------------
63 TransliteratorAlias::TransliteratorAlias(const UnicodeString
& theAliasID
) :
69 type(TransliteratorAlias::SIMPLE
) {
72 TransliteratorAlias::TransliteratorAlias(const UnicodeString
& theID
,
73 const UnicodeString
& idBlock
,
74 Transliterator
* adopted
,
75 int32_t theIDSplitPoint
,
76 const UnicodeSet
* cpdFilter
) :
80 compoundFilter(cpdFilter
),
81 idSplitPoint(theIDSplitPoint
),
82 type(TransliteratorAlias::COMPOUND
) {
85 TransliteratorAlias::TransliteratorAlias(const UnicodeString
& theID
,
86 const UnicodeString
& rules
,
87 UTransDirection dir
) :
89 aliasID(rules
), // bad name -- rename aliasID!
92 idSplitPoint((int32_t) dir
), // bad name -- rename idSplitPoint!
93 type(TransliteratorAlias::RULES
) {
96 TransliteratorAlias::~TransliteratorAlias() {
101 Transliterator
* TransliteratorAlias::create(UParseError
& pe
,
106 Transliterator
*t
= NULL
;
109 t
= Transliterator::createInstance(aliasID
, UTRANS_FORWARD
, pe
, ec
);
112 t
= new CompoundTransliterator(ID
, aliasID
, idSplitPoint
,
116 ec
= U_MEMORY_ALLOCATION_ERROR
;
119 trans
= 0; // so we don't delete it later
120 if (compoundFilter
) {
121 // TODO: Is this right? Are we leaking memory here?
122 // I'm suspicious because of the "trans = 0" line above;
123 // doesn't seem to fit the cloning here. Don't have time
124 // to track this down right now. [alan 3.0]
125 t
->adoptFilter((UnicodeSet
*) compoundFilter
->clone());
129 U_ASSERT(FALSE
); // don't call create() if isRuleBased() returns TRUE!
135 UBool
TransliteratorAlias::isRuleBased() const {
136 return type
== RULES
;
139 void TransliteratorAlias::parse(TransliteratorParser
& parser
,
140 UParseError
& pe
, UErrorCode
& ec
) const {
141 U_ASSERT(type
== RULES
);
146 // aliasID is really rules -- rename it!
147 // idSplitPoint is really UTransDirection -- rename it!
148 parser
.parse(aliasID
, (UTransDirection
) idSplitPoint
, pe
, ec
);
151 //----------------------------------------------------------------------
153 //----------------------------------------------------------------------
156 * A Spec is a string specifying either a source or a target. In more
157 * general terms, it may also specify a variant, but we only use the
158 * Spec class for sources and targets.
160 * A Spec may be a locale or a script. If it is a locale, it has a
161 * fallback chain that goes xx_YY_ZZZ -> xx_YY -> xx -> ssss, where
162 * ssss is the script mapping of xx_YY_ZZZ. The Spec API methods
163 * hasFallback(), next(), and reset() iterate over this fallback
166 * The Spec class canonicalizes itself, so the locale is put into
167 * canonical form, or the script is transformed from an abbreviation
170 class Spec
: public UMemory
{
172 Spec(const UnicodeString
& spec
);
175 const UnicodeString
& get() const;
176 UBool
hasFallback() const;
177 const UnicodeString
& next();
180 UBool
isLocale() const;
181 ResourceBundle
& getBundle() const;
183 operator const UnicodeString
&() const { return get(); }
184 const UnicodeString
& getTop() const { return top
; }
191 UnicodeString nextSpec
;
192 UnicodeString scriptName
;
193 UBool isSpecLocale
; // TRUE if spec is a locale
194 UBool isNextLocale
; // TRUE if nextSpec is a locale
197 Spec(const Spec
&other
); // forbid copying of this class
198 Spec
&operator=(const Spec
&other
); // forbid copying of this class
201 Spec::Spec(const UnicodeString
& theSpec
) : top(theSpec
) {
202 UErrorCode status
= U_ZERO_ERROR
;
203 CharString
topch(top
);
204 Locale
toploc(topch
);
205 res
= new ResourceBundle(U_ICUDATA_TRANSLIT
, toploc
, status
);
210 if (U_FAILURE(status
) || status
== U_USING_DEFAULT_WARNING
) {
215 // Canonicalize script name -or- do locale->script mapping
216 status
= U_ZERO_ERROR
;
217 const int32_t capacity
= 10;
218 UScriptCode script
[capacity
]={USCRIPT_INVALID_CODE
};
219 int32_t num
= uscript_getCode(topch
,script
,capacity
, &status
);
220 if (num
> 0 && script
[0] != USCRIPT_INVALID_CODE
) {
221 scriptName
= UnicodeString(uscript_getName(script
[0]), "");
227 // Canonicalize locale name
228 status
= U_ZERO_ERROR
;
229 uloc_getName(topch
, buf
, sizeof(buf
), &status
);
230 if (U_SUCCESS(status
) && status
!= U_STRING_NOT_TERMINATED_WARNING
) {
231 top
= UnicodeString(buf
, "");
233 } else if (scriptName
.length() != 0) {
234 // We are a script; use canonical name
238 // assert(spec != top);
246 UBool
Spec::hasFallback() const {
247 return nextSpec
.length() != 0;
253 isSpecLocale
= (res
!= 0);
258 void Spec::setupNext() {
259 isNextLocale
= FALSE
;
262 int32_t i
= nextSpec
.lastIndexOf(LOCALE_SEP
);
263 // If i == 0 then we have _FOO, so we fall through
264 // to the scriptName.
266 nextSpec
.truncate(i
);
269 nextSpec
= scriptName
; // scriptName may be empty
272 // spec is a script, so we are at the end
273 nextSpec
.truncate(0);
278 // for(const UnicodeString& s(spec.get());
279 // spec.hasFallback(); s(spec.next())) { ...
281 const UnicodeString
& Spec::next() {
283 isSpecLocale
= isNextLocale
;
288 const UnicodeString
& Spec::get() const {
292 UBool
Spec::isLocale() const {
296 ResourceBundle
& Spec::getBundle() const {
300 //----------------------------------------------------------------------
304 // Vector of Entry pointers currently in use
305 static UVector
* DEBUG_entries
= NULL
;
307 static void DEBUG_setup() {
308 if (DEBUG_entries
== NULL
) {
309 UErrorCode ec
= U_ZERO_ERROR
;
310 DEBUG_entries
= new UVector(ec
);
314 // Caller must call DEBUG_setup first. Return index of given Entry,
315 // if it is in use (not deleted yet), or -1 if not found.
316 static int DEBUG_findEntry(Entry
* e
) {
317 for (int i
=0; i
<DEBUG_entries
->size(); ++i
) {
318 if (e
== (Entry
*) DEBUG_entries
->elementAt(i
)) {
325 // Track object creation
326 static void DEBUG_newEntry(Entry
* e
) {
328 if (DEBUG_findEntry(e
) >= 0) {
329 // This should really never happen unless the heap is broken
330 printf("ERROR DEBUG_newEntry duplicate new pointer %08X\n", e
);
333 UErrorCode ec
= U_ZERO_ERROR
;
334 DEBUG_entries
->addElement(e
, ec
);
337 // Track object deletion
338 static void DEBUG_delEntry(Entry
* e
) {
340 int i
= DEBUG_findEntry(e
);
342 printf("ERROR DEBUG_delEntry possible double deletion %08X\n", e
);
345 DEBUG_entries
->removeElementAt(i
);
348 // Track object usage
349 static void DEBUG_useEntry(Entry
* e
) {
350 if (e
== NULL
) return;
352 int i
= DEBUG_findEntry(e
);
354 printf("ERROR DEBUG_useEntry possible dangling pointer %08X\n", e
);
359 // If we're not debugging then make these macros into NOPs
360 #define DEBUG_newEntry(x)
361 #define DEBUG_delEntry(x)
362 #define DEBUG_useEntry(x)
365 //----------------------------------------------------------------------
367 //----------------------------------------------------------------------
370 * The Entry object stores objects of different types and
371 * singleton objects as placeholders for rule-based transliterators to
372 * be built as needed. Instances of this struct can be placeholders,
373 * can represent prototype transliterators to be cloned, or can
374 * represent TransliteratorData objects. We don't support storing
375 * classes in the registry because we don't have the rtti infrastructure
376 * for it. We could easily add this if there is a need for it in the
379 class Entry
: public UMemory
{
390 NONE
// Only used for uninitialized entries
392 // NOTE: stringArg cannot go inside the union because
393 // it has a copy constructor
394 UnicodeString stringArg
; // For RULES_*, ALIAS, COMPOUND_RBT
395 int32_t intArg
; // For COMPOUND_RBT, LOCALE_RULES
396 UnicodeSet
* compoundFilter
; // For COMPOUND_RBT
398 Transliterator
* prototype
; // For PROTOTYPE
399 TransliterationRuleData
* data
; // For RBT_DATA, COMPOUND_RBT
401 Transliterator::Factory function
;
402 Transliterator::Token context
;
403 } factory
; // For FACTORY
407 void adoptPrototype(Transliterator
* adopted
);
408 void setFactory(Transliterator::Factory factory
,
409 Transliterator::Token context
);
413 Entry(const Entry
&other
); // forbid copying of this class
414 Entry
&operator=(const Entry
&other
); // forbid copying of this class
419 compoundFilter
= NULL
;
421 DEBUG_newEntry(this);
425 DEBUG_delEntry(this);
426 if (entryType
== PROTOTYPE
) {
428 } else if (entryType
== RBT_DATA
|| entryType
== COMPOUND_RBT
) {
429 // The data object is shared between instances of RBT. The
430 // entry object owns it. It should only be deleted when the
431 // transliterator component is being cleaned up. Doing so
432 // invalidates any RBTs that the user has instantiated.
435 delete compoundFilter
;
438 void Entry::adoptPrototype(Transliterator
* adopted
) {
439 if (entryType
== PROTOTYPE
) {
442 entryType
= PROTOTYPE
;
443 u
.prototype
= adopted
;
446 void Entry::setFactory(Transliterator::Factory factory
,
447 Transliterator::Token context
) {
448 if (entryType
== PROTOTYPE
) {
452 u
.factory
.function
= factory
;
453 u
.factory
.context
= context
;
456 // UObjectDeleter for Hashtable::setValueDeleter
458 static void U_EXPORT2 U_CALLCONV
459 deleteEntry(void* obj
) {
464 //----------------------------------------------------------------------
465 // class TransliteratorRegistry: Basic public API
466 //----------------------------------------------------------------------
468 TransliteratorRegistry::TransliteratorRegistry(UErrorCode
& status
) :
469 registry(TRUE
, status
),
470 specDAG(TRUE
, status
),
473 registry
.setValueDeleter(deleteEntry
);
474 availableIDs
.setDeleter(uhash_deleteUnicodeString
);
475 availableIDs
.setComparer(uhash_compareCaselessUnicodeString
);
476 specDAG
.setValueDeleter(uhash_deleteHashtable
);
479 TransliteratorRegistry::~TransliteratorRegistry() {
480 // Through the magic of C++, everything cleans itself up
483 Transliterator
* TransliteratorRegistry::get(const UnicodeString
& ID
,
484 TransliteratorAlias
*& aliasReturn
,
485 UErrorCode
& status
) {
486 U_ASSERT(aliasReturn
== NULL
);
487 Entry
*entry
= find(ID
);
488 return (entry
== 0) ? 0
489 : instantiateEntry(ID
, entry
, aliasReturn
, status
);
492 Transliterator
* TransliteratorRegistry::reget(const UnicodeString
& ID
,
493 TransliteratorParser
& parser
,
494 TransliteratorAlias
*& aliasReturn
,
495 UErrorCode
& status
) {
496 U_ASSERT(aliasReturn
== NULL
);
497 Entry
*entry
= find(ID
);
500 // We get to this point if there are two threads, one of which
501 // is instantiating an ID, and another of which is removing
502 // the same ID from the registry, and the timing is just right.
506 // The usage model for the caller is that they will first call
507 // reg->get() inside the mutex, they'll get back an alias, they call
508 // alias->isRuleBased(), and if they get TRUE, they call alias->parse()
509 // outside the mutex, then reg->reget() inside the mutex again. A real
510 // mess, but it gets things working for ICU 3.0. [alan].
512 // Note: It's possible that in between the caller calling
513 // alias->parse() and reg->reget(), that another thread will have
514 // called reg->reget(), and the entry will already have been fixed up.
515 // We have to detect this so we don't stomp over existing entry
516 // data members and potentially leak memory (u.data and compoundFilter).
518 if (entry
->entryType
== Entry::RULES_FORWARD
||
519 entry
->entryType
== Entry::RULES_REVERSE
||
520 entry
->entryType
== Entry::LOCALE_RULES
) {
522 entry
->u
.data
= parser
.orphanData();
523 entry
->stringArg
= parser
.idBlock
;
524 entry
->intArg
= parser
.idSplitPoint
;
525 entry
->compoundFilter
= parser
.orphanCompoundFilter();
527 // Reset entry->entryType to encapsulate the parsed data. The
528 // next time we instantiate this ID (including this very next
529 // time, at the end of this function) we won't have to parse
531 // NOTE: The logic here matches that in
532 // Transliterator::createFromRules().
533 if (entry
->stringArg
.length() == 0) {
534 if (entry
->u
.data
== 0) {
535 // No idBlock, no data -- this is just an
537 entry
->entryType
= Entry::ALIAS
;
538 entry
->stringArg
= NullTransliterator::ID
;
540 // No idBlock, data != 0 -- this is an
542 entry
->entryType
= Entry::RBT_DATA
;
545 if (entry
->u
.data
== 0) {
546 // idBlock, no data -- this is an alias. The ID has
547 // been munged from reverse into forward mode, if
548 // necessary, so instantiate the ID in the forward
550 entry
->entryType
= Entry::ALIAS
;
552 // idBlock and data -- this is a compound
554 entry
->entryType
= Entry::COMPOUND_RBT
;
560 instantiateEntry(ID
, entry
, aliasReturn
, status
);
564 void TransliteratorRegistry::put(Transliterator
* adoptedProto
,
566 Entry
*entry
= new Entry();
567 entry
->adoptPrototype(adoptedProto
);
568 registerEntry(adoptedProto
->getID(), entry
, visible
);
571 void TransliteratorRegistry::put(const UnicodeString
& ID
,
572 Transliterator::Factory factory
,
573 Transliterator::Token context
,
575 Entry
*entry
= new Entry();
576 entry
->setFactory(factory
, context
);
577 registerEntry(ID
, entry
, visible
);
580 void TransliteratorRegistry::put(const UnicodeString
& ID
,
581 const UnicodeString
& resourceName
,
584 Entry
*entry
= new Entry();
585 entry
->entryType
= (dir
== UTRANS_FORWARD
) ? Entry::RULES_FORWARD
586 : Entry::RULES_REVERSE
;
587 entry
->stringArg
= resourceName
;
588 registerEntry(ID
, entry
, visible
);
591 void TransliteratorRegistry::put(const UnicodeString
& ID
,
592 const UnicodeString
& alias
,
594 Entry
*entry
= new Entry();
595 entry
->entryType
= Entry::ALIAS
;
596 entry
->stringArg
= alias
;
597 registerEntry(ID
, entry
, visible
);
600 void TransliteratorRegistry::remove(const UnicodeString
& ID
) {
601 UnicodeString source
, target
, variant
;
603 TransliteratorIDParser::IDtoSTV(ID
, source
, target
, variant
, sawSource
);
604 // Only need to do this if ID.indexOf('-') < 0
606 TransliteratorIDParser::STVtoID(source
, target
, variant
, id
);
608 removeSTV(source
, target
, variant
);
609 availableIDs
.removeElement((void*) &id
);
612 //----------------------------------------------------------------------
613 // class TransliteratorRegistry: Public ID and spec management
614 //----------------------------------------------------------------------
617 * == OBSOLETE - remove in ICU 3.4 ==
618 * Return the number of IDs currently registered with the system.
619 * To retrieve the actual IDs, call getAvailableID(i) with
620 * i from 0 to countAvailableIDs() - 1.
622 int32_t TransliteratorRegistry::countAvailableIDs(void) const {
623 return availableIDs
.size();
627 * == OBSOLETE - remove in ICU 3.4 ==
628 * Return the index-th available ID. index must be between 0
629 * and countAvailableIDs() - 1, inclusive. If index is out of
630 * range, the result of getAvailableID(0) is returned.
632 const UnicodeString
& TransliteratorRegistry::getAvailableID(int32_t index
) const {
633 if (index
< 0 || index
>= availableIDs
.size()) {
636 return *(const UnicodeString
*) availableIDs
[index
];
639 StringEnumeration
* TransliteratorRegistry::getAvailableIDs() const {
640 return new Enumeration(*this);
643 int32_t TransliteratorRegistry::countAvailableSources(void) const {
644 return specDAG
.count();
647 UnicodeString
& TransliteratorRegistry::getAvailableSource(int32_t index
,
648 UnicodeString
& result
) const {
650 const UHashElement
*e
= 0;
651 while (index
-- >= 0) {
652 e
= specDAG
.nextElement(pos
);
660 result
= *(UnicodeString
*) e
->key
.pointer
;
665 int32_t TransliteratorRegistry::countAvailableTargets(const UnicodeString
& source
) const {
666 Hashtable
*targets
= (Hashtable
*) specDAG
.get(source
);
667 return (targets
== 0) ? 0 : targets
->count();
670 UnicodeString
& TransliteratorRegistry::getAvailableTarget(int32_t index
,
671 const UnicodeString
& source
,
672 UnicodeString
& result
) const {
673 Hashtable
*targets
= (Hashtable
*) specDAG
.get(source
);
675 result
.truncate(0); // invalid source
679 const UHashElement
*e
= 0;
680 while (index
-- >= 0) {
681 e
= targets
->nextElement(pos
);
687 result
.truncate(0); // invalid index
689 result
= *(UnicodeString
*) e
->key
.pointer
;
694 int32_t TransliteratorRegistry::countAvailableVariants(const UnicodeString
& source
,
695 const UnicodeString
& target
) const {
696 Hashtable
*targets
= (Hashtable
*) specDAG
.get(source
);
700 UVector
*variants
= (UVector
*) targets
->get(target
);
701 // variants may be 0 if the source/target are invalid
702 return (variants
== 0) ? 0 : variants
->size();
705 UnicodeString
& TransliteratorRegistry::getAvailableVariant(int32_t index
,
706 const UnicodeString
& source
,
707 const UnicodeString
& target
,
708 UnicodeString
& result
) const {
709 Hashtable
*targets
= (Hashtable
*) specDAG
.get(source
);
711 result
.truncate(0); // invalid source
714 UVector
*variants
= (UVector
*) targets
->get(target
);
716 result
.truncate(0); // invalid target
719 UnicodeString
*v
= (UnicodeString
*) variants
->elementAt(index
);
721 result
.truncate(0); // invalid index
728 //----------------------------------------------------------------------
729 // class TransliteratorRegistry::Enumeration
730 //----------------------------------------------------------------------
732 TransliteratorRegistry::Enumeration::Enumeration(const TransliteratorRegistry
& _reg
) :
733 index(0), reg(_reg
) {
736 TransliteratorRegistry::Enumeration::~Enumeration() {
739 int32_t TransliteratorRegistry::Enumeration::count(UErrorCode
& /*status*/) const {
740 return reg
.availableIDs
.size();
743 const UnicodeString
* TransliteratorRegistry::Enumeration::snext(UErrorCode
& status
) {
744 // This is sloppy but safe -- if we get out of sync with the underlying
745 // registry, we will still return legal strings, but they might not
746 // correspond to the snapshot at construction time. So there could be
747 // duplicate IDs or omitted IDs if insertions or deletions occur in one
748 // thread while another is iterating. To be more rigorous, add a timestamp,
749 // which is incremented with any modification, and validate this iterator
750 // against the timestamp at construction time. This probably isn't worth
751 // doing as long as there is some possibility of removing this code in favor
752 // of some new code based on Doug's service framework.
753 if (U_FAILURE(status
)) {
756 int32_t n
= reg
.availableIDs
.size();
758 status
= U_ENUM_OUT_OF_SYNC_ERROR
;
760 // index == n is okay -- this means we've reached the end
762 // Copy the string! This avoids lifetime problems.
763 unistr
= *(const UnicodeString
*)reg
.availableIDs
[index
++];
770 void TransliteratorRegistry::Enumeration::reset(UErrorCode
& /*status*/) {
774 UOBJECT_DEFINE_RTTI_IMPLEMENTATION(TransliteratorRegistry::Enumeration
)
776 //----------------------------------------------------------------------
777 // class TransliteratorRegistry: internal
778 //----------------------------------------------------------------------
781 * Convenience method. Calls 6-arg registerEntry().
783 void TransliteratorRegistry::registerEntry(const UnicodeString
& source
,
784 const UnicodeString
& target
,
785 const UnicodeString
& variant
,
789 UnicodeString
s(source
);
790 if (s
.length() == 0) {
793 TransliteratorIDParser::STVtoID(source
, target
, variant
, ID
);
794 registerEntry(ID
, s
, target
, variant
, adopted
, visible
);
798 * Convenience method. Calls 6-arg registerEntry().
800 void TransliteratorRegistry::registerEntry(const UnicodeString
& ID
,
803 UnicodeString source
, target
, variant
;
805 TransliteratorIDParser::IDtoSTV(ID
, source
, target
, variant
, sawSource
);
806 // Only need to do this if ID.indexOf('-') < 0
808 TransliteratorIDParser::STVtoID(source
, target
, variant
, id
);
809 registerEntry(id
, source
, target
, variant
, adopted
, visible
);
813 * Register an entry object (adopted) with the given ID, source,
814 * target, and variant strings.
816 void TransliteratorRegistry::registerEntry(const UnicodeString
& ID
,
817 const UnicodeString
& source
,
818 const UnicodeString
& target
,
819 const UnicodeString
& variant
,
822 UErrorCode status
= U_ZERO_ERROR
;
823 registry
.put(ID
, adopted
, status
);
825 registerSTV(source
, target
, variant
);
826 if (!availableIDs
.contains((void*) &ID
)) {
827 UnicodeString
*newID
= (UnicodeString
*)ID
.clone();
828 // NUL-terminate the ID string
829 newID
->getTerminatedBuffer();
830 availableIDs
.addElement(newID
, status
);
833 removeSTV(source
, target
, variant
);
834 availableIDs
.removeElement((void*) &ID
);
839 * Register a source-target/variant in the specDAG. Variant may be
840 * empty, but source and target must not be. If variant is empty then
841 * the special variant NO_VARIANT is stored in slot zero of the
842 * UVector of variants.
844 void TransliteratorRegistry::registerSTV(const UnicodeString
& source
,
845 const UnicodeString
& target
,
846 const UnicodeString
& variant
) {
847 // assert(source.length() > 0);
848 // assert(target.length() > 0);
849 UErrorCode status
= U_ZERO_ERROR
;
850 Hashtable
*targets
= (Hashtable
*) specDAG
.get(source
);
852 targets
= new Hashtable(TRUE
, status
);
853 if (U_FAILURE(status
) || targets
== 0) {
856 targets
->setValueDeleter(uhash_deleteUVector
);
857 specDAG
.put(source
, targets
, status
);
859 UVector
*variants
= (UVector
*) targets
->get(target
);
861 variants
= new UVector(uhash_deleteUnicodeString
,
862 uhash_compareCaselessUnicodeString
, status
);
866 targets
->put(target
, variants
, status
);
868 // assert(NO_VARIANT == "");
869 // We add the variant string. If it is the special "no variant"
870 // string, that is, the empty string, we add it at position zero.
871 if (!variants
->contains((void*) &variant
)) {
872 if (variant
.length() > 0) {
873 variants
->addElement(new UnicodeString(variant
), status
);
875 variants
->insertElementAt(new UnicodeString(NO_VARIANT
), 0, status
);
881 * Remove a source-target/variant from the specDAG.
883 void TransliteratorRegistry::removeSTV(const UnicodeString
& source
,
884 const UnicodeString
& target
,
885 const UnicodeString
& variant
) {
886 // assert(source.length() > 0);
887 // assert(target.length() > 0);
888 // UErrorCode status = U_ZERO_ERROR;
889 Hashtable
*targets
= (Hashtable
*) specDAG
.get(source
);
891 return; // should never happen for valid s-t/v
893 UVector
*variants
= (UVector
*) targets
->get(target
);
895 return; // should never happen for valid s-t/v
897 variants
->removeElement((void*) &variant
);
898 if (variants
->size() == 0) {
899 targets
->remove(target
); // should delete variants
900 if (targets
->count() == 0) {
901 specDAG
.remove(source
); // should delete targets
907 * Attempt to find a source-target/variant in the dynamic registry
908 * store. Return 0 on failure.
910 * Caller does NOT own returned object.
912 Entry
* TransliteratorRegistry::findInDynamicStore(const Spec
& src
,
914 const UnicodeString
& variant
) const {
916 TransliteratorIDParser::STVtoID(src
, trg
, variant
, ID
);
917 Entry
*e
= (Entry
*) registry
.get(ID
);
923 * Attempt to find a source-target/variant in the static locale
924 * resource store. Do not perform fallback. Return 0 on failure.
926 * On success, create a new entry object, register it in the dynamic
927 * store, and return a pointer to it, but do not make it public --
928 * just because someone requested something, we do not expand the
929 * available ID list (or spec DAG).
931 * Caller does NOT own returned object.
933 Entry
* TransliteratorRegistry::findInStaticStore(const Spec
& src
,
935 const UnicodeString
& variant
) {
937 if (src
.isLocale()) {
938 entry
= findInBundle(src
, trg
, variant
, UTRANS_FORWARD
);
939 } else if (trg
.isLocale()) {
940 entry
= findInBundle(trg
, src
, variant
, UTRANS_REVERSE
);
943 // If we found an entry, store it in the Hashtable for next
946 registerEntry(src
.getTop(), trg
.getTop(), variant
, entry
, FALSE
);
952 // As of 2.0, resource bundle keys cannot contain '_'
953 static const UChar TRANSLITERATE_TO
[] = {84,114,97,110,115,108,105,116,101,114,97,116,101,84,111,0}; // "TransliterateTo"
955 static const UChar TRANSLITERATE_FROM
[] = {84,114,97,110,115,108,105,116,101,114,97,116,101,70,114,111,109,0}; // "TransliterateFrom"
957 static const UChar TRANSLITERATE
[] = {84,114,97,110,115,108,105,116,101,114,97,116,101,0}; // "Transliterate"
960 * Attempt to find an entry in a single resource bundle. This is
961 * a one-sided lookup. findInStaticStore() performs up to two such
962 * lookups, one for the source, and one for the target.
964 * Do not perform fallback. Return 0 on failure.
966 * On success, create a new Entry object, populate it, and return it.
967 * The caller owns the returned object.
969 Entry
* TransliteratorRegistry::findInBundle(const Spec
& specToOpen
,
970 const Spec
& specToFind
,
971 const UnicodeString
& variant
,
972 UTransDirection direction
)
975 UnicodeString resStr
;
978 for (pass
=0; pass
<2; ++pass
) {
980 // First try either TransliteratorTo_xxx or
981 // TransliterateFrom_xxx, then try the bidirectional
982 // Transliterate_xxx. This precedence order is arbitrary
983 // but must be consistent and documented.
985 utag
.append(direction
== UTRANS_FORWARD
?
986 TRANSLITERATE_TO
: TRANSLITERATE_FROM
);
988 utag
.append(TRANSLITERATE
);
990 UnicodeString
s(specToFind
.get());
991 utag
.append(s
.toUpper());
992 CharString
tag(utag
);
994 UErrorCode status
= U_ZERO_ERROR
;
995 ResourceBundle
subres(specToOpen
.getBundle().get(tag
, status
));
996 if (U_FAILURE(status
) || status
== U_USING_DEFAULT_WARNING
) {
1000 if (specToOpen
.get() != subres
.getLocale().getName()) {
1004 if (variant
.length() != 0) {
1005 CharString
var(variant
);
1006 status
= U_ZERO_ERROR
;
1007 resStr
= subres
.getStringEx(var
, status
);
1008 if (U_SUCCESS(status
)) {
1009 // Exit loop successfully
1015 // Variant is empty, which means match the first variant listed.
1016 status
= U_ZERO_ERROR
;
1017 resStr
= subres
.getStringEx(1, status
);
1018 if (U_SUCCESS(status
)) {
1019 // Exit loop successfully
1030 // We have succeeded in loading a string from the locale
1031 // resources. Create a new registry entry to hold it and return it.
1032 Entry
*entry
= new Entry();
1034 // The direction is always forward for the
1035 // TransliterateTo_xxx and TransliterateFrom_xxx
1036 // items; those are unidirectional forward rules.
1037 // For the bidirectional Transliterate_xxx items,
1038 // the direction is the value passed in to this
1040 int32_t dir
= (pass
== 0) ? UTRANS_FORWARD
: direction
;
1041 entry
->entryType
= Entry::LOCALE_RULES
;
1042 entry
->stringArg
= resStr
;
1043 entry
->intArg
= dir
;
1050 * Convenience method. Calls 3-arg find().
1052 Entry
* TransliteratorRegistry::find(const UnicodeString
& ID
) {
1053 UnicodeString source
, target
, variant
;
1055 TransliteratorIDParser::IDtoSTV(ID
, source
, target
, variant
, sawSource
);
1056 return find(source
, target
, variant
);
1060 * Top-level find method. Attempt to find a source-target/variant in
1061 * either the dynamic or the static (locale resource) store. Perform
1064 * Lookup sequence for ss_SS_SSS-tt_TT_TTT/v:
1066 * ss_SS_SSS-tt_TT_TTT/v -- in hashtable
1067 * ss_SS_SSS-tt_TT_TTT/v -- in ss_SS_SSS (no fallback)
1069 * repeat with t = tt_TT_TTT, tt_TT, tt, and tscript
1076 * Here * matches the first variant listed.
1078 * Caller does NOT own returned object. Return 0 on failure.
1080 Entry
* TransliteratorRegistry::find(UnicodeString
& source
,
1081 UnicodeString
& target
,
1082 UnicodeString
& variant
) {
1088 if (variant
.length() != 0) {
1090 // Seek exact match in hashtable
1091 entry
= findInDynamicStore(src
, trg
, variant
);
1096 // Seek exact match in locale resources
1097 entry
= findInStaticStore(src
, trg
, variant
);
1106 // Seek match in hashtable
1107 entry
= findInDynamicStore(src
, trg
, NO_VARIANT
);
1112 // Seek match in locale resources
1113 entry
= findInStaticStore(src
, trg
, NO_VARIANT
);
1117 if (!src
.hasFallback()) {
1122 if (!trg
.hasFallback()) {
1132 * Given an Entry object, instantiate it. Caller owns result. Return
1135 * Return a non-empty aliasReturn value if the ID points to an alias.
1136 * We cannot instantiate it ourselves because the alias may contain
1137 * filters or compounds, which we do not understand. Caller should
1138 * make aliasReturn empty before calling.
1140 * The entry object is assumed to reside in the dynamic store. It may be
1143 Transliterator
* TransliteratorRegistry::instantiateEntry(const UnicodeString
& ID
,
1145 TransliteratorAlias
* &aliasReturn
,
1146 UErrorCode
& status
) {
1147 Transliterator
*t
= 0;
1148 U_ASSERT(aliasReturn
== 0);
1150 switch (entry
->entryType
) {
1151 case Entry::RBT_DATA
:
1152 t
= new RuleBasedTransliterator(ID
, entry
->u
.data
);
1154 status
= U_MEMORY_ALLOCATION_ERROR
;
1157 case Entry::PROTOTYPE
:
1158 t
= entry
->u
.prototype
->clone();
1160 status
= U_MEMORY_ALLOCATION_ERROR
;
1164 aliasReturn
= new TransliteratorAlias(entry
->stringArg
);
1165 if (aliasReturn
== 0) {
1166 status
= U_MEMORY_ALLOCATION_ERROR
;
1169 case Entry::FACTORY
:
1170 t
= entry
->u
.factory
.function(ID
, entry
->u
.factory
.context
);
1172 status
= U_MEMORY_ALLOCATION_ERROR
;
1175 case Entry::COMPOUND_RBT
:
1177 UnicodeString
id((UChar
)0x005F); /* "_" */
1178 Transliterator
*t
= new RuleBasedTransliterator(id
, entry
->u
.data
);
1180 status
= U_MEMORY_ALLOCATION_ERROR
;
1183 aliasReturn
= new TransliteratorAlias(ID
, entry
->stringArg
, t
, entry
->intArg
, entry
->compoundFilter
);
1185 if (aliasReturn
== 0) {
1186 status
= U_MEMORY_ALLOCATION_ERROR
;
1189 case Entry::LOCALE_RULES
:
1190 aliasReturn
= new TransliteratorAlias(ID
, entry
->stringArg
,
1191 (UTransDirection
) entry
->intArg
);
1192 if (aliasReturn
== 0) {
1193 status
= U_MEMORY_ALLOCATION_ERROR
;
1196 case Entry::RULES_FORWARD
:
1197 case Entry::RULES_REVERSE
:
1198 // Process the rule data into a TransliteratorRuleData object,
1199 // and possibly also into an ::id header and/or footer. Then
1200 // we modify the registry with the parsed data and retry.
1202 TransliteratorParser parser
;
1204 // We use the file name, taken from another resource bundle
1205 // 2-d array at static init time, as a locale language. We're
1206 // just using the locale mechanism to map through to a file
1207 // name; this in no way represents an actual locale.
1208 //CharString ch(entry->stringArg);
1209 //UResourceBundle *bundle = ures_openDirect(0, ch, &status);
1210 UnicodeString rules
= entry
->stringArg
;
1211 //ures_close(bundle);
1213 //if (U_FAILURE(status)) {
1214 // We have a failure of some kind. Remove the ID from the
1215 // registry so we don't keep trying. NOTE: This will throw off
1216 // anyone who is, at the moment, trying to iterate over the
1217 // available IDs. That's acceptable since we should never
1218 // really get here except under installation, configuration,
1219 // or unrecoverable run time memory failures.
1223 // If the status indicates a failure, then we don't have any
1224 // rules -- there is probably an installation error. The list
1225 // in the root locale should correspond to all the installed
1226 // transliterators; if it lists something that's not
1227 // installed, we'll get an error from ResourceBundle.
1228 aliasReturn
= new TransliteratorAlias(ID
, rules
,
1229 ((entry
->entryType
== Entry::RULES_REVERSE
) ?
1230 UTRANS_REVERSE
: UTRANS_FORWARD
));
1231 if (aliasReturn
== 0) {
1232 status
= U_MEMORY_ALLOCATION_ERROR
;
1238 U_ASSERT(FALSE
); // can't get here
1244 #endif /* #if !UCONFIG_NO_TRANSLITERATION */