Home | History | Annotate | Download | only in i18n
      1 /*
      2 *******************************************************************************
      3 * Copyright (C) 1997-2010, International Business Machines Corporation and    *
      4 * others. All Rights Reserved.                                                *
      5 *******************************************************************************
      6 *
      7 * File TIMEZONE.CPP
      8 *
      9 * Modification History:
     10 *
     11 *   Date        Name        Description
     12 *   12/05/96    clhuang     Creation.
     13 *   04/21/97    aliu        General clean-up and bug fixing.
     14 *   05/08/97    aliu        Fixed Hashtable code per code review.
     15 *   07/09/97    helena      Changed createInstance to createDefault.
     16 *   07/29/97    aliu        Updated with all-new list of 96 UNIX-derived
     17 *                           TimeZones.  Changed mechanism to load from static
     18 *                           array rather than resource bundle.
     19 *   07/07/1998  srl         Bugfixes from the Java side: UTC GMT CAT NST
     20 *                           Added getDisplayName API
     21 *                           going to add custom parsing.
     22 *
     23 *                           ISSUES:
     24 *                               - should getDisplayName cache something?
     25 *                               - should custom time zones be cached? [probably]
     26 *  08/10/98     stephen     Brought getDisplayName() API in-line w/ conventions
     27 *  08/19/98     stephen     Changed createTimeZone() to never return 0
     28 *  09/02/98     stephen     Added getOffset(monthLen) and hasSameRules()
     29 *  09/15/98     stephen     Added getStaticClassID()
     30 *  02/22/99     stephen     Removed character literals for EBCDIC safety
     31 *  05/04/99     stephen     Changed initDefault() for Mutex issues
     32 *  07/12/99     helena      HPUX 11 CC Port.
     33 *  12/03/99     aliu        Moved data out of static table into icudata.dll.
     34 *                           Substantial rewrite of zone lookup, default zone, and
     35 *                           available IDs code.  Misc. cleanup.
     36 *********************************************************************************/
     37 
     38 #include "unicode/utypes.h"
     39 #include "unicode/ustring.h"
     40 
     41 #ifdef U_DEBUG_TZ
     42 # include <stdio.h>
     43 # include "uresimp.h" // for debugging
     44 
     45 static void debug_tz_loc(const char *f, int32_t l)
     46 {
     47   fprintf(stderr, "%s:%d: ", f, l);
     48 }
     49 
     50 static void debug_tz_msg(const char *pat, ...)
     51 {
     52   va_list ap;
     53   va_start(ap, pat);
     54   vfprintf(stderr, pat, ap);
     55   fflush(stderr);
     56 }
     57 static char gStrBuf[256];
     58 #define U_DEBUG_TZ_STR(x) u_austrncpy(gStrBuf,x,sizeof(gStrBuf)-1)
     59 // must use double parens, i.e.:  U_DEBUG_TZ_MSG(("four is: %d",4));
     60 #define U_DEBUG_TZ_MSG(x) {debug_tz_loc(__FILE__,__LINE__);debug_tz_msg x;}
     61 #else
     62 #define U_DEBUG_TZ_MSG(x)
     63 #endif
     64 
     65 #if !UCONFIG_NO_FORMATTING
     66 
     67 #include "unicode/simpletz.h"
     68 #include "unicode/smpdtfmt.h"
     69 #include "unicode/calendar.h"
     70 #include "unicode/gregocal.h"
     71 #include "unicode/ures.h"
     72 #include "gregoimp.h"
     73 #include "uresimp.h" // struct UResourceBundle
     74 #include "olsontz.h"
     75 #include "mutex.h"
     76 #include "unicode/udata.h"
     77 #include "ucln_in.h"
     78 #include "cstring.h"
     79 #include "cmemory.h"
     80 #include "unicode/strenum.h"
     81 #include "uassert.h"
     82 #include "zonemeta.h"
     83 
     84 #define kZONEINFO "zoneinfo64"
     85 #define kREGIONS  "Regions"
     86 #define kZONES    "Zones"
     87 #define kRULES    "Rules"
     88 #define kNAMES    "Names"
     89 #define kTZVERSION  "TZVersion"
     90 #define kLINKS    "links"
     91 #define kMAX_CUSTOM_HOUR    23
     92 #define kMAX_CUSTOM_MIN     59
     93 #define kMAX_CUSTOM_SEC     59
     94 #define MINUS 0x002D
     95 #define PLUS 0x002B
     96 #define ZERO_DIGIT 0x0030
     97 #define COLON 0x003A
     98 
     99 // Static data and constants
    100 
    101 static const UChar         WORLD[] = {0x30, 0x30, 0x31, 0x00}; /* "001" */
    102 
    103 static const UChar         GMT_ID[] = {0x47, 0x4D, 0x54, 0x00}; /* "GMT" */
    104 static const UChar         Z_STR[] = {0x7A, 0x00}; /* "z" */
    105 static const UChar         ZZZZ_STR[] = {0x7A, 0x7A, 0x7A, 0x7A, 0x00}; /* "zzzz" */
    106 static const UChar         Z_UC_STR[] = {0x5A, 0x00}; /* "Z" */
    107 static const UChar         ZZZZ_UC_STR[] = {0x5A, 0x5A, 0x5A, 0x5A, 0x00}; /* "ZZZZ" */
    108 static const UChar         V_STR[] = {0x76, 0x00}; /* "v" */
    109 static const UChar         VVVV_STR[] = {0x76, 0x76, 0x76, 0x76, 0x00}; /* "vvvv" */
    110 static const UChar         V_UC_STR[] = {0x56, 0x00}; /* "V" */
    111 static const UChar         VVVV_UC_STR[] = {0x56, 0x56, 0x56, 0x56, 0x00}; /* "VVVV" */
    112 static const int32_t       GMT_ID_LENGTH = 3;
    113 
    114 static UMTX                             LOCK;
    115 static UMTX                             TZSET_LOCK;
    116 static U_NAMESPACE_QUALIFIER TimeZone*  DEFAULT_ZONE = NULL;
    117 static U_NAMESPACE_QUALIFIER TimeZone*  _GMT = NULL; // cf. TimeZone::GMT
    118 
    119 static char TZDATA_VERSION[16];
    120 static UBool TZDataVersionInitialized = FALSE;
    121 
    122 U_CDECL_BEGIN
    123 static UBool U_CALLCONV timeZone_cleanup(void)
    124 {
    125     delete DEFAULT_ZONE;
    126     DEFAULT_ZONE = NULL;
    127 
    128     delete _GMT;
    129     _GMT = NULL;
    130 
    131     uprv_memset(TZDATA_VERSION, 0, sizeof(TZDATA_VERSION));
    132     TZDataVersionInitialized = FALSE;
    133 
    134     if (LOCK) {
    135         umtx_destroy(&LOCK);
    136         LOCK = NULL;
    137     }
    138     if (TZSET_LOCK) {
    139         umtx_destroy(&TZSET_LOCK);
    140         TZSET_LOCK = NULL;
    141     }
    142 
    143     return TRUE;
    144 }
    145 U_CDECL_END
    146 
    147 U_NAMESPACE_BEGIN
    148 
    149 /**
    150  * The Olson data is stored the "zoneinfo" resource bundle.
    151  * Sub-resources are organized into three ranges of data: Zones, final
    152  * rules, and country tables.  There is also a meta-data resource
    153  * which has 3 integers: The number of zones, rules, and countries,
    154  * respectively.  The country count includes the non-country 'Default'.
    155  */
    156 static int32_t OLSON_ZONE_COUNT = 0;  // count of zones
    157 
    158 /**
    159  * Given a pointer to an open "zoneinfo" resource, load up the Olson
    160  * meta-data. Return TRUE if successful.
    161  */
    162 static UBool getOlsonMeta(const UResourceBundle* top) {
    163     if (OLSON_ZONE_COUNT == 0) {
    164         UErrorCode ec = U_ZERO_ERROR;
    165         UResourceBundle res;
    166         ures_initStackObject(&res);
    167         ures_getByKey(top, kZONES, &res, &ec);
    168         if(U_SUCCESS(ec)) {
    169             OLSON_ZONE_COUNT = ures_getSize(&res);
    170             U_DEBUG_TZ_MSG(("OZC%d\n",OLSON_ZONE_COUNT));
    171         }
    172         ures_close(&res);
    173     }
    174     return (OLSON_ZONE_COUNT > 0);
    175 }
    176 
    177 /**
    178  * Load up the Olson meta-data. Return TRUE if successful.
    179  */
    180 static UBool getOlsonMeta() {
    181     if (OLSON_ZONE_COUNT == 0) {
    182         UErrorCode ec = U_ZERO_ERROR;
    183         UResourceBundle *top = ures_openDirect(0, kZONEINFO, &ec);
    184         if (U_SUCCESS(ec)) {
    185             getOlsonMeta(top);
    186         }
    187         ures_close(top);
    188     }
    189     return (OLSON_ZONE_COUNT > 0);
    190 }
    191 
    192 static int32_t findInStringArray(UResourceBundle* array, const UnicodeString& id, UErrorCode &status)
    193 {
    194     UnicodeString copy;
    195     const UChar *u;
    196     int32_t len;
    197 
    198     int32_t start = 0;
    199     int32_t limit = ures_getSize(array);
    200     int32_t mid;
    201     int32_t lastMid = INT32_MAX;
    202     if(U_FAILURE(status) || (limit < 1)) {
    203         return -1;
    204     }
    205     U_DEBUG_TZ_MSG(("fisa: Looking for %s, between %d and %d\n", U_DEBUG_TZ_STR(UnicodeString(id).getTerminatedBuffer()), start, limit));
    206 
    207     for (;;) {
    208         mid = (int32_t)((start + limit) / 2);
    209         if (lastMid == mid) {   /* Have we moved? */
    210             break;  /* We haven't moved, and it wasn't found. */
    211         }
    212         lastMid = mid;
    213         u = ures_getStringByIndex(array, mid, &len, &status);
    214         if (U_FAILURE(status)) {
    215             break;
    216         }
    217         U_DEBUG_TZ_MSG(("tz: compare to %s, %d .. [%d] .. %d\n", U_DEBUG_TZ_STR(u), start, mid, limit));
    218         copy.setTo(TRUE, u, len);
    219         int r = id.compare(copy);
    220         if(r==0) {
    221             U_DEBUG_TZ_MSG(("fisa: found at %d\n", mid));
    222             return mid;
    223         } else if(r<0) {
    224             limit = mid;
    225         } else {
    226             start = mid;
    227         }
    228     }
    229     U_DEBUG_TZ_MSG(("fisa: not found\n"));
    230     return -1;
    231 }
    232 
    233 /**
    234  * Fetch a specific zone by name.  Replaces the getByKey call.
    235  * @param top Top timezone resource
    236  * @param id Time zone ID
    237  * @param oldbundle Bundle for reuse (or NULL).   see 'ures_open()'
    238  * @return the zone's bundle if found, or undefined if error.  Reuses oldbundle.
    239  */
    240 static UResourceBundle* getZoneByName(const UResourceBundle* top, const UnicodeString& id, UResourceBundle *oldbundle, UErrorCode& status) {
    241     // load the Rules object
    242     UResourceBundle *tmp = ures_getByKey(top, kNAMES, NULL, &status);
    243 
    244     // search for the string
    245     int32_t idx = findInStringArray(tmp, id, status);
    246 
    247     if((idx == -1) && U_SUCCESS(status)) {
    248         // not found
    249         status = U_MISSING_RESOURCE_ERROR;
    250         //ures_close(oldbundle);
    251         //oldbundle = NULL;
    252     } else {
    253         U_DEBUG_TZ_MSG(("gzbn: oldbundle= size %d, type %d, %s\n", ures_getSize(tmp), ures_getType(tmp), u_errorName(status)));
    254         tmp = ures_getByKey(top, kZONES, tmp, &status); // get Zones object from top
    255         U_DEBUG_TZ_MSG(("gzbn: loaded ZONES, size %d, type %d, path %s %s\n", ures_getSize(tmp), ures_getType(tmp), ures_getPath(tmp), u_errorName(status)));
    256         oldbundle = ures_getByIndex(tmp, idx, oldbundle, &status); // get nth Zone object
    257         U_DEBUG_TZ_MSG(("gzbn: loaded z#%d, size %d, type %d, path %s, %s\n", idx, ures_getSize(oldbundle), ures_getType(oldbundle), ures_getPath(oldbundle),  u_errorName(status)));
    258     }
    259     ures_close(tmp);
    260     if(U_FAILURE(status)) {
    261         //ures_close(oldbundle);
    262         return NULL;
    263     } else {
    264         return oldbundle;
    265     }
    266 }
    267 
    268 
    269 UResourceBundle* TimeZone::loadRule(const UResourceBundle* top, const UnicodeString& ruleid, UResourceBundle* oldbundle, UErrorCode& status) {
    270     char key[64];
    271     ruleid.extract(0, sizeof(key)-1, key, (int32_t)sizeof(key)-1, US_INV);
    272     U_DEBUG_TZ_MSG(("loadRule(%s)\n", key));
    273     UResourceBundle *r = ures_getByKey(top, kRULES, oldbundle, &status);
    274     U_DEBUG_TZ_MSG(("loadRule(%s) -> kRULES [%s]\n", key, u_errorName(status)));
    275     r = ures_getByKey(r, key, r, &status);
    276     U_DEBUG_TZ_MSG(("loadRule(%s) -> item [%s]\n", key, u_errorName(status)));
    277     return r;
    278 }
    279 
    280 /**
    281  * Given an ID, open the appropriate resource for the given time zone.
    282  * Dereference aliases if necessary.
    283  * @param id zone id
    284  * @param res resource, which must be ready for use (initialized but not open)
    285  * @param ec input-output error code
    286  * @return top-level resource bundle
    287  */
    288 static UResourceBundle* openOlsonResource(const UnicodeString& id,
    289                                           UResourceBundle& res,
    290                                           UErrorCode& ec)
    291 {
    292 #if U_DEBUG_TZ
    293     char buf[128];
    294     id.extract(0, sizeof(buf)-1, buf, sizeof(buf), "");
    295 #endif
    296     UResourceBundle *top = ures_openDirect(0, kZONEINFO, &ec);
    297     U_DEBUG_TZ_MSG(("pre: res sz=%d\n", ures_getSize(&res)));
    298     /* &res = */ getZoneByName(top, id, &res, ec);
    299     // Dereference if this is an alias.  Docs say result should be 1
    300     // but it is 0 in 2.8 (?).
    301     U_DEBUG_TZ_MSG(("Loading zone '%s' (%s, size %d) - %s\n", buf, ures_getKey((UResourceBundle*)&res), ures_getSize(&res), u_errorName(ec)));
    302     if (ures_getType(&res) == URES_INT && getOlsonMeta(top)) {
    303         int32_t deref = ures_getInt(&res, &ec) + 0;
    304         U_DEBUG_TZ_MSG(("getInt: %s - type is %d\n", u_errorName(ec), ures_getType(&res)));
    305         UResourceBundle *ares = ures_getByKey(top, kZONES, NULL, &ec); // dereference Zones section
    306         ures_getByIndex(ares, deref, &res, &ec);
    307         ures_close(ares);
    308         U_DEBUG_TZ_MSG(("alias to #%d (%s) - %s\n", deref, "??", u_errorName(ec)));
    309     } else {
    310         U_DEBUG_TZ_MSG(("not an alias - size %d\n", ures_getSize(&res)));
    311     }
    312     U_DEBUG_TZ_MSG(("%s - final status is %s\n", buf, u_errorName(ec)));
    313     return top;
    314 }
    315 
    316 // -------------------------------------
    317 
    318 const TimeZone* U_EXPORT2
    319 TimeZone::getGMT(void)
    320 {
    321     UBool needsInit;
    322     UMTX_CHECK(&LOCK, (_GMT == NULL), needsInit);   /* This is here to prevent race conditions. */
    323 
    324     // Initialize _GMT independently of other static data; it should
    325     // be valid even if we can't load the time zone UDataMemory.
    326     if (needsInit) {
    327         SimpleTimeZone *tmpGMT = new SimpleTimeZone(0, UnicodeString(TRUE, GMT_ID, GMT_ID_LENGTH));
    328         umtx_lock(&LOCK);
    329         if (_GMT == 0) {
    330             _GMT = tmpGMT;
    331             tmpGMT = NULL;
    332         }
    333         umtx_unlock(&LOCK);
    334         ucln_i18n_registerCleanup(UCLN_I18N_TIMEZONE, timeZone_cleanup);
    335         delete tmpGMT;
    336     }
    337     return _GMT;
    338 }
    339 
    340 // *****************************************************************************
    341 // class TimeZone
    342 // *****************************************************************************
    343 
    344 UOBJECT_DEFINE_ABSTRACT_RTTI_IMPLEMENTATION(TimeZone)
    345 
    346 TimeZone::TimeZone()
    347     :   UObject(), fID()
    348 {
    349 }
    350 
    351 // -------------------------------------
    352 
    353 TimeZone::TimeZone(const UnicodeString &id)
    354     :   UObject(), fID(id)
    355 {
    356 }
    357 
    358 // -------------------------------------
    359 
    360 TimeZone::~TimeZone()
    361 {
    362 }
    363 
    364 // -------------------------------------
    365 
    366 TimeZone::TimeZone(const TimeZone &source)
    367     :   UObject(source), fID(source.fID)
    368 {
    369 }
    370 
    371 // -------------------------------------
    372 
    373 TimeZone &
    374 TimeZone::operator=(const TimeZone &right)
    375 {
    376     if (this != &right) fID = right.fID;
    377     return *this;
    378 }
    379 
    380 // -------------------------------------
    381 
    382 UBool
    383 TimeZone::operator==(const TimeZone& that) const
    384 {
    385     return getDynamicClassID() == that.getDynamicClassID() &&
    386         fID == that.fID;
    387 }
    388 
    389 // -------------------------------------
    390 
    391 TimeZone* U_EXPORT2
    392 TimeZone::createTimeZone(const UnicodeString& ID)
    393 {
    394     /* We first try to lookup the zone ID in our system list.  If this
    395      * fails, we try to parse it as a custom string GMT[+-]hh:mm.  If
    396      * all else fails, we return GMT, which is probably not what the
    397      * user wants, but at least is a functioning TimeZone object.
    398      *
    399      * We cannot return NULL, because that would break compatibility
    400      * with the JDK.
    401      */
    402     TimeZone* result = createSystemTimeZone(ID);
    403 
    404     if (result == 0) {
    405         U_DEBUG_TZ_MSG(("failed to load system time zone with id - falling to custom"));
    406         result = createCustomTimeZone(ID);
    407     }
    408     if (result == 0) {
    409         U_DEBUG_TZ_MSG(("failed to load time zone with id - falling to GMT"));
    410         const TimeZone* temptz = getGMT();
    411         if (temptz == NULL) {
    412             result = NULL;
    413         } else {
    414             result = temptz->clone();
    415         }
    416     }
    417     return result;
    418 }
    419 
    420 /**
    421  * Lookup the given name in our system zone table.  If found,
    422  * instantiate a new zone of that name and return it.  If not
    423  * found, return 0.
    424  */
    425 TimeZone*
    426 TimeZone::createSystemTimeZone(const UnicodeString& id) {
    427     TimeZone* z = 0;
    428     UErrorCode ec = U_ZERO_ERROR;
    429     UResourceBundle res;
    430     ures_initStackObject(&res);
    431     U_DEBUG_TZ_MSG(("pre-err=%s\n", u_errorName(ec)));
    432     UResourceBundle *top = openOlsonResource(id, res, ec);
    433     U_DEBUG_TZ_MSG(("post-err=%s\n", u_errorName(ec)));
    434     if (U_SUCCESS(ec)) {
    435         z = new OlsonTimeZone(top, &res, ec);
    436         if (z) {
    437           z->setID(id);
    438         } else {
    439           U_DEBUG_TZ_MSG(("cstz: olson time zone failed to initialize - err %s\n", u_errorName(ec)));
    440         }
    441     }
    442     ures_close(&res);
    443     ures_close(top);
    444     if (U_FAILURE(ec)) {
    445         U_DEBUG_TZ_MSG(("cstz: failed to create, err %s\n", u_errorName(ec)));
    446         delete z;
    447         z = 0;
    448     }
    449     return z;
    450 }
    451 
    452 // -------------------------------------
    453 
    454 /**
    455  * Initialize DEFAULT_ZONE from the system default time zone.  The
    456  * caller should confirm that DEFAULT_ZONE is NULL before calling.
    457  * Upon return, DEFAULT_ZONE will not be NULL, unless operator new()
    458  * returns NULL.
    459  *
    460  * Must be called OUTSIDE mutex.
    461  */
    462 void
    463 TimeZone::initDefault()
    464 {
    465     // We access system timezone data through TPlatformUtilities,
    466     // including tzset(), timezone, and tzname[].
    467     int32_t rawOffset = 0;
    468     const char *hostID;
    469 
    470     // First, try to create a system timezone, based
    471     // on the string ID in tzname[0].
    472     {
    473         // NOTE: Local mutex here. TimeZone mutex below
    474         // mutexed to avoid threading issues in the platform functions.
    475         // Some of the locale/timezone OS functions may not be thread safe,
    476         // so the intent is that any setting from anywhere within ICU
    477         // happens while the ICU mutex is held.
    478         // The operating system might actually use ICU to implement timezones.
    479         // So we may have ICU calling ICU here, like on AIX.
    480         // In order to prevent a double lock of a non-reentrant mutex in a
    481         // different part of ICU, we use TZSET_LOCK to allow only one instance
    482         // of ICU to query these thread unsafe OS functions at any given time.
    483         Mutex lock(&TZSET_LOCK);
    484 
    485         ucln_i18n_registerCleanup(UCLN_I18N_TIMEZONE, timeZone_cleanup);
    486         uprv_tzset(); // Initialize tz... system data
    487 
    488         // Get the timezone ID from the host.  This function should do
    489         // any required host-specific remapping; e.g., on Windows this
    490         // function maps the Date and Time control panel setting to an
    491         // ICU timezone ID.
    492         hostID = uprv_tzname(0);
    493 
    494         // Invert sign because UNIX semantics are backwards
    495         rawOffset = uprv_timezone() * -U_MILLIS_PER_SECOND;
    496     }
    497 
    498     UBool initialized;
    499     UMTX_CHECK(&LOCK, (DEFAULT_ZONE != NULL), initialized);
    500     if (initialized) {
    501         /* Hrmph? Either a race condition happened, or tzset initialized ICU. */
    502         return;
    503     }
    504 
    505     TimeZone* default_zone = NULL;
    506 
    507     /* Make sure that the string is NULL terminated to prevent BoundsChecker/Purify warnings. */
    508     UnicodeString hostStrID(hostID, -1, US_INV);
    509     hostStrID.append((UChar)0);
    510     hostStrID.truncate(hostStrID.length()-1);
    511     default_zone = createSystemTimeZone(hostStrID);
    512 
    513 #ifdef U_WINDOWS
    514     // hostID points to a heap-allocated location on Windows.
    515     uprv_free(const_cast<char *>(hostID));
    516 #endif
    517 
    518     int32_t hostIDLen = hostStrID.length();
    519     if (default_zone != NULL && rawOffset != default_zone->getRawOffset()
    520         && (3 <= hostIDLen && hostIDLen <= 4))
    521     {
    522         // Uh oh. This probably wasn't a good id.
    523         // It was probably an ambiguous abbreviation
    524         delete default_zone;
    525         default_zone = NULL;
    526     }
    527 
    528     // Construct a fixed standard zone with the host's ID
    529     // and raw offset.
    530     if (default_zone == NULL) {
    531         default_zone = new SimpleTimeZone(rawOffset, hostStrID);
    532     }
    533 
    534     // If we _still_ don't have a time zone, use GMT.
    535     if (default_zone == NULL) {
    536         const TimeZone* temptz = getGMT();
    537         // If we can't use GMT, get out.
    538         if (temptz == NULL) {
    539             return;
    540         }
    541         default_zone = temptz->clone();
    542     }
    543 
    544     // If DEFAULT_ZONE is still NULL, set it up.
    545     umtx_lock(&LOCK);
    546     if (DEFAULT_ZONE == NULL) {
    547         DEFAULT_ZONE = default_zone;
    548         default_zone = NULL;
    549         ucln_i18n_registerCleanup(UCLN_I18N_TIMEZONE, timeZone_cleanup);
    550     }
    551     umtx_unlock(&LOCK);
    552 
    553     delete default_zone;
    554 }
    555 
    556 // -------------------------------------
    557 
    558 TimeZone* U_EXPORT2
    559 TimeZone::createDefault()
    560 {
    561     /* This is here to prevent race conditions. */
    562     UBool needsInit;
    563     UMTX_CHECK(&LOCK, (DEFAULT_ZONE == NULL), needsInit);
    564     if (needsInit) {
    565         initDefault();
    566     }
    567 
    568     Mutex lock(&LOCK); // In case adoptDefault is called
    569     return (DEFAULT_ZONE != NULL) ? DEFAULT_ZONE->clone() : NULL;
    570 }
    571 
    572 // -------------------------------------
    573 
    574 void U_EXPORT2
    575 TimeZone::adoptDefault(TimeZone* zone)
    576 {
    577     if (zone != NULL)
    578     {
    579         TimeZone* old = NULL;
    580 
    581         umtx_lock(&LOCK);
    582         old = DEFAULT_ZONE;
    583         DEFAULT_ZONE = zone;
    584         umtx_unlock(&LOCK);
    585 
    586         delete old;
    587         ucln_i18n_registerCleanup(UCLN_I18N_TIMEZONE, timeZone_cleanup);
    588     }
    589 }
    590 // -------------------------------------
    591 
    592 void U_EXPORT2
    593 TimeZone::setDefault(const TimeZone& zone)
    594 {
    595     adoptDefault(zone.clone());
    596 }
    597 
    598 //----------------------------------------------------------------------
    599 
    600 /**
    601  * This is the default implementation for subclasses that do not
    602  * override this method.  This implementation calls through to the
    603  * 8-argument getOffset() method after suitable computations, and
    604  * correctly adjusts GMT millis to local millis when necessary.
    605  */
    606 void TimeZone::getOffset(UDate date, UBool local, int32_t& rawOffset,
    607                          int32_t& dstOffset, UErrorCode& ec) const {
    608     if (U_FAILURE(ec)) {
    609         return;
    610     }
    611 
    612     rawOffset = getRawOffset();
    613     if (!local) {
    614         date += rawOffset; // now in local standard millis
    615     }
    616 
    617     // When local == TRUE, date might not be in local standard
    618     // millis.  getOffset taking 7 parameters used here assume
    619     // the given time in day is local standard time.
    620     // At STD->DST transition, there is a range of time which
    621     // does not exist.  When 'date' is in this time range
    622     // (and local == TRUE), this method interprets the specified
    623     // local time as DST.  At DST->STD transition, there is a
    624     // range of time which occurs twice.  In this case, this
    625     // method interprets the specified local time as STD.
    626     // To support the behavior above, we need to call getOffset
    627     // (with 7 args) twice when local == true and DST is
    628     // detected in the initial call.
    629     for (int32_t pass=0; ; ++pass) {
    630         int32_t year, month, dom, dow;
    631         double day = uprv_floor(date / U_MILLIS_PER_DAY);
    632         int32_t millis = (int32_t) (date - day * U_MILLIS_PER_DAY);
    633 
    634         Grego::dayToFields(day, year, month, dom, dow);
    635 
    636         dstOffset = getOffset(GregorianCalendar::AD, year, month, dom,
    637                               (uint8_t) dow, millis,
    638                               Grego::monthLength(year, month),
    639                               ec) - rawOffset;
    640 
    641         // Recompute if local==TRUE, dstOffset!=0.
    642         if (pass!=0 || !local || dstOffset == 0) {
    643             break;
    644         }
    645         // adjust to local standard millis
    646         date -= dstOffset;
    647     }
    648 }
    649 
    650 // -------------------------------------
    651 
    652 // New available IDs API as of ICU 2.4.  Uses StringEnumeration API.
    653 
    654 class TZEnumeration : public StringEnumeration {
    655 private:
    656 
    657     // Map into to zones.  Our results are zone[map[i]] for
    658     // i=0..len-1, where zone[i] is the i-th Olson zone.  If map==NULL
    659     // then our results are zone[i] for i=0..len-1.  Len will be zero
    660     // iff the zone data could not be loaded.
    661     int32_t* map;
    662     int32_t  len;
    663     int32_t  pos;
    664 
    665     UBool getID(int32_t i) {
    666         UErrorCode ec = U_ZERO_ERROR;
    667         int32_t idLen = 0;
    668         const UChar* id = NULL;
    669         UResourceBundle *top = ures_openDirect(0, kZONEINFO, &ec);
    670         top = ures_getByKey(top, kNAMES, top, &ec); // dereference Zones section
    671         id = ures_getStringByIndex(top, i, &idLen, &ec);
    672         if(U_FAILURE(ec)) {
    673             unistr.truncate(0);
    674         }
    675         else {
    676             unistr.fastCopyFrom(UnicodeString(TRUE, id, idLen));
    677         }
    678         ures_close(top);
    679         return U_SUCCESS(ec);
    680     }
    681 
    682 public:
    683     TZEnumeration() : map(NULL), len(0), pos(0) {
    684         if (getOlsonMeta()) {
    685             len = OLSON_ZONE_COUNT;
    686         }
    687     }
    688 
    689     TZEnumeration(int32_t rawOffset) : map(NULL), len(0), pos(0) {
    690         if (!getOlsonMeta()) {
    691             return;
    692         }
    693 
    694         // Allocate more space than we'll need.  The end of the array will
    695         // be blank.
    696         map = (int32_t*)uprv_malloc(OLSON_ZONE_COUNT * sizeof(int32_t));
    697         if (map == 0) {
    698             return;
    699         }
    700 
    701         uprv_memset(map, 0, sizeof(int32_t) * OLSON_ZONE_COUNT);
    702 
    703         UnicodeString s;
    704         for (int32_t i=0; i<OLSON_ZONE_COUNT; ++i) {
    705             if (getID(i)) {
    706                 // This is VERY inefficient.
    707                 TimeZone* z = TimeZone::createTimeZone(unistr);
    708                 // Make sure we get back the ID we wanted (if the ID is
    709                 // invalid we get back GMT).
    710                 if (z != 0 && z->getID(s) == unistr &&
    711                     z->getRawOffset() == rawOffset) {
    712                     map[len++] = i;
    713                 }
    714                 delete z;
    715             }
    716         }
    717     }
    718 
    719     TZEnumeration(const char* country) : map(NULL), len(0), pos(0) {
    720         if (!getOlsonMeta()) {
    721             return;
    722         }
    723 
    724         UErrorCode ec = U_ZERO_ERROR;
    725         UResourceBundle *res = ures_openDirect(0, kZONEINFO, &ec);
    726         ures_getByKey(res, kREGIONS, res, &ec);
    727         if (U_SUCCESS(ec) && ures_getType(res) == URES_ARRAY) {
    728             UChar uCountry[] = {0, 0, 0, 0};
    729             if (country) {
    730                 u_charsToUChars(country, uCountry, 2);
    731             } else {
    732                 u_strcpy(uCountry, WORLD);
    733             }
    734 
    735             // count matches
    736             int32_t count = 0;
    737             int32_t i;
    738             const UChar *region;
    739             for (i = 0; i < ures_getSize(res); i++) {
    740                 region = ures_getStringByIndex(res, i, NULL, &ec);
    741                 if (U_FAILURE(ec)) {
    742                     break;
    743                 }
    744                 if (u_strcmp(uCountry, region) == 0) {
    745                     count++;
    746                 }
    747             }
    748 
    749             if (count > 0) {
    750                 map = (int32_t*)uprv_malloc(sizeof(int32_t) * count);
    751                 if (map != NULL) {
    752                     int32_t idx = 0;
    753                     for (i = 0; i < ures_getSize(res); i++) {
    754                         region = ures_getStringByIndex(res, i, NULL, &ec);
    755                         if (U_FAILURE(ec)) {
    756                             break;
    757                         }
    758                         if (u_strcmp(uCountry, region) == 0) {
    759                             map[idx++] = i;
    760                         }
    761                     }
    762                     if (U_SUCCESS(ec)) {
    763                         len = count;
    764                     } else {
    765                         uprv_free(map);
    766                         map = NULL;
    767                     }
    768                 } else {
    769                     U_DEBUG_TZ_MSG(("Failed to load tz for region %s: %s\n", country, u_errorName(ec)));
    770                 }
    771             }
    772         }
    773         ures_close(res);
    774     }
    775 
    776   TZEnumeration(const TZEnumeration &other) : StringEnumeration(), map(NULL), len(0), pos(0) {
    777         if(other.len > 0) {
    778             if(other.map != NULL) {
    779                 map = (int32_t *)uprv_malloc(other.len * sizeof(int32_t));
    780                 if(map != NULL) {
    781                     len = other.len;
    782                     uprv_memcpy(map, other.map, len * sizeof(int32_t));
    783                     pos = other.pos;
    784                 }
    785             } else {
    786                 len = other.len;
    787                 pos = other.pos;
    788             }
    789         }
    790     }
    791 
    792     virtual ~TZEnumeration() {
    793         uprv_free(map);
    794     }
    795 
    796     virtual StringEnumeration *clone() const {
    797         return new TZEnumeration(*this);
    798     }
    799 
    800     virtual int32_t count(UErrorCode& status) const {
    801         return U_FAILURE(status) ? 0 : len;
    802     }
    803 
    804     virtual const UnicodeString* snext(UErrorCode& status) {
    805         if (U_SUCCESS(status) && pos < len) {
    806             getID((map == 0) ? pos : map[pos]);
    807             ++pos;
    808             return &unistr;
    809         }
    810         return 0;
    811     }
    812 
    813     virtual void reset(UErrorCode& /*status*/) {
    814         pos = 0;
    815     }
    816 
    817 public:
    818     static UClassID U_EXPORT2 getStaticClassID(void);
    819     virtual UClassID getDynamicClassID(void) const;
    820 };
    821 
    822 UOBJECT_DEFINE_RTTI_IMPLEMENTATION(TZEnumeration)
    823 
    824 StringEnumeration* U_EXPORT2
    825 TimeZone::createEnumeration() {
    826     return new TZEnumeration();
    827 }
    828 
    829 StringEnumeration* U_EXPORT2
    830 TimeZone::createEnumeration(int32_t rawOffset) {
    831     return new TZEnumeration(rawOffset);
    832 }
    833 
    834 StringEnumeration* U_EXPORT2
    835 TimeZone::createEnumeration(const char* country) {
    836     return new TZEnumeration(country);
    837 }
    838 
    839 // ---------------------------------------
    840 
    841 int32_t U_EXPORT2
    842 TimeZone::countEquivalentIDs(const UnicodeString& id) {
    843     int32_t result = 0;
    844     UErrorCode ec = U_ZERO_ERROR;
    845     UResourceBundle res;
    846     ures_initStackObject(&res);
    847     U_DEBUG_TZ_MSG(("countEquivalentIDs..\n"));
    848     UResourceBundle *top = openOlsonResource(id, res, ec);
    849     if (U_SUCCESS(ec)) {
    850         UResourceBundle r;
    851         ures_initStackObject(&r);
    852         ures_getByKey(&res, kLINKS, &r, &ec);
    853         ures_getIntVector(&r, &result, &ec);
    854         ures_close(&r);
    855     }
    856     ures_close(&res);
    857     ures_close(top);
    858     return result;
    859 }
    860 
    861 // ---------------------------------------
    862 
    863 const UnicodeString U_EXPORT2
    864 TimeZone::getEquivalentID(const UnicodeString& id, int32_t index) {
    865     U_DEBUG_TZ_MSG(("gEI(%d)\n", index));
    866     UnicodeString result;
    867     UErrorCode ec = U_ZERO_ERROR;
    868     UResourceBundle res;
    869     ures_initStackObject(&res);
    870     UResourceBundle *top = openOlsonResource(id, res, ec);
    871     int32_t zone = -1;
    872     if (U_SUCCESS(ec)) {
    873         UResourceBundle r;
    874         ures_initStackObject(&r);
    875         int32_t size;
    876         ures_getByKey(&res, kLINKS, &r, &ec);
    877         const int32_t* v = ures_getIntVector(&r, &size, &ec);
    878         if (U_SUCCESS(ec)) {
    879             if (index >= 0 && index < size && getOlsonMeta()) {
    880                 zone = v[index];
    881             }
    882         }
    883         ures_close(&r);
    884     }
    885     ures_close(&res);
    886     if (zone >= 0) {
    887         UResourceBundle *ares = ures_getByKey(top, kNAMES, NULL, &ec); // dereference Zones section
    888         if (U_SUCCESS(ec)) {
    889             int32_t idLen = 0;
    890             const UChar* id = ures_getStringByIndex(ares, zone, &idLen, &ec);
    891             result.fastCopyFrom(UnicodeString(TRUE, id, idLen));
    892             U_DEBUG_TZ_MSG(("gei(%d) -> %d, len%d, %s\n", index, zone, result.length(), u_errorName(ec)));
    893         }
    894         ures_close(ares);
    895     }
    896     ures_close(top);
    897 #if defined(U_DEBUG_TZ)
    898     if(result.length() ==0) {
    899       U_DEBUG_TZ_MSG(("equiv [__, #%d] -> 0 (%s)\n", index, u_errorName(ec)));
    900     }
    901 #endif
    902     return result;
    903 }
    904 
    905 // ---------------------------------------
    906 
    907 // These two methods are used by ZoneMeta class only.
    908 
    909 const UChar*
    910 TimeZone::dereferOlsonLink(const UnicodeString& id) {
    911     const UChar *result = NULL;
    912     UErrorCode ec = U_ZERO_ERROR;
    913     UResourceBundle *rb = ures_openDirect(NULL, kZONEINFO, &ec);
    914 
    915     // resolve zone index by name
    916     UResourceBundle *names = ures_getByKey(rb, kNAMES, NULL, &ec);
    917     int32_t idx = findInStringArray(names, id, ec);
    918     result = ures_getStringByIndex(names, idx, NULL, &ec);
    919 
    920     // open the zone bundle by index
    921     ures_getByKey(rb, kZONES, rb, &ec);
    922     ures_getByIndex(rb, idx, rb, &ec);
    923 
    924     if (U_SUCCESS(ec)) {
    925         if (ures_getType(rb) == URES_INT) {
    926             // this is a link - dereference the link
    927             int32_t deref = ures_getInt(rb, &ec);
    928             const UChar* tmp = ures_getStringByIndex(names, deref, NULL, &ec);
    929             if (U_SUCCESS(ec)) {
    930                 result = tmp;
    931             }
    932         }
    933     }
    934 
    935     ures_close(names);
    936     ures_close(rb);
    937 
    938     return result;
    939 }
    940 
    941 const UChar*
    942 TimeZone::getRegion(const UnicodeString& id) {
    943     const UChar *result = WORLD;
    944     UErrorCode ec = U_ZERO_ERROR;
    945     UResourceBundle *rb = ures_openDirect(NULL, kZONEINFO, &ec);
    946 
    947     // resolve zone index by name
    948     UResourceBundle *res = ures_getByKey(rb, kNAMES, NULL, &ec);
    949     int32_t idx = findInStringArray(res, id, ec);
    950 
    951     // get region mapping
    952     ures_getByKey(rb, kREGIONS, res, &ec);
    953     const UChar *tmp = ures_getStringByIndex(res, idx, NULL, &ec);
    954     if (U_SUCCESS(ec)) {
    955         result = tmp;
    956     }
    957 
    958     ures_close(res);
    959     ures_close(rb);
    960 
    961     return result;
    962 }
    963 
    964 // ---------------------------------------
    965 
    966 
    967 UnicodeString&
    968 TimeZone::getDisplayName(UnicodeString& result) const
    969 {
    970     return getDisplayName(FALSE,LONG,Locale::getDefault(), result);
    971 }
    972 
    973 UnicodeString&
    974 TimeZone::getDisplayName(const Locale& locale, UnicodeString& result) const
    975 {
    976     return getDisplayName(FALSE, LONG, locale, result);
    977 }
    978 
    979 UnicodeString&
    980 TimeZone::getDisplayName(UBool daylight, EDisplayType style, UnicodeString& result)  const
    981 {
    982     return getDisplayName(daylight,style, Locale::getDefault(), result);
    983 }
    984 //--------------------------------------
    985 int32_t
    986 TimeZone::getDSTSavings()const {
    987     if (useDaylightTime()) {
    988         return 3600000;
    989     }
    990     return 0;
    991 }
    992 //---------------------------------------
    993 UnicodeString&
    994 TimeZone::getDisplayName(UBool daylight, EDisplayType style, const Locale& locale, UnicodeString& result) const
    995 {
    996     // SRL TODO: cache the SDF, just like java.
    997     UErrorCode status = U_ZERO_ERROR;
    998 #ifdef U_DEBUG_TZ
    999     char buf[128];
   1000     fID.extract(0, sizeof(buf)-1, buf, sizeof(buf), "");
   1001 #endif
   1002 
   1003     // select the proper format string
   1004     UnicodeString pat;
   1005     switch(style){
   1006     case LONG:
   1007         pat = ZZZZ_STR;
   1008         break;
   1009     case SHORT_GENERIC:
   1010         pat = V_STR;
   1011         break;
   1012     case LONG_GENERIC:
   1013         pat = VVVV_STR;
   1014         break;
   1015     case SHORT_GMT:
   1016         pat = Z_UC_STR;
   1017         break;
   1018     case LONG_GMT:
   1019         pat = ZZZZ_UC_STR;
   1020         break;
   1021     case SHORT_COMMONLY_USED:
   1022         pat = V_UC_STR;
   1023         break;
   1024     case GENERIC_LOCATION:
   1025         pat = VVVV_UC_STR;
   1026         break;
   1027     default: // SHORT
   1028         pat = Z_STR;
   1029         break;
   1030     }
   1031 
   1032     SimpleDateFormat format(pat, locale, status);
   1033     U_DEBUG_TZ_MSG(("getDisplayName(%s)\n", buf));
   1034     if(!U_SUCCESS(status))
   1035     {
   1036 #ifdef U_DEBUG_TZ
   1037       char buf2[128];
   1038       result.extract(0, sizeof(buf2)-1, buf2, sizeof(buf2), "");
   1039       U_DEBUG_TZ_MSG(("getDisplayName(%s) -> %s\n", buf, buf2));
   1040 #endif
   1041       return result.remove();
   1042     }
   1043 
   1044     UDate d = Calendar::getNow();
   1045     int32_t  rawOffset;
   1046     int32_t  dstOffset;
   1047     this->getOffset(d, FALSE, rawOffset, dstOffset, status);
   1048     if (U_FAILURE(status)) {
   1049         return result.remove();
   1050     }
   1051 
   1052     if ((daylight && dstOffset != 0) ||
   1053         (!daylight && dstOffset == 0) ||
   1054         (style == SHORT_GENERIC) ||
   1055         (style == LONG_GENERIC)
   1056        ) {
   1057         // Current time and the request (daylight / not daylight) agree.
   1058         format.setTimeZone(*this);
   1059         return format.format(d, result);
   1060     }
   1061 
   1062     // Create a new SimpleTimeZone as a stand-in for this zone; the
   1063     // stand-in will have no DST, or DST during July, but the same ID and offset,
   1064     // and hence the same display name.
   1065     // We don't cache these because they're small and cheap to create.
   1066     UnicodeString tempID;
   1067     getID(tempID);
   1068     SimpleTimeZone *tz = NULL;
   1069     if(daylight && useDaylightTime()){
   1070         // The display name for daylight saving time was requested, but currently not in DST
   1071         // Set a fixed date (July 1) in this Gregorian year
   1072         GregorianCalendar cal(*this, status);
   1073         if (U_FAILURE(status)) {
   1074             return result.remove();
   1075         }
   1076         cal.set(UCAL_MONTH, UCAL_JULY);
   1077         cal.set(UCAL_DATE, 1);
   1078 
   1079         // Get July 1 date
   1080         d = cal.getTime(status);
   1081 
   1082         // Check if it is in DST
   1083         if (cal.get(UCAL_DST_OFFSET, status) == 0) {
   1084             // We need to create a fake time zone
   1085             tz = new SimpleTimeZone(rawOffset, tempID,
   1086                                 UCAL_JUNE, 1, 0, 0,
   1087                                 UCAL_AUGUST, 1, 0, 0,
   1088                                 getDSTSavings(), status);
   1089             if (U_FAILURE(status) || tz == NULL) {
   1090                 if (U_SUCCESS(status)) {
   1091                     status = U_MEMORY_ALLOCATION_ERROR;
   1092                 }
   1093                 return result.remove();
   1094             }
   1095             format.adoptTimeZone(tz);
   1096         } else {
   1097             format.setTimeZone(*this);
   1098         }
   1099     } else {
   1100         // The display name for standard time was requested, but currently in DST
   1101         // or display name for daylight saving time was requested, but this zone no longer
   1102         // observes DST.
   1103         tz = new SimpleTimeZone(rawOffset, tempID);
   1104         if (U_FAILURE(status) || tz == NULL) {
   1105             if (U_SUCCESS(status)) {
   1106                 status = U_MEMORY_ALLOCATION_ERROR;
   1107             }
   1108             return result.remove();
   1109         }
   1110         format.adoptTimeZone(tz);
   1111     }
   1112 
   1113     format.format(d, result, status);
   1114     return  result;
   1115 }
   1116 
   1117 /**
   1118  * Parse a custom time zone identifier and return a corresponding zone.
   1119  * @param id a string of the form GMT[+-]hh:mm, GMT[+-]hhmm, or
   1120  * GMT[+-]hh.
   1121  * @return a newly created SimpleTimeZone with the given offset and
   1122  * no Daylight Savings Time, or null if the id cannot be parsed.
   1123 */
   1124 TimeZone*
   1125 TimeZone::createCustomTimeZone(const UnicodeString& id)
   1126 {
   1127     int32_t sign, hour, min, sec;
   1128     if (parseCustomID(id, sign, hour, min, sec)) {
   1129         UnicodeString customID;
   1130         formatCustomID(hour, min, sec, (sign < 0), customID);
   1131         int32_t offset = sign * ((hour * 60 + min) * 60 + sec) * 1000;
   1132         return new SimpleTimeZone(offset, customID);
   1133     }
   1134     return NULL;
   1135 }
   1136 
   1137 UnicodeString&
   1138 TimeZone::getCustomID(const UnicodeString& id, UnicodeString& normalized, UErrorCode& status) {
   1139     normalized.remove();
   1140     if (U_FAILURE(status)) {
   1141         return normalized;
   1142     }
   1143     int32_t sign, hour, min, sec;
   1144     if (parseCustomID(id, sign, hour, min, sec)) {
   1145         formatCustomID(hour, min, sec, (sign < 0), normalized);
   1146     }
   1147     return normalized;
   1148 }
   1149 
   1150 UBool
   1151 TimeZone::parseCustomID(const UnicodeString& id, int32_t& sign,
   1152                         int32_t& hour, int32_t& min, int32_t& sec) {
   1153     static const int32_t         kParseFailed = -99999;
   1154 
   1155     NumberFormat* numberFormat = 0;
   1156     UnicodeString idUppercase = id;
   1157     idUppercase.toUpper();
   1158 
   1159     if (id.length() > GMT_ID_LENGTH &&
   1160         idUppercase.startsWith(GMT_ID))
   1161     {
   1162         ParsePosition pos(GMT_ID_LENGTH);
   1163         sign = 1;
   1164         hour = 0;
   1165         min = 0;
   1166         sec = 0;
   1167 
   1168         if (id[pos.getIndex()] == MINUS /*'-'*/) {
   1169             sign = -1;
   1170         } else if (id[pos.getIndex()] != PLUS /*'+'*/) {
   1171             return FALSE;
   1172         }
   1173         pos.setIndex(pos.getIndex() + 1);
   1174 
   1175         UErrorCode success = U_ZERO_ERROR;
   1176         numberFormat = NumberFormat::createInstance(success);
   1177         if(U_FAILURE(success)){
   1178             return FALSE;
   1179         }
   1180         numberFormat->setParseIntegerOnly(TRUE);
   1181 
   1182         // Look for either hh:mm, hhmm, or hh
   1183         int32_t start = pos.getIndex();
   1184         Formattable n(kParseFailed);
   1185         numberFormat->parse(id, n, pos);
   1186         if (pos.getIndex() == start) {
   1187             delete numberFormat;
   1188             return FALSE;
   1189         }
   1190         hour = n.getLong();
   1191 
   1192         if (pos.getIndex() < id.length()) {
   1193             if (pos.getIndex() - start > 2
   1194                 || id[pos.getIndex()] != COLON) {
   1195                 delete numberFormat;
   1196                 return FALSE;
   1197             }
   1198             // hh:mm
   1199             pos.setIndex(pos.getIndex() + 1);
   1200             int32_t oldPos = pos.getIndex();
   1201             n.setLong(kParseFailed);
   1202             numberFormat->parse(id, n, pos);
   1203             if ((pos.getIndex() - oldPos) != 2) {
   1204                 // must be 2 digits
   1205                 delete numberFormat;
   1206                 return FALSE;
   1207             }
   1208             min = n.getLong();
   1209             if (pos.getIndex() < id.length()) {
   1210                 if (id[pos.getIndex()] != COLON) {
   1211                     delete numberFormat;
   1212                     return FALSE;
   1213                 }
   1214                 // [:ss]
   1215                 pos.setIndex(pos.getIndex() + 1);
   1216                 oldPos = pos.getIndex();
   1217                 n.setLong(kParseFailed);
   1218                 numberFormat->parse(id, n, pos);
   1219                 if (pos.getIndex() != id.length()
   1220                         || (pos.getIndex() - oldPos) != 2) {
   1221                     delete numberFormat;
   1222                     return FALSE;
   1223                 }
   1224                 sec = n.getLong();
   1225             }
   1226         } else {
   1227             // Supported formats are below -
   1228             //
   1229             // HHmmss
   1230             // Hmmss
   1231             // HHmm
   1232             // Hmm
   1233             // HH
   1234             // H
   1235 
   1236             int32_t length = pos.getIndex() - start;
   1237             if (length <= 0 || 6 < length) {
   1238                 // invalid length
   1239                 delete numberFormat;
   1240                 return FALSE;
   1241             }
   1242             switch (length) {
   1243                 case 1:
   1244                 case 2:
   1245                     // already set to hour
   1246                     break;
   1247                 case 3:
   1248                 case 4:
   1249                     min = hour % 100;
   1250                     hour /= 100;
   1251                     break;
   1252                 case 5:
   1253                 case 6:
   1254                     sec = hour % 100;
   1255                     min = (hour/100) % 100;
   1256                     hour /= 10000;
   1257                     break;
   1258             }
   1259         }
   1260 
   1261         delete numberFormat;
   1262 
   1263         if (hour > kMAX_CUSTOM_HOUR || min > kMAX_CUSTOM_MIN || sec > kMAX_CUSTOM_SEC) {
   1264             return FALSE;
   1265         }
   1266         return TRUE;
   1267     }
   1268     return FALSE;
   1269 }
   1270 
   1271 UnicodeString&
   1272 TimeZone::formatCustomID(int32_t hour, int32_t min, int32_t sec,
   1273                          UBool negative, UnicodeString& id) {
   1274     // Create time zone ID - GMT[+|-]hhmm[ss]
   1275     id.setTo(GMT_ID);
   1276     if (hour | min | sec) {
   1277         if (negative) {
   1278             id += (UChar)MINUS;
   1279         } else {
   1280             id += (UChar)PLUS;
   1281         }
   1282 
   1283         if (hour < 10) {
   1284             id += (UChar)ZERO_DIGIT;
   1285         } else {
   1286             id += (UChar)(ZERO_DIGIT + hour/10);
   1287         }
   1288         id += (UChar)(ZERO_DIGIT + hour%10);
   1289         id += (UChar)COLON;
   1290         if (min < 10) {
   1291             id += (UChar)ZERO_DIGIT;
   1292         } else {
   1293             id += (UChar)(ZERO_DIGIT + min/10);
   1294         }
   1295         id += (UChar)(ZERO_DIGIT + min%10);
   1296 
   1297         if (sec) {
   1298             id += (UChar)COLON;
   1299             if (sec < 10) {
   1300                 id += (UChar)ZERO_DIGIT;
   1301             } else {
   1302                 id += (UChar)(ZERO_DIGIT + sec/10);
   1303             }
   1304             id += (UChar)(ZERO_DIGIT + sec%10);
   1305         }
   1306     }
   1307     return id;
   1308 }
   1309 
   1310 
   1311 UBool
   1312 TimeZone::hasSameRules(const TimeZone& other) const
   1313 {
   1314     return (getRawOffset() == other.getRawOffset() &&
   1315             useDaylightTime() == other.useDaylightTime());
   1316 }
   1317 
   1318 const char*
   1319 TimeZone::getTZDataVersion(UErrorCode& status)
   1320 {
   1321     /* This is here to prevent race conditions. */
   1322     UBool needsInit;
   1323     UMTX_CHECK(&LOCK, !TZDataVersionInitialized, needsInit);
   1324     if (needsInit) {
   1325         int32_t len = 0;
   1326         UResourceBundle *bundle = ures_openDirect(NULL, kZONEINFO, &status);
   1327         const UChar *tzver = ures_getStringByKey(bundle, kTZVERSION,
   1328             &len, &status);
   1329 
   1330         if (U_SUCCESS(status)) {
   1331             if (len >= (int32_t)sizeof(TZDATA_VERSION)) {
   1332                 // Ensure that there is always space for a trailing nul in TZDATA_VERSION
   1333                 len = sizeof(TZDATA_VERSION) - 1;
   1334             }
   1335             umtx_lock(&LOCK);
   1336             if (!TZDataVersionInitialized) {
   1337                 u_UCharsToChars(tzver, TZDATA_VERSION, len);
   1338                 TZDataVersionInitialized = TRUE;
   1339             }
   1340             umtx_unlock(&LOCK);
   1341             ucln_i18n_registerCleanup(UCLN_I18N_TIMEZONE, timeZone_cleanup);
   1342         }
   1343 
   1344         ures_close(bundle);
   1345     }
   1346     if (U_FAILURE(status)) {
   1347         return NULL;
   1348     }
   1349     return (const char*)TZDATA_VERSION;
   1350 }
   1351 
   1352 UnicodeString&
   1353 TimeZone::getCanonicalID(const UnicodeString& id, UnicodeString& canonicalID, UErrorCode& status)
   1354 {
   1355     UBool isSystemID = FALSE;
   1356     return getCanonicalID(id, canonicalID, isSystemID, status);
   1357 }
   1358 
   1359 UnicodeString&
   1360 TimeZone::getCanonicalID(const UnicodeString& id, UnicodeString& canonicalID, UBool& isSystemID,
   1361                          UErrorCode& status)
   1362 {
   1363     canonicalID.remove();
   1364     isSystemID = FALSE;
   1365     if (U_FAILURE(status)) {
   1366         return canonicalID;
   1367     }
   1368     ZoneMeta::getCanonicalSystemID(id, canonicalID, status);
   1369     if (U_SUCCESS(status)) {
   1370         isSystemID = TRUE;
   1371     } else {
   1372         // Not a system ID
   1373         status = U_ZERO_ERROR;
   1374         getCustomID(id, canonicalID, status);
   1375     }
   1376     return canonicalID;
   1377 }
   1378 
   1379 U_NAMESPACE_END
   1380 
   1381 #endif /* #if !UCONFIG_NO_FORMATTING */
   1382 
   1383 //eof
   1384