Coverage Report

Created: 2026-09-28 06:10

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/icu/icu4c/source/i18n/zonemeta.cpp
Line
Count
Source
1
// © 2016 and later: Unicode, Inc. and others.
2
// License & terms of use: http://www.unicode.org/copyright.html
3
/*
4
*******************************************************************************
5
* Copyright (C) 2007-2014, International Business Machines Corporation and
6
* others. All Rights Reserved.
7
*******************************************************************************
8
*/
9
10
#include "unicode/utypes.h"
11
12
#if !UCONFIG_NO_FORMATTING
13
14
#include "zonemeta.h"
15
16
#include "unicode/timezone.h"
17
#include "unicode/ustring.h"
18
#include "unicode/putil.h"
19
#include "unicode/simpletz.h"
20
#include "unicode/strenum.h"
21
#include "umutex.h"
22
#include "uvector.h"
23
#include "cmemory.h"
24
#include "gregoimp.h"
25
#include "cstring.h"
26
#include "ucln_in.h"
27
#include "uassert.h"
28
#include "uresimp.h"
29
#include "uhash.h"
30
#include "olsontz.h"
31
#include "uinvchar.h"
32
33
static icu::UMutex gZoneMetaLock;
34
35
// CLDR Canonical ID mapping table
36
static UHashtable *gCanonicalIDCache = nullptr;
37
static icu::UInitOnce gCanonicalIDCacheInitOnce {};
38
39
// Metazone mapping table
40
static UHashtable *gOlsonToMeta = nullptr;
41
static icu::UInitOnce gOlsonToMetaInitOnce {};
42
43
// Available metazone IDs vector and table
44
static icu::UVector *gMetaZoneIDs = nullptr;
45
static UHashtable *gMetaZoneIDTable = nullptr;
46
static icu::UInitOnce gMetaZoneIDsInitOnce {};
47
48
// Country info vectors
49
static icu::UVector *gSingleZoneCountries = nullptr;
50
static icu::UVector *gMultiZonesCountries = nullptr;
51
static icu::UInitOnce gCountryInfoVectorsInitOnce {};
52
53
U_CDECL_BEGIN
54
55
/**
56
 * Cleanup callback func
57
 */
58
static UBool U_CALLCONV zoneMeta_cleanup()
59
0
{
60
0
    if (gCanonicalIDCache != nullptr) {
61
0
        uhash_close(gCanonicalIDCache);
62
0
        gCanonicalIDCache = nullptr;
63
0
    }
64
0
    gCanonicalIDCacheInitOnce.reset();
65
66
0
    if (gOlsonToMeta != nullptr) {
67
0
        uhash_close(gOlsonToMeta);
68
0
        gOlsonToMeta = nullptr;
69
0
    }
70
0
    gOlsonToMetaInitOnce.reset();
71
72
0
    if (gMetaZoneIDTable != nullptr) {
73
0
        uhash_close(gMetaZoneIDTable);
74
0
        gMetaZoneIDTable = nullptr;
75
0
    }
76
    // delete after closing gMetaZoneIDTable, because it holds
77
    // value objects held by the hashtable
78
0
    delete gMetaZoneIDs;
79
0
    gMetaZoneIDs = nullptr;
80
0
    gMetaZoneIDsInitOnce.reset();
81
82
0
    delete gSingleZoneCountries;
83
0
    gSingleZoneCountries = nullptr;
84
0
    delete gMultiZonesCountries;
85
0
    gMultiZonesCountries = nullptr;
86
0
    gCountryInfoVectorsInitOnce.reset();
87
88
0
    return true;
89
0
}
90
91
/**
92
 * Deleter for char16_t* string
93
 */
94
static void U_CALLCONV
95
0
deleteUCharString(void *obj) {
96
0
    char16_t *entry = (char16_t*)obj;
97
0
    uprv_free(entry);
98
0
}
99
100
/**
101
 * Deleter for OlsonToMetaMappingEntry
102
 */
103
static void U_CALLCONV
104
0
deleteOlsonToMetaMappingEntry(void *obj) {
105
0
    icu::OlsonToMetaMappingEntry *entry = (icu::OlsonToMetaMappingEntry*)obj;
106
0
    delete entry;
107
0
}
108
109
U_CDECL_END
110
111
U_NAMESPACE_BEGIN
112
113
486k
#define ZID_KEY_MAX 128
114
115
static const char gMetaZones[]          = "metaZones";
116
static const char gMetazoneInfo[]       = "metazoneInfo";
117
static const char gMapTimezonesTag[]    = "mapTimezones";
118
119
static const char gKeyTypeData[]        = "keyTypeData";
120
static const char gTypeAliasTag[]       = "typeAlias";
121
static const char gTypeMapTag[]         = "typeMap";
122
static const char gTimezoneTag[]        = "timezone";
123
static const char gIanaMapTag[]         = "ianaMap";
124
125
static const char gPrimaryZonesTag[]    = "primaryZones";
126
127
static const char gWorldTag[]           = "001";
128
129
static const char16_t gWorld[] = {0x30, 0x30, 0x31, 0x00}; // "001"
130
131
static const char16_t gDefaultFrom[] = {0x31, 0x39, 0x37, 0x30, 0x2D, 0x30, 0x31, 0x2D, 0x30, 0x31,
132
                                     0x20, 0x30, 0x30, 0x3A, 0x30, 0x30, 0x00}; // "1970-01-01 00:00"
133
static const char16_t gDefaultTo[]   = {0x39, 0x39, 0x39, 0x39, 0x2D, 0x31, 0x32, 0x2D, 0x33, 0x31,
134
                                     0x20, 0x32, 0x33, 0x3A, 0x35, 0x39, 0x00}; // "9999-12-31 23:59"
135
136
static const char16_t gCustomTzPrefix[]    = {0x47, 0x4D, 0x54, 0};    // "GMT"
137
138
22.9k
#define ASCII_DIGIT(c) (((c)>=0x30 && (c)<=0x39) ? (c)-0x30 : -1)
139
140
/*
141
 * Convert a date string used by metazone mappings to UDate.
142
 * The format used by CLDR metazone mapping is "yyyy-MM-dd HH:mm".
143
 */
144
static UDate
145
1.91k
parseDate (const char16_t *text, UErrorCode &status) {
146
1.91k
    if (U_FAILURE(status)) {
147
0
        return 0;
148
0
    }
149
1.91k
    int32_t len = u_strlen(text);
150
1.91k
    if (len != 16 && len != 10) {
151
        // It must be yyyy-MM-dd HH:mm (length 16) or yyyy-MM-dd (length 10)
152
0
        status = U_INVALID_FORMAT_ERROR;
153
0
        return 0;
154
0
    }
155
156
1.91k
    int32_t year = 0, month = 0, day = 0, hour = 0, min = 0, n;
157
1.91k
    int32_t idx;
158
159
    // "yyyy" (0 - 3)
160
9.55k
    for (idx = 0; idx <= 3 && U_SUCCESS(status); idx++) {
161
7.64k
        n = ASCII_DIGIT((int32_t)text[idx]);
162
7.64k
        if (n >= 0) {
163
7.64k
            year = 10*year + n;
164
7.64k
        } else {
165
0
            status = U_INVALID_FORMAT_ERROR;
166
0
        }
167
7.64k
    }
168
    // "MM" (5 - 6)
169
5.73k
    for (idx = 5; idx <= 6 && U_SUCCESS(status); idx++) {
170
3.82k
        n = ASCII_DIGIT((int32_t)text[idx]);
171
3.82k
        if (n >= 0) {
172
3.82k
            month = 10*month + n;
173
3.82k
        } else {
174
0
            status = U_INVALID_FORMAT_ERROR;
175
0
        }
176
3.82k
    }
177
    // "dd" (8 - 9)
178
5.73k
    for (idx = 8; idx <= 9 && U_SUCCESS(status); idx++) {
179
3.82k
        n = ASCII_DIGIT((int32_t)text[idx]);
180
3.82k
        if (n >= 0) {
181
3.82k
            day = 10*day + n;
182
3.82k
        } else {
183
0
            status = U_INVALID_FORMAT_ERROR;
184
0
        }
185
3.82k
    }
186
1.91k
    if (len == 16) {
187
        // "HH" (11 - 12)
188
5.73k
        for (idx = 11; idx <= 12 && U_SUCCESS(status); idx++) {
189
3.82k
            n = ASCII_DIGIT((int32_t)text[idx]);
190
3.82k
            if (n >= 0) {
191
3.82k
                hour = 10*hour + n;
192
3.82k
            } else {
193
0
                status = U_INVALID_FORMAT_ERROR;
194
0
            }
195
3.82k
        }
196
        // "mm" (14 - 15)
197
5.73k
        for (idx = 14; idx <= 15 && U_SUCCESS(status); idx++) {
198
3.82k
            n = ASCII_DIGIT((int32_t)text[idx]);
199
3.82k
            if (n >= 0) {
200
3.82k
                min = 10*min + n;
201
3.82k
            } else {
202
0
                status = U_INVALID_FORMAT_ERROR;
203
0
            }
204
3.82k
        }
205
1.91k
    }
206
207
1.91k
    if (U_SUCCESS(status)) {
208
1.91k
        UDate date = Grego::fieldsToDay(year, month - 1, day) * U_MILLIS_PER_DAY
209
1.91k
            + hour * U_MILLIS_PER_HOUR + min * U_MILLIS_PER_MINUTE;
210
1.91k
        return date;
211
1.91k
    }
212
0
    return 0;
213
1.91k
}
214
215
7
static void U_CALLCONV initCanonicalIDCache(UErrorCode &status) {
216
7
    gCanonicalIDCache = uhash_open(uhash_hashUChars, uhash_compareUChars, nullptr, &status);
217
7
    if (gCanonicalIDCache == nullptr) {
218
0
        status = U_MEMORY_ALLOCATION_ERROR;
219
0
    }
220
7
    if (U_FAILURE(status)) {
221
0
        gCanonicalIDCache = nullptr;
222
0
    }
223
    // No key/value deleters - keys/values are from a resource bundle
224
7
    ucln_i18n_registerCleanup(UCLN_I18N_ZONEMETA, zoneMeta_cleanup);
225
7
}
226
227
228
const char16_t* U_EXPORT2
229
54.3k
ZoneMeta::getCanonicalCLDRID(const UnicodeString &tzid, UErrorCode& status) {
230
54.3k
    if (U_FAILURE(status)) {
231
0
        return nullptr;
232
0
    }
233
234
54.3k
    if (tzid.isBogus() || tzid.length() > ZID_KEY_MAX) {
235
402
        status = U_ILLEGAL_ARGUMENT_ERROR;
236
402
        return nullptr;
237
402
    }
238
239
    // Checking the cached results
240
53.9k
    umtx_initOnce(gCanonicalIDCacheInitOnce, &initCanonicalIDCache, status);
241
53.9k
    if (U_FAILURE(status)) {
242
0
        return nullptr;
243
0
    }
244
245
53.9k
    const char16_t *canonicalID = nullptr;
246
247
53.9k
    UErrorCode tmpStatus = U_ZERO_ERROR;
248
53.9k
    char16_t utzid[ZID_KEY_MAX + 1];
249
53.9k
    tzid.extract(utzid, ZID_KEY_MAX + 1, tmpStatus);
250
53.9k
    U_ASSERT(tmpStatus == U_ZERO_ERROR);    // we checked the length of tzid already
251
252
53.9k
    if (!uprv_isInvariantUString(utzid, -1)) {
253
        // All of known tz IDs are only containing ASCII invariant characters.
254
3.26k
        status = U_ILLEGAL_ARGUMENT_ERROR;
255
3.26k
        return nullptr;
256
3.26k
    }
257
258
    // Check if it was already cached
259
50.6k
    umtx_lock(&gZoneMetaLock);
260
50.6k
    {
261
50.6k
        canonicalID = static_cast<const char16_t*>(uhash_get(gCanonicalIDCache, utzid));
262
50.6k
    }
263
50.6k
    umtx_unlock(&gZoneMetaLock);
264
265
50.6k
    if (canonicalID != nullptr) {
266
45.4k
        return canonicalID;
267
45.4k
    }
268
269
    // If not, resolve CLDR canonical ID with resource data
270
5.26k
    UBool isInputCanonical = false;
271
5.26k
    char id[ZID_KEY_MAX + 1];
272
5.26k
    tzid.extract(0, 0x7fffffff, id, UPRV_LENGTHOF(id), US_INV);
273
274
    // replace '/' with ':'
275
5.26k
    char *p = id;
276
48.9k
    while (*p++) {
277
43.6k
        if (*p == '/') {
278
6.47k
            *p = ':';
279
6.47k
        }
280
43.6k
    }
281
282
5.26k
    UResourceBundle *top = ures_openDirect(nullptr, gKeyTypeData, &tmpStatus);
283
5.26k
    UResourceBundle *rb = ures_getByKey(top, gTypeMapTag, nullptr, &tmpStatus);
284
5.26k
    ures_getByKey(rb, gTimezoneTag, rb, &tmpStatus);
285
5.26k
    ures_getByKey(rb, id, rb, &tmpStatus);
286
5.26k
    if (U_SUCCESS(tmpStatus)) {
287
        // type entry (canonical) found
288
        // the input is the canonical ID. resolve to const char16_t*
289
1.02k
        canonicalID = TimeZone::findID(tzid);
290
1.02k
        isInputCanonical = true;
291
1.02k
    }
292
293
5.26k
    if (canonicalID == nullptr) {
294
        // If a map element not found, then look for an alias
295
4.31k
        tmpStatus = U_ZERO_ERROR;
296
4.31k
        ures_getByKey(top, gTypeAliasTag, rb, &tmpStatus);
297
4.31k
        ures_getByKey(rb, gTimezoneTag, rb, &tmpStatus);
298
4.31k
        const char16_t *canonical = ures_getStringByKey(rb,id,nullptr,&tmpStatus);
299
4.31k
        if (U_SUCCESS(tmpStatus)) {
300
            // canonical map found
301
406
            canonicalID = canonical;
302
406
        }
303
304
4.31k
        if (canonicalID == nullptr) {
305
            // Dereference the input ID using the tz data
306
3.91k
            const char16_t *derefer = TimeZone::dereferOlsonLink(tzid);
307
3.91k
            if (derefer == nullptr) {
308
3.77k
                status = U_ILLEGAL_ARGUMENT_ERROR;
309
3.77k
            } else {
310
140
                int32_t len = u_strlen(derefer);
311
140
                u_UCharsToChars(derefer,id,len);
312
140
                id[len] = static_cast<char>(0); // Make sure it is null terminated.
313
314
                // replace '/' with ':'
315
140
                char *q = id;
316
2.29k
                while (*q++) {
317
2.15k
                    if (*q == '/') {
318
150
                        *q = ':';
319
150
                    }
320
2.15k
                }
321
322
                // If a dereference turned something up then look for an alias.
323
                // rb still points to the alias table, so we don't have to go looking
324
                // for it.
325
140
                tmpStatus = U_ZERO_ERROR;
326
140
                canonical = ures_getStringByKey(rb,id,nullptr,&tmpStatus);
327
140
                if (U_SUCCESS(tmpStatus)) {
328
                    // canonical map for the dereferenced ID found
329
20
                    canonicalID = canonical;
330
120
                } else {
331
120
                    canonicalID = derefer;
332
120
                    isInputCanonical = true;
333
120
                }
334
140
            }
335
3.91k
        }
336
4.31k
    }
337
5.26k
    ures_close(rb);
338
5.26k
    ures_close(top);
339
340
5.26k
    if (U_SUCCESS(status)) {
341
1.48k
        U_ASSERT(canonicalID != nullptr);  // canocanilD must be non-nullptr here
342
343
        // Put the resolved canonical ID to the cache
344
1.48k
        umtx_lock(&gZoneMetaLock);
345
1.48k
        {
346
1.48k
            const char16_t* idInCache = static_cast<const char16_t*>(uhash_get(gCanonicalIDCache, utzid));
347
1.48k
            if (idInCache == nullptr) {
348
1.48k
                const char16_t* key = ZoneMeta::findTimeZoneID(tzid);
349
1.48k
                U_ASSERT(key != nullptr);
350
1.48k
                if (key != nullptr) {
351
1.44k
                    idInCache = static_cast<const char16_t*>(uhash_put(gCanonicalIDCache, const_cast<char16_t*>(key), const_cast<char16_t*>(canonicalID), &status));
352
1.44k
                    U_ASSERT(idInCache == nullptr);
353
1.44k
                }
354
1.48k
            }
355
1.48k
            if (U_SUCCESS(status) && isInputCanonical) {
356
                // Also put canonical ID itself into the cache if not exist
357
1.06k
                const char16_t* canonicalInCache = static_cast<const char16_t*>(uhash_get(gCanonicalIDCache, canonicalID));
358
1.06k
                if (canonicalInCache == nullptr) {
359
72
                    canonicalInCache = static_cast<const char16_t*>(uhash_put(gCanonicalIDCache, const_cast<char16_t*>(canonicalID), const_cast<char16_t*>(canonicalID), &status));
360
72
                    U_ASSERT(canonicalInCache == nullptr);
361
72
                }
362
1.06k
            }
363
1.48k
        }
364
1.48k
        umtx_unlock(&gZoneMetaLock);
365
1.48k
    }
366
367
5.26k
    return canonicalID;
368
50.6k
}
369
370
UnicodeString& U_EXPORT2
371
48.1k
ZoneMeta::getCanonicalCLDRID(const UnicodeString &tzid, UnicodeString &systemID, UErrorCode& status) {
372
48.1k
    const char16_t *canonicalID = getCanonicalCLDRID(tzid, status);
373
48.1k
    if (U_FAILURE(status) || canonicalID == nullptr) {
374
6.42k
        systemID.setToBogus();
375
6.42k
        return systemID;
376
6.42k
    }
377
41.7k
    systemID.setTo(true, canonicalID, -1);
378
41.7k
    return systemID;
379
48.1k
}
380
381
const char16_t* U_EXPORT2
382
9.02k
ZoneMeta::getCanonicalCLDRID(const TimeZone& tz) {
383
9.02k
    if (dynamic_cast<const OlsonTimeZone *>(&tz) != nullptr) {
384
        // short cut for OlsonTimeZone
385
9.02k
        const OlsonTimeZone *otz = (const OlsonTimeZone*)&tz;
386
9.02k
        return otz->getCanonicalID();
387
9.02k
    }
388
0
    UErrorCode status = U_ZERO_ERROR;
389
0
    UnicodeString tzID;
390
0
    return getCanonicalCLDRID(tz.getID(tzID), status);
391
9.02k
}
392
393
UnicodeString& U_EXPORT2
394
1.17k
ZoneMeta::getIanaID(const UnicodeString& tzid, UnicodeString& ianaID, UErrorCode& status) {
395
    // First, get CLDR canonical ID
396
1.17k
    const char16_t *canonicalID = getCanonicalCLDRID(tzid, status);
397
1.17k
    if (U_FAILURE(status) || canonicalID == nullptr) {
398
1.01k
        ianaID.setToBogus();
399
1.01k
        return ianaID;
400
1.01k
    }
401
    // Find IANA mapping if any.
402
167
    UErrorCode tmpStatus = U_ZERO_ERROR;
403
167
    UnicodeString tmpKey(canonicalID);
404
167
    tmpKey.findAndReplace(UnicodeString("/"), UnicodeString(":"));
405
167
    char keyBuf[ZID_KEY_MAX + 1];
406
167
    /* int32_t keyLen = */ tmpKey.extract(0, tmpKey.length(), keyBuf, sizeof(keyBuf), US_INV);
407
408
167
    StackUResourceBundle r;
409
167
    ures_openDirectFillIn(r.getAlias(), nullptr, gKeyTypeData, &tmpStatus);
410
167
    ures_getByKey(r.getAlias(), gIanaMapTag, r.getAlias(), &tmpStatus);
411
167
    ures_getByKey(r.getAlias(), gTimezoneTag, r.getAlias(), &tmpStatus);
412
167
    int32_t tmpLen = 0;
413
167
    const char16_t* tmpIana = ures_getStringByKey(r.getAlias(), keyBuf, &tmpLen, &tmpStatus);
414
167
    if (U_SUCCESS(tmpStatus)) {
415
18
        ianaID.setTo(true, tmpIana, -1);
416
149
    } else {
417
149
        ianaID.setTo(true, canonicalID, -1);
418
149
    }
419
167
    return ianaID;
420
1.17k
}
421
422
0
static void U_CALLCONV countryInfoVectorsInit(UErrorCode &status) {
423
    // Create empty vectors
424
    // No deleters for these UVectors, it's a reference to a resource bundle string.
425
0
    gSingleZoneCountries = new UVector(nullptr, uhash_compareUChars, status);
426
0
    if (gSingleZoneCountries == nullptr) {
427
0
        status = U_MEMORY_ALLOCATION_ERROR;
428
0
    }
429
0
    gMultiZonesCountries = new UVector(nullptr, uhash_compareUChars, status);
430
0
    if (gMultiZonesCountries == nullptr) {
431
0
        status = U_MEMORY_ALLOCATION_ERROR;
432
0
    }
433
434
0
    if (U_FAILURE(status)) {
435
0
        delete gSingleZoneCountries;
436
0
        delete gMultiZonesCountries;
437
0
        gSingleZoneCountries = nullptr;
438
0
        gMultiZonesCountries  = nullptr;
439
0
    }
440
0
    ucln_i18n_registerCleanup(UCLN_I18N_ZONEMETA, zoneMeta_cleanup);
441
0
}
442
443
444
UnicodeString& U_EXPORT2
445
133k
ZoneMeta::getCanonicalCountry(const UnicodeString &tzid, UnicodeString &country, UBool *isPrimary /* = nullptr */) {
446
133k
    if (isPrimary != nullptr) {
447
254
        *isPrimary = false;
448
254
    }
449
450
133k
    const char16_t *region = TimeZone::getRegion(tzid);
451
133k
    if (region != nullptr && u_strcmp(gWorld, region) != 0) {
452
111k
        country.setTo(region, -1);
453
111k
    } else {
454
22.8k
        country.setToBogus();
455
22.8k
        return country;
456
22.8k
    }
457
458
111k
    if (isPrimary != nullptr) {
459
0
        char regionBuf[] = {0, 0, 0};
460
461
        // Checking the cached results
462
0
        UErrorCode status = U_ZERO_ERROR;
463
0
        umtx_initOnce(gCountryInfoVectorsInitOnce, &countryInfoVectorsInit, status);
464
0
        if (U_FAILURE(status)) {
465
0
            return country;
466
0
        }
467
468
        // Check if it was already cached
469
0
        UBool cached = false;
470
0
        UBool singleZone = false;
471
0
        umtx_lock(&gZoneMetaLock);
472
0
        {
473
0
            singleZone = cached = gSingleZoneCountries->contains((void*)region);
474
0
            if (!cached) {
475
0
                cached = gMultiZonesCountries->contains((void*)region);
476
0
            }
477
0
        }
478
0
        umtx_unlock(&gZoneMetaLock);
479
480
0
        if (!cached) {
481
            // We need to go through all zones associated with the region.
482
            // This is relatively heavy operation.
483
484
0
            U_ASSERT(u_strlen(region) == 2);
485
486
0
            u_UCharsToChars(region, regionBuf, 2);
487
488
0
            StringEnumeration *ids = TimeZone::createTimeZoneIDEnumeration(UCAL_ZONE_TYPE_CANONICAL_LOCATION, regionBuf, nullptr, status);
489
0
            int32_t idsLen = ids->count(status);
490
0
            if (U_SUCCESS(status) && idsLen == 1) {
491
                // only the single zone is available for the region
492
0
                singleZone = true;
493
0
            }
494
0
            delete ids;
495
496
            // Cache the result
497
0
            umtx_lock(&gZoneMetaLock);
498
0
            {
499
0
                UErrorCode ec = U_ZERO_ERROR;
500
0
                if (singleZone) {
501
0
                    if (!gSingleZoneCountries->contains((void*)region)) {
502
0
                        gSingleZoneCountries->addElement((void*)region, ec);
503
0
                    }
504
0
                } else {
505
0
                    if (!gMultiZonesCountries->contains((void*)region)) {
506
0
                        gMultiZonesCountries->addElement((void*)region, ec);
507
0
                    }
508
0
                }
509
0
            }
510
0
            umtx_unlock(&gZoneMetaLock);
511
0
        }
512
513
0
        if (singleZone) {
514
0
            *isPrimary = true;
515
0
        } else {
516
            // Note: We may cache the primary zone map in future.
517
518
            // Even a country has multiple zones, one of them might be
519
            // dominant and treated as a primary zone
520
0
            int32_t idLen = 0;
521
0
            if (regionBuf[0] == 0) {
522
0
                u_UCharsToChars(region, regionBuf, 2);
523
0
            }
524
525
0
            UResourceBundle *rb = ures_openDirect(nullptr, gMetaZones, &status);
526
0
            ures_getByKey(rb, gPrimaryZonesTag, rb, &status);
527
0
            const char16_t *primaryZone = ures_getStringByKey(rb, regionBuf, &idLen, &status);
528
0
            if (U_SUCCESS(status)) {
529
0
                if (tzid.compare(primaryZone, idLen) == 0) {
530
0
                    *isPrimary = true;
531
0
                } else {
532
                    // The given ID might not be a canonical ID
533
0
                    UnicodeString canonicalID;
534
0
                    TimeZone::getCanonicalID(tzid, canonicalID, status);
535
0
                    if (U_SUCCESS(status) && canonicalID.compare(primaryZone, idLen) == 0) {
536
0
                        *isPrimary = true;
537
0
                    }
538
0
                }
539
0
            }
540
0
            ures_close(rb);
541
0
        }
542
0
    }
543
544
111k
    return country;
545
111k
}
546
547
UnicodeString& U_EXPORT2
548
296k
ZoneMeta::getMetazoneID(const UnicodeString &tzid, UDate date, UnicodeString &result) {
549
296k
    UBool isSet = false;
550
296k
    const UVector *mappings = getMetazoneMappings(tzid);
551
296k
    if (mappings != nullptr) {
552
390k
        for (int32_t i = 0; i < mappings->size(); i++) {
553
387k
            OlsonToMetaMappingEntry* mzm = static_cast<OlsonToMetaMappingEntry*>(mappings->elementAt(i));
554
387k
            if (mzm->from <= date && mzm->to > date) {
555
264k
                result.setTo(mzm->mzid, -1);
556
264k
                isSet = true;
557
264k
                break;
558
264k
            }
559
387k
        }
560
266k
    }
561
296k
    if (!isSet) {
562
32.2k
        result.setToBogus();
563
32.2k
    }
564
296k
    return result;
565
296k
}
566
567
3
static void U_CALLCONV olsonToMetaInit(UErrorCode &status) {
568
3
    U_ASSERT(gOlsonToMeta == nullptr);
569
3
    ucln_i18n_registerCleanup(UCLN_I18N_ZONEMETA, zoneMeta_cleanup);
570
3
    gOlsonToMeta = uhash_open(uhash_hashUChars, uhash_compareUChars, nullptr, &status);
571
3
    if (U_FAILURE(status)) {
572
0
        gOlsonToMeta = nullptr;
573
3
    } else {
574
3
        uhash_setKeyDeleter(gOlsonToMeta, deleteUCharString);
575
3
        uhash_setValueDeleter(gOlsonToMeta, uprv_deleteUObject);
576
3
    }
577
3
}
578
579
580
const UVector* U_EXPORT2
581
378k
ZoneMeta::getMetazoneMappings(const UnicodeString &tzid) {
582
378k
    UErrorCode status = U_ZERO_ERROR;
583
378k
    char16_t tzidUChars[ZID_KEY_MAX + 1];
584
378k
    tzid.extract(tzidUChars, ZID_KEY_MAX + 1, status);
585
378k
    if (U_FAILURE(status) || status == U_STRING_NOT_TERMINATED_WARNING) {
586
2.59k
        return nullptr;
587
2.59k
    }
588
589
375k
    umtx_initOnce(gOlsonToMetaInitOnce, &olsonToMetaInit, status);
590
375k
    if (U_FAILURE(status)) {
591
0
        return nullptr;
592
0
    }
593
594
    // get the mapping from cache
595
375k
    const UVector *result = nullptr;
596
597
375k
    umtx_lock(&gZoneMetaLock);
598
375k
    {
599
375k
        result = static_cast<UVector*>(uhash_get(gOlsonToMeta, tzidUChars));
600
375k
    }
601
375k
    umtx_unlock(&gZoneMetaLock);
602
603
375k
    if (result != nullptr) {
604
330k
        return result;
605
330k
    }
606
607
    // miss the cache - create new one
608
45.1k
    UVector *tmpResult = createMetazoneMappings(tzid);
609
45.1k
    if (tmpResult == nullptr) {
610
        // not available
611
44.5k
        return nullptr;
612
44.5k
    }
613
614
    // put the new one into the cache
615
641
    umtx_lock(&gZoneMetaLock);
616
641
    {
617
        // make sure it's already created
618
641
        result = static_cast<UVector*>(uhash_get(gOlsonToMeta, tzidUChars));
619
641
        if (result == nullptr) {
620
            // add the one just created
621
641
            int32_t tzidLen = tzid.length() + 1;
622
641
            char16_t* key = static_cast<char16_t*>(uprv_malloc(tzidLen * sizeof(char16_t)));
623
641
            if (key == nullptr) {
624
                // memory allocation error..  just return nullptr
625
0
                result = nullptr;
626
0
                delete tmpResult;
627
641
            } else {
628
641
                tzid.extract(key, tzidLen, status);
629
641
                uhash_put(gOlsonToMeta, key, tmpResult, &status);
630
641
                if (U_FAILURE(status)) {
631
                    // delete the mapping
632
0
                    result = nullptr;
633
0
                    delete tmpResult;
634
641
                } else {
635
641
                    result = tmpResult;
636
641
                }
637
641
            }
638
641
        } else {
639
            // another thread already put the one
640
0
            delete tmpResult;
641
0
        }
642
641
    }
643
641
    umtx_unlock(&gZoneMetaLock);
644
645
641
    return result;
646
45.1k
}
647
648
UVector*
649
45.1k
ZoneMeta::createMetazoneMappings(const UnicodeString &tzid) {
650
45.1k
    LocalPointer <UVector> mzMappings;
651
45.1k
    UErrorCode status = U_ZERO_ERROR;
652
653
45.1k
    UnicodeString canonicalID;
654
45.1k
    UResourceBundle *rb = ures_openDirect(nullptr, gMetaZones, &status);
655
45.1k
    ures_getByKey(rb, gMetazoneInfo, rb, &status);
656
45.1k
    getCanonicalCLDRID(tzid, canonicalID, status);
657
658
45.1k
    if (U_SUCCESS(status)) {
659
40.7k
        char tzKey[ZID_KEY_MAX + 1];
660
40.7k
        int32_t tzKeyLen = canonicalID.extract(0, canonicalID.length(), tzKey, sizeof(tzKey), US_INV);
661
40.7k
        tzKey[tzKeyLen] = 0;
662
663
        // tzid keys are using ':' as separators
664
40.7k
        char *p = tzKey;
665
441k
        while (*p) {
666
400k
            if (*p == '/') {
667
37.7k
                *p = ':';
668
37.7k
            }
669
400k
            p++;
670
400k
        }
671
672
40.7k
        ures_getByKey(rb, tzKey, rb, &status);
673
674
40.7k
        if (U_SUCCESS(status)) {
675
641
            UResourceBundle *mz = nullptr;
676
1.59k
            while (ures_hasNext(rb)) {
677
955
                mz = ures_getNextResource(rb, mz, &status);
678
679
955
                const char16_t *mz_name = ures_getStringByIndex(mz, 0, nullptr, &status);
680
955
                const char16_t *mz_from = gDefaultFrom;
681
955
                const char16_t *mz_to = gDefaultTo;
682
683
955
                if (ures_getSize(mz) >= 3) {
684
527
                    mz_from = ures_getStringByIndex(mz, 1, nullptr, &status);
685
527
                    mz_to   = ures_getStringByIndex(mz, 2, nullptr, &status);
686
527
                }
687
688
955
                if(U_FAILURE(status)){
689
0
                    status = U_ZERO_ERROR;
690
0
                    continue;
691
0
                }
692
                // We do not want to use SimpleDateformat to parse boundary dates,
693
                // because this code could be triggered by the initialization code
694
                // used by SimpleDateFormat.
695
955
                UDate from = parseDate(mz_from, status);
696
955
                UDate to = parseDate(mz_to, status);
697
955
                if (U_FAILURE(status)) {
698
0
                    status = U_ZERO_ERROR;
699
0
                    continue;
700
0
                }
701
702
955
                LocalPointer<OlsonToMetaMappingEntry> entry(new OlsonToMetaMappingEntry, status);
703
955
                if (U_FAILURE(status)) {
704
0
                    break;
705
0
                }
706
955
                entry->mzid = mz_name;
707
955
                entry->from = from;
708
955
                entry->to = to;
709
710
955
                if (mzMappings.isNull()) {
711
641
                    mzMappings.adoptInsteadAndCheckErrorCode(
712
641
                        new UVector(deleteOlsonToMetaMappingEntry, nullptr, status), status);
713
641
                    if (U_FAILURE(status)) {
714
0
                        break;
715
0
                    }
716
641
                }
717
718
955
                mzMappings->adoptElement(entry.orphan(), status);
719
955
                if (U_FAILURE(status)) {
720
0
                    break;
721
0
                }
722
955
            }
723
641
            ures_close(mz);
724
641
        }
725
40.7k
    }
726
45.1k
    ures_close(rb);
727
45.1k
    return U_SUCCESS(status) ? mzMappings.orphan() : nullptr;
728
45.1k
}
729
730
UnicodeString& U_EXPORT2
731
0
ZoneMeta::getZoneIdByMetazone(const UnicodeString &mzid, const UnicodeString &region, UnicodeString &result) {
732
0
    UErrorCode status = U_ZERO_ERROR;
733
0
    const char16_t *tzid = nullptr;
734
0
    int32_t tzidLen = 0;
735
0
    char keyBuf[ZID_KEY_MAX + 1];
736
0
    int32_t keyLen = 0;
737
738
0
    if (mzid.isBogus() || mzid.length() > ZID_KEY_MAX) {
739
0
        result.setToBogus();
740
0
        return result;
741
0
    }
742
743
0
    keyLen = mzid.extract(0, mzid.length(), keyBuf, ZID_KEY_MAX + 1, US_INV);
744
0
    keyBuf[keyLen] = 0;
745
746
0
    UResourceBundle *rb = ures_openDirect(nullptr, gMetaZones, &status);
747
0
    ures_getByKey(rb, gMapTimezonesTag, rb, &status);
748
0
    ures_getByKey(rb, keyBuf, rb, &status);
749
750
0
    if (U_SUCCESS(status)) {
751
        // check region mapping
752
0
        if (region.length() == 2 || region.length() == 3) {
753
0
            keyLen = region.extract(0, region.length(), keyBuf, ZID_KEY_MAX + 1, US_INV);
754
0
            keyBuf[keyLen] = 0;
755
0
            tzid = ures_getStringByKey(rb, keyBuf, &tzidLen, &status);
756
0
            if (status == U_MISSING_RESOURCE_ERROR) {
757
0
                status = U_ZERO_ERROR;
758
0
            }
759
0
        }
760
0
        if (U_SUCCESS(status) && tzid == nullptr) {
761
            // try "001"
762
0
            tzid = ures_getStringByKey(rb, gWorldTag, &tzidLen, &status);
763
0
        }
764
0
    }
765
0
    ures_close(rb);
766
767
0
    if (tzid == nullptr) {
768
0
        result.setToBogus();
769
0
    } else {
770
0
        result.setTo(tzid, tzidLen);
771
0
    }
772
773
0
    return result;
774
0
}
775
776
2
static void U_CALLCONV initAvailableMetaZoneIDs () {
777
2
    U_ASSERT(gMetaZoneIDs == nullptr);
778
2
    U_ASSERT(gMetaZoneIDTable == nullptr);
779
2
    ucln_i18n_registerCleanup(UCLN_I18N_ZONEMETA, zoneMeta_cleanup);
780
781
2
    UErrorCode status = U_ZERO_ERROR;
782
2
    gMetaZoneIDTable = uhash_open(uhash_hashUnicodeString, uhash_compareUnicodeString, nullptr, &status);
783
2
    if (U_FAILURE(status) || gMetaZoneIDTable == nullptr) {
784
0
        gMetaZoneIDTable = nullptr;
785
0
        return;
786
0
    }
787
2
    uhash_setKeyDeleter(gMetaZoneIDTable, uprv_deleteUObject);
788
    // No valueDeleter, because the vector maintain the value objects
789
2
    gMetaZoneIDs = new UVector(nullptr, uhash_compareUChars, status);
790
2
    if (U_FAILURE(status) || gMetaZoneIDs == nullptr) {
791
0
        delete gMetaZoneIDs;
792
0
        gMetaZoneIDs = nullptr;
793
0
        uhash_close(gMetaZoneIDTable);
794
0
        gMetaZoneIDTable = nullptr;
795
0
        return;
796
0
    }
797
2
    gMetaZoneIDs->setDeleter(uprv_free);
798
799
2
    UResourceBundle *rb = ures_openDirect(nullptr, gMetaZones, &status);
800
2
    UResourceBundle *bundle = ures_getByKey(rb, gMapTimezonesTag, nullptr, &status);
801
2
    StackUResourceBundle res;
802
312
    while (U_SUCCESS(status) && ures_hasNext(bundle)) {
803
310
        ures_getNextResource(bundle, res.getAlias(), &status);
804
310
        if (U_FAILURE(status)) {
805
0
            break;
806
0
        }
807
310
        const char *mzID = ures_getKey(res.getAlias());
808
310
        int32_t len = static_cast<int32_t>(uprv_strlen(mzID));
809
310
        LocalMemory<char16_t> uMzID(static_cast<char16_t*>(uprv_malloc(sizeof(char16_t) * (len + 1))));
810
310
        if (uMzID.isNull()) {
811
0
            status = U_MEMORY_ALLOCATION_ERROR;
812
0
            break;
813
0
        }
814
310
        u_charsToUChars(mzID, uMzID.getAlias(), len);
815
310
        uMzID[len] = 0;
816
310
        LocalPointer<UnicodeString> usMzID(new UnicodeString(uMzID.getAlias()), status);
817
310
        if (U_FAILURE(status)) {
818
0
            break;
819
0
        }
820
310
        if (uhash_get(gMetaZoneIDTable, usMzID.getAlias()) == nullptr) {
821
            // Note: gMetaZoneIDTable adopts its keys, but not its values.
822
            //       gMetaZoneIDs adopts its values.
823
310
            uhash_put(gMetaZoneIDTable, usMzID.orphan(), uMzID.getAlias(), &status);
824
310
            gMetaZoneIDs->adoptElement(uMzID.orphan(), status);
825
310
        }
826
310
    }
827
2
    ures_close(bundle);
828
2
    ures_close(rb);
829
830
2
    if (U_FAILURE(status)) {
831
0
        uhash_close(gMetaZoneIDTable);
832
0
        delete gMetaZoneIDs;
833
0
        gMetaZoneIDTable = nullptr;
834
0
        gMetaZoneIDs = nullptr;
835
0
    }
836
2
}
837
838
const UVector*
839
2.79k
ZoneMeta::getAvailableMetazoneIDs() {
840
2.79k
    umtx_initOnce(gMetaZoneIDsInitOnce, &initAvailableMetaZoneIDs);
841
2.79k
    return gMetaZoneIDs;
842
2.79k
}
843
844
const char16_t*
845
47.2k
ZoneMeta::findMetaZoneID(const UnicodeString& mzid) {
846
47.2k
    umtx_initOnce(gMetaZoneIDsInitOnce, &initAvailableMetaZoneIDs);
847
47.2k
    if (gMetaZoneIDTable == nullptr) {
848
0
        return nullptr;
849
0
    }
850
47.2k
    return static_cast<const char16_t*>(uhash_get(gMetaZoneIDTable, &mzid));
851
47.2k
}
852
853
const char16_t*
854
194k
ZoneMeta::findTimeZoneID(const UnicodeString& tzid) {
855
194k
    return TimeZone::findID(tzid);
856
194k
}
857
858
859
TimeZone*
860
0
ZoneMeta::createCustomTimeZone(int32_t offset) {
861
0
    UBool negative = false;
862
0
    int32_t tmp = offset;
863
0
    if (offset < 0) {
864
0
        negative = true;
865
0
        tmp = -offset;
866
0
    }
867
0
    uint8_t hour, min, sec;
868
869
0
    tmp /= 1000;
870
0
    sec = static_cast<uint8_t>(tmp % 60);
871
0
    tmp /= 60;
872
0
    min = static_cast<uint8_t>(tmp % 60);
873
0
    hour = static_cast<uint8_t>(tmp / 60);
874
875
0
    UnicodeString zid;
876
0
    formatCustomID(hour, min, sec, negative, zid);
877
0
    return new SimpleTimeZone(offset, zid);
878
0
}
879
880
UnicodeString&
881
0
ZoneMeta::formatCustomID(uint8_t hour, uint8_t min, uint8_t sec, UBool negative, UnicodeString& id) {
882
    // Create normalized time zone ID - GMT[+|-]HH:mm[:ss]
883
0
    id.setTo(gCustomTzPrefix, -1);
884
0
    if (hour != 0 || min != 0) {
885
0
        if (negative) {
886
0
          id.append(static_cast<char16_t>(0x2D)); // '-'
887
0
        } else {
888
0
          id.append(static_cast<char16_t>(0x2B)); // '+'
889
0
        }
890
        // Always use US-ASCII digits
891
0
        id.append(static_cast<char16_t>(0x30 + (hour % 100) / 10));
892
0
        id.append(static_cast<char16_t>(0x30 + (hour % 10)));
893
0
        id.append(static_cast<char16_t>(0x3A)); // ':'
894
0
        id.append(static_cast<char16_t>(0x30 + (min % 100) / 10));
895
0
        id.append(static_cast<char16_t>(0x30 + (min % 10)));
896
0
        if (sec != 0) {
897
0
          id.append(static_cast<char16_t>(0x3A)); // ':'
898
0
          id.append(static_cast<char16_t>(0x30 + (sec % 100) / 10));
899
0
          id.append(static_cast<char16_t>(0x30 + (sec % 10)));
900
0
        }
901
0
    }
902
0
    return id;
903
0
}
904
905
const char16_t*
906
231
ZoneMeta::getShortID(const TimeZone& tz) {
907
231
    const char16_t* canonicalID = nullptr;
908
231
    if (dynamic_cast<const OlsonTimeZone *>(&tz) != nullptr) {
909
        // short cut for OlsonTimeZone
910
231
        const OlsonTimeZone *otz = (const OlsonTimeZone*)&tz;
911
231
        canonicalID = otz->getCanonicalID();
912
231
    }
913
231
    if (canonicalID == nullptr) {
914
0
        return nullptr;
915
0
    }
916
231
    return getShortIDFromCanonical(canonicalID);
917
231
}
918
919
const char16_t*
920
0
ZoneMeta::getShortID(const UnicodeString& id) {
921
0
    UErrorCode status = U_ZERO_ERROR;
922
0
    const char16_t* canonicalID = ZoneMeta::getCanonicalCLDRID(id, status);
923
0
    if (U_FAILURE(status) || canonicalID == nullptr) {
924
0
        return nullptr;
925
0
    }
926
0
    return ZoneMeta::getShortIDFromCanonical(canonicalID);
927
0
}
928
929
const char16_t*
930
231
ZoneMeta::getShortIDFromCanonical(const char16_t* canonicalID) {
931
231
    const char16_t* shortID = nullptr;
932
231
    int32_t len = u_strlen(canonicalID);
933
231
    char tzidKey[ZID_KEY_MAX + 1];
934
935
231
    u_UCharsToChars(canonicalID, tzidKey, len);
936
231
    tzidKey[len] = static_cast<char>(0); // Make sure it is null terminated.
937
938
    // replace '/' with ':'
939
231
    char *p = tzidKey;
940
1.84k
    while (*p++) {
941
1.61k
        if (*p == '/') {
942
231
            *p = ':';
943
231
        }
944
1.61k
    }
945
946
231
    UErrorCode status = U_ZERO_ERROR;
947
231
    UResourceBundle *rb = ures_openDirect(nullptr, gKeyTypeData, &status);
948
231
    ures_getByKey(rb, gTypeMapTag, rb, &status);
949
231
    ures_getByKey(rb, gTimezoneTag, rb, &status);
950
231
    shortID = ures_getStringByKey(rb, tzidKey, nullptr, &status);
951
231
    ures_close(rb);
952
953
231
    return shortID;
954
231
}
955
956
U_NAMESPACE_END
957
958
#endif /* #if !UCONFIG_NO_FORMATTING */