Coverage Report

Created: 2018-09-25 14:53

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