Coverage Report

Created: 2025-06-24 06:43

/src/icu/source/i18n/erarules.cpp
Line
Count
Source (jump to first uncovered line)
1
// © 2018 and later: Unicode, Inc. and others.
2
// License & terms of use: http://www.unicode.org/copyright.html
3
4
#include <utility>
5
6
#include "unicode/utypes.h"
7
8
#if !UCONFIG_NO_FORMATTING
9
10
#include <stdlib.h>
11
#include "unicode/ucal.h"
12
#include "unicode/ures.h"
13
#include "unicode/ustring.h"
14
#include "unicode/timezone.h"
15
#include "cmemory.h"
16
#include "cstring.h"
17
#include "erarules.h"
18
#include "gregoimp.h"
19
#include "uassert.h"
20
21
U_NAMESPACE_BEGIN
22
23
static const int32_t MAX_ENCODED_START_YEAR = 32767;
24
static const int32_t MIN_ENCODED_START_YEAR = -32768;
25
static const int32_t MIN_ENCODED_START = -2147483391;   // encodeDate(MIN_ENCODED_START_YEAR, 1, 1, ...);
26
27
static const int32_t YEAR_MASK = 0xFFFF0000;
28
static const int32_t MONTH_MASK = 0x0000FF00;
29
static const int32_t DAY_MASK = 0x000000FF;
30
31
static const int32_t MAX_INT32 = 0x7FFFFFFF;
32
static const int32_t MIN_INT32 = 0xFFFFFFFF;
33
34
static const UChar VAL_FALSE[] = {0x66, 0x61, 0x6c, 0x73, 0x65};    // "false"
35
static const UChar VAL_FALSE_LEN = 5;
36
37
0
static UBool isSet(int startDate) {
38
0
    return startDate != 0;
39
0
}
40
41
0
static UBool isValidRuleStartDate(int32_t year, int32_t month, int32_t day) {
42
0
    return year >= MIN_ENCODED_START_YEAR && year <= MAX_ENCODED_START_YEAR
43
0
            && month >= 1 && month <= 12 && day >=1 && day <= 31;
44
0
}
45
46
/**
47
 * Encode year/month/date to a single integer.
48
 * year is high 16 bits (-32768 to 32767), month is
49
 * next 8 bits and day of month is last 8 bits.
50
 *
51
 * @param year  year
52
 * @param month month (1-base)
53
 * @param day   day of month
54
 * @return  an encoded date.
55
 */
56
0
static int32_t encodeDate(int32_t year, int32_t month, int32_t day) {
57
0
    return year << 16 | month << 8 | day;
58
0
}
59
60
0
static void decodeDate(int32_t encodedDate, int32_t (&fields)[3]) {
61
0
    if (encodedDate == MIN_ENCODED_START) {
62
0
        fields[0] = MIN_INT32;
63
0
        fields[1] = 1;
64
0
        fields[2] = 1;
65
0
    } else {
66
0
        fields[0] = (encodedDate & YEAR_MASK) >> 16;
67
0
        fields[1] = (encodedDate & MONTH_MASK) >> 8;
68
0
        fields[2] = encodedDate & DAY_MASK;
69
0
    }
70
0
}
71
72
/**
73
 * Compare an encoded date with another date specified by year/month/day.
74
 * @param encoded   An encoded date
75
 * @param year      Year of another date
76
 * @param month     Month of another date
77
 * @param day       Day of another date
78
 * @return -1 when encoded date is earlier, 0 when two dates are same,
79
 *          and 1 when encoded date is later.
80
 */
81
0
static int32_t compareEncodedDateWithYMD(int encoded, int year, int month, int day) {
82
0
    if (year < MIN_ENCODED_START_YEAR) {
83
0
        if (encoded == MIN_ENCODED_START) {
84
0
            if (year > MIN_INT32 || month > 1 || day > 1) {
85
0
                return -1;
86
0
            }
87
0
            return 0;
88
0
        } else {
89
0
            return 1;
90
0
        }
91
0
    } else if (year > MAX_ENCODED_START_YEAR) {
92
0
        return -1;
93
0
    } else {
94
0
        int tmp = encodeDate(year, month, day);
95
0
        if (encoded < tmp) {
96
0
            return -1;
97
0
        } else if (encoded == tmp) {
98
0
            return 0;
99
0
        } else {
100
0
            return 1;
101
0
        }
102
0
    }
103
0
}
104
105
EraRules::EraRules(LocalMemory<int32_t>& eraStartDates, int32_t numEras)
106
0
    : numEras(numEras) {
107
0
    startDates = std::move(eraStartDates);
108
0
    initCurrentEra();
109
0
}
110
111
0
EraRules::~EraRules() {
112
0
}
113
114
0
EraRules* EraRules::createInstance(const char *calType, UBool includeTentativeEra, UErrorCode& status) {
115
0
    if(U_FAILURE(status)) {
116
0
        return nullptr;
117
0
    }
118
0
    LocalUResourceBundlePointer rb(ures_openDirect(nullptr, "supplementalData", &status));
119
0
    ures_getByKey(rb.getAlias(), "calendarData", rb.getAlias(), &status);
120
0
    ures_getByKey(rb.getAlias(), calType, rb.getAlias(), &status);
121
0
    ures_getByKey(rb.getAlias(), "eras", rb.getAlias(), &status);
122
123
0
    if (U_FAILURE(status)) {
124
0
        return nullptr;
125
0
    }
126
127
0
    int32_t numEras = ures_getSize(rb.getAlias());
128
0
    int32_t firstTentativeIdx = MAX_INT32;
129
130
0
    LocalMemory<int32_t> startDates(static_cast<int32_t *>(uprv_malloc(numEras * sizeof(int32_t))));
131
0
    if (startDates.isNull()) {
132
0
        status = U_MEMORY_ALLOCATION_ERROR;
133
0
        return nullptr;
134
0
    }
135
0
    uprv_memset(startDates.getAlias(), 0 , numEras * sizeof(int32_t));
136
137
0
    while (ures_hasNext(rb.getAlias())) {
138
0
        LocalUResourceBundlePointer eraRuleRes(ures_getNextResource(rb.getAlias(), nullptr, &status));
139
0
        if (U_FAILURE(status)) {
140
0
            return nullptr;
141
0
        }
142
0
        const char *eraIdxStr = ures_getKey(eraRuleRes.getAlias());
143
0
        char *endp;
144
0
        int32_t eraIdx = (int32_t)strtol(eraIdxStr, &endp, 10);
145
0
        if ((size_t)(endp - eraIdxStr) != uprv_strlen(eraIdxStr)) {
146
0
            status = U_INVALID_FORMAT_ERROR;
147
0
            return nullptr;
148
0
        }
149
0
        if (eraIdx < 0 || eraIdx >= numEras) {
150
0
            status = U_INVALID_FORMAT_ERROR;
151
0
            return nullptr;
152
0
        }
153
0
        if (isSet(startDates[eraIdx])) {
154
            // start date of the index was already set
155
0
            status = U_INVALID_FORMAT_ERROR;
156
0
            return nullptr;
157
0
        }
158
159
0
        UBool hasName = TRUE;
160
0
        UBool hasEnd = TRUE;
161
0
        int32_t len;
162
0
        while (ures_hasNext(eraRuleRes.getAlias())) {
163
0
            LocalUResourceBundlePointer res(ures_getNextResource(eraRuleRes.getAlias(), nullptr, &status));
164
0
            if (U_FAILURE(status)) {
165
0
                return nullptr;
166
0
            }
167
0
            const char *key = ures_getKey(res.getAlias());
168
0
            if (uprv_strcmp(key, "start") == 0) {
169
0
                const int32_t *fields = ures_getIntVector(res.getAlias(), &len, &status);
170
0
                if (U_FAILURE(status)) {
171
0
                    return nullptr;
172
0
                }
173
0
                if (len != 3 || !isValidRuleStartDate(fields[0], fields[1], fields[2])) {
174
0
                    status = U_INVALID_FORMAT_ERROR;
175
0
                    return nullptr;
176
0
                }
177
0
                startDates[eraIdx] = encodeDate(fields[0], fields[1], fields[2]);
178
0
            } else if (uprv_strcmp(key, "named") == 0) {
179
0
                const UChar *val = ures_getString(res.getAlias(), &len, &status);
180
0
                if (u_strncmp(val, VAL_FALSE, VAL_FALSE_LEN) == 0) {
181
0
                    hasName = FALSE;
182
0
                }
183
0
            } else if (uprv_strcmp(key, "end") == 0) {
184
0
                hasEnd = TRUE;
185
0
            }
186
0
        }
187
188
0
        if (isSet(startDates[eraIdx])) {
189
0
            if (hasEnd) {
190
                // This implementation assumes either start or end is available, not both.
191
                // For now, just ignore the end rule.
192
0
            }
193
0
        } else {
194
0
            if (hasEnd) {
195
0
                if (eraIdx != 0) {
196
                    // This implementation does not support end only rule for eras other than
197
                    // the first one.
198
0
                    status = U_INVALID_FORMAT_ERROR;
199
0
                    return nullptr;
200
0
                }
201
0
                U_ASSERT(eraIdx == 0);
202
0
                startDates[eraIdx] = MIN_ENCODED_START;
203
0
            } else {
204
0
                status = U_INVALID_FORMAT_ERROR;
205
0
                return nullptr;
206
0
            }
207
0
        }
208
209
0
        if (hasName) {
210
0
            if (eraIdx >= firstTentativeIdx) {
211
0
                status = U_INVALID_FORMAT_ERROR;
212
0
                return nullptr;
213
0
            }
214
0
        } else {
215
0
            if (eraIdx < firstTentativeIdx) {
216
0
                firstTentativeIdx = eraIdx;
217
0
            }
218
0
        }
219
0
    }
220
221
0
    EraRules *result;
222
0
    if (firstTentativeIdx < MAX_INT32 && !includeTentativeEra) {
223
0
        result = new EraRules(startDates, firstTentativeIdx);
224
0
    } else {
225
0
        result = new EraRules(startDates, numEras);
226
0
    }
227
228
0
    if (result == nullptr) {
229
0
        status = U_MEMORY_ALLOCATION_ERROR;
230
0
    }
231
0
    return result;
232
0
}
233
234
0
void EraRules::getStartDate(int32_t eraIdx, int32_t (&fields)[3], UErrorCode& status) const {
235
0
    if(U_FAILURE(status)) {
236
0
        return;
237
0
    }
238
0
    if (eraIdx < 0 || eraIdx >= numEras) {
239
0
        status = U_ILLEGAL_ARGUMENT_ERROR;
240
0
        return;
241
0
    }
242
0
    decodeDate(startDates[eraIdx], fields);
243
0
}
244
245
0
int32_t EraRules::getStartYear(int32_t eraIdx, UErrorCode& status) const {
246
0
    int year = MAX_INT32;   // bogus value
247
0
    if(U_FAILURE(status)) {
248
0
        return year;
249
0
    }
250
0
    if (eraIdx < 0 || eraIdx >= numEras) {
251
0
        status = U_ILLEGAL_ARGUMENT_ERROR;
252
0
        return year;
253
0
    }
254
0
    int fields[3];
255
0
    decodeDate(startDates[eraIdx], fields);
256
0
    year = fields[0];
257
258
0
    return year;
259
0
}
260
261
0
int32_t EraRules::getEraIndex(int32_t year, int32_t month, int32_t day, UErrorCode& status) const {
262
0
    if(U_FAILURE(status)) {
263
0
        return -1;
264
0
    }
265
266
0
    if (month < 1 || month > 12 || day < 1 || day > 31) {
267
0
        status = U_ILLEGAL_ARGUMENT_ERROR;
268
0
        return -1;
269
0
    }
270
0
    int32_t high = numEras; // last index + 1
271
0
    int32_t low;
272
273
    // Short circuit for recent years.  Most modern computations will
274
    // occur in the last few eras.
275
0
    if (compareEncodedDateWithYMD(startDates[getCurrentEraIndex()], year, month, day) <= 0) {
276
0
        low = getCurrentEraIndex();
277
0
    } else {
278
0
        low = 0;
279
0
    }
280
281
    // Do binary search
282
0
    while (low < high - 1) {
283
0
        int i = (low + high) / 2;
284
0
        if (compareEncodedDateWithYMD(startDates[i], year, month, day) <= 0) {
285
0
            low = i;
286
0
        } else {
287
0
            high = i;
288
0
        }
289
0
    }
290
0
    return low;
291
0
}
292
293
0
void EraRules::initCurrentEra() {
294
    // Compute local wall time in millis using ICU's default time zone.
295
0
    UErrorCode ec = U_ZERO_ERROR;
296
0
    UDate localMillis = ucal_getNow();
297
298
0
    int32_t rawOffset, dstOffset;
299
0
    TimeZone* zone = TimeZone::createDefault();
300
    // If we failed to create the default time zone, we are in a bad state and don't
301
    // really have many options. Carry on using UTC millis as a fallback.
302
0
    if (zone != nullptr) {
303
0
        zone->getOffset(localMillis, FALSE, rawOffset, dstOffset, ec);
304
0
        delete zone;
305
0
        localMillis += (rawOffset + dstOffset);
306
0
    }
307
308
0
    int year, month0, dom, dow, doy, mid;
309
0
    Grego::timeToFields(localMillis, year, month0, dom, dow, doy, mid);
310
0
    int currentEncodedDate = encodeDate(year, month0 + 1 /* changes to 1-base */, dom);
311
0
    int eraIdx = numEras - 1;
312
0
    while (eraIdx > 0) {
313
0
        if (currentEncodedDate >= startDates[eraIdx]) {
314
0
            break;
315
0
        }
316
0
        eraIdx--;
317
0
    }
318
    // Note: current era could be before the first era.
319
    // In this case, this implementation returns the first era index (0).
320
0
    currentEra = eraIdx;
321
0
}
322
323
U_NAMESPACE_END
324
#endif /* #if !UCONFIG_NO_FORMATTING */
325
326