1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
|
// © 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
/*******************************************************************************
* Copyright (C) 2008-2016, International Business Machines Corporation and
* others. All Rights Reserved.
*******************************************************************************
*
* File DTITVINF.CPP
*
*******************************************************************************
*/
#include "unicode/dtitvinf.h"
#if !UCONFIG_NO_FORMATTING
//TODO: define it in compiler time
//#define DTITVINF_DEBUG 1
#ifdef DTITVINF_DEBUG
#include <iostream>
#endif
#include "cmemory.h"
#include "cstring.h"
#include "unicode/msgfmt.h"
#include "unicode/uloc.h"
#include "unicode/ures.h"
#include "dtitv_impl.h"
#include "charstr.h"
#include "hash.h"
#include "gregoimp.h"
#include "uresimp.h"
#include "hash.h"
#include "gregoimp.h"
#include "uresimp.h"
U_NAMESPACE_BEGIN
#ifdef DTITVINF_DEBUG
#define PRINTMESG(msg) UPRV_BLOCK_MACRO_BEGIN { \
std::cout << "(" << __FILE__ << ":" << __LINE__ << ") " << msg << "\n"; \
} UPRV_BLOCK_MACRO_END
#endif
UOBJECT_DEFINE_RTTI_IMPLEMENTATION(DateIntervalInfo)
static const char gCalendarTag[]="calendar";
static const char gGregorianTag[]="gregorian";
static const char gIntervalDateTimePatternTag[]="intervalFormats";
static const char gFallbackPatternTag[]="fallback";
// {0}
static const UChar gFirstPattern[] = {LEFT_CURLY_BRACKET, DIGIT_ZERO, RIGHT_CURLY_BRACKET};
// {1}
static const UChar gSecondPattern[] = {LEFT_CURLY_BRACKET, DIGIT_ONE, RIGHT_CURLY_BRACKET};
// default fall-back
static const UChar gDefaultFallbackPattern[] = {LEFT_CURLY_BRACKET, DIGIT_ZERO, RIGHT_CURLY_BRACKET, SPACE, EN_DASH, SPACE, LEFT_CURLY_BRACKET, DIGIT_ONE, RIGHT_CURLY_BRACKET, 0};
DateIntervalInfo::DateIntervalInfo(UErrorCode& status)
: fFallbackIntervalPattern(gDefaultFallbackPattern),
fFirstDateInPtnIsLaterDate(false),
fIntervalPatterns(nullptr)
{
fIntervalPatterns = initHash(status);
}
DateIntervalInfo::DateIntervalInfo(const Locale& locale, UErrorCode& status)
: fFallbackIntervalPattern(gDefaultFallbackPattern),
fFirstDateInPtnIsLaterDate(false),
fIntervalPatterns(nullptr)
{
initializeData(locale, status);
}
void
DateIntervalInfo::setIntervalPattern(const UnicodeString& skeleton,
UCalendarDateFields lrgDiffCalUnit,
const UnicodeString& intervalPattern,
UErrorCode& status) {
if ( lrgDiffCalUnit == UCAL_HOUR_OF_DAY ) {
setIntervalPatternInternally(skeleton, UCAL_AM_PM, intervalPattern, status);
setIntervalPatternInternally(skeleton, UCAL_HOUR, intervalPattern, status);
} else if ( lrgDiffCalUnit == UCAL_DAY_OF_MONTH ||
lrgDiffCalUnit == UCAL_DAY_OF_WEEK ) {
setIntervalPatternInternally(skeleton, UCAL_DATE, intervalPattern, status);
} else {
setIntervalPatternInternally(skeleton, lrgDiffCalUnit, intervalPattern, status);
}
}
void
DateIntervalInfo::setFallbackIntervalPattern(
const UnicodeString& fallbackPattern,
UErrorCode& status) {
if ( U_FAILURE(status) ) {
return;
}
int32_t firstPatternIndex = fallbackPattern.indexOf(gFirstPattern,
UPRV_LENGTHOF(gFirstPattern), 0);
int32_t secondPatternIndex = fallbackPattern.indexOf(gSecondPattern,
UPRV_LENGTHOF(gSecondPattern), 0);
if ( firstPatternIndex == -1 || secondPatternIndex == -1 ) {
status = U_ILLEGAL_ARGUMENT_ERROR;
return;
}
if ( firstPatternIndex > secondPatternIndex ) {
fFirstDateInPtnIsLaterDate = true;
}
fFallbackIntervalPattern = fallbackPattern;
}
DateIntervalInfo::DateIntervalInfo(const DateIntervalInfo& dtitvinf)
: UObject(dtitvinf),
fIntervalPatterns(nullptr)
{
*this = dtitvinf;
}
DateIntervalInfo&
DateIntervalInfo::operator=(const DateIntervalInfo& dtitvinf) {
if ( this == &dtitvinf ) {
return *this;
}
UErrorCode status = U_ZERO_ERROR;
deleteHash(fIntervalPatterns);
fIntervalPatterns = initHash(status);
copyHash(dtitvinf.fIntervalPatterns, fIntervalPatterns, status);
if ( U_FAILURE(status) ) {
return *this;
}
fFallbackIntervalPattern = dtitvinf.fFallbackIntervalPattern;
fFirstDateInPtnIsLaterDate = dtitvinf.fFirstDateInPtnIsLaterDate;
return *this;
}
DateIntervalInfo*
DateIntervalInfo::clone() const {
return new DateIntervalInfo(*this);
}
DateIntervalInfo::~DateIntervalInfo() {
deleteHash(fIntervalPatterns);
fIntervalPatterns = nullptr;
}
bool
DateIntervalInfo::operator==(const DateIntervalInfo& other) const {
bool equal = (
fFallbackIntervalPattern == other.fFallbackIntervalPattern &&
fFirstDateInPtnIsLaterDate == other.fFirstDateInPtnIsLaterDate );
if ( equal ) {
equal = fIntervalPatterns->equals(*(other.fIntervalPatterns));
}
return equal;
}
UnicodeString&
DateIntervalInfo::getIntervalPattern(const UnicodeString& skeleton,
UCalendarDateFields field,
UnicodeString& result,
UErrorCode& status) const {
if ( U_FAILURE(status) ) {
return result;
}
const UnicodeString* patternsOfOneSkeleton = (UnicodeString*) fIntervalPatterns->get(skeleton);
if ( patternsOfOneSkeleton != nullptr ) {
IntervalPatternIndex index = calendarFieldToIntervalIndex(field, status);
if ( U_FAILURE(status) ) {
return result;
}
const UnicodeString& intervalPattern = patternsOfOneSkeleton[index];
if ( !intervalPattern.isEmpty() ) {
result = intervalPattern;
}
}
return result;
}
UBool
DateIntervalInfo::getDefaultOrder() const {
return fFirstDateInPtnIsLaterDate;
}
UnicodeString&
DateIntervalInfo::getFallbackIntervalPattern(UnicodeString& result) const {
result = fFallbackIntervalPattern;
return result;
}
#define ULOC_LOCALE_IDENTIFIER_CAPACITY (ULOC_FULLNAME_CAPACITY + 1 + ULOC_KEYWORD_AND_VALUES_CAPACITY)
static const int32_t PATH_PREFIX_LENGTH = 17;
static const UChar PATH_PREFIX[] = {SOLIDUS, CAP_L, CAP_O, CAP_C, CAP_A, CAP_L, CAP_E, SOLIDUS,
LOW_C, LOW_A, LOW_L, LOW_E, LOW_N, LOW_D, LOW_A, LOW_R, SOLIDUS};
static const int32_t PATH_SUFFIX_LENGTH = 16;
static const UChar PATH_SUFFIX[] = {SOLIDUS, LOW_I, LOW_N, LOW_T, LOW_E, LOW_R, LOW_V, LOW_A,
LOW_L, CAP_F, LOW_O, LOW_R, LOW_M, LOW_A, LOW_T, LOW_S};
/**
* Sink for enumerating all of the date interval skeletons.
*/
struct DateIntervalInfo::DateIntervalSink : public ResourceSink {
// Output data
DateIntervalInfo &dateIntervalInfo;
// Next calendar type
UnicodeString nextCalendarType;
DateIntervalSink(DateIntervalInfo &diInfo, const char *currentCalendarType)
: dateIntervalInfo(diInfo), nextCalendarType(currentCalendarType, -1, US_INV) { }
virtual ~DateIntervalSink();
virtual void put(const char *key, ResourceValue &value, UBool /*noFallback*/, UErrorCode &errorCode) override {
if (U_FAILURE(errorCode)) { return; }
// Iterate over all the calendar entries and only pick the 'intervalFormats' table.
ResourceTable dateIntervalData = value.getTable(errorCode);
if (U_FAILURE(errorCode)) { return; }
for (int32_t i = 0; dateIntervalData.getKeyAndValue(i, key, value); i++) {
if (uprv_strcmp(key, gIntervalDateTimePatternTag) != 0) {
continue;
}
// Handle aliases and tables. Ignore the rest.
if (value.getType() == URES_ALIAS) {
// Get the calendar type for the alias path.
const UnicodeString &aliasPath = value.getAliasUnicodeString(errorCode);
if (U_FAILURE(errorCode)) { return; }
nextCalendarType.remove();
getCalendarTypeFromPath(aliasPath, nextCalendarType, errorCode);
if (U_FAILURE(errorCode)) {
resetNextCalendarType();
}
break;
} else if (value.getType() == URES_TABLE) {
// Iterate over all the skeletons in the 'intervalFormat' table.
ResourceTable skeletonData = value.getTable(errorCode);
if (U_FAILURE(errorCode)) { return; }
for (int32_t j = 0; skeletonData.getKeyAndValue(j, key, value); j++) {
if (value.getType() == URES_TABLE) {
// Process the skeleton
processSkeletonTable(key, value, errorCode);
if (U_FAILURE(errorCode)) { return; }
}
}
break;
}
}
}
/**
* Processes the patterns for a skeleton table
*/
void processSkeletonTable(const char *key, ResourceValue &value, UErrorCode &errorCode) {
if (U_FAILURE(errorCode)) { return; }
// Iterate over all the patterns in the current skeleton table
const char *currentSkeleton = key;
ResourceTable patternData = value.getTable(errorCode);
if (U_FAILURE(errorCode)) { return; }
for (int32_t k = 0; patternData.getKeyAndValue(k, key, value); k++) {
if (value.getType() == URES_STRING) {
// Process the key
UCalendarDateFields calendarField = validateAndProcessPatternLetter(key);
// If the calendar field has a valid value
if (calendarField < UCAL_FIELD_COUNT) {
// Set the interval pattern
setIntervalPatternIfAbsent(currentSkeleton, calendarField, value, errorCode);
if (U_FAILURE(errorCode)) { return; }
}
}
}
}
/**
* Extracts the calendar type from the path.
*/
static void getCalendarTypeFromPath(const UnicodeString &path, UnicodeString &calendarType,
UErrorCode &errorCode) {
if (U_FAILURE(errorCode)) { return; }
if (!path.startsWith(PATH_PREFIX, PATH_PREFIX_LENGTH) || !path.endsWith(PATH_SUFFIX, PATH_SUFFIX_LENGTH)) {
errorCode = U_INVALID_FORMAT_ERROR;
return;
}
path.extractBetween(PATH_PREFIX_LENGTH, path.length() - PATH_SUFFIX_LENGTH, calendarType);
}
/**
* Validates and processes the pattern letter
*/
UCalendarDateFields validateAndProcessPatternLetter(const char *patternLetter) {
// Check that patternLetter is just one letter
char c0;
if ((c0 = patternLetter[0]) != 0 && patternLetter[1] == 0) {
// Check that the pattern letter is accepted
if (c0 == 'G') {
return UCAL_ERA;
} else if (c0 == 'y') {
return UCAL_YEAR;
} else if (c0 == 'M') {
return UCAL_MONTH;
} else if (c0 == 'd') {
return UCAL_DATE;
} else if (c0 == 'a') {
return UCAL_AM_PM;
} else if (c0 == 'B') {
// TODO: Using AM/PM as a proxy for flexible day period isn't really correct, but it's close
return UCAL_AM_PM;
} else if (c0 == 'h' || c0 == 'H') {
return UCAL_HOUR;
} else if (c0 == 'm') {
return UCAL_MINUTE;
}// TODO(ticket:12190): Why icu4c doesn't accept the calendar field "s" but icu4j does?
}
return UCAL_FIELD_COUNT;
}
/**
* Stores the interval pattern for the current skeleton in the internal data structure
* if it's not present.
*/
void setIntervalPatternIfAbsent(const char *currentSkeleton, UCalendarDateFields lrgDiffCalUnit,
const ResourceValue &value, UErrorCode &errorCode) {
// Check if the pattern has already been stored on the data structure
IntervalPatternIndex index =
dateIntervalInfo.calendarFieldToIntervalIndex(lrgDiffCalUnit, errorCode);
if (U_FAILURE(errorCode)) { return; }
UnicodeString skeleton(currentSkeleton, -1, US_INV);
UnicodeString* patternsOfOneSkeleton =
(UnicodeString*)(dateIntervalInfo.fIntervalPatterns->get(skeleton));
if (patternsOfOneSkeleton == nullptr || patternsOfOneSkeleton[index].isEmpty()) {
UnicodeString pattern = value.getUnicodeString(errorCode);
dateIntervalInfo.setIntervalPatternInternally(skeleton, lrgDiffCalUnit,
pattern, errorCode);
}
}
const UnicodeString &getNextCalendarType() {
return nextCalendarType;
}
void resetNextCalendarType() {
nextCalendarType.setToBogus();
}
};
// Virtual destructors must be defined out of line.
DateIntervalInfo::DateIntervalSink::~DateIntervalSink() {}
void
DateIntervalInfo::initializeData(const Locale& locale, UErrorCode& status)
{
fIntervalPatterns = initHash(status);
if (U_FAILURE(status)) {
return;
}
const char *locName = locale.getName();
// Get the correct calendar type
const char * calendarTypeToUse = gGregorianTag; // initial default
char calendarType[ULOC_KEYWORDS_CAPACITY]; // to be filled in with the type to use, if all goes well
char localeWithCalendarKey[ULOC_LOCALE_IDENTIFIER_CAPACITY];
// obtain a locale that always has the calendar key value that should be used
(void)ures_getFunctionalEquivalent(localeWithCalendarKey, ULOC_LOCALE_IDENTIFIER_CAPACITY, nullptr,
"calendar", "calendar", locName, nullptr, FALSE, &status);
localeWithCalendarKey[ULOC_LOCALE_IDENTIFIER_CAPACITY-1] = 0; // ensure null termination
// now get the calendar key value from that locale
int32_t calendarTypeLen = uloc_getKeywordValue(localeWithCalendarKey, "calendar", calendarType,
ULOC_KEYWORDS_CAPACITY, &status);
if (U_SUCCESS(status) && calendarTypeLen < ULOC_KEYWORDS_CAPACITY) {
calendarTypeToUse = calendarType;
}
status = U_ZERO_ERROR;
// Instantiate the resource bundles
UResourceBundle *rb, *calBundle;
rb = ures_open(nullptr, locName, &status);
if (U_FAILURE(status)) {
return;
}
calBundle = ures_getByKeyWithFallback(rb, gCalendarTag, nullptr, &status);
if (U_SUCCESS(status)) {
UResourceBundle *calTypeBundle, *itvDtPtnResource;
// Get the fallback pattern
const UChar* resStr = nullptr;
int32_t resStrLen = 0;
calTypeBundle = ures_getByKeyWithFallback(calBundle, calendarTypeToUse, nullptr, &status);
itvDtPtnResource = ures_getByKeyWithFallback(calTypeBundle,
gIntervalDateTimePatternTag, nullptr, &status);
// TODO(ICU-20400): After the fixing, we should find the "fallback" from
// the rb directly by the path "calendar/${calendar}/intervalFormats/fallback".
if ( U_SUCCESS(status) ) {
resStr = ures_getStringByKeyWithFallback(itvDtPtnResource, gFallbackPatternTag,
&resStrLen, &status);
}
if ( U_SUCCESS(status) && (resStr != nullptr)) {
UnicodeString pattern = UnicodeString(TRUE, resStr, resStrLen);
setFallbackIntervalPattern(pattern, status);
}
ures_close(itvDtPtnResource);
ures_close(calTypeBundle);
// Instantiate the sink
DateIntervalSink sink(*this, calendarTypeToUse);
const UnicodeString &calendarTypeToUseUString = sink.getNextCalendarType();
// Already loaded calendar types
Hashtable loadedCalendarTypes(FALSE, status);
if (U_SUCCESS(status)) {
while (!calendarTypeToUseUString.isBogus()) {
// Set an error when a loop is detected
if (loadedCalendarTypes.geti(calendarTypeToUseUString) == 1) {
status = U_INVALID_FORMAT_ERROR;
break;
}
// Register the calendar type to avoid loops
loadedCalendarTypes.puti(calendarTypeToUseUString, 1, status);
if (U_FAILURE(status)) { break; }
// Get the calendar string
CharString calTypeBuffer;
calTypeBuffer.appendInvariantChars(calendarTypeToUseUString, status);
if (U_FAILURE(status)) { break; }
const char *calType = calTypeBuffer.data();
// Reset the next calendar type to load.
sink.resetNextCalendarType();
// Get all resources for this calendar type
ures_getAllItemsWithFallback(calBundle, calType, sink, status);
}
}
}
// Close the opened resource bundles
ures_close(calBundle);
ures_close(rb);
}
void
DateIntervalInfo::setIntervalPatternInternally(const UnicodeString& skeleton,
UCalendarDateFields lrgDiffCalUnit,
const UnicodeString& intervalPattern,
UErrorCode& status) {
IntervalPatternIndex index = calendarFieldToIntervalIndex(lrgDiffCalUnit,status);
if ( U_FAILURE(status) ) {
return;
}
UnicodeString* patternsOfOneSkeleton = (UnicodeString*)(fIntervalPatterns->get(skeleton));
UBool emptyHash = false;
if ( patternsOfOneSkeleton == nullptr ) {
patternsOfOneSkeleton = new UnicodeString[kIPI_MAX_INDEX];
if (patternsOfOneSkeleton == nullptr) {
status = U_MEMORY_ALLOCATION_ERROR;
return;
}
emptyHash = true;
}
patternsOfOneSkeleton[index] = intervalPattern;
if ( emptyHash == TRUE ) {
fIntervalPatterns->put(skeleton, patternsOfOneSkeleton, status);
}
}
void
DateIntervalInfo::parseSkeleton(const UnicodeString& skeleton,
int32_t* skeletonFieldWidth) {
const int8_t PATTERN_CHAR_BASE = 0x41;
int32_t i;
for ( i = 0; i < skeleton.length(); ++i ) {
// it is an ASCII char in skeleton
int8_t ch = (int8_t)skeleton.charAt(i);
++skeletonFieldWidth[ch - PATTERN_CHAR_BASE];
}
}
UBool
DateIntervalInfo::stringNumeric(int32_t fieldWidth, int32_t anotherFieldWidth,
char patternLetter) {
if ( patternLetter == 'M' ) {
if ( (fieldWidth <= 2 && anotherFieldWidth > 2) ||
(fieldWidth > 2 && anotherFieldWidth <= 2 )) {
return true;
}
}
return false;
}
const UnicodeString*
DateIntervalInfo::getBestSkeleton(const UnicodeString& skeleton,
int8_t& bestMatchDistanceInfo) const {
#ifdef DTITVINF_DEBUG
char result[1000];
char result_1[1000];
char mesg[2000];
skeleton.extract(0, skeleton.length(), result, "UTF-8");
sprintf(mesg, "in getBestSkeleton: skeleton: %s; \n", result);
PRINTMESG(mesg)
#endif
int32_t inputSkeletonFieldWidth[] =
{
// A B C D E F G H I J K L M N O
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
// P Q R S T U V W X Y Z
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
// a b c d e f g h i j k l m n o
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
// p q r s t u v w x y z
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
};
int32_t skeletonFieldWidth[] =
{
// A B C D E F G H I J K L M N O
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
// P Q R S T U V W X Y Z
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
// a b c d e f g h i j k l m n o
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
// p q r s t u v w x y z
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
};
const int32_t DIFFERENT_FIELD = 0x1000;
const int32_t STRING_NUMERIC_DIFFERENCE = 0x100;
const int32_t BASE = 0x41;
// hack for certain alternate characters
// resource bundles only have time skeletons containing 'v', 'h', and 'H'
// but not time skeletons containing 'z', 'K', or 'k'
// the skeleton may also include 'a' or 'b', which never occur in the resource bundles, so strip them out too
UBool replacedAlternateChars = false;
const UnicodeString* inputSkeleton = &skeleton;
UnicodeString copySkeleton;
if ( skeleton.indexOf(LOW_Z) != -1 || skeleton.indexOf(LOW_K) != -1 || skeleton.indexOf(CAP_K) != -1 || skeleton.indexOf(LOW_A) != -1 || skeleton.indexOf(LOW_B) != -1 ) {
copySkeleton = skeleton;
copySkeleton.findAndReplace(UnicodeString(LOW_Z), UnicodeString(LOW_V));
copySkeleton.findAndReplace(UnicodeString(LOW_K), UnicodeString(CAP_H));
copySkeleton.findAndReplace(UnicodeString(CAP_K), UnicodeString(LOW_H));
copySkeleton.findAndReplace(UnicodeString(LOW_A), UnicodeString());
copySkeleton.findAndReplace(UnicodeString(LOW_B), UnicodeString());
inputSkeleton = ©Skeleton;
replacedAlternateChars = true;
}
parseSkeleton(*inputSkeleton, inputSkeletonFieldWidth);
int32_t bestDistance = MAX_POSITIVE_INT;
const UnicodeString* bestSkeleton = nullptr;
// 0 means exact the same skeletons;
// 1 means having the same field, but with different length,
// 2 means only z/v, h/K, or H/k differs
// -1 means having different field.
bestMatchDistanceInfo = 0;
int8_t fieldLength = UPRV_LENGTHOF(skeletonFieldWidth);
int32_t pos = UHASH_FIRST;
const UHashElement* elem = nullptr;
while ( (elem = fIntervalPatterns->nextElement(pos)) != nullptr ) {
const UHashTok keyTok = elem->key;
UnicodeString* newSkeleton = (UnicodeString*)keyTok.pointer;
#ifdef DTITVINF_DEBUG
skeleton->extract(0, skeleton->length(), result, "UTF-8");
sprintf(mesg, "available skeletons: skeleton: %s; \n", result);
PRINTMESG(mesg)
#endif
// clear skeleton field width
int8_t i;
for ( i = 0; i < fieldLength; ++i ) {
skeletonFieldWidth[i] = 0;
}
parseSkeleton(*newSkeleton, skeletonFieldWidth);
// calculate distance
int32_t distance = 0;
int8_t fieldDifference = 1;
for ( i = 0; i < fieldLength; ++i ) {
int32_t inputFieldWidth = inputSkeletonFieldWidth[i];
int32_t fieldWidth = skeletonFieldWidth[i];
if ( inputFieldWidth == fieldWidth ) {
continue;
}
if ( inputFieldWidth == 0 ) {
fieldDifference = -1;
distance += DIFFERENT_FIELD;
} else if ( fieldWidth == 0 ) {
fieldDifference = -1;
distance += DIFFERENT_FIELD;
} else if (stringNumeric(inputFieldWidth, fieldWidth,
(char)(i+BASE) ) ) {
distance += STRING_NUMERIC_DIFFERENCE;
} else {
distance += (inputFieldWidth > fieldWidth) ?
(inputFieldWidth - fieldWidth) :
(fieldWidth - inputFieldWidth);
}
}
if ( distance < bestDistance ) {
bestSkeleton = newSkeleton;
bestDistance = distance;
bestMatchDistanceInfo = fieldDifference;
}
if ( distance == 0 ) {
bestMatchDistanceInfo = 0;
break;
}
}
if ( replacedAlternateChars && bestMatchDistanceInfo != -1 ) {
bestMatchDistanceInfo = 2;
}
return bestSkeleton;
}
DateIntervalInfo::IntervalPatternIndex
DateIntervalInfo::calendarFieldToIntervalIndex(UCalendarDateFields field,
UErrorCode& status) {
if ( U_FAILURE(status) ) {
return kIPI_MAX_INDEX;
}
IntervalPatternIndex index = kIPI_MAX_INDEX;
switch ( field ) {
case UCAL_ERA:
index = kIPI_ERA;
break;
case UCAL_YEAR:
index = kIPI_YEAR;
break;
case UCAL_MONTH:
index = kIPI_MONTH;
break;
case UCAL_DATE:
case UCAL_DAY_OF_WEEK:
//case UCAL_DAY_OF_MONTH:
index = kIPI_DATE;
break;
case UCAL_AM_PM:
index = kIPI_AM_PM;
break;
case UCAL_HOUR:
case UCAL_HOUR_OF_DAY:
index = kIPI_HOUR;
break;
case UCAL_MINUTE:
index = kIPI_MINUTE;
break;
case UCAL_SECOND:
index = kIPI_SECOND;
break;
case UCAL_MILLISECOND:
index = kIPI_MILLISECOND;
break;
default:
status = U_ILLEGAL_ARGUMENT_ERROR;
}
return index;
}
void
DateIntervalInfo::deleteHash(Hashtable* hTable)
{
if ( hTable == nullptr ) {
return;
}
int32_t pos = UHASH_FIRST;
const UHashElement* element = nullptr;
while ( (element = hTable->nextElement(pos)) != nullptr ) {
const UHashTok valueTok = element->value;
const UnicodeString* value = (UnicodeString*)valueTok.pointer;
delete[] value;
}
delete fIntervalPatterns;
}
U_CDECL_BEGIN
/**
* set hash table value comparator
*
* @param val1 one value in comparison
* @param val2 the other value in comparison
* @return TRUE if 2 values are the same, FALSE otherwise
*/
static UBool U_CALLCONV dtitvinfHashTableValueComparator(UHashTok val1, UHashTok val2);
static UBool
U_CALLCONV dtitvinfHashTableValueComparator(UHashTok val1, UHashTok val2) {
const UnicodeString* pattern1 = (UnicodeString*)val1.pointer;
const UnicodeString* pattern2 = (UnicodeString*)val2.pointer;
UBool ret = TRUE;
int8_t i;
for ( i = 0; i < DateIntervalInfo::kMaxIntervalPatternIndex && ret == TRUE; ++i ) {
ret = (pattern1[i] == pattern2[i]);
}
return ret;
}
U_CDECL_END
Hashtable*
DateIntervalInfo::initHash(UErrorCode& status) {
if ( U_FAILURE(status) ) {
return nullptr;
}
Hashtable* hTable;
if ( (hTable = new Hashtable(FALSE, status)) == nullptr ) {
status = U_MEMORY_ALLOCATION_ERROR;
return nullptr;
}
if ( U_FAILURE(status) ) {
delete hTable;
return nullptr;
}
hTable->setValueComparator(dtitvinfHashTableValueComparator);
return hTable;
}
void
DateIntervalInfo::copyHash(const Hashtable* source,
Hashtable* target,
UErrorCode& status) {
if ( U_FAILURE(status) ) {
return;
}
int32_t pos = UHASH_FIRST;
const UHashElement* element = nullptr;
if ( source ) {
while ( (element = source->nextElement(pos)) != nullptr ) {
const UHashTok keyTok = element->key;
const UnicodeString* key = (UnicodeString*)keyTok.pointer;
const UHashTok valueTok = element->value;
const UnicodeString* value = (UnicodeString*)valueTok.pointer;
UnicodeString* copy = new UnicodeString[kIPI_MAX_INDEX];
if (copy == nullptr) {
status = U_MEMORY_ALLOCATION_ERROR;
return;
}
int8_t i;
for ( i = 0; i < kIPI_MAX_INDEX; ++i ) {
copy[i] = value[i];
}
target->put(UnicodeString(*key), copy, status);
if ( U_FAILURE(status) ) {
return;
}
}
}
}
U_NAMESPACE_END
#endif
|