• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // © 2016 and later: Unicode, Inc. and others.
2 // License & terms of use: http://www.unicode.org/copyright.html
3 /*
4 *******************************************************************************
5 * Copyright (C) 2014-2016, International Business Machines Corporation and
6 * others. All Rights Reserved.
7 *******************************************************************************
8 *
9 *
10 * File REGION.CPP
11 *
12 * Modification History:*
13 *   Date        Name        Description
14 * 01/15/13      Emmons      Original Port from ICU4J
15 ********************************************************************************
16 */
17 
18 /**
19  * \file
20  * \brief C++ API: Region classes (territory containment)
21  */
22 
23 #include "unicode/region.h"
24 #include "unicode/utypes.h"
25 #include "unicode/uobject.h"
26 #include "unicode/unistr.h"
27 #include "unicode/ures.h"
28 #include "ucln_in.h"
29 #include "cstring.h"
30 #include "mutex.h"
31 #include "uhash.h"
32 #include "umutex.h"
33 #include "uresimp.h"
34 #include "region_impl.h"
35 #include "util.h"
36 
37 #if !UCONFIG_NO_FORMATTING
38 
39 
40 U_CDECL_BEGIN
41 
42 static void U_CALLCONV
deleteRegion(void * obj)43 deleteRegion(void *obj) {
44     delete (icu::Region *)obj;
45 }
46 
47 /**
48  * Cleanup callback func
49  */
region_cleanup(void)50 static UBool U_CALLCONV region_cleanup(void)
51 {
52     icu::Region::cleanupRegionData();
53 
54     return TRUE;
55 }
56 
57 U_CDECL_END
58 
59 U_NAMESPACE_BEGIN
60 
61 static UInitOnce gRegionDataInitOnce = U_INITONCE_INITIALIZER;
62 static UVector* availableRegions[URGN_LIMIT];
63 
64 static UHashtable *regionAliases = NULL;
65 static UHashtable *regionIDMap = NULL;
66 static UHashtable *numericCodeMap = NULL;
67 static UVector *allRegions = NULL;
68 
69 static const UChar UNKNOWN_REGION_ID [] = { 0x5A, 0x5A, 0 };  /* "ZZ" */
70 static const UChar OUTLYING_OCEANIA_REGION_ID [] = { 0x51, 0x4F, 0 };  /* "QO" */
71 static const UChar WORLD_ID [] = { 0x30, 0x30, 0x31, 0 };  /* "001" */
72 static const UChar RANGE_MARKER = 0x7E; /* '~' */
73 
UOBJECT_DEFINE_RTTI_IMPLEMENTATION(RegionNameEnumeration)74 UOBJECT_DEFINE_RTTI_IMPLEMENTATION(RegionNameEnumeration)
75 
76 /*
77  * Initializes the region data from the ICU resource bundles.  The region data
78  * contains the basic relationships such as which regions are known, what the numeric
79  * codes are, any known aliases, and the territory containment data.
80  *
81  * If the region data has already loaded, then this method simply returns without doing
82  * anything meaningful.
83  */
84 void U_CALLCONV Region::loadRegionData(UErrorCode &status) {
85 
86     // Construct service objs first
87     LocalUHashtablePointer newRegionIDMap(uhash_open(uhash_hashUnicodeString, uhash_compareUnicodeString, NULL, &status));
88     LocalUHashtablePointer newNumericCodeMap(uhash_open(uhash_hashLong,uhash_compareLong,NULL,&status));
89     LocalUHashtablePointer newRegionAliases(uhash_open(uhash_hashUnicodeString,uhash_compareUnicodeString,NULL,&status));
90 
91     LocalPointer<UVector> continents(new UVector(uprv_deleteUObject, uhash_compareUnicodeString, status), status);
92     LocalPointer<UVector> groupings(new UVector(uprv_deleteUObject, uhash_compareUnicodeString, status), status);
93     allRegions = new UVector(uprv_deleteUObject, uhash_compareUnicodeString, status);
94 
95     LocalUResourceBundlePointer metadata(ures_openDirect(NULL,"metadata",&status));
96     LocalUResourceBundlePointer metadataAlias(ures_getByKey(metadata.getAlias(),"alias",NULL,&status));
97     LocalUResourceBundlePointer territoryAlias(ures_getByKey(metadataAlias.getAlias(),"territory",NULL,&status));
98 
99     LocalUResourceBundlePointer supplementalData(ures_openDirect(NULL,"supplementalData",&status));
100     LocalUResourceBundlePointer codeMappings(ures_getByKey(supplementalData.getAlias(),"codeMappings",NULL,&status));
101 
102     LocalUResourceBundlePointer idValidity(ures_getByKey(supplementalData.getAlias(),"idValidity",NULL,&status));
103     LocalUResourceBundlePointer regionList(ures_getByKey(idValidity.getAlias(),"region",NULL,&status));
104     LocalUResourceBundlePointer regionRegular(ures_getByKey(regionList.getAlias(),"regular",NULL,&status));
105     LocalUResourceBundlePointer regionMacro(ures_getByKey(regionList.getAlias(),"macroregion",NULL,&status));
106     LocalUResourceBundlePointer regionUnknown(ures_getByKey(regionList.getAlias(),"unknown",NULL,&status));
107 
108     LocalUResourceBundlePointer territoryContainment(ures_getByKey(supplementalData.getAlias(),"territoryContainment",NULL,&status));
109     LocalUResourceBundlePointer worldContainment(ures_getByKey(territoryContainment.getAlias(),"001",NULL,&status));
110     LocalUResourceBundlePointer groupingContainment(ures_getByKey(territoryContainment.getAlias(),"grouping",NULL,&status));
111 
112     if (U_FAILURE(status)) {
113         return;
114     }
115 
116     // now, initialize
117     uhash_setValueDeleter(newRegionIDMap.getAlias(), deleteRegion);  // regionIDMap owns objs
118     uhash_setKeyDeleter(newRegionAliases.getAlias(), uprv_deleteUObject); // regionAliases owns the string keys
119 
120 
121     while ( ures_hasNext(regionRegular.getAlias()) ) {
122         UnicodeString regionName = ures_getNextUnicodeString(regionRegular.getAlias(),NULL,&status);
123         int32_t rangeMarkerLocation = regionName.indexOf(RANGE_MARKER);
124         UChar buf[6];
125         regionName.extract(buf,6,status);
126         if ( rangeMarkerLocation > 0 ) {
127             UChar endRange = regionName.charAt(rangeMarkerLocation+1);
128             buf[rangeMarkerLocation] = 0;
129             while ( buf[rangeMarkerLocation-1] <= endRange ) {
130                 LocalPointer<UnicodeString> newRegion(new UnicodeString(buf), status);
131                 allRegions->addElementX(newRegion.orphan(),status);
132                 buf[rangeMarkerLocation-1]++;
133             }
134         } else {
135             LocalPointer<UnicodeString> newRegion(new UnicodeString(regionName), status);
136             allRegions->addElementX(newRegion.orphan(),status);
137         }
138     }
139 
140     while ( ures_hasNext(regionMacro.getAlias()) ) {
141         UnicodeString regionName = ures_getNextUnicodeString(regionMacro.getAlias(),NULL,&status);
142         int32_t rangeMarkerLocation = regionName.indexOf(RANGE_MARKER);
143         UChar buf[6];
144         regionName.extract(buf,6,status);
145         if ( rangeMarkerLocation > 0 ) {
146             UChar endRange = regionName.charAt(rangeMarkerLocation+1);
147             buf[rangeMarkerLocation] = 0;
148             while ( buf[rangeMarkerLocation-1] <= endRange ) {
149                 LocalPointer<UnicodeString> newRegion(new UnicodeString(buf), status);
150                 allRegions->addElementX(newRegion.orphan(),status);
151                 buf[rangeMarkerLocation-1]++;
152             }
153         } else {
154             LocalPointer<UnicodeString> newRegion(new UnicodeString(regionName), status);
155             allRegions->addElementX(newRegion.orphan(),status);
156         }
157     }
158 
159     while ( ures_hasNext(regionUnknown.getAlias()) ) {
160         LocalPointer<UnicodeString> regionName (new UnicodeString(ures_getNextUnicodeString(regionUnknown.getAlias(),NULL,&status),status));
161         allRegions->addElementX(regionName.orphan(),status);
162     }
163 
164     while ( ures_hasNext(worldContainment.getAlias()) ) {
165         UnicodeString *continentName = new UnicodeString(ures_getNextUnicodeString(worldContainment.getAlias(),NULL,&status));
166         continents->addElementX(continentName,status);
167     }
168 
169     for ( int32_t i = 0 ; i < allRegions->size() ; i++ ) {
170         LocalPointer<Region> r(new Region(), status);
171         if ( U_FAILURE(status) ) {
172            return;
173         }
174         UnicodeString *regionName = (UnicodeString *)allRegions->elementAt(i);
175         r->idStr = *regionName;
176 
177         r->idStr.extract(0,r->idStr.length(),r->id,sizeof(r->id),US_INV);
178         r->fType = URGN_TERRITORY; // Only temporary - figure out the real type later once the aliases are known.
179 
180         int32_t pos = 0;
181         int32_t result = ICU_Utility::parseAsciiInteger(r->idStr, pos);
182         if (pos > 0) {
183             r->code = result; // Convert string to number
184             uhash_iput(newNumericCodeMap.getAlias(),r->code,(void *)(r.getAlias()),&status);
185             r->fType = URGN_SUBCONTINENT;
186         } else {
187             r->code = -1;
188         }
189         void* idStrAlias = (void*)&(r->idStr); // about to orphan 'r'. Save this off.
190         uhash_put(newRegionIDMap.getAlias(),idStrAlias,(void *)(r.orphan()),&status); // regionIDMap takes ownership
191     }
192 
193     UResourceBundle *groupingBundle = nullptr;
194     while ( ures_hasNext(groupingContainment.getAlias()) ) {
195         groupingBundle = ures_getNextResource(groupingContainment.getAlias(), groupingBundle, &status);
196         if (U_FAILURE(status)) {
197             break;
198         }
199         UnicodeString *groupingName = new UnicodeString(ures_getKey(groupingBundle), -1, US_INV);
200         groupings->addElementX(groupingName,status);
201         Region *grouping = (Region *) uhash_get(newRegionIDMap.getAlias(),groupingName);
202         if (grouping != NULL) {
203             for (int32_t i = 0; i < ures_getSize(groupingBundle); i++) {
204                 UnicodeString child = ures_getUnicodeStringByIndex(groupingBundle, i, &status);
205                 if (U_SUCCESS(status)) {
206                     if (grouping->containedRegions == NULL) {
207                         grouping->containedRegions = new UVector(uprv_deleteUObject, uhash_compareUnicodeString, status);
208                     }
209                     grouping->containedRegions->addElementX(new UnicodeString(child), status);
210                 }
211             }
212         }
213     }
214     ures_close(groupingBundle);
215 
216     // Process the territory aliases
217     while ( ures_hasNext(territoryAlias.getAlias()) ) {
218         LocalUResourceBundlePointer res(ures_getNextResource(territoryAlias.getAlias(),NULL,&status));
219         const char *aliasFrom = ures_getKey(res.getAlias());
220         LocalPointer<UnicodeString> aliasFromStr(new UnicodeString(aliasFrom, -1, US_INV), status);
221         UnicodeString aliasTo = ures_getUnicodeStringByKey(res.getAlias(),"replacement",&status);
222         res.adoptInstead(NULL);
223 
224         const Region *aliasToRegion = (Region *) uhash_get(newRegionIDMap.getAlias(),&aliasTo);
225         Region *aliasFromRegion = (Region *)uhash_get(newRegionIDMap.getAlias(),aliasFromStr.getAlias());
226 
227         if ( aliasToRegion != NULL && aliasFromRegion == NULL ) { // This is just an alias from some string to a region
228             uhash_put(newRegionAliases.getAlias(),(void *)aliasFromStr.orphan(), (void *)aliasToRegion,&status);
229         } else {
230             if ( aliasFromRegion == NULL ) { // Deprecated region code not in the primary codes list - so need to create a deprecated region for it.
231                 LocalPointer<Region> newRgn(new Region, status);
232                 if ( U_SUCCESS(status) ) {
233                     aliasFromRegion = newRgn.orphan();
234                 } else {
235                     return; // error out
236                 }
237                 aliasFromRegion->idStr.setTo(*aliasFromStr);
238                 aliasFromRegion->idStr.extract(0,aliasFromRegion->idStr.length(),aliasFromRegion->id,sizeof(aliasFromRegion->id),US_INV);
239                 uhash_put(newRegionIDMap.getAlias(),(void *)&(aliasFromRegion->idStr),(void *)aliasFromRegion,&status);
240                 int32_t pos = 0;
241                 int32_t result = ICU_Utility::parseAsciiInteger(aliasFromRegion->idStr, pos);
242                 if ( pos > 0 ) {
243                     aliasFromRegion->code = result; // Convert string to number
244                     uhash_iput(newNumericCodeMap.getAlias(),aliasFromRegion->code,(void *)aliasFromRegion,&status);
245                 } else {
246                     aliasFromRegion->code = -1;
247                 }
248                 aliasFromRegion->fType = URGN_DEPRECATED;
249             } else {
250                 aliasFromRegion->fType = URGN_DEPRECATED;
251             }
252 
253             {
254                 LocalPointer<UVector> newPreferredValues(new UVector(uprv_deleteUObject, uhash_compareUnicodeString, status), status);
255                 aliasFromRegion->preferredValues = newPreferredValues.orphan();
256             }
257             if( U_FAILURE(status)) {
258                 return;
259             }
260             UnicodeString currentRegion;
261             //currentRegion.remove();   TODO: was already 0 length?
262             for (int32_t i = 0 ; i < aliasTo.length() ; i++ ) {
263                 if ( aliasTo.charAt(i) != 0x0020 ) {
264                     currentRegion.append(aliasTo.charAt(i));
265                 }
266                 if ( aliasTo.charAt(i) == 0x0020 || i+1 == aliasTo.length() ) {
267                     Region *target = (Region *)uhash_get(newRegionIDMap.getAlias(),(void *)&currentRegion);
268                     if (target) {
269                         LocalPointer<UnicodeString> preferredValue(new UnicodeString(target->idStr), status);
270                         aliasFromRegion->preferredValues->addElementX((void *)preferredValue.orphan(),status);  // may add null if err
271                     }
272                     currentRegion.remove();
273                 }
274             }
275         }
276     }
277 
278     // Process the code mappings - This will allow us to assign numeric codes to most of the territories.
279     while ( ures_hasNext(codeMappings.getAlias()) ) {
280         UResourceBundle *mapping = ures_getNextResource(codeMappings.getAlias(),NULL,&status);
281         if ( ures_getType(mapping) == URES_ARRAY && ures_getSize(mapping) == 3) {
282             UnicodeString codeMappingID = ures_getUnicodeStringByIndex(mapping,0,&status);
283             UnicodeString codeMappingNumber = ures_getUnicodeStringByIndex(mapping,1,&status);
284             UnicodeString codeMapping3Letter = ures_getUnicodeStringByIndex(mapping,2,&status);
285 
286             Region *r = (Region *)uhash_get(newRegionIDMap.getAlias(),(void *)&codeMappingID);
287             if ( r ) {
288                 int32_t pos = 0;
289                 int32_t result = ICU_Utility::parseAsciiInteger(codeMappingNumber, pos);
290                 if ( pos > 0 ) {
291                     r->code = result; // Convert string to number
292                     uhash_iput(newNumericCodeMap.getAlias(),r->code,(void *)r,&status);
293                 }
294                 LocalPointer<UnicodeString> code3(new UnicodeString(codeMapping3Letter), status);
295                 uhash_put(newRegionAliases.getAlias(),(void *)code3.orphan(), (void *)r,&status);
296             }
297         }
298         ures_close(mapping);
299     }
300 
301     // Now fill in the special cases for WORLD, UNKNOWN, CONTINENTS, and GROUPINGS
302     Region *r;
303     UnicodeString WORLD_ID_STRING(WORLD_ID);
304     r = (Region *) uhash_get(newRegionIDMap.getAlias(),(void *)&WORLD_ID_STRING);
305     if ( r ) {
306         r->fType = URGN_WORLD;
307     }
308 
309     UnicodeString UNKNOWN_REGION_ID_STRING(UNKNOWN_REGION_ID);
310     r = (Region *) uhash_get(newRegionIDMap.getAlias(),(void *)&UNKNOWN_REGION_ID_STRING);
311     if ( r ) {
312         r->fType = URGN_UNKNOWN;
313     }
314 
315     for ( int32_t i = 0 ; i < continents->size() ; i++ ) {
316         r = (Region *) uhash_get(newRegionIDMap.getAlias(),(void *)continents->elementAt(i));
317         if ( r ) {
318             r->fType = URGN_CONTINENT;
319         }
320     }
321 
322     for ( int32_t i = 0 ; i < groupings->size() ; i++ ) {
323         r = (Region *) uhash_get(newRegionIDMap.getAlias(),(void *)groupings->elementAt(i));
324         if ( r ) {
325             r->fType = URGN_GROUPING;
326         }
327     }
328 
329     // Special case: The region code "QO" (Outlying Oceania) is a subcontinent code added by CLDR
330     // even though it looks like a territory code.  Need to handle it here.
331 
332     UnicodeString OUTLYING_OCEANIA_REGION_ID_STRING(OUTLYING_OCEANIA_REGION_ID);
333     r = (Region *) uhash_get(newRegionIDMap.getAlias(),(void *)&OUTLYING_OCEANIA_REGION_ID_STRING);
334     if ( r ) {
335         r->fType = URGN_SUBCONTINENT;
336     }
337 
338     // Load territory containment info from the supplemental data.
339     while ( ures_hasNext(territoryContainment.getAlias()) ) {
340         LocalUResourceBundlePointer mapping(ures_getNextResource(territoryContainment.getAlias(),NULL,&status));
341         if( U_FAILURE(status) ) {
342             return;  // error out
343         }
344         const char *parent = ures_getKey(mapping.getAlias());
345         if (uprv_strcmp(parent, "containedGroupings") == 0 || uprv_strcmp(parent, "deprecated") == 0) {
346             continue; // handle new pseudo-parent types added in ICU data per cldrbug 7808; for now just skip.
347             // #11232 is to do something useful with these.
348         }
349         UnicodeString parentStr = UnicodeString(parent, -1 , US_INV);
350         Region *parentRegion = (Region *) uhash_get(newRegionIDMap.getAlias(),(void *)&parentStr);
351 
352         for ( int j = 0 ; j < ures_getSize(mapping.getAlias()); j++ ) {
353             UnicodeString child = ures_getUnicodeStringByIndex(mapping.getAlias(),j,&status);
354             Region *childRegion = (Region *) uhash_get(newRegionIDMap.getAlias(),(void *)&child);
355             if ( parentRegion != NULL && childRegion != NULL ) {
356 
357                 // Add the child region to the set of regions contained by the parent
358                 if (parentRegion->containedRegions == NULL) {
359                     parentRegion->containedRegions = new UVector(uprv_deleteUObject, uhash_compareUnicodeString, status);
360                 }
361 
362                 LocalPointer<UnicodeString> childStr(new UnicodeString(), status);
363                 if( U_FAILURE(status) ) {
364                     return;  // error out
365                 }
366                 childStr->fastCopyFrom(childRegion->idStr);
367                 parentRegion->containedRegions->addElementX((void *)childStr.orphan(),status);
368 
369                 // Set the parent region to be the containing region of the child.
370                 // Regions of type GROUPING can't be set as the parent, since another region
371                 // such as a SUBCONTINENT, CONTINENT, or WORLD must always be the parent.
372                 if ( parentRegion->fType != URGN_GROUPING) {
373                     childRegion->containingRegion = parentRegion;
374                 }
375             }
376         }
377     }
378 
379     // Create the availableRegions lists
380     int32_t pos = UHASH_FIRST;
381     while ( const UHashElement* element = uhash_nextElement(newRegionIDMap.getAlias(),&pos)) {
382         Region *ar = (Region *)element->value.pointer;
383         if ( availableRegions[ar->fType] == NULL ) {
384             LocalPointer<UVector> newAr(new UVector(uprv_deleteUObject, uhash_compareUnicodeString, status), status);
385             availableRegions[ar->fType] = newAr.orphan();
386         }
387         LocalPointer<UnicodeString> arString(new UnicodeString(ar->idStr), status);
388         if( U_FAILURE(status) ) {
389             return;  // error out
390         }
391         availableRegions[ar->fType]->addElementX((void *)arString.orphan(),status);
392     }
393 
394     ucln_i18n_registerCleanup(UCLN_I18N_REGION, region_cleanup);
395     // copy hashtables
396     numericCodeMap = newNumericCodeMap.orphan();
397     regionIDMap = newRegionIDMap.orphan();
398     regionAliases = newRegionAliases.orphan();
399 }
400 
cleanupRegionData()401 void Region::cleanupRegionData() {
402     for (int32_t i = 0 ; i < URGN_LIMIT ; i++ ) {
403         if ( availableRegions[i] ) {
404             delete availableRegions[i];
405         }
406     }
407 
408     if (regionAliases) {
409         uhash_close(regionAliases);
410     }
411 
412     if (numericCodeMap) {
413         uhash_close(numericCodeMap);
414     }
415 
416     if (regionIDMap) {
417         uhash_close(regionIDMap);
418     }
419     if (allRegions) {
420         allRegions->removeAllElements(); // Don't need the temporary list anymore.
421         delete allRegions;
422         allRegions = NULL;
423     }
424 
425     regionAliases = numericCodeMap = regionIDMap = NULL;
426 
427     gRegionDataInitOnce.reset();
428 }
429 
Region()430 Region::Region ()
431         : code(-1),
432           fType(URGN_UNKNOWN),
433           containingRegion(NULL),
434           containedRegions(NULL),
435           preferredValues(NULL) {
436     id[0] = 0;
437 }
438 
~Region()439 Region::~Region () {
440         if (containedRegions) {
441             delete containedRegions;
442         }
443         if (preferredValues) {
444             delete preferredValues;
445         }
446 }
447 
448 /**
449  * Returns true if the two regions are equal.
450  * Per PMC, just use pointer compare, since we have at most one instance of each Region.
451  */
452 bool
operator ==(const Region & that) const453 Region::operator==(const Region &that) const {
454     return (idStr == that.idStr);
455 }
456 
457 /**
458  * Returns true if the two regions are NOT equal; that is, if operator ==() returns false.
459  * Per PMC, just use pointer compare, since we have at most one instance of each Region.
460  */
461 bool
operator !=(const Region & that) const462 Region::operator!=(const Region &that) const {
463         return (idStr != that.idStr);
464 }
465 
466 /**
467  * Returns a pointer to a Region using the given region code.  The region code can be either 2-letter ISO code,
468  * 3-letter ISO code,  UNM.49 numeric code, or other valid Unicode Region Code as defined by the LDML specification.
469  * The identifier will be canonicalized internally using the supplemental metadata as defined in the CLDR.
470  * If the region code is NULL or not recognized, the appropriate error code will be set ( U_ILLEGAL_ARGUMENT_ERROR )
471  */
472 const Region* U_EXPORT2
getInstance(const char * region_code,UErrorCode & status)473 Region::getInstance(const char *region_code, UErrorCode &status) {
474 
475     umtx_initOnce(gRegionDataInitOnce, &loadRegionData, status);
476     if (U_FAILURE(status)) {
477         return NULL;
478     }
479 
480     if ( !region_code ) {
481         status = U_ILLEGAL_ARGUMENT_ERROR;
482         return NULL;
483     }
484 
485     UnicodeString regionCodeString = UnicodeString(region_code, -1, US_INV);
486     Region *r = (Region *)uhash_get(regionIDMap,(void *)&regionCodeString);
487 
488     if ( !r ) {
489         r = (Region *)uhash_get(regionAliases,(void *)&regionCodeString);
490     }
491 
492     if ( !r ) { // Unknown region code
493         status = U_ILLEGAL_ARGUMENT_ERROR;
494         return NULL;
495     }
496 
497     if ( r->fType == URGN_DEPRECATED && r->preferredValues->size() == 1) {
498         StringEnumeration *pv = r->getPreferredValues(status);
499         pv->reset(status);
500         const UnicodeString *ustr = pv->snext(status);
501         r = (Region *)uhash_get(regionIDMap,(void *)ustr);
502         delete pv;
503     }
504 
505     return r;
506 
507 }
508 
509 /**
510  * Returns a pointer to a Region using the given numeric region code. If the numeric region code is not recognized,
511  * the appropriate error code will be set ( U_ILLEGAL_ARGUMENT_ERROR ).
512  */
513 const Region* U_EXPORT2
getInstance(int32_t code,UErrorCode & status)514 Region::getInstance (int32_t code, UErrorCode &status) {
515 
516     umtx_initOnce(gRegionDataInitOnce, &loadRegionData, status);
517     if (U_FAILURE(status)) {
518         return NULL;
519     }
520 
521     Region *r = (Region *)uhash_iget(numericCodeMap,code);
522 
523     if ( !r ) { // Just in case there's an alias that's numeric, try to find it.
524         UnicodeString id;
525         ICU_Utility::appendNumber(id, code, 10, 1);
526         r = (Region *)uhash_get(regionAliases,&id);
527     }
528 
529     if( U_FAILURE(status) ) {
530         return NULL;
531     }
532 
533     if ( !r ) {
534         status = U_ILLEGAL_ARGUMENT_ERROR;
535         return NULL;
536     }
537 
538     if ( r->fType == URGN_DEPRECATED && r->preferredValues->size() == 1) {
539         StringEnumeration *pv = r->getPreferredValues(status);
540         pv->reset(status);
541         const UnicodeString *ustr = pv->snext(status);
542         r = (Region *)uhash_get(regionIDMap,(void *)ustr);
543         delete pv;
544     }
545 
546     return r;
547 }
548 
549 
550 /**
551  * Returns an enumeration over the IDs of all known regions that match the given type.
552  */
553 StringEnumeration* U_EXPORT2
getAvailable(URegionType type,UErrorCode & status)554 Region::getAvailable(URegionType type, UErrorCode &status) {
555     umtx_initOnce(gRegionDataInitOnce, &loadRegionData, status); // returns immediately if U_FAILURE(status)
556     if (U_FAILURE(status)) {
557         return NULL;
558     }
559     return new RegionNameEnumeration(availableRegions[type],status);
560 }
561 
562 /**
563  * Returns a pointer to the region that contains this region.  Returns NULL if this region is code "001" (World)
564  * or "ZZ" (Unknown region). For example, calling this method with region "IT" (Italy) returns the
565  * region "039" (Southern Europe).
566  */
567 const Region*
getContainingRegion() const568 Region::getContainingRegion() const {
569     UErrorCode status = U_ZERO_ERROR;
570     umtx_initOnce(gRegionDataInitOnce, &loadRegionData, status);
571     return containingRegion;
572 }
573 
574 /**
575  * Return a pointer to the region that geographically contains this region and matches the given type,
576  * moving multiple steps up the containment chain if necessary.  Returns NULL if no containing region can be found
577  * that matches the given type. Note: The URegionTypes = "URGN_GROUPING", "URGN_DEPRECATED", or "URGN_UNKNOWN"
578  * are not appropriate for use in this API. NULL will be returned in this case. For example, calling this method
579  * with region "IT" (Italy) for type "URGN_CONTINENT" returns the region "150" ( Europe ).
580  */
581 const Region*
getContainingRegion(URegionType type) const582 Region::getContainingRegion(URegionType type) const {
583     UErrorCode status = U_ZERO_ERROR;
584     umtx_initOnce(gRegionDataInitOnce, &loadRegionData, status);
585     if ( containingRegion == NULL ) {
586         return NULL;
587     }
588 
589     return ( containingRegion->fType == type)? containingRegion: containingRegion->getContainingRegion(type);
590 }
591 
592 /**
593  * Return an enumeration over the IDs of all the regions that are immediate children of this region in the
594  * region hierarchy. These returned regions could be either macro regions, territories, or a mixture of the two,
595  * depending on the containment data as defined in CLDR.  This API may return NULL if this region doesn't have
596  * any sub-regions. For example, calling this method with region "150" (Europe) returns an enumeration containing
597  * the various sub regions of Europe - "039" (Southern Europe) - "151" (Eastern Europe) - "154" (Northern Europe)
598  * and "155" (Western Europe).
599  */
600 StringEnumeration*
getContainedRegions(UErrorCode & status) const601 Region::getContainedRegions(UErrorCode &status) const {
602     umtx_initOnce(gRegionDataInitOnce, &loadRegionData, status); // returns immediately if U_FAILURE(status)
603     if (U_FAILURE(status)) {
604         return NULL;
605     }
606     return new RegionNameEnumeration(containedRegions,status);
607 }
608 
609 /**
610  * Returns an enumeration over the IDs of all the regions that are children of this region anywhere in the region
611  * hierarchy and match the given type.  This API may return an empty enumeration if this region doesn't have any
612  * sub-regions that match the given type. For example, calling this method with region "150" (Europe) and type
613  * "URGN_TERRITORY" returns a set containing all the territories in Europe ( "FR" (France) - "IT" (Italy) - "DE" (Germany) etc. )
614  */
615 StringEnumeration*
getContainedRegions(URegionType type,UErrorCode & status) const616 Region::getContainedRegions( URegionType type, UErrorCode &status ) const {
617     umtx_initOnce(gRegionDataInitOnce, &loadRegionData, status); // returns immediately if U_FAILURE(status)
618     if (U_FAILURE(status)) {
619         return NULL;
620     }
621 
622     UVector *result = new UVector(NULL, uhash_compareChars, status);
623 
624     StringEnumeration *cr = getContainedRegions(status);
625 
626     for ( int32_t i = 0 ; i < cr->count(status) ; i++ ) {
627         const char *regionId = cr->next(NULL,status);
628         const Region *r = Region::getInstance(regionId,status);
629         if ( r->getType() == type) {
630             result->addElementX((void *)&r->idStr,status);
631         } else {
632             StringEnumeration *children = r->getContainedRegions(type, status);
633             for ( int32_t j = 0 ; j < children->count(status) ; j++ ) {
634                 const char *id2 = children->next(NULL,status);
635                 const Region *r2 = Region::getInstance(id2,status);
636                 result->addElementX((void *)&r2->idStr,status);
637             }
638             delete children;
639         }
640     }
641     delete cr;
642     StringEnumeration* resultEnumeration = new RegionNameEnumeration(result,status);
643     delete result;
644     return resultEnumeration;
645 }
646 
647 /**
648  * Returns true if this region contains the supplied other region anywhere in the region hierarchy.
649  */
650 UBool
contains(const Region & other) const651 Region::contains(const Region &other) const {
652     UErrorCode status = U_ZERO_ERROR;
653     umtx_initOnce(gRegionDataInitOnce, &loadRegionData, status);
654 
655     if (!containedRegions) {
656           return FALSE;
657     }
658     if (containedRegions->contains((void *)&other.idStr)) {
659         return TRUE;
660     } else {
661         for ( int32_t i = 0 ; i < containedRegions->size() ; i++ ) {
662             UnicodeString *crStr = (UnicodeString *)containedRegions->elementAt(i);
663             Region *cr = (Region *) uhash_get(regionIDMap,(void *)crStr);
664             if ( cr && cr->contains(other) ) {
665                 return TRUE;
666             }
667         }
668     }
669 
670     return FALSE;
671 }
672 
673 /**
674  * For deprecated regions, return an enumeration over the IDs of the regions that are the preferred replacement
675  * regions for this region.  Returns NULL for a non-deprecated region.  For example, calling this method with region
676  * "SU" (Soviet Union) would return a list of the regions containing "RU" (Russia), "AM" (Armenia), "AZ" (Azerbaijan), etc...
677  */
678 StringEnumeration*
getPreferredValues(UErrorCode & status) const679 Region::getPreferredValues(UErrorCode &status) const {
680     umtx_initOnce(gRegionDataInitOnce, &loadRegionData, status); // returns immediately if U_FAILURE(status)
681     if (U_FAILURE(status) || fType != URGN_DEPRECATED) {
682         return NULL;
683     }
684     return new RegionNameEnumeration(preferredValues,status);
685 }
686 
687 
688 /**
689  * Return this region's canonical region code.
690  */
691 const char*
getRegionCode() const692 Region::getRegionCode() const {
693     return id;
694 }
695 
696 int32_t
getNumericCode() const697 Region::getNumericCode() const {
698     return code;
699 }
700 
701 /**
702  * Returns the region type of this region.
703  */
704 URegionType
getType() const705 Region::getType() const {
706     return fType;
707 }
708 
RegionNameEnumeration(UVector * fNameList,UErrorCode & status)709 RegionNameEnumeration::RegionNameEnumeration(UVector *fNameList, UErrorCode& status) {
710     pos=0;
711     if (fNameList && U_SUCCESS(status)) {
712         fRegionNames = new UVector(uprv_deleteUObject, uhash_compareUnicodeString, fNameList->size(),status);
713         for ( int32_t i = 0 ; i < fNameList->size() ; i++ ) {
714             UnicodeString* this_region_name = (UnicodeString *)fNameList->elementAt(i);
715             UnicodeString* new_region_name = new UnicodeString(*this_region_name);
716             fRegionNames->addElementX((void *)new_region_name,status);
717         }
718     }
719     else {
720         fRegionNames = NULL;
721     }
722 }
723 
724 const UnicodeString*
snext(UErrorCode & status)725 RegionNameEnumeration::snext(UErrorCode& status) {
726   if (U_FAILURE(status) || (fRegionNames==NULL)) {
727     return NULL;
728   }
729   const UnicodeString* nextStr = (const UnicodeString *)fRegionNames->elementAt(pos);
730   if (nextStr!=NULL) {
731     pos++;
732   }
733   return nextStr;
734 }
735 
736 void
reset(UErrorCode &)737 RegionNameEnumeration::reset(UErrorCode& /*status*/) {
738     pos=0;
739 }
740 
741 int32_t
count(UErrorCode &) const742 RegionNameEnumeration::count(UErrorCode& /*status*/) const {
743     return (fRegionNames==NULL) ? 0 : fRegionNames->size();
744 }
745 
~RegionNameEnumeration()746 RegionNameEnumeration::~RegionNameEnumeration() {
747     delete fRegionNames;
748 }
749 
750 U_NAMESPACE_END
751 
752 #endif /* #if !UCONFIG_NO_FORMATTING */
753 
754 //eof
755