]> git.saurik.com Git - apple/icu.git/blobdiff - icuSources/i18n/coll.cpp
ICU-511.34.tar.gz
[apple/icu.git] / icuSources / i18n / coll.cpp
index 6715a77ecfa75d16590b893bc42e367f0b790f57..9e9ca0239d0a269641120420a7f0e68512b793e1 100644 (file)
@@ -1,41 +1,43 @@
 /*
-******************************************************************************
-* Copyright (C) 1996-2004, International Business Machines Corporation and   *
-* others. All Rights Reserved.                                               *
-******************************************************************************
-*/
+ ******************************************************************************
+ * Copyright (C) 1996-2012, International Business Machines Corporation and
+ * others. All Rights Reserved.
+ ******************************************************************************
+ */
 
 /**
-* File coll.cpp
-*
-* Created by: Helena Shih
-*
-* Modification History:
-*
-*  Date        Name        Description
-*  2/5/97      aliu        Modified createDefault to load collation data from
-*                          binary files when possible.  Added related methods
-*                          createCollationFromFile, chopLocale, createPathName.
-*  2/11/97     aliu        Added methods addToCache, findInCache, which implement
-*                          a Collation cache.  Modified createDefault to look in
-*                          cache first, and also to store newly created Collation
-*                          objects in the cache.  Modified to not use gLocPath.
-*  2/12/97     aliu        Modified to create objects from RuleBasedCollator cache.
-*                          Moved cache out of Collation class.
-*  2/13/97     aliu        Moved several methods out of this class and into
-*                          RuleBasedCollator, with modifications.  Modified
-*                          createDefault() to call new RuleBasedCollator(Locale&)
-*                          constructor.  General clean up and documentation.
-*  2/20/97     helena      Added clone, operator==, operator!=, operator=, and copy
-*                          constructor.
-* 05/06/97     helena      Added memory allocation error detection.
-* 05/08/97     helena      Added createInstance().
-*  6/20/97     helena      Java class name change.
-* 04/23/99     stephen     Removed EDecompositionMode, merged with 
-*                          Normalizer::EMode
-* 11/23/9      srl         Inlining of some critical functions
-* 01/29/01     synwee      Modified into a C++ wrapper calling C APIs (ucol.h)
-*/
+ * File coll.cpp
+ *
+ * Created by: Helena Shih
+ *
+ * Modification History:
+ *
+ *  Date        Name        Description
+ *  2/5/97      aliu        Modified createDefault to load collation data from
+ *                          binary files when possible.  Added related methods
+ *                          createCollationFromFile, chopLocale, createPathName.
+ *  2/11/97     aliu        Added methods addToCache, findInCache, which implement
+ *                          a Collation cache.  Modified createDefault to look in
+ *                          cache first, and also to store newly created Collation
+ *                          objects in the cache.  Modified to not use gLocPath.
+ *  2/12/97     aliu        Modified to create objects from RuleBasedCollator cache.
+ *                          Moved cache out of Collation class.
+ *  2/13/97     aliu        Moved several methods out of this class and into
+ *                          RuleBasedCollator, with modifications.  Modified
+ *                          createDefault() to call new RuleBasedCollator(Locale&)
+ *                          constructor.  General clean up and documentation.
+ *  2/20/97     helena      Added clone, operator==, operator!=, operator=, and copy
+ *                          constructor.
+ * 05/06/97     helena      Added memory allocation error detection.
+ * 05/08/97     helena      Added createInstance().
+ *  6/20/97     helena      Java class name change.
+ * 04/23/99     stephen     Removed EDecompositionMode, merged with 
+ *                          Normalizer::EMode
+ * 11/23/9      srl         Inlining of some critical functions
+ * 01/29/01     synwee      Modified into a C++ wrapper calling C APIs (ucol.h)
+ */
+
+#include "utypeinfo.h"  // for 'typeid' to work
 
 #include "unicode/utypes.h"
 
 #include "unicode/coll.h"
 #include "unicode/tblcoll.h"
 #include "ucol_imp.h"
+#include "cstring.h"
 #include "cmemory.h"
-#include "mutex.h"
-#include "iculserv.h"
+#include "umutex.h"
+#include "servloc.h"
 #include "ustrenum.h"
+#include "uresimp.h"
 #include "ucln_in.h"
 
-U_NAMESPACE_BEGIN
-#if !UCONFIG_NO_SERVICE
-U_NAMESPACE_END
+static icu::Locale* availableLocaleList = NULL;
+static int32_t  availableLocaleListCount;
+static icu::ICULocaleService* gService = NULL;
 
-static ICULocaleService* gService = NULL;
 /**
  * Release all static memory held by collator.
  */
 U_CDECL_BEGIN
 static UBool U_CALLCONV collator_cleanup(void) {
+#if !UCONFIG_NO_SERVICE
     if (gService) {
         delete gService;
         gService = NULL;
     }
+#endif
+    if (availableLocaleList) {
+        delete []availableLocaleList;
+        availableLocaleList = NULL;
+    }
+    availableLocaleListCount = 0;
+
     return TRUE;
 }
+
 U_CDECL_END
 
 U_NAMESPACE_BEGIN
 
+#if !UCONFIG_NO_SERVICE
+
 // ------------------------------------------
 //
 // Registration
@@ -100,11 +114,14 @@ CollatorFactory::getDisplayName(const Locale& objectLocale,
 
 class ICUCollatorFactory : public ICUResourceBundleFactory {
  public:
-    ICUCollatorFactory():  ICUResourceBundleFactory(UnicodeString(U_ICUDATA_COLL, (char*)NULL)) { } 
+    ICUCollatorFactory() : ICUResourceBundleFactory(UnicodeString(U_ICUDATA_COLL, -1, US_INV)) { }
+    virtual ~ICUCollatorFactory();
  protected:
     virtual UObject* create(const ICUServiceKey& key, const ICUService* service, UErrorCode& status) const;
 };
 
+ICUCollatorFactory::~ICUCollatorFactory() {}
+
 UObject*
 ICUCollatorFactory::create(const ICUServiceKey& key, const ICUService* /* service */, UErrorCode& status) const {
     if (handlesKey(key, status)) {
@@ -125,12 +142,14 @@ ICUCollatorFactory::create(const ICUServiceKey& key, const ICUService* /* servic
 class ICUCollatorService : public ICULocaleService {
 public:
     ICUCollatorService()
-        : ICULocaleService("Collator")
+        : ICULocaleService(UNICODE_STRING_SIMPLE("Collator"))
     {
         UErrorCode status = U_ZERO_ERROR;
         registerFactory(new ICUCollatorFactory(), status);
     }
-    
+
+    virtual ~ICUCollatorService();
+
     virtual UObject* cloneInstance(UObject* instance) const {
         return ((Collator*)instance)->clone();
     }
@@ -165,8 +184,8 @@ public:
             Locale canonicalLocale("");
             Locale currentLocale("");
             
-            result->setLocales(lkey.canonicalLocale(canonicalLocale), 
-                LocaleUtility::initLocaleFromName(*actualReturn, currentLocale));
+            LocaleUtility::initLocaleFromName(*actualReturn, currentLocale);
+            result->setLocales(lkey.canonicalLocale(canonicalLocale), currentLocale, currentLocale);
         }
         return result;
     }
@@ -176,34 +195,30 @@ public:
     }
 };
 
-// -------------------------------------
+ICUCollatorService::~ICUCollatorService() {}
 
-class ICUCollatorService;
+// -------------------------------------
 
 static ICULocaleService* 
 getService(void)
 {
     UBool needInit;
-    {
-        Mutex mutex;
-        needInit = (UBool)(gService == NULL);
-    }
+    UMTX_CHECK(NULL, (UBool)(gService == NULL), needInit);
     if(needInit) {
         ICULocaleService *newservice = new ICUCollatorService();
         if(newservice) {
-            Mutex mutex;
+            umtx_lock(NULL);
             if(gService == NULL) {
                 gService = newservice;
                 newservice = NULL;
             }
+            umtx_unlock(NULL);
         }
         if(newservice) {
             delete newservice;
         }
         else {
-#if !UCONFIG_NO_SERVICE
             ucln_i18n_registerCleanup(UCLN_I18N_COLLATOR, collator_cleanup);
-#endif
         }
     }
     return gService;
@@ -211,11 +226,12 @@ getService(void)
 
 // -------------------------------------
 
-static UBool
+static inline UBool
 hasService(void) 
 {
-    Mutex mutex;
-    return gService != NULL;
+    UBool retVal;
+    UMTX_CHECK(NULL, gService != NULL, retVal);
+    return retVal;
 }
 
 // -------------------------------------
@@ -228,14 +244,25 @@ Collator::createUCollator(const char *loc,
     if (status && U_SUCCESS(*status) && hasService()) {
         Locale desiredLocale(loc);
         Collator *col = (Collator*)gService->get(desiredLocale, *status);
-        if (col && col->getDynamicClassID() == RuleBasedCollator::getStaticClassID()) {
-            RuleBasedCollator *rbc = (RuleBasedCollator *)col;
+        RuleBasedCollator *rbc;
+        if (col && (rbc = dynamic_cast<RuleBasedCollator *>(col))) {
             if (!rbc->dataIsOwned) {
                 result = ucol_safeClone(rbc->ucollator, NULL, NULL, status);
             } else {
                 result = rbc->ucollator;
                 rbc->ucollator = NULL; // to prevent free on delete
             }
+        } else {
+          // should go in a function- ucol_initDelegate(delegate)
+          result = (UCollator *)uprv_malloc(sizeof(UCollator));
+          if(result == NULL) {
+            *status = U_MEMORY_ALLOCATION_ERROR;
+          } else {
+            uprv_memset(result, 0, sizeof(UCollator));
+            result->delegate = col;
+            result->freeOnClose = TRUE; // do free on close.
+            col = NULL; // to prevent free on delete.
+          }
         }
         delete col;
     }
@@ -243,6 +270,57 @@ Collator::createUCollator(const char *loc,
 }
 #endif /* UCONFIG_NO_SERVICE */
 
+static UBool isAvailableLocaleListInitialized(UErrorCode &status) {
+    // for now, there is a hardcoded list, so just walk through that list and set it up.
+    UBool needInit;
+    UMTX_CHECK(NULL, availableLocaleList == NULL, needInit);
+
+    if (needInit) {
+        UResourceBundle *index = NULL;
+        UResourceBundle installed;
+        Locale * temp;
+        int32_t i = 0;
+        int32_t localeCount;
+        
+        ures_initStackObject(&installed);
+        index = ures_openDirect(U_ICUDATA_COLL, "res_index", &status);
+        ures_getByKey(index, "InstalledLocales", &installed, &status);
+        
+        if(U_SUCCESS(status)) {
+            localeCount = ures_getSize(&installed);
+            temp = new Locale[localeCount];
+            
+            if (temp != NULL) {
+                ures_resetIterator(&installed);
+                while(ures_hasNext(&installed)) {
+                    const char *tempKey = NULL;
+                    ures_getNextString(&installed, NULL, &tempKey, &status);
+                    temp[i++] = Locale(tempKey);
+                }
+                
+                umtx_lock(NULL);
+                if (availableLocaleList == NULL)
+                {
+                    availableLocaleListCount = localeCount;
+                    availableLocaleList = temp;
+                    temp = NULL;
+                    ucln_i18n_registerCleanup(UCLN_I18N_COLLATOR, collator_cleanup);
+                } 
+                umtx_unlock(NULL);
+
+                needInit = FALSE;
+                if (temp) {
+                    delete []temp;
+                }
+            }
+
+            ures_close(&installed);
+        }
+        ures_close(index);
+    }
+    return !needInit;
+}
+
 // Collator public methods -----------------------------------------------
 
 Collator* U_EXPORT2 Collator::createInstance(UErrorCode& success) 
@@ -261,6 +339,7 @@ Collator* U_EXPORT2 Collator::createInstance(const Locale& desiredLocale,
         Locale actualLoc;
         Collator *result =
             (Collator*)gService->get(desiredLocale, &actualLoc, status);
+
         // Ugly Hack Alert! If the returned locale is empty (not root,
         // but empty -- getName() == "") then that means the service
         // returned a default object, not a "real" service object.  In
@@ -268,7 +347,7 @@ Collator* U_EXPORT2 Collator::createInstance(const Locale& desiredLocale,
         // correctly already, and we don't want to overwrite it. (TODO
         // remove in 3.0) [aliu]
         if (*actualLoc.getName() != 0) {
-            result->setLocales(desiredLocale, actualLoc);
+            result->setLocales(desiredLocale, actualLoc, actualLoc);
         }
         return result;
     }
@@ -291,7 +370,7 @@ Collator* Collator::makeInstance(const Locale&  desiredLocale,
     // non-table-based Collator in some other way, when it sees that it needs 
     // to.
     // The specific caution is this: RuleBasedCollator(Locale&) will ALWAYS 
-    // return a valid collation object, if the system if functioning properly.  
+    // return a valid collation object, if the system is functioning properly.  
     // The reason is that it will fall back, use the default locale, and even 
     // use the built-in default collation rules. THEREFORE, createInstance() 
     // should in general ONLY CALL RuleBasedCollator(Locale&) IF IT KNOWS IN 
@@ -346,12 +425,17 @@ Collator::createInstance(const Locale &loc,
 }
 #endif
 
+Collator *
+Collator::safeClone() const {
+    return clone();
+}
+
 // implement deprecated, previously abstract method
 Collator::EComparisonResult Collator::compare(const UnicodeString& source, 
                                     const UnicodeString& target) const
 {
     UErrorCode ec = U_ZERO_ERROR;
-    return (Collator::EComparisonResult)compare(source, target, ec);
+    return (EComparisonResult)compare(source, target, ec);
 }
 
 // implement deprecated, previously abstract method
@@ -360,7 +444,7 @@ Collator::EComparisonResult Collator::compare(const UnicodeString& source,
                                     int32_t length) const
 {
     UErrorCode ec = U_ZERO_ERROR;
-    return (Collator::EComparisonResult)compare(source, target, length, ec);
+    return (EComparisonResult)compare(source, target, length, ec);
 }
 
 // implement deprecated, previously abstract method
@@ -369,7 +453,29 @@ Collator::EComparisonResult Collator::compare(const UChar* source, int32_t sourc
                                     const
 {
     UErrorCode ec = U_ZERO_ERROR;
-    return (Collator::EComparisonResult)compare(source, sourceLength, target, targetLength, ec);
+    return (EComparisonResult)compare(source, sourceLength, target, targetLength, ec);
+}
+
+UCollationResult Collator::compare(UCharIterator &/*sIter*/,
+                                   UCharIterator &/*tIter*/,
+                                   UErrorCode &status) const {
+    if(U_SUCCESS(status)) {
+        // Not implemented in the base class.
+        status = U_UNSUPPORTED_ERROR;
+    }
+    return UCOL_EQUAL;
+}
+
+UCollationResult Collator::compareUTF8(const StringPiece &source,
+                                       const StringPiece &target,
+                                       UErrorCode &status) const {
+    if(U_FAILURE(status)) {
+        return UCOL_EQUAL;
+    }
+    UCharIterator sIter, tIter;
+    uiter_setUTF8(&sIter, source.data(), source.length());
+    uiter_setUTF8(&tIter, target.data(), target.length());
+    return compare(sIter, tIter, status);
 }
 
 UBool Collator::equals(const UnicodeString& source, 
@@ -397,7 +503,15 @@ UBool Collator::greater(const UnicodeString& source,
 // array of indefinite lifetime
 const Locale* U_EXPORT2 Collator::getAvailableLocales(int32_t& count) 
 {
-    return Locale::getAvailableLocales(count);
+    UErrorCode status = U_ZERO_ERROR;
+    Locale *result = NULL;
+    count = 0;
+    if (isAvailableLocaleListInitialized(status))
+    {
+        result = availableLocaleList;
+        count = availableLocaleListCount;
+    }
+    return result;
 }
 
 UnicodeString& U_EXPORT2 Collator::getDisplayName(const Locale& objectLocale,
@@ -406,7 +520,9 @@ UnicodeString& U_EXPORT2 Collator::getDisplayName(const Locale& objectLocale,
 {
 #if !UCONFIG_NO_SERVICE
     if (hasService()) {
-        return gService->getDisplayName(objectLocale.getName(), name, displayLocale);
+        UnicodeString locNameStr;
+        LocaleUtility::initNameFromLocale(objectLocale, locNameStr);
+        return gService->getDisplayName(locNameStr, name, displayLocale);
     }
 #endif
     return objectLocale.getDisplayName(displayLocale, name);
@@ -465,7 +581,8 @@ Collator::Collator(const Collator &other)
 
 UBool Collator::operator==(const Collator& other) const
 {
-    return (UBool)(this == &other);
+    // Subclasses: Call this method and then add more specific checks.
+    return typeid(*this) == typeid(other);
 }
 
 UBool Collator::operator!=(const Collator& other) const
@@ -485,7 +602,7 @@ int32_t U_EXPORT2 Collator::getBound(const uint8_t       *source,
 }
 
 void
-Collator::setLocales(const Locale& /* requestedLocale */, const Locale& /* validLocale */) {
+Collator::setLocales(const Locale& /* requestedLocale */, const Locale& /* validLocale */, const Locale& /*actualLocale*/) {
 }
 
 UnicodeSet *Collator::getTailoredSet(UErrorCode &status) const
@@ -540,13 +657,9 @@ public:
             }
         }
     }
-    
-    virtual ~CFactory()
-    {
-        delete _delegate;
-        delete _ids;
-    }
-    
+
+    virtual ~CFactory();
+
     virtual UObject* create(const ICUServiceKey& key, const ICUService* service, UErrorCode& status) const;
     
 protected:
@@ -562,6 +675,12 @@ protected:
         getDisplayName(const UnicodeString& id, const Locale& locale, UnicodeString& result) const;
 };
 
+CFactory::~CFactory()
+{
+    delete _delegate;
+    delete _ids;
+}
+
 UObject* 
 CFactory::create(const ICUServiceKey& key, const ICUService* /* service */, UErrorCode& status) const
 {
@@ -616,15 +735,85 @@ Collator::unregister(URegistryKey key, UErrorCode& status)
     }
     return FALSE;
 }
+#endif /* UCONFIG_NO_SERVICE */
+
+class CollationLocaleListEnumeration : public StringEnumeration {
+private:
+    int32_t index;
+public:
+    static UClassID U_EXPORT2 getStaticClassID(void);
+    virtual UClassID getDynamicClassID(void) const;
+public:
+    CollationLocaleListEnumeration()
+        : index(0)
+    {
+        // The global variables should already be initialized.
+        //isAvailableLocaleListInitialized(status);
+    }
+
+    virtual ~CollationLocaleListEnumeration();
+
+    virtual StringEnumeration * clone() const
+    {
+        CollationLocaleListEnumeration *result = new CollationLocaleListEnumeration();
+        if (result) {
+            result->index = index;
+        }
+        return result;
+    }
+
+    virtual int32_t count(UErrorCode &/*status*/) const {
+        return availableLocaleListCount;
+    }
+
+    virtual const char* next(int32_t* resultLength, UErrorCode& /*status*/) {
+        const char* result;
+        if(index < availableLocaleListCount) {
+            result = availableLocaleList[index++].getName();
+            if(resultLength != NULL) {
+                *resultLength = (int32_t)uprv_strlen(result);
+            }
+        } else {
+            if(resultLength != NULL) {
+                *resultLength = 0;
+            }
+            result = NULL;
+        }
+        return result;
+    }
+
+    virtual const UnicodeString* snext(UErrorCode& status) {
+        int32_t resultLength = 0;
+        const char *s = next(&resultLength, status);
+        return setChars(s, resultLength, status);
+    }
+
+    virtual void reset(UErrorCode& /*status*/) {
+        index = 0;
+    }
+};
+
+CollationLocaleListEnumeration::~CollationLocaleListEnumeration() {}
+
+UOBJECT_DEFINE_RTTI_IMPLEMENTATION(CollationLocaleListEnumeration)
+
 
 // -------------------------------------
 
 StringEnumeration* U_EXPORT2
 Collator::getAvailableLocales(void)
 {
-    return getService()->getAvailableLocales();
-}
+#if !UCONFIG_NO_SERVICE
+    if (hasService()) {
+        return getService()->getAvailableLocales();
+    }
 #endif /* UCONFIG_NO_SERVICE */
+    UErrorCode status = U_ZERO_ERROR;
+    if (isAvailableLocaleListInitialized(status)) {
+        return new CollationLocaleListEnumeration();
+    }
+    return NULL;
+}
 
 StringEnumeration* U_EXPORT2
 Collator::getKeywords(UErrorCode& status) {
@@ -648,6 +837,19 @@ Collator::getKeywordValues(const char *keyword, UErrorCode& status) {
     return new UStringEnumeration(uenum);
 }
 
+StringEnumeration* U_EXPORT2
+Collator::getKeywordValuesForLocale(const char* key, const Locale& locale,
+                                    UBool commonlyUsed, UErrorCode& status) {
+    // This is a wrapper over ucol_getKeywordValuesForLocale
+    UEnumeration *uenum = ucol_getKeywordValuesForLocale(key, locale.getName(),
+                                                        commonlyUsed, &status);
+    if (U_FAILURE(status)) {
+        uenum_close(uenum);
+        return NULL;
+    }
+    return new UStringEnumeration(uenum);
+}
+
 Locale U_EXPORT2
 Collator::getFunctionalEquivalent(const char* keyword, const Locale& locale,
                                   UBool& isAvailable, UErrorCode& status) {
@@ -661,6 +863,62 @@ Collator::getFunctionalEquivalent(const char* keyword, const Locale& locale,
     return Locale::createFromName(loc);
 }
 
+Collator::ECollationStrength
+Collator::getStrength(void) const {
+    UErrorCode intStatus = U_ZERO_ERROR;
+    return (ECollationStrength)getAttribute(UCOL_STRENGTH, intStatus);
+}
+
+void
+Collator::setStrength(ECollationStrength newStrength) {
+    UErrorCode intStatus = U_ZERO_ERROR;
+    setAttribute(UCOL_STRENGTH, (UColAttributeValue)newStrength, intStatus);
+}
+
+int32_t
+Collator::getReorderCodes(int32_t* /* dest*/,
+                          int32_t /* destCapacity*/,
+                          UErrorCode& status) const
+{
+    if (U_SUCCESS(status)) {
+        status = U_UNSUPPORTED_ERROR;
+    }
+    return 0;
+}
+
+void
+Collator::setReorderCodes(const int32_t* /* reorderCodes */,
+                          int32_t /* reorderCodesLength */,
+                          UErrorCode& status)
+{
+    if (U_SUCCESS(status)) {
+        status = U_UNSUPPORTED_ERROR;
+    }
+}
+
+int32_t U_EXPORT2
+Collator::getEquivalentReorderCodes(int32_t /* reorderCode */,
+                                    int32_t* /* dest */,
+                                    int32_t /* destCapacity */,
+                                    UErrorCode& status)
+{
+    if (U_SUCCESS(status)) {
+        status = U_UNSUPPORTED_ERROR;
+    }
+    return 0;
+}
+
+int32_t
+Collator::internalGetShortDefinitionString(const char * /*locale*/,
+                                                             char * /*buffer*/,
+                                                             int32_t /*capacity*/,
+                                                             UErrorCode &status) const {
+  if(U_SUCCESS(status)) {
+    status = U_UNSUPPORTED_ERROR; /* Shouldn't happen, internal function */
+  }
+  return 0;
+}
+
 // UCollator private data members ----------------------------------------
 
 /* This is useless information */