+// © 2016 and later: Unicode, Inc. and others.
+// License & terms of use: http://www.unicode.org/copyright.html
/*
*******************************************************************************
-* Copyright (C) 1997-2013, International Business Machines Corporation and *
-* others. All Rights Reserved. *
+* Copyright (C) 1997-2016, International Business Machines Corporation and
+* others. All Rights Reserved.
*******************************************************************************
*
* File TIMEZONE.CPP
#include "unicode/utypes.h"
#include "unicode/ustring.h"
+#include "uassert.h"
#include "ustr_imp.h"
#ifdef U_DEBUG_TZ
static const int32_t GMT_ID_LENGTH = 3;
static const int32_t UNKNOWN_ZONE_ID_LENGTH = 11;
-static UMutex LOCK = U_MUTEX_INITIALIZER;
-static UMutex TZSET_LOCK = U_MUTEX_INITIALIZER;
static icu::TimeZone* DEFAULT_ZONE = NULL;
-static icu::TimeZone* _GMT = NULL;
-static icu::TimeZone* _UNKNOWN_ZONE = NULL;
+static icu::UInitOnce gDefaultZoneInitOnce = U_INITONCE_INITIALIZER;
+
+alignas(icu::SimpleTimeZone)
+static char gRawGMT[sizeof(icu::SimpleTimeZone)];
+
+alignas(icu::SimpleTimeZone)
+static char gRawUNKNOWN[sizeof(icu::SimpleTimeZone)];
+
+static icu::UInitOnce gStaticZonesInitOnce = U_INITONCE_INITIALIZER;
+static UBool gStaticZonesInitialized = FALSE; // Whether the static zones are initialized and ready to use.
static char TZDATA_VERSION[16];
-static UBool TZDataVersionInitialized = FALSE;
+static icu::UInitOnce gTZDataVersionInitOnce = U_INITONCE_INITIALIZER;
static int32_t* MAP_SYSTEM_ZONES = NULL;
static int32_t* MAP_CANONICAL_SYSTEM_ZONES = NULL;
static int32_t LEN_CANONICAL_SYSTEM_ZONES = 0;
static int32_t LEN_CANONICAL_SYSTEM_LOCATION_ZONES = 0;
+static icu::UInitOnce gSystemZonesInitOnce = U_INITONCE_INITIALIZER;
+static icu::UInitOnce gCanonicalZonesInitOnce = U_INITONCE_INITIALIZER;
+static icu::UInitOnce gCanonicalLocationZonesInitOnce = U_INITONCE_INITIALIZER;
+
U_CDECL_BEGIN
static UBool U_CALLCONV timeZone_cleanup(void)
{
+ U_NAMESPACE_USE
delete DEFAULT_ZONE;
DEFAULT_ZONE = NULL;
+ gDefaultZoneInitOnce.reset();
- delete _GMT;
- _GMT = NULL;
-
- delete _UNKNOWN_ZONE;
- _UNKNOWN_ZONE = NULL;
+ if (gStaticZonesInitialized) {
+ reinterpret_cast<SimpleTimeZone*>(gRawGMT)->~SimpleTimeZone();
+ reinterpret_cast<SimpleTimeZone*>(gRawUNKNOWN)->~SimpleTimeZone();
+ gStaticZonesInitialized = FALSE;
+ gStaticZonesInitOnce.reset();
+ }
uprv_memset(TZDATA_VERSION, 0, sizeof(TZDATA_VERSION));
- TZDataVersionInitialized = FALSE;
+ gTZDataVersionInitOnce.reset();
LEN_SYSTEM_ZONES = 0;
uprv_free(MAP_SYSTEM_ZONES);
MAP_SYSTEM_ZONES = 0;
+ gSystemZonesInitOnce.reset();
LEN_CANONICAL_SYSTEM_ZONES = 0;
uprv_free(MAP_CANONICAL_SYSTEM_ZONES);
MAP_CANONICAL_SYSTEM_ZONES = 0;
+ gCanonicalZonesInitOnce.reset();
LEN_CANONICAL_SYSTEM_LOCATION_ZONES = 0;
uprv_free(MAP_CANONICAL_SYSTEM_LOCATION_ZONES);
MAP_CANONICAL_SYSTEM_LOCATION_ZONES = 0;
+ gCanonicalLocationZonesInitOnce.reset();
return TRUE;
}
UResourceBundle& res,
UErrorCode& ec)
{
-#if U_DEBUG_TZ
+#ifdef U_DEBUG_TZ
char buf[128];
id.extract(0, sizeof(buf)-1, buf, sizeof(buf), "");
#endif
namespace {
-void
-ensureStaticTimeZones() {
- UBool needsInit;
- UMTX_CHECK(&LOCK, (_GMT == NULL), needsInit); /* This is here to prevent race conditions. */
-
+void U_CALLCONV initStaticTimeZones() {
// Initialize _GMT independently of other static data; it should
// be valid even if we can't load the time zone UDataMemory.
- if (needsInit) {
- SimpleTimeZone *tmpUnknown =
- new SimpleTimeZone(0, UnicodeString(TRUE, UNKNOWN_ZONE_ID, UNKNOWN_ZONE_ID_LENGTH));
- SimpleTimeZone *tmpGMT = new SimpleTimeZone(0, UnicodeString(TRUE, GMT_ID, GMT_ID_LENGTH));
- umtx_lock(&LOCK);
- if (_UNKNOWN_ZONE == 0) {
- _UNKNOWN_ZONE = tmpUnknown;
- tmpUnknown = NULL;
- }
- if (_GMT == 0) {
- _GMT = tmpGMT;
- tmpGMT = NULL;
- }
- umtx_unlock(&LOCK);
- ucln_i18n_registerCleanup(UCLN_I18N_TIMEZONE, timeZone_cleanup);
- delete tmpUnknown;
- delete tmpGMT;
- }
+ ucln_i18n_registerCleanup(UCLN_I18N_TIMEZONE, timeZone_cleanup);
+
+ // new can't fail below, as we use placement new into staticly allocated space.
+ new(gRawGMT) SimpleTimeZone(0, UnicodeString(TRUE, GMT_ID, GMT_ID_LENGTH));
+ new(gRawUNKNOWN) SimpleTimeZone(0, UnicodeString(TRUE, UNKNOWN_ZONE_ID, UNKNOWN_ZONE_ID_LENGTH));
+
+ gStaticZonesInitialized = TRUE;
}
} // anonymous namespace
const TimeZone& U_EXPORT2
TimeZone::getUnknown()
{
- ensureStaticTimeZones();
- return *_UNKNOWN_ZONE;
+ umtx_initOnce(gStaticZonesInitOnce, &initStaticTimeZones);
+ return *reinterpret_cast<SimpleTimeZone*>(gRawUNKNOWN);
}
const TimeZone* U_EXPORT2
TimeZone::getGMT(void)
{
- ensureStaticTimeZones();
- return _GMT;
+ umtx_initOnce(gStaticZonesInitOnce, &initStaticTimeZones);
+ return reinterpret_cast<SimpleTimeZone*>(gRawGMT);
}
// *****************************************************************************
// -------------------------------------
+namespace {
+TimeZone*
+createSystemTimeZone(const UnicodeString& id, UErrorCode& ec) {
+ if (U_FAILURE(ec)) {
+ return NULL;
+ }
+ TimeZone* z = 0;
+ StackUResourceBundle res;
+ U_DEBUG_TZ_MSG(("pre-err=%s\n", u_errorName(ec)));
+ UResourceBundle *top = openOlsonResource(id, res.ref(), ec);
+ U_DEBUG_TZ_MSG(("post-err=%s\n", u_errorName(ec)));
+ if (U_SUCCESS(ec)) {
+ z = new OlsonTimeZone(top, res.getAlias(), id, ec);
+ if (z == NULL) {
+ ec = U_MEMORY_ALLOCATION_ERROR;
+ U_DEBUG_TZ_MSG(("cstz: olson time zone failed to initialize - err %s\n", u_errorName(ec)));
+ }
+ }
+ ures_close(top);
+ if (U_FAILURE(ec)) {
+ U_DEBUG_TZ_MSG(("cstz: failed to create, err %s\n", u_errorName(ec)));
+ delete z;
+ z = NULL;
+ }
+ return z;
+}
+
+/**
+ * Lookup the given name in our system zone table. If found,
+ * instantiate a new zone of that name and return it. If not
+ * found, return 0.
+ */
+TimeZone*
+createSystemTimeZone(const UnicodeString& id) {
+ UErrorCode ec = U_ZERO_ERROR;
+ return createSystemTimeZone(id, ec);
+}
+
+}
+
TimeZone* U_EXPORT2
TimeZone::createTimeZone(const UnicodeString& ID)
{
*/
TimeZone* result = createSystemTimeZone(ID);
- if (result == 0) {
+ if (result == NULL) {
U_DEBUG_TZ_MSG(("failed to load system time zone with id - falling to custom"));
result = createCustomTimeZone(ID);
}
- if (result == 0) {
+ if (result == NULL) {
U_DEBUG_TZ_MSG(("failed to load time zone with id - falling to Etc/Unknown(GMT)"));
- result = getUnknown().clone();
+ const TimeZone& unknown = getUnknown();
+ // Unknown zone uses staticly allocated memory, so creation of it can never fail due to OOM.
+ result = unknown.clone();
}
return result;
}
-/**
- * Lookup the given name in our system zone table. If found,
- * instantiate a new zone of that name and return it. If not
- * found, return 0.
- */
-TimeZone*
-TimeZone::createSystemTimeZone(const UnicodeString& id) {
- UErrorCode ec = U_ZERO_ERROR;
- return createSystemTimeZone(id, ec);
-}
-
-TimeZone*
-TimeZone::createSystemTimeZone(const UnicodeString& id, UErrorCode& ec) {
- if (U_FAILURE(ec)) {
- return NULL;
- }
- TimeZone* z = 0;
- UResourceBundle res;
- ures_initStackObject(&res);
- U_DEBUG_TZ_MSG(("pre-err=%s\n", u_errorName(ec)));
- UResourceBundle *top = openOlsonResource(id, res, ec);
- U_DEBUG_TZ_MSG(("post-err=%s\n", u_errorName(ec)));
- if (U_SUCCESS(ec)) {
- z = new OlsonTimeZone(top, &res, id, ec);
- if (z == NULL) {
- U_DEBUG_TZ_MSG(("cstz: olson time zone failed to initialize - err %s\n", u_errorName(ec)));
- }
- }
- ures_close(&res);
- ures_close(top);
- if (U_FAILURE(ec)) {
- U_DEBUG_TZ_MSG(("cstz: failed to create, err %s\n", u_errorName(ec)));
- delete z;
- z = 0;
- }
- return z;
-}
-
// -------------------------------------
-/**
- * Initialize DEFAULT_ZONE from the system default time zone. The
- * caller should confirm that DEFAULT_ZONE is NULL before calling.
- * Upon return, DEFAULT_ZONE will not be NULL, unless operator new()
- * returns NULL.
- *
- * Must be called OUTSIDE mutex.
- */
-void
-TimeZone::initDefault()
+TimeZone* U_EXPORT2
+TimeZone::detectHostTimeZone()
{
- // We access system timezone data through TPlatformUtilities,
- // including tzset(), timezone, and tzname[].
+ // We access system timezone data through uprv_tzset(), uprv_tzname(), and others,
+ // which have platform specific implementations in putil.cpp
int32_t rawOffset = 0;
const char *hostID;
+ UBool hostDetectionSucceeded = TRUE;
// First, try to create a system timezone, based
// on the string ID in tzname[0].
- {
- // NOTE: Local mutex here. TimeZone mutex below
- // mutexed to avoid threading issues in the platform functions.
- // Some of the locale/timezone OS functions may not be thread safe,
- // so the intent is that any setting from anywhere within ICU
- // happens while the ICU mutex is held.
- // The operating system might actually use ICU to implement timezones.
- // So we may have ICU calling ICU here, like on AIX.
- // In order to prevent a double lock of a non-reentrant mutex in a
- // different part of ICU, we use TZSET_LOCK to allow only one instance
- // of ICU to query these thread unsafe OS functions at any given time.
- Mutex lock(&TZSET_LOCK);
- ucln_i18n_registerCleanup(UCLN_I18N_TIMEZONE, timeZone_cleanup);
- uprv_tzset(); // Initialize tz... system data
+ uprv_tzset(); // Initialize tz... system data
- // Get the timezone ID from the host. This function should do
- // any required host-specific remapping; e.g., on Windows this
- // function maps the Date and Time control panel setting to an
- // ICU timezone ID.
- hostID = uprv_tzname(0);
+ uprv_tzname_clear_cache();
- // Invert sign because UNIX semantics are backwards
- rawOffset = uprv_timezone() * -U_MILLIS_PER_SECOND;
- }
+ // Get the timezone ID from the host. This function should do
+ // any required host-specific remapping; e.g., on Windows this
+ // function maps the Windows Time Zone name to an ICU timezone ID.
+ hostID = uprv_tzname(0);
- UBool initialized;
- UMTX_CHECK(&LOCK, (DEFAULT_ZONE != NULL), initialized);
- if (initialized) {
- /* Hrmph? Either a race condition happened, or tzset initialized ICU. */
- return;
- }
+ // Invert sign because UNIX semantics are backwards
+ rawOffset = uprv_timezone() * -U_MILLIS_PER_SECOND;
- TimeZone* default_zone = NULL;
+ TimeZone* hostZone = NULL;
- /* Make sure that the string is NULL terminated to prevent BoundsChecker/Purify warnings. */
UnicodeString hostStrID(hostID, -1, US_INV);
- hostStrID.append((UChar)0);
- hostStrID.truncate(hostStrID.length()-1);
- default_zone = createSystemTimeZone(hostStrID);
+
+ if (hostStrID.length() == 0) {
+ // The host time zone detection (or remapping) above has failed and
+ // we have no name at all. Fallback to using the Unknown zone.
+ hostStrID = UnicodeString(TRUE, UNKNOWN_ZONE_ID, UNKNOWN_ZONE_ID_LENGTH);
+ hostDetectionSucceeded = FALSE;
+ }
+
+ hostZone = createSystemTimeZone(hostStrID);
#if U_PLATFORM_USES_ONLY_WIN32_API
// hostID points to a heap-allocated location on Windows.
#endif
int32_t hostIDLen = hostStrID.length();
- if (default_zone != NULL && rawOffset != default_zone->getRawOffset()
+ if (hostZone != NULL && rawOffset != hostZone->getRawOffset()
&& (3 <= hostIDLen && hostIDLen <= 4))
{
// Uh oh. This probably wasn't a good id.
// It was probably an ambiguous abbreviation
- delete default_zone;
- default_zone = NULL;
+ delete hostZone;
+ hostZone = NULL;
}
// Construct a fixed standard zone with the host's ID
// and raw offset.
- if (default_zone == NULL) {
- default_zone = new SimpleTimeZone(rawOffset, hostStrID);
+ if (hostZone == NULL && hostDetectionSucceeded) {
+ hostZone = new SimpleTimeZone(rawOffset, hostStrID);
}
- // If we _still_ don't have a time zone, use GMT.
- if (default_zone == NULL) {
- const TimeZone* temptz = getGMT();
- // If we can't use GMT, get out.
- if (temptz == NULL) {
- return;
- }
- default_zone = temptz->clone();
+ // If we _still_ don't have a time zone, use the Unknown zone.
+ //
+ // Note: This is extremely unlikely situation. If
+ // new SimpleTimeZone(...) above fails, the following
+ // code may also fail.
+ if (hostZone == NULL) {
+ // Unknown zone uses static allocated memory, so it must always exist.
+ // However, clone() allocates memory and can fail.
+ hostZone = TimeZone::getUnknown().clone();
}
- // If DEFAULT_ZONE is still NULL, set it up.
- umtx_lock(&LOCK);
- if (DEFAULT_ZONE == NULL) {
- DEFAULT_ZONE = default_zone;
- default_zone = NULL;
- ucln_i18n_registerCleanup(UCLN_I18N_TIMEZONE, timeZone_cleanup);
- }
- umtx_unlock(&LOCK);
+ return hostZone;
+}
- delete default_zone;
+// -------------------------------------
+
+/**
+ * Initialize DEFAULT_ZONE from the system default time zone.
+ * Upon return, DEFAULT_ZONE will not be NULL, unless operator new()
+ * returns NULL.
+ */
+static void U_CALLCONV initDefault()
+{
+ ucln_i18n_registerCleanup(UCLN_I18N_TIMEZONE, timeZone_cleanup);
+
+ // If setDefault() has already been called we can skip getting the
+ // default zone information from the system.
+ if (DEFAULT_ZONE != NULL) {
+ return;
+ }
+
+ // NOTE: this code is safely single threaded, being only
+ // run via umtx_initOnce().
+ //
+ // Some of the locale/timezone OS functions may not be thread safe,
+ //
+ // The operating system might actually use ICU to implement timezones.
+ // So we may have ICU calling ICU here, like on AIX.
+ // There shouldn't be a problem with this; initOnce does not hold a mutex
+ // while the init function is being run.
+
+ // The code detecting the host time zone was separated from this
+ // and implemented as TimeZone::detectHostTimeZone()
+
+ TimeZone *default_zone = TimeZone::detectHostTimeZone();
+
+ // The only way for DEFAULT_ZONE to be non-null at this point is if the user
+ // made a thread-unsafe call to setDefault() or adoptDefault() in another
+ // thread while this thread was doing something that required getting the default.
+ U_ASSERT(DEFAULT_ZONE == NULL);
+
+ DEFAULT_ZONE = default_zone;
}
// -------------------------------------
TimeZone* U_EXPORT2
TimeZone::createDefault()
{
- /* This is here to prevent race conditions. */
- UBool needsInit;
- UMTX_CHECK(&LOCK, (DEFAULT_ZONE == NULL), needsInit);
- if (needsInit) {
- initDefault();
- }
-
- Mutex lock(&LOCK); // In case adoptDefault is called
+ umtx_initOnce(gDefaultZoneInitOnce, initDefault);
return (DEFAULT_ZONE != NULL) ? DEFAULT_ZONE->clone() : NULL;
}
{
if (zone != NULL)
{
- TimeZone* old = NULL;
-
- umtx_lock(&LOCK);
- old = DEFAULT_ZONE;
+ TimeZone *old = DEFAULT_ZONE;
DEFAULT_ZONE = zone;
- umtx_unlock(&LOCK);
-
delete old;
ucln_i18n_registerCleanup(UCLN_I18N_TIMEZONE, timeZone_cleanup);
}
//----------------------------------------------------------------------
+
+static void U_CALLCONV initMap(USystemTimeZoneType type, UErrorCode& ec) {
+ ucln_i18n_registerCleanup(UCLN_I18N_TIMEZONE, timeZone_cleanup);
+
+ UResourceBundle *res = ures_openDirect(0, kZONEINFO, &ec);
+ res = ures_getByKey(res, kNAMES, res, &ec); // dereference Zones section
+ if (U_SUCCESS(ec)) {
+ int32_t size = ures_getSize(res);
+ int32_t *m = (int32_t *)uprv_malloc(size * sizeof(int32_t));
+ if (m == NULL) {
+ ec = U_MEMORY_ALLOCATION_ERROR;
+ } else {
+ int32_t numEntries = 0;
+ for (int32_t i = 0; i < size; i++) {
+ UnicodeString id = ures_getUnicodeStringByIndex(res, i, &ec);
+ if (U_FAILURE(ec)) {
+ break;
+ }
+ if (0 == id.compare(UNKNOWN_ZONE_ID, UNKNOWN_ZONE_ID_LENGTH)) {
+ // exclude Etc/Unknown
+ continue;
+ }
+ if (type == UCAL_ZONE_TYPE_CANONICAL || type == UCAL_ZONE_TYPE_CANONICAL_LOCATION) {
+ UnicodeString canonicalID;
+ ZoneMeta::getCanonicalCLDRID(id, canonicalID, ec);
+ if (U_FAILURE(ec)) {
+ break;
+ }
+ if (canonicalID != id) {
+ // exclude aliases
+ continue;
+ }
+ }
+ if (type == UCAL_ZONE_TYPE_CANONICAL_LOCATION) {
+ const UChar *region = TimeZone::getRegion(id, ec);
+ if (U_FAILURE(ec)) {
+ break;
+ }
+ if (u_strcmp(region, WORLD) == 0) {
+ // exclude non-location ("001")
+ continue;
+ }
+ }
+ m[numEntries++] = i;
+ }
+ if (U_SUCCESS(ec)) {
+ int32_t *tmp = m;
+ m = (int32_t *)uprv_realloc(tmp, numEntries * sizeof(int32_t));
+ if (m == NULL) {
+ // realloc failed.. use the original one even it has unused
+ // area at the end
+ m = tmp;
+ }
+
+ switch(type) {
+ case UCAL_ZONE_TYPE_ANY:
+ U_ASSERT(MAP_SYSTEM_ZONES == NULL);
+ MAP_SYSTEM_ZONES = m;
+ LEN_SYSTEM_ZONES = numEntries;
+ break;
+ case UCAL_ZONE_TYPE_CANONICAL:
+ U_ASSERT(MAP_CANONICAL_SYSTEM_ZONES == NULL);
+ MAP_CANONICAL_SYSTEM_ZONES = m;
+ LEN_CANONICAL_SYSTEM_ZONES = numEntries;
+ break;
+ case UCAL_ZONE_TYPE_CANONICAL_LOCATION:
+ U_ASSERT(MAP_CANONICAL_SYSTEM_LOCATION_ZONES == NULL);
+ MAP_CANONICAL_SYSTEM_LOCATION_ZONES = m;
+ LEN_CANONICAL_SYSTEM_LOCATION_ZONES = numEntries;
+ break;
+ }
+ }
+ }
+ }
+ ures_close(res);
+}
+
+
/**
* This is the default implementation for subclasses that do not
* override this method. This implementation calls through to the
len = mapLen;
}
- UBool getID(int32_t i) {
- UErrorCode ec = U_ZERO_ERROR;
+ UBool getID(int32_t i, UErrorCode& ec) {
int32_t idLen = 0;
const UChar* id = NULL;
UResourceBundle *top = ures_openDirect(0, kZONEINFO, &ec);
int32_t* m = NULL;
switch (type) {
case UCAL_ZONE_TYPE_ANY:
+ umtx_initOnce(gSystemZonesInitOnce, &initMap, type, ec);
m = MAP_SYSTEM_ZONES;
len = LEN_SYSTEM_ZONES;
break;
case UCAL_ZONE_TYPE_CANONICAL:
+ umtx_initOnce(gCanonicalZonesInitOnce, &initMap, type, ec);
m = MAP_CANONICAL_SYSTEM_ZONES;
len = LEN_CANONICAL_SYSTEM_ZONES;
break;
case UCAL_ZONE_TYPE_CANONICAL_LOCATION:
+ umtx_initOnce(gCanonicalLocationZonesInitOnce, &initMap, type, ec);
m = MAP_CANONICAL_SYSTEM_LOCATION_ZONES;
len = LEN_CANONICAL_SYSTEM_LOCATION_ZONES;
break;
- }
- UBool needsInit = FALSE;
- UMTX_CHECK(&LOCK, (len == 0), needsInit);
- if (needsInit) {
- m = initMap(type, len, ec);
+ default:
+ ec = U_ILLEGAL_ARGUMENT_ERROR;
+ m = NULL;
+ len = 0;
+ break;
}
return m;
}
- static int32_t* initMap(USystemTimeZoneType type, int32_t& len, UErrorCode& ec) {
- len = 0;
- if (U_FAILURE(ec)) {
- return NULL;
- }
-
- int32_t *result = NULL;
-
- UResourceBundle *res = ures_openDirect(0, kZONEINFO, &ec);
- res = ures_getByKey(res, kNAMES, res, &ec); // dereference Zones section
- if (U_SUCCESS(ec)) {
- int32_t size = ures_getSize(res);
- int32_t *m = (int32_t *)uprv_malloc(size * sizeof(int32_t));
- if (m == NULL) {
- ec = U_MEMORY_ALLOCATION_ERROR;
- } else {
- int32_t numEntries = 0;
- for (int32_t i = 0; i < size; i++) {
- UnicodeString id = ures_getUnicodeStringByIndex(res, i, &ec);
- if (U_FAILURE(ec)) {
- break;
- }
- if (0 == id.compare(UNKNOWN_ZONE_ID, UNKNOWN_ZONE_ID_LENGTH)) {
- // exclude Etc/Unknown
- continue;
- }
- if (type == UCAL_ZONE_TYPE_CANONICAL || type == UCAL_ZONE_TYPE_CANONICAL_LOCATION) {
- UnicodeString canonicalID;
- ZoneMeta::getCanonicalCLDRID(id, canonicalID, ec);
- if (U_FAILURE(ec)) {
- break;
- }
- if (canonicalID != id) {
- // exclude aliases
- continue;
- }
- }
- if (type == UCAL_ZONE_TYPE_CANONICAL_LOCATION) {
- const UChar *region = TimeZone::getRegion(id, ec);
- if (U_FAILURE(ec)) {
- break;
- }
- if (u_strcmp(region, WORLD) == 0) {
- // exclude non-location ("001")
- continue;
- }
- }
- m[numEntries++] = i;
- }
- if (U_SUCCESS(ec)) {
- int32_t *tmp = m;
- m = (int32_t *)uprv_realloc(tmp, numEntries * sizeof(int32_t));
- if (m == NULL) {
- // realloc failed.. use the original one even it has unused
- // area at the end
- m = tmp;
- }
-
- umtx_lock(&LOCK);
- {
- switch(type) {
- case UCAL_ZONE_TYPE_ANY:
- if (MAP_SYSTEM_ZONES == NULL) {
- MAP_SYSTEM_ZONES = m;
- LEN_SYSTEM_ZONES = numEntries;
- m = NULL;
- ucln_i18n_registerCleanup(UCLN_I18N_TIMEZONE, timeZone_cleanup);
- }
- result = MAP_SYSTEM_ZONES;
- len = LEN_SYSTEM_ZONES;
- break;
- case UCAL_ZONE_TYPE_CANONICAL:
- if (MAP_CANONICAL_SYSTEM_ZONES == NULL) {
- MAP_CANONICAL_SYSTEM_ZONES = m;
- LEN_CANONICAL_SYSTEM_ZONES = numEntries;
- m = NULL;
- ucln_i18n_registerCleanup(UCLN_I18N_TIMEZONE, timeZone_cleanup);
- }
- result = MAP_CANONICAL_SYSTEM_ZONES;
- len = LEN_CANONICAL_SYSTEM_ZONES;
- break;
- case UCAL_ZONE_TYPE_CANONICAL_LOCATION:
- if (MAP_CANONICAL_SYSTEM_LOCATION_ZONES == NULL) {
- MAP_CANONICAL_SYSTEM_LOCATION_ZONES = m;
- LEN_CANONICAL_SYSTEM_LOCATION_ZONES = numEntries;
- m = NULL;
- ucln_i18n_registerCleanup(UCLN_I18N_TIMEZONE, timeZone_cleanup);
- }
- result = MAP_CANONICAL_SYSTEM_LOCATION_ZONES;
- len = LEN_CANONICAL_SYSTEM_LOCATION_ZONES;
- break;
- }
- }
- umtx_unlock(&LOCK);
- }
- uprv_free(m);
- }
- }
-
- ures_close(res);
- return result;
- }
-
public:
#define DEFAULT_FILTERED_MAP_SIZE 8
if (rawOffset != NULL) {
// Filter by raw offset
// Note: This is VERY inefficient
- TimeZone *z = TimeZone::createSystemTimeZone(id, ec);
+ TimeZone *z = createSystemTimeZone(id, ec);
if (U_FAILURE(ec)) {
break;
}
virtual const UnicodeString* snext(UErrorCode& status) {
if (U_SUCCESS(status) && map != NULL && pos < len) {
- getID(map[pos]);
+ getID(map[pos], status);
++pos;
return &unistr;
}
TimeZone::countEquivalentIDs(const UnicodeString& id) {
int32_t result = 0;
UErrorCode ec = U_ZERO_ERROR;
- UResourceBundle res;
- ures_initStackObject(&res);
+ StackUResourceBundle res;
U_DEBUG_TZ_MSG(("countEquivalentIDs..\n"));
- UResourceBundle *top = openOlsonResource(id, res, ec);
+ UResourceBundle *top = openOlsonResource(id, res.ref(), ec);
if (U_SUCCESS(ec)) {
- UResourceBundle r;
- ures_initStackObject(&r);
- ures_getByKey(&res, kLINKS, &r, &ec);
- ures_getIntVector(&r, &result, &ec);
- ures_close(&r);
+ StackUResourceBundle r;
+ ures_getByKey(res.getAlias(), kLINKS, r.getAlias(), &ec);
+ ures_getIntVector(r.getAlias(), &result, &ec);
}
- ures_close(&res);
ures_close(top);
return result;
}
U_DEBUG_TZ_MSG(("gEI(%d)\n", index));
UnicodeString result;
UErrorCode ec = U_ZERO_ERROR;
- UResourceBundle res;
- ures_initStackObject(&res);
- UResourceBundle *top = openOlsonResource(id, res, ec);
+ StackUResourceBundle res;
+ UResourceBundle *top = openOlsonResource(id, res.ref(), ec);
int32_t zone = -1;
if (U_SUCCESS(ec)) {
- UResourceBundle r;
- ures_initStackObject(&r);
+ StackUResourceBundle r;
int32_t size;
- ures_getByKey(&res, kLINKS, &r, &ec);
- const int32_t* v = ures_getIntVector(&r, &size, &ec);
+ ures_getByKey(res.getAlias(), kLINKS, r.getAlias(), &ec);
+ const int32_t *v = ures_getIntVector(r.getAlias(), &size, &ec);
if (U_SUCCESS(ec)) {
if (index >= 0 && index < size) {
zone = v[index];
}
}
- ures_close(&r);
}
- ures_close(&res);
if (zone >= 0) {
UResourceBundle *ares = ures_getByKey(top, kNAMES, NULL, &ec); // dereference Zones section
if (U_SUCCESS(ec)) {
int32_t idLen = 0;
- const UChar* id = ures_getStringByIndex(ares, zone, &idLen, &ec);
- result.fastCopyFrom(UnicodeString(TRUE, id, idLen));
+ const UChar* id2 = ures_getStringByIndex(ares, zone, &idLen, &ec);
+ result.fastCopyFrom(UnicodeString(TRUE, id2, idLen));
U_DEBUG_TZ_MSG(("gei(%d) -> %d, len%d, %s\n", index, zone, result.length(), u_errorName(ec)));
}
ures_close(ares);
}
UnicodeString&
-TimeZone::getDisplayName(UBool daylight, EDisplayType style, UnicodeString& result) const
+TimeZone::getDisplayName(UBool inDaylight, EDisplayType style, UnicodeString& result) const
{
- return getDisplayName(daylight,style, Locale::getDefault(), result);
+ return getDisplayName(inDaylight,style, Locale::getDefault(), result);
}
//--------------------------------------
int32_t
}
//---------------------------------------
UnicodeString&
-TimeZone::getDisplayName(UBool daylight, EDisplayType style, const Locale& locale, UnicodeString& result) const
+TimeZone::getDisplayName(UBool inDaylight, EDisplayType style, const Locale& locale, UnicodeString& result) const
{
UErrorCode status = U_ZERO_ERROR;
UDate date = Calendar::getNow();
- UTimeZoneFormatTimeType timeType;
+ UTimeZoneFormatTimeType timeType = UTZFMT_TIME_TYPE_UNKNOWN;
int32_t offset;
if (style == GENERIC_LOCATION || style == LONG_GENERIC || style == SHORT_GENERIC) {
tzfmt->format(UTZFMT_STYLE_GENERIC_SHORT, *this, date, result, &timeType);
break;
default:
- U_ASSERT(FALSE);
+ UPRV_UNREACHABLE;
}
// Generic format many use Localized GMT as the final fallback.
// When Localized GMT format is used, the result might not be
// appropriate for the requested daylight value.
- if ((daylight && timeType == UTZFMT_TIME_TYPE_STANDARD) || (!daylight && timeType == UTZFMT_TIME_TYPE_DAYLIGHT)) {
- offset = daylight ? getRawOffset() + getDSTSavings() : getRawOffset();
+ if ((inDaylight && timeType == UTZFMT_TIME_TYPE_STANDARD) || (!inDaylight && timeType == UTZFMT_TIME_TYPE_DAYLIGHT)) {
+ offset = inDaylight ? getRawOffset() + getDSTSavings() : getRawOffset();
if (style == SHORT_GENERIC) {
tzfmt->formatOffsetShortLocalizedGMT(offset, result, status);
} else {
result.remove();
return result;
}
- offset = daylight && useDaylightTime() ? getRawOffset() + getDSTSavings() : getRawOffset();
+ offset = inDaylight && useDaylightTime() ? getRawOffset() + getDSTSavings() : getRawOffset();
switch (style) {
case LONG_GMT:
tzfmt->formatOffsetLocalizedGMT(offset, result, status);
tzfmt->formatOffsetISO8601Basic(offset, FALSE, FALSE, FALSE, result, status);
break;
default:
- U_ASSERT(FALSE);
+ UPRV_UNREACHABLE;
}
} else {
UTimeZoneNameType nameType = UTZNM_UNKNOWN;
switch (style) {
case LONG:
- nameType = daylight ? UTZNM_LONG_DAYLIGHT : UTZNM_LONG_STANDARD;
+ nameType = inDaylight ? UTZNM_LONG_DAYLIGHT : UTZNM_LONG_STANDARD;
break;
case SHORT:
case SHORT_COMMONLY_USED:
- nameType = daylight ? UTZNM_SHORT_DAYLIGHT : UTZNM_SHORT_STANDARD;
+ nameType = inDaylight ? UTZNM_SHORT_DAYLIGHT : UTZNM_SHORT_STANDARD;
break;
default:
- U_ASSERT(FALSE);
+ UPRV_UNREACHABLE;
}
LocalPointer<TimeZoneNames> tznames(TimeZoneNames::createInstance(locale, status));
if (U_FAILURE(status)) {
if (result.isEmpty()) {
// Fallback to localized GMT
LocalPointer<TimeZoneFormat> tzfmt(TimeZoneFormat::createInstance(locale, status));
- offset = daylight && useDaylightTime() ? getRawOffset() + getDSTSavings() : getRawOffset();
+ offset = inDaylight && useDaylightTime() ? getRawOffset() + getDSTSavings() : getRawOffset();
if (style == LONG) {
tzfmt->formatOffsetLocalizedGMT(offset, result, status);
} else {
int32_t sign, hour, min, sec;
if (parseCustomID(id, sign, hour, min, sec)) {
formatCustomID(hour, min, sec, (sign < 0), normalized);
+ } else {
+ status = U_ILLEGAL_ARGUMENT_ERROR;
}
return normalized;
}
useDaylightTime() == other.useDaylightTime());
}
-const char*
-TimeZone::getTZDataVersion(UErrorCode& status)
-{
- /* This is here to prevent race conditions. */
- UBool needsInit;
- UMTX_CHECK(&LOCK, !TZDataVersionInitialized, needsInit);
- if (needsInit) {
- int32_t len = 0;
- UResourceBundle *bundle = ures_openDirect(NULL, kZONEINFO, &status);
- const UChar *tzver = ures_getStringByKey(bundle, kTZVERSION,
- &len, &status);
+static void U_CALLCONV initTZDataVersion(UErrorCode &status) {
+ ucln_i18n_registerCleanup(UCLN_I18N_TIMEZONE, timeZone_cleanup);
+ int32_t len = 0;
+ StackUResourceBundle bundle;
+ ures_openDirectFillIn(bundle.getAlias(), NULL, kZONEINFO, &status);
+ const UChar *tzver = ures_getStringByKey(bundle.getAlias(), kTZVERSION, &len, &status);
- if (U_SUCCESS(status)) {
- if (len >= (int32_t)sizeof(TZDATA_VERSION)) {
- // Ensure that there is always space for a trailing nul in TZDATA_VERSION
- len = sizeof(TZDATA_VERSION) - 1;
- }
- umtx_lock(&LOCK);
- if (!TZDataVersionInitialized) {
- u_UCharsToChars(tzver, TZDATA_VERSION, len);
- TZDataVersionInitialized = TRUE;
- }
- umtx_unlock(&LOCK);
- ucln_i18n_registerCleanup(UCLN_I18N_TIMEZONE, timeZone_cleanup);
+ if (U_SUCCESS(status)) {
+ if (len >= (int32_t)sizeof(TZDATA_VERSION)) {
+ // Ensure that there is always space for a trailing nul in TZDATA_VERSION
+ len = sizeof(TZDATA_VERSION) - 1;
}
-
- ures_close(bundle);
- }
- if (U_FAILURE(status)) {
- return NULL;
+ u_UCharsToChars(tzver, TZDATA_VERSION, len);
}
+}
+
+const char*
+TimeZone::getTZDataVersion(UErrorCode& status)
+{
+ umtx_initOnce(gTZDataVersionInitOnce, &initTZDataVersion, status);
return (const char*)TZDATA_VERSION;
}
return canonicalID;
}
+UnicodeString&
+TimeZone::getWindowsID(const UnicodeString& id, UnicodeString& winid, UErrorCode& status) {
+ winid.remove();
+ if (U_FAILURE(status)) {
+ return winid;
+ }
+
+ // canonicalize the input ID
+ UnicodeString canonicalID;
+ UBool isSystemID = FALSE;
+
+ getCanonicalID(id, canonicalID, isSystemID, status);
+ if (U_FAILURE(status) || !isSystemID) {
+ // mapping data is only applicable to tz database IDs
+ if (status == U_ILLEGAL_ARGUMENT_ERROR) {
+ // getWindowsID() sets an empty string where
+ // getCanonicalID() sets a U_ILLEGAL_ARGUMENT_ERROR.
+ status = U_ZERO_ERROR;
+ }
+ return winid;
+ }
+
+ UResourceBundle *mapTimezones = ures_openDirect(NULL, "windowsZones", &status);
+ ures_getByKey(mapTimezones, "mapTimezones", mapTimezones, &status);
+
+ if (U_FAILURE(status)) {
+ return winid;
+ }
+
+ UResourceBundle *winzone = NULL;
+ UBool found = FALSE;
+ while (ures_hasNext(mapTimezones) && !found) {
+ winzone = ures_getNextResource(mapTimezones, winzone, &status);
+ if (U_FAILURE(status)) {
+ break;
+ }
+ if (ures_getType(winzone) != URES_TABLE) {
+ continue;
+ }
+ UResourceBundle *regionalData = NULL;
+ while (ures_hasNext(winzone) && !found) {
+ regionalData = ures_getNextResource(winzone, regionalData, &status);
+ if (U_FAILURE(status)) {
+ break;
+ }
+ if (ures_getType(regionalData) != URES_STRING) {
+ continue;
+ }
+ int32_t len;
+ const UChar *tzids = ures_getString(regionalData, &len, &status);
+ if (U_FAILURE(status)) {
+ break;
+ }
+
+ const UChar *start = tzids;
+ UBool hasNext = TRUE;
+ while (hasNext) {
+ const UChar *end = u_strchr(start, (UChar)0x20);
+ if (end == NULL) {
+ end = tzids + len;
+ hasNext = FALSE;
+ }
+ if (canonicalID.compare(start, static_cast<int32_t>(end - start)) == 0) {
+ winid = UnicodeString(ures_getKey(winzone), -1 , US_INV);
+ found = TRUE;
+ break;
+ }
+ start = end + 1;
+ }
+ }
+ ures_close(regionalData);
+ }
+ ures_close(winzone);
+ ures_close(mapTimezones);
+
+ return winid;
+}
+
+#define MAX_WINDOWS_ID_SIZE 128
+
+UnicodeString&
+TimeZone::getIDForWindowsID(const UnicodeString& winid, const char* region, UnicodeString& id, UErrorCode& status) {
+ id.remove();
+ if (U_FAILURE(status)) {
+ return id;
+ }
+
+ UResourceBundle *zones = ures_openDirect(NULL, "windowsZones", &status);
+ ures_getByKey(zones, "mapTimezones", zones, &status);
+ if (U_FAILURE(status)) {
+ ures_close(zones);
+ return id;
+ }
+
+ UErrorCode tmperr = U_ZERO_ERROR;
+ char winidKey[MAX_WINDOWS_ID_SIZE];
+ int32_t winKeyLen = winid.extract(0, winid.length(), winidKey, sizeof(winidKey) - 1, US_INV);
+
+ if (winKeyLen == 0 || winKeyLen >= (int32_t)sizeof(winidKey)) {
+ ures_close(zones);
+ return id;
+ }
+ winidKey[winKeyLen] = 0;
+
+ ures_getByKey(zones, winidKey, zones, &tmperr); // use tmperr, because windows mapping might not
+ // be avaiable by design
+ if (U_FAILURE(tmperr)) {
+ ures_close(zones);
+ return id;
+ }
+
+ const UChar *tzid = NULL;
+ int32_t len = 0;
+ UBool gotID = FALSE;
+ if (region) {
+ const UChar *tzids = ures_getStringByKey(zones, region, &len, &tmperr); // use tmperr, because
+ // regional mapping is optional
+ if (U_SUCCESS(tmperr)) {
+ // first ID delimited by space is the defasult one
+ const UChar *end = u_strchr(tzids, (UChar)0x20);
+ if (end == NULL) {
+ id.setTo(tzids, -1);
+ } else {
+ id.setTo(tzids, static_cast<int32_t>(end - tzids));
+ }
+ gotID = TRUE;
+ }
+ }
+
+ if (!gotID) {
+ tzid = ures_getStringByKey(zones, "001", &len, &status); // using status, because "001" must be
+ // available at this point
+ if (U_SUCCESS(status)) {
+ id.setTo(tzid, len);
+ }
+ }
+
+ ures_close(zones);
+ return id;
+}
+
+
U_NAMESPACE_END
#endif /* #if !UCONFIG_NO_FORMATTING */