Debian Codegraph @

intl/components/src/TimeZone.cpp

raw
1 /* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
4
5 #include "mozilla/intl/TimeZone.h"
6
7 #include "mozilla/Vector.h"
8
9 #include <algorithm>
10 #include <string_view>
11
12 #include "unicode/uenum.h"
13 #if MOZ_INTL_USE_ICU_CPP_TIMEZONE
14 # include "unicode/basictz.h"
15 #endif
16
17 namespace mozilla::intl {
18
19 /* static */
20 Result<UniquePtr<TimeZone>, ICUError> TimeZone::TryCreate(
21 Maybe<Span<const char16_t>> aTimeZoneOverride) {
22 const UChar* zoneID = nullptr;
23 int32_t zoneIDLen = 0;
24 if (aTimeZoneOverride) {
25 zoneIDLen = static_cast<int32_t>(aTimeZoneOverride->Length());
26 zoneID = aTimeZoneOverride->Elements();
27 }
28
29 #if MOZ_INTL_USE_ICU_CPP_TIMEZONE
30 UniquePtr<icu::TimeZone> tz;
31 if (zoneID) {
32 tz.reset(
33 icu::TimeZone::createTimeZone(icu::UnicodeString(zoneID, zoneIDLen)));
34 } else {
35 tz.reset(icu::TimeZone::createDefault());
36 }
37 MOZ_ASSERT(tz);
38
39 if (*tz == icu::TimeZone::getUnknown()) {
40 return Err(ICUError::InternalError);
41 }
42
43 return MakeUnique<TimeZone>(std::move(tz));
44 #else
45 // An empty string is used for the root locale. This is regarded as the base
46 // locale of all locales, and is used as the language/country neutral locale
47 // for locale sensitive operations.
48 const char* rootLocale = "";
49
50 UErrorCode status = U_ZERO_ERROR;
51 UCalendar* calendar =
52 ucal_open(zoneID, zoneIDLen, rootLocale, UCAL_DEFAULT, &status);
53
54 if (U_FAILURE(status)) {
55 return Err(ToICUError(status));
56 }
57
58 // https://tc39.es/ecma262/#sec-time-values-and-time-range
59 //
60 // A time value supports a slightly smaller range of -8,640,000,000,000,000 to
61 // 8,640,000,000,000,000 milliseconds.
62 constexpr double StartOfTime = -8.64e15;
63
64 // Ensure all computations are performed in the proleptic Gregorian calendar.
65 ucal_setGregorianChange(calendar, StartOfTime, &status);
66
67 if (U_FAILURE(status)) {
68 return Err(ToICUError(status));
69 }
70
71 return MakeUnique<TimeZone>(calendar);
72 #endif
73 }
74
75 Result<int32_t, ICUError> TimeZone::GetRawOffsetMs() {
76 #if MOZ_INTL_USE_ICU_CPP_TIMEZONE
77 return mTimeZone->getRawOffset();
78 #else
79 // Reset the time in case the calendar has been modified.
80 UErrorCode status = U_ZERO_ERROR;
81 ucal_setMillis(mCalendar, ucal_getNow(), &status);
82 if (U_FAILURE(status)) {
83 return Err(ToICUError(status));
84 }
85
86 int32_t offset = ucal_get(mCalendar, UCAL_ZONE_OFFSET, &status);
87 if (U_FAILURE(status)) {
88 return Err(ToICUError(status));
89 }
90
91 return offset;
92 #endif
93 }
94
95 Result<int32_t, ICUError> TimeZone::GetDSTOffsetMs(int64_t aUTCMilliseconds) {
96 UDate date = UDate(aUTCMilliseconds);
97
98 #if MOZ_INTL_USE_ICU_CPP_TIMEZONE
99 constexpr bool dateIsLocalTime = false;
100 int32_t rawOffset, dstOffset;
101 UErrorCode status = U_ZERO_ERROR;
102
103 mTimeZone->getOffset(date, dateIsLocalTime, rawOffset, dstOffset, status);
104 if (U_FAILURE(status)) {
105 return Err(ToICUError(status));
106 }
107
108 return dstOffset;
109 #else
110 UErrorCode status = U_ZERO_ERROR;
111 ucal_setMillis(mCalendar, date, &status);
112 if (U_FAILURE(status)) {
113 return Err(ToICUError(status));
114 }
115
116 int32_t dstOffset = ucal_get(mCalendar, UCAL_DST_OFFSET, &status);
117 if (U_FAILURE(status)) {
118 return Err(ToICUError(status));
119 }
120
121 return dstOffset;
122 #endif
123 }
124
125 Result<int32_t, ICUError> TimeZone::GetOffsetMs(int64_t aUTCMilliseconds) {
126 UDate date = UDate(aUTCMilliseconds);
127
128 #if MOZ_INTL_USE_ICU_CPP_TIMEZONE
129 constexpr bool dateIsLocalTime = false;
130 int32_t rawOffset, dstOffset;
131 UErrorCode status = U_ZERO_ERROR;
132
133 mTimeZone->getOffset(date, dateIsLocalTime, rawOffset, dstOffset, status);
134 if (U_FAILURE(status)) {
135 return Err(ToICUError(status));
136 }
137
138 return rawOffset + dstOffset;
139 #else
140 UErrorCode status = U_ZERO_ERROR;
141 ucal_setMillis(mCalendar, date, &status);
142 if (U_FAILURE(status)) {
143 return Err(ToICUError(status));
144 }
145
146 int32_t rawOffset = ucal_get(mCalendar, UCAL_ZONE_OFFSET, &status);
147 if (U_FAILURE(status)) {
148 return Err(ToICUError(status));
149 }
150
151 int32_t dstOffset = ucal_get(mCalendar, UCAL_DST_OFFSET, &status);
152 if (U_FAILURE(status)) {
153 return Err(ToICUError(status));
154 }
155
156 return rawOffset + dstOffset;
157 #endif
158 }
159
160 Result<int32_t, ICUError> TimeZone::GetUTCOffsetMs(int64_t aLocalMilliseconds) {
161 // https://tc39.es/ecma262/#sec-local-time-zone-adjustment
162 //
163 // LocalTZA ( t, isUTC )
164 //
165 // When t_local represents local time repeating multiple times at a negative
166 // time zone transition (e.g. when the daylight saving time ends or the time
167 // zone offset is decreased due to a time zone rule change) or skipped local
168 // time at a positive time zone transitions (e.g. when the daylight saving
169 // time starts or the time zone offset is increased due to a time zone rule
170 // change), t_local must be interpreted using the time zone offset before the
171 // transition.
172 constexpr LocalOption skippedTime = LocalOption::Former;
173 constexpr LocalOption repeatedTime = LocalOption::Former;
174
175 return GetUTCOffsetMs(aLocalMilliseconds, skippedTime, repeatedTime);
176 }
177
178 static UTimeZoneLocalOption ToUTimeZoneLocalOption(
179 TimeZone::LocalOption aOption) {
180 switch (aOption) {
181 case TimeZone::LocalOption::Former:
182 return UTimeZoneLocalOption::UCAL_TZ_LOCAL_FORMER;
183 case TimeZone::LocalOption::Latter:
184 return UTimeZoneLocalOption::UCAL_TZ_LOCAL_LATTER;
185 }
186 MOZ_CRASH("Unexpected TimeZone::LocalOption");
187 }
188
189 Result<int32_t, ICUError> TimeZone::GetUTCOffsetMs(int64_t aLocalMilliseconds,
190 LocalOption aSkippedTime,
191 LocalOption aRepeatedTime) {
192 UDate date = UDate(aLocalMilliseconds);
193 UTimeZoneLocalOption skippedTime = ToUTimeZoneLocalOption(aSkippedTime);
194 UTimeZoneLocalOption repeatedTime = ToUTimeZoneLocalOption(aRepeatedTime);
195
196 #if MOZ_INTL_USE_ICU_CPP_TIMEZONE
197 int32_t rawOffset, dstOffset;
198 UErrorCode status = U_ZERO_ERROR;
199
200 // All ICU TimeZone classes derive from BasicTimeZone, so we can safely
201 // perform the static_cast.
202 // Once <https://unicode-org.atlassian.net/browse/ICU-13705> is fixed we
203 // can remove this extra cast.
204 auto* basicTz = static_cast<icu::BasicTimeZone*>(mTimeZone.get());
205 basicTz->getOffsetFromLocal(date, skippedTime, repeatedTime, rawOffset,
206 dstOffset, status);
207 if (U_FAILURE(status)) {
208 return Err(ToICUError(status));
209 }
210
211 return rawOffset + dstOffset;
212 #else
213 UErrorCode status = U_ZERO_ERROR;
214 ucal_setMillis(mCalendar, date, &status);
215 if (U_FAILURE(status)) {
216 return Err(ToICUError(status));
217 }
218
219 int32_t rawOffset, dstOffset;
220 ucal_getTimeZoneOffsetFromLocal(mCalendar, skippedTime, repeatedTime,
221 &rawOffset, &dstOffset, &status);
222 if (U_FAILURE(status)) {
223 return Err(ToICUError(status));
224 }
225
226 return rawOffset + dstOffset;
227 #endif
228 }
229
230 Result<Maybe<int64_t>, ICUError> TimeZone::GetPreviousTransition(
231 int64_t aUTCMilliseconds) {
232 UDate date = UDate(aUTCMilliseconds);
233
234 #if MOZ_INTL_USE_ICU_CPP_TIMEZONE
235 // All ICU TimeZone classes derive from BasicTimeZone, so we can safely
236 // perform the static_cast.
237 auto* basicTz = static_cast<icu::BasicTimeZone*>(mTimeZone.get());
238
239 constexpr bool inclusive = false;
240 icu::TimeZoneTransition transition;
241 if (!basicTz->getPreviousTransition(date, inclusive, transition)) {
242 return Maybe<int64_t>();
243 }
244 return Some(int64_t(transition.getTime()));
245 #else
246 UDate transition = 0;
247 UErrorCode status = U_ZERO_ERROR;
248 bool found = ucal_getTimeZoneTransitionDate(
249 mCalendar, UCAL_TZ_TRANSITION_PREVIOUS, &transition, &status);
250 if (U_FAILURE(status)) {
251 return Err(ToICUError(status));
252 }
253 if (!found) {
254 return Maybe<int64_t>();
255 }
256 return Some(int64_t(transition));
257 #endif
258 }
259
260 Result<Maybe<int64_t>, ICUError> TimeZone::GetNextTransition(
261 int64_t aUTCMilliseconds) {
262 UDate date = UDate(aUTCMilliseconds);
263
264 #if MOZ_INTL_USE_ICU_CPP_TIMEZONE
265 // All ICU TimeZone classes derive from BasicTimeZone, so we can safely
266 // perform the static_cast.
267 auto* basicTz = static_cast<icu::BasicTimeZone*>(mTimeZone.get());
268
269 constexpr bool inclusive = false;
270 icu::TimeZoneTransition transition;
271 if (!basicTz->getNextTransition(date, inclusive, transition)) {
272 return Maybe<int64_t>();
273 }
274 return Some(int64_t(transition.getTime()));
275 #else
276 UDate transition = 0;
277 UErrorCode status = U_ZERO_ERROR;
278 bool found = ucal_getTimeZoneTransitionDate(
279 mCalendar, UCAL_TZ_TRANSITION_NEXT, &transition, &status);
280 if (U_FAILURE(status)) {
281 return Err(ToICUError(status));
282 }
283 if (!found) {
284 return Maybe<int64_t>();
285 }
286 return Some(int64_t(transition));
287 #endif
288 }
289
290 using TimeZoneIdentifierVector =
291 Vector<char16_t, TimeZone::TimeZoneIdentifierLength>;
292
293 #if !MOZ_INTL_USE_ICU_CPP_TIMEZONE
294 static bool IsUnknownTimeZone(const TimeZoneIdentifierVector& timeZone) {
295 constexpr std::string_view unknownTimeZone = UCAL_UNKNOWN_ZONE_ID;
296
297 return timeZone.length() == unknownTimeZone.length() &&
298 std::equal(timeZone.begin(), timeZone.end(), unknownTimeZone.begin(),
299 unknownTimeZone.end());
300 }
301
302 static ICUResult SetDefaultTimeZone(TimeZoneIdentifierVector& timeZone) {
303 // The string mustn't already be null-terminated.
304 MOZ_ASSERT_IF(!timeZone.empty(), timeZone.end()[-1] != '\0');
305
306 // The time zone identifier must be a null-terminated string.
307 if (!timeZone.append('\0')) {
308 return Err(ICUError::OutOfMemory);
309 }
310
311 UErrorCode status = U_ZERO_ERROR;
312 ucal_setDefaultTimeZone(timeZone.begin(), &status);
313 if (U_FAILURE(status)) {
314 return Err(ToICUError(status));
315 }
316
317 return Ok{};
318 }
319 #endif
320
321 Result<bool, ICUError> TimeZone::SetDefaultTimeZone(
322 Span<const char> aTimeZone) {
323 #if MOZ_INTL_USE_ICU_CPP_TIMEZONE
324 icu::UnicodeString tzid(aTimeZone.data(), aTimeZone.size(), US_INV);
325 if (tzid.isBogus()) {
326 return Err(ICUError::OutOfMemory);
327 }
328
329 UniquePtr<icu::TimeZone> newTimeZone(icu::TimeZone::createTimeZone(tzid));
330 MOZ_ASSERT(newTimeZone);
331
332 if (*newTimeZone != icu::TimeZone::getUnknown()) {
333 // adoptDefault() takes ownership of the time zone.
334 icu::TimeZone::adoptDefault(newTimeZone.release());
335 return true;
336 }
337 #else
338 TimeZoneIdentifierVector tzid;
339 if (!tzid.append(aTimeZone.data(), aTimeZone.size())) {
340 return Err(ICUError::OutOfMemory);
341 }
342
343 // Retrieve the current default time zone in case we need to restore it.
344 TimeZoneIdentifierVector defaultTimeZone;
345 MOZ_TRY(FillBufferWithICUCall(defaultTimeZone, ucal_getDefaultTimeZone));
346
347 // Try to set the new time zone.
348 MOZ_TRY(mozilla::intl::SetDefaultTimeZone(tzid));
349
350 // Check if the time zone was actually applied.
351 TimeZoneIdentifierVector newTimeZone;
352 MOZ_TRY(FillBufferWithICUCall(newTimeZone, ucal_getDefaultTimeZone));
353
354 // Return if the new time zone was successfully applied.
355 if (!IsUnknownTimeZone(newTimeZone)) {
356 return true;
357 }
358
359 // Otherwise restore the original time zone.
360 MOZ_TRY(mozilla::intl::SetDefaultTimeZone(defaultTimeZone));
361 #endif
362
363 return false;
364 }
365
366 ICUResult TimeZone::SetDefaultTimeZoneFromHostTimeZone() {
367 #if MOZ_INTL_USE_ICU_CPP_TIMEZONE
368 if (icu::TimeZone* defaultZone = icu::TimeZone::detectHostTimeZone()) {
369 icu::TimeZone::adoptDefault(defaultZone);
370 }
371 #else
372 TimeZoneIdentifierVector hostTimeZone;
373 MOZ_TRY(FillBufferWithICUCall(hostTimeZone, ucal_getHostTimeZone));
374
375 MOZ_TRY(mozilla::intl::SetDefaultTimeZone(hostTimeZone));
376 #endif
377
378 return Ok{};
379 }
380
381 Result<Span<const char>, ICUError> TimeZone::GetTZDataVersion() {
382 UErrorCode status = U_ZERO_ERROR;
383 const char* tzdataVersion = ucal_getTZDataVersion(&status);
384 if (U_FAILURE(status)) {
385 return Err(ToICUError(status));
386 }
387 return MakeStringSpan(tzdataVersion);
388 }
389
390 Result<SpanEnumeration<char>, ICUError> TimeZone::GetAvailableTimeZones(
391 const char* aRegion) {
392 // Get the time zones that are commonly used in the given region. Uses the
393 // UCAL_ZONE_TYPE_ANY filter so we have more fine-grained control over the
394 // returned time zones and don't omit time zones which are considered links in
395 // ICU, but are treated as proper zones in IANA.
396 UErrorCode status = U_ZERO_ERROR;
397 UEnumeration* enumeration = ucal_openTimeZoneIDEnumeration(
398 UCAL_ZONE_TYPE_ANY, aRegion, nullptr, &status);
399 if (U_FAILURE(status)) {
400 return Err(ToICUError(status));
401 }
402
403 return SpanEnumeration<char>(enumeration);
404 }
405
406 Result<SpanEnumeration<char>, ICUError> TimeZone::GetAvailableTimeZones() {
407 UErrorCode status = U_ZERO_ERROR;
408 UEnumeration* enumeration = ucal_openTimeZones(&status);
409 if (U_FAILURE(status)) {
410 return Err(ToICUError(status));
411 }
412
413 return SpanEnumeration<char>(enumeration);
414 }
415
416 #if !MOZ_INTL_USE_ICU_CPP_TIMEZONE
417 TimeZone::~TimeZone() {
418 MOZ_ASSERT(mCalendar);
419 ucal_close(mCalendar);
420 }
421 #endif
422
423 } // namespace mozilla::intl