2 ******************************************************************************
3 * Copyright (C) 1996-2006, International Business Machines Corporation and *
4 * others. All Rights Reserved. *
5 ******************************************************************************
11 * Created by: Helena Shih
13 * Modification History:
15 * Date Name Description
16 * 2/5/97 aliu Added streamIn and streamOut methods. Added
17 * constructor which reads RuleBasedCollator object from
18 * a binary file. Added writeToFile method which streams
19 * RuleBasedCollator out to a binary file. The streamIn
20 * and streamOut methods use istream and ostream objects
22 * 2/11/97 aliu Moved declarations out of for loop initializer.
23 * Added Mac compatibility #ifdef for ios::nocreate.
24 * 2/12/97 aliu Modified to use TableCollationData sub-object to
25 * hold invariant data.
26 * 2/13/97 aliu Moved several methods into this class from Collation.
27 * Added a private RuleBasedCollator(Locale&) constructor,
28 * to be used by Collator::getInstance(). General
29 * clean up. Made use of UErrorCode variables consistent.
30 * 2/20/97 helena Added clone, operator==, operator!=, operator=, and copy
31 * constructor and getDynamicClassID.
32 * 3/5/97 aliu Changed compaction cycle to improve performance. We
33 * use the maximum allowable value which is kBlockCount.
34 * Modified getRules() to load rules dynamically. Changed
35 * constructFromFile() call to accomodate this (added
36 * parameter to specify whether binary loading is to
38 * 05/06/97 helena Added memory allocation error check.
39 * 6/20/97 helena Java class name change.
40 * 6/23/97 helena Adding comments to make code more readable.
41 * 09/03/97 helena Added createCollationKeyValues().
42 * 06/26/98 erm Changes for CollationKeys using byte arrays.
43 * 08/10/98 erm Synched with 1.2 version of RuleBasedCollator.java
44 * 04/23/99 stephen Removed EDecompositionMode, merged with
46 * 06/14/99 stephen Removed kResourceBundleSuffix
47 * 06/22/99 stephen Fixed logic in constructFromFile() since .ctx
48 * files are no longer used.
49 * 11/02/99 helena Collator performance enhancements. Special case
50 * for NO_OP situations.
51 * 11/17/99 srl More performance enhancements. Inlined some internal functions.
52 * 12/15/99 aliu Update to support Thai collation. Move NormalizerIterator
53 * to implementation file.
54 * 01/29/01 synwee Modified into a C++ wrapper calling C APIs (ucol.h)
57 #include "unicode/utypes.h"
59 #if !UCONFIG_NO_COLLATION
61 #include "unicode/tblcoll.h"
62 #include "unicode/coleitr.h"
63 #include "unicode/ures.h"
64 #include "unicode/uset.h"
72 /* public RuleBasedCollator constructor ---------------------------------- */
77 * Copy constructor, aliasing, not write-through
79 RuleBasedCollator::RuleBasedCollator(const RuleBasedCollator
& that
)
82 , isWriteThroughAlias(FALSE
)
85 RuleBasedCollator::operator=(that
);
88 RuleBasedCollator::RuleBasedCollator(const UnicodeString
& rules
,
93 UCOL_DEFAULT_STRENGTH
,
98 RuleBasedCollator::RuleBasedCollator(const UnicodeString
& rules
,
99 ECollationStrength collationStrength
,
100 UErrorCode
& status
) : dataIsOwned(FALSE
)
103 getUCollationStrength(collationStrength
),
108 RuleBasedCollator::RuleBasedCollator(const UnicodeString
& rules
,
109 UColAttributeValue decompositionMode
,
110 UErrorCode
& status
) :
114 UCOL_DEFAULT_STRENGTH
,
119 RuleBasedCollator::RuleBasedCollator(const UnicodeString
& rules
,
120 ECollationStrength collationStrength
,
121 UColAttributeValue decompositionMode
,
122 UErrorCode
& status
) : dataIsOwned(FALSE
)
125 getUCollationStrength(collationStrength
),
129 RuleBasedCollator::RuleBasedCollator(const uint8_t *bin
, int32_t length
,
130 const RuleBasedCollator
*base
,
131 UErrorCode
&status
) :
133 isWriteThroughAlias(FALSE
)
135 ucollator
= ucol_openBinary(bin
, length
, base
->ucollator
, &status
);
139 RuleBasedCollator::setRuleStringFromCollator()
142 const UChar
*r
= ucol_getRules(ucollator
, &length
);
144 if (r
&& length
> 0) {
145 // alias the rules string
146 urulestring
.setTo(TRUE
, r
, length
);
149 urulestring
.truncate(0); // Clear string.
153 // not aliasing, not write-through
155 RuleBasedCollator::construct(const UnicodeString
& rules
,
156 UColAttributeValue collationStrength
,
157 UColAttributeValue decompositionMode
,
160 ucollator
= ucol_openRules(rules
.getBuffer(), rules
.length(),
161 decompositionMode
, collationStrength
,
164 dataIsOwned
= TRUE
; // since we own a collator now, we need to get rid of it
165 isWriteThroughAlias
= FALSE
;
167 if(ucollator
== NULL
) {
168 if(U_SUCCESS(status
)) {
169 status
= U_MEMORY_ALLOCATION_ERROR
;
174 setRuleStringFromCollator();
177 /* RuleBasedCollator public destructor ----------------------------------- */
179 RuleBasedCollator::~RuleBasedCollator()
183 ucol_close(ucollator
);
188 /* RuleBaseCollator public methods --------------------------------------- */
190 UBool
RuleBasedCollator::operator==(const Collator
& that
) const
192 /* only checks for address equals here */
193 if (Collator::operator==(that
))
196 if (getDynamicClassID() != that
.getDynamicClassID())
197 return FALSE
; /* not the same class */
199 RuleBasedCollator
& thatAlias
= (RuleBasedCollator
&)that
;
201 // weiv: use C function, commented code below is wrong
202 return ucol_equals(this->ucollator
, thatAlias
.ucollator
);
204 synwee : orginal code does not check for data compatibility
207 if (ucollator != thatAlias.ucollator)
214 UBool
RuleBasedCollator::operator!=(const Collator
& other
) const
216 return !(*this == other
);
219 // aliasing, not write-through
220 RuleBasedCollator
& RuleBasedCollator::operator=(const RuleBasedCollator
& that
)
226 ucol_close(ucollator
);
229 urulestring
.truncate(0); // empty the rule string
231 isWriteThroughAlias
= FALSE
;
233 UErrorCode intStatus
= U_ZERO_ERROR
;
234 int32_t buffersize
= U_COL_SAFECLONE_BUFFERSIZE
;
235 ucollator
= ucol_safeClone(that
.ucollator
, NULL
, &buffersize
,
237 if (U_SUCCESS(intStatus
)) {
238 setRuleStringFromCollator();
244 // aliasing, not write-through
245 Collator
* RuleBasedCollator::clone() const
247 return new RuleBasedCollator(*this);
250 CollationElementIterator
* RuleBasedCollator::createCollationElementIterator
251 (const UnicodeString
& source
) const
253 UErrorCode status
= U_ZERO_ERROR
;
254 CollationElementIterator
*result
= new CollationElementIterator(source
, this,
256 if (U_FAILURE(status
)) {
265 * Create a CollationElementIterator object that will iterate over the
266 * elements in a string, using the collation rules defined in this
269 CollationElementIterator
* RuleBasedCollator::createCollationElementIterator
270 (const CharacterIterator
& source
) const
272 UErrorCode status
= U_ZERO_ERROR
;
273 CollationElementIterator
*result
= new CollationElementIterator(source
, this,
276 if (U_FAILURE(status
)) {
285 * Return a string representation of this collator's rules. The string can
286 * later be passed to the constructor that takes a UnicodeString argument,
287 * which will construct a collator that's functionally identical to this one.
288 * You can also allow users to edit the string in order to change the collation
289 * data, or you can print it out for inspection, or whatever.
291 const UnicodeString
& RuleBasedCollator::getRules() const
296 void RuleBasedCollator::getRules(UColRuleOption delta
, UnicodeString
&buffer
)
298 int32_t rulesize
= ucol_getRulesEx(ucollator
, delta
, NULL
, -1);
301 UChar
*rules
= (UChar
*) uprv_malloc( sizeof(UChar
) * (rulesize
) );
303 ucol_getRulesEx(ucollator
, delta
, rules
, rulesize
);
304 buffer
.setTo(rules
, rulesize
);
306 } else { // couldn't allocate
316 RuleBasedCollator::getTailoredSet(UErrorCode
&status
) const
318 if(U_FAILURE(status
)) {
321 return (UnicodeSet
*)ucol_getTailoredSet(this->ucollator
, &status
);
325 void RuleBasedCollator::getVersion(UVersionInfo versionInfo
) const
327 if (versionInfo
!=NULL
){
328 ucol_getVersion(ucollator
, versionInfo
);
332 Collator::EComparisonResult
RuleBasedCollator::compare(
333 const UnicodeString
& source
,
334 const UnicodeString
& target
,
335 int32_t length
) const
337 UErrorCode status
= U_ZERO_ERROR
;
338 return getEComparisonResult(compare(source
.getBuffer(), uprv_min(length
,source
.length()), target
.getBuffer(), uprv_min(length
,target
.length()), status
));
341 UCollationResult
RuleBasedCollator::compare(
342 const UnicodeString
& source
,
343 const UnicodeString
& target
,
345 UErrorCode
&status
) const
347 return compare(source
.getBuffer(), uprv_min(length
,source
.length()), target
.getBuffer(), uprv_min(length
,target
.length()), status
);
350 Collator::EComparisonResult
RuleBasedCollator::compare(const UChar
* source
,
351 int32_t sourceLength
,
353 int32_t targetLength
)
356 return getEComparisonResult(ucol_strcoll(ucollator
, source
, sourceLength
,
357 target
, targetLength
));
360 UCollationResult
RuleBasedCollator::compare(const UChar
* source
,
361 int32_t sourceLength
,
363 int32_t targetLength
,
364 UErrorCode
&status
) const
366 if(U_SUCCESS(status
)) {
367 return ucol_strcoll(ucollator
, source
, sourceLength
, target
, targetLength
);
374 * Compare two strings using this collator
376 Collator::EComparisonResult
RuleBasedCollator::compare(
377 const UnicodeString
& source
,
378 const UnicodeString
& target
) const
380 return getEComparisonResult(ucol_strcoll(ucollator
, source
.getBuffer(), source
.length(),
381 target
.getBuffer(), target
.length()));
384 UCollationResult
RuleBasedCollator::compare(
385 const UnicodeString
& source
,
386 const UnicodeString
& target
,
387 UErrorCode
&status
) const
389 if(U_SUCCESS(status
)) {
390 return ucol_strcoll(ucollator
, source
.getBuffer(), source
.length(),
391 target
.getBuffer(), target
.length());
398 * Retrieve a collation key for the specified string. The key can be compared
399 * with other collation keys using a bitwise comparison (e.g. memcmp) to find
400 * the ordering of their respective source strings. This is handy when doing a
401 * sort, where each sort key must be compared many times.
403 * The basic algorithm here is to find all of the collation elements for each
404 * character in the source string, convert them to an ASCII representation, and
405 * put them into the collation key. But it's trickier than that. Each
406 * collation element in a string has three components: primary ('A' vs 'B'),
407 * secondary ('u' vs '\u00FC'), and tertiary ('A' vs 'a'), and a primary difference
408 * at the end of a string takes precedence over a secondary or tertiary
409 * difference earlier in the string.
411 * To account for this, we put all of the primary orders at the beginning of
412 * the string, followed by the secondary and tertiary orders. Each set of
413 * orders is terminated by nulls so that a key for a string which is a initial
414 * substring of another key will compare less without any special case.
416 * Here's a hypothetical example, with the collation element represented as a
417 * three-digit number, one digit for primary, one for secondary, etc.
419 * String: A a B \u00C9
420 * Collation Elements: 101 100 201 511
421 * Collation Key: 1125<null>0001<null>1011<null>
423 * To make things even trickier, secondary differences (accent marks) are
424 * compared starting at the *end* of the string in languages with French
425 * secondary ordering. But when comparing the accent marks on a single base
426 * character, they are compared from the beginning. To handle this, we reverse
427 * all of the accents that belong to each base character, then we reverse the
428 * entire string of secondary orderings at the end.
430 CollationKey
& RuleBasedCollator::getCollationKey(
431 const UnicodeString
& source
,
432 CollationKey
& sortkey
,
433 UErrorCode
& status
) const
435 return getCollationKey(source
.getBuffer(), source
.length(), sortkey
, status
);
438 CollationKey
& RuleBasedCollator::getCollationKey(const UChar
* source
,
440 CollationKey
& sortkey
,
441 UErrorCode
& status
) const
443 if (U_FAILURE(status
))
445 return sortkey
.setToBogus();
448 if ((!source
) || (sourceLen
== 0)) {
449 return sortkey
.reset();
453 int32_t resultLen
= ucol_getSortKeyWithAllocation(ucollator
,
457 sortkey
.adopt(result
, resultLen
);
462 * Return the maximum length of any expansion sequences that end with the
463 * specified comparison order.
464 * @param order a collation order returned by previous or next.
465 * @return the maximum length of any expansion seuences ending with the
466 * specified order or 1 if collation order does not occur at the end of any
467 * expansion sequence.
468 * @see CollationElementIterator#getMaxExpansion
470 int32_t RuleBasedCollator::getMaxExpansion(int32_t order
) const
473 UCOL_GETMAXEXPANSION(ucollator
, (uint32_t)order
, result
);
477 uint8_t* RuleBasedCollator::cloneRuleData(int32_t &length
,
480 return ucol_cloneRuleData(ucollator
, &length
, &status
);
484 int32_t RuleBasedCollator::cloneBinary(uint8_t *buffer
, int32_t capacity
, UErrorCode
&status
)
486 return ucol_cloneBinary(ucollator
, buffer
, capacity
, &status
);
489 void RuleBasedCollator::setAttribute(UColAttribute attr
,
490 UColAttributeValue value
,
493 if (U_FAILURE(status
))
496 ucol_setAttribute(ucollator
, attr
, value
, &status
);
499 UColAttributeValue
RuleBasedCollator::getAttribute(UColAttribute attr
,
502 if (U_FAILURE(status
))
504 return ucol_getAttribute(ucollator
, attr
, &status
);
507 uint32_t RuleBasedCollator::setVariableTop(const UChar
*varTop
, int32_t len
, UErrorCode
&status
) {
509 return ucol_setVariableTop(ucollator
, varTop
, len
, &status
);
512 uint32_t RuleBasedCollator::setVariableTop(const UnicodeString varTop
, UErrorCode
&status
) {
514 return ucol_setVariableTop(ucollator
, varTop
.getBuffer(), varTop
.length(), &status
);
517 void RuleBasedCollator::setVariableTop(const uint32_t varTop
, UErrorCode
&status
) {
519 ucol_restoreVariableTop(ucollator
, varTop
, &status
);
522 uint32_t RuleBasedCollator::getVariableTop(UErrorCode
&status
) const {
523 return ucol_getVariableTop(ucollator
, &status
);
526 Collator
* RuleBasedCollator::safeClone(void)
528 UErrorCode intStatus
= U_ZERO_ERROR
;
529 int32_t buffersize
= U_COL_SAFECLONE_BUFFERSIZE
;
530 UCollator
*ucol
= ucol_safeClone(ucollator
, NULL
, &buffersize
,
532 if (U_FAILURE(intStatus
)) {
536 RuleBasedCollator
*result
= new RuleBasedCollator();
537 result
->ucollator
= ucol
;
538 result
->dataIsOwned
= TRUE
;
539 result
->isWriteThroughAlias
= FALSE
;
540 setRuleStringFromCollator();
546 int32_t RuleBasedCollator::getSortKey(const UnicodeString
& source
,
547 uint8_t *result
, int32_t resultLength
)
550 return ucol_getSortKey(ucollator
, source
.getBuffer(), source
.length(), result
, resultLength
);
553 int32_t RuleBasedCollator::getSortKey(const UChar
*source
,
554 int32_t sourceLength
, uint8_t *result
,
555 int32_t resultLength
) const
557 return ucol_getSortKey(ucollator
, source
, sourceLength
, result
, resultLength
);
560 Collator::ECollationStrength
RuleBasedCollator::getStrength(void) const
562 UErrorCode intStatus
= U_ZERO_ERROR
;
563 return getECollationStrength(ucol_getAttribute(ucollator
, UCOL_STRENGTH
,
567 void RuleBasedCollator::setStrength(ECollationStrength newStrength
)
570 UErrorCode intStatus
= U_ZERO_ERROR
;
571 UCollationStrength strength
= getUCollationStrength(newStrength
);
572 ucol_setAttribute(ucollator
, UCOL_STRENGTH
, strength
, &intStatus
);
576 * Create a hash code for this collation. Just hash the main rule table -- that
577 * should be good enough for almost any use.
579 int32_t RuleBasedCollator::hashCode() const
582 const UChar
*rules
= ucol_getRules(ucollator
, &length
);
583 return uhash_hashUCharsN(rules
, length
);
587 * return the locale of this collator
589 const Locale
RuleBasedCollator::getLocale(ULocDataLocaleType type
, UErrorCode
&status
) const {
590 const char *result
= ucol_getLocale(ucollator
, type
, &status
);
596 return Locale(result
);
601 RuleBasedCollator::setLocales(const Locale
& requestedLocale
, const Locale
& validLocale
) {
603 size_t rlen
= uprv_strlen(requestedLocale
.getName());
604 char* rloc
= (char *)uprv_malloc((rlen
+1)*sizeof(char));
606 uprv_strcpy(rloc
, requestedLocale
.getName());
607 size_t vlen
= uprv_strlen(validLocale
.getName());
608 char* vloc
= (char*)uprv_malloc((vlen
+1)*sizeof(char));
610 uprv_strcpy(vloc
, validLocale
.getName());
611 ucol_setReqValidLocales(ucollator
, rloc
, vloc
);
618 // RuleBaseCollatorNew private constructor ----------------------------------
620 RuleBasedCollator::RuleBasedCollator()
621 : dataIsOwned(FALSE
), isWriteThroughAlias(FALSE
), ucollator(NULL
)
625 RuleBasedCollator::RuleBasedCollator(const Locale
& desiredLocale
,
627 : dataIsOwned(FALSE
), isWriteThroughAlias(FALSE
), ucollator(NULL
)
629 if (U_FAILURE(status
))
633 Try to load, in order:
634 1. The desired locale's collation.
635 2. A fallback of the desired locale.
636 3. The default locale's collation.
637 4. A fallback of the default locale.
638 5. The default collation rules, which contains en_US collation rules.
640 To reiterate, we try:
642 language+country+variant
646 language+country+variant
649 Root: (aka DEFAULTRULES)
650 steps 1-5 are handled by resource bundle fallback mechanism.
651 however, in a very unprobable situation that no resource bundle
652 data exists, step 5 is repeated with hardcoded default rules.
655 setUCollator(desiredLocale
, status
);
657 if (U_FAILURE(status
))
659 status
= U_ZERO_ERROR
;
661 setUCollator(kRootLocaleName
, status
);
662 if (status
== U_ZERO_ERROR
) {
663 status
= U_USING_DEFAULT_WARNING
;
667 if (U_SUCCESS(status
))
669 setRuleStringFromCollator();
674 RuleBasedCollator::setUCollator(const char *locale
,
677 if (U_FAILURE(status
))
679 if (ucollator
&& dataIsOwned
)
680 ucol_close(ucollator
);
681 ucollator
= ucol_open_internal(locale
, &status
);
683 isWriteThroughAlias
= FALSE
;
688 RuleBasedCollator::checkOwned() {
689 if (!(dataIsOwned
|| isWriteThroughAlias
)) {
690 UErrorCode status
= U_ZERO_ERROR
;
691 ucollator
= ucol_safeClone(ucollator
, NULL
, NULL
, &status
);
692 setRuleStringFromCollator();
694 isWriteThroughAlias
= FALSE
;
698 /* RuleBasedCollator private data members -------------------------------- */
702 * These should probably be enums (<=0xffff) or #defines (>0xffff)
703 * for better performance.
704 * Include ucol_imp.h and use its constants if possible.
705 * Only used in coleitr.h?!
709 /* need look up in .commit() */
710 const int32_t RuleBasedCollator::CHARINDEX
= 0x70000000;
711 /* Expand index follows */
712 const int32_t RuleBasedCollator::EXPANDCHARINDEX
= 0x7E000000;
713 /* contract indexes follows */
714 const int32_t RuleBasedCollator::CONTRACTCHARINDEX
= 0x7F000000;
715 /* unmapped character values */
716 const int32_t RuleBasedCollator::UNMAPPED
= 0xFFFFFFFF;
717 /* primary strength increment */
718 const int32_t RuleBasedCollator::PRIMARYORDERINCREMENT
= 0x00010000;
719 /* secondary strength increment */
720 const int32_t RuleBasedCollator::SECONDARYORDERINCREMENT
= 0x00000100;
721 /* tertiary strength increment */
722 const int32_t RuleBasedCollator::TERTIARYORDERINCREMENT
= 0x00000001;
723 /* mask off anything but primary order */
724 const int32_t RuleBasedCollator::PRIMARYORDERMASK
= 0xffff0000;
725 /* mask off anything but secondary order */
726 const int32_t RuleBasedCollator::SECONDARYORDERMASK
= 0x0000ff00;
727 /* mask off anything but tertiary order */
728 const int32_t RuleBasedCollator::TERTIARYORDERMASK
= 0x000000ff;
729 /* mask off ignorable char order */
730 const int32_t RuleBasedCollator::IGNORABLEMASK
= 0x0000ffff;
731 /* use only the primary difference */
732 const int32_t RuleBasedCollator::PRIMARYDIFFERENCEONLY
= 0xffff0000;
733 /* use only the primary and secondary difference */
734 const int32_t RuleBasedCollator::SECONDARYDIFFERENCEONLY
= 0xffffff00;
735 /* primary order shift */
736 const int32_t RuleBasedCollator::PRIMARYORDERSHIFT
= 16;
737 /* secondary order shift */
738 const int32_t RuleBasedCollator::SECONDARYORDERSHIFT
= 8;
739 /* starting value for collation elements */
740 const int32_t RuleBasedCollator::COLELEMENTSTART
= 0x02020202;
741 /* testing mask for primary low element */
742 const int32_t RuleBasedCollator::PRIMARYLOWZEROMASK
= 0x00FF0000;
743 /* reseting value for secondaries and tertiaries */
744 const int32_t RuleBasedCollator::RESETSECONDARYTERTIARY
= 0x00000202;
745 /* reseting value for tertiaries */
746 const int32_t RuleBasedCollator::RESETTERTIARY
= 0x00000002;
748 const int32_t RuleBasedCollator::PRIMIGNORABLE
= 0x0202;
750 UOBJECT_DEFINE_RTTI_IMPLEMENTATION(RuleBasedCollator
)
754 #endif /* #if !UCONFIG_NO_COLLATION */