#if U_CHARSET_FAMILY==U_EBCDIC_FAMILY /** * If we are on EBCDIC, use an iterator which will * traverse the bundles in ASCII order.
*/ #define U_USE_ASCII_BUNDLE_ITERATOR #define U_SORT_ASCII_BUNDLE_ITERATOR #endif
// ***************************************************************************** // class DateTimePatternGenerator // ***************************************************************************** staticconst char16_t Canonical_Items[] = { // GyQMwWEDFdaHmsSv
CAP_G, LOW_Y, CAP_Q, CAP_M, LOW_W, CAP_W, CAP_E,
CAP_D, CAP_F, LOW_D, LOW_A, // The UDATPG_x_FIELD constants and these fields have a different order than in ICU4J
CAP_H, LOW_M, LOW_S, CAP_S, LOW_V, 0
};
{LOW_A, UDATPG_DAYPERIOD_FIELD, DT_SHORT, 1, 3},
{LOW_A, UDATPG_DAYPERIOD_FIELD, DT_LONG, 4, 0},
{LOW_A, UDATPG_DAYPERIOD_FIELD, DT_NARROW, 5, 0},
{LOW_B, UDATPG_DAYPERIOD_FIELD, DT_SHORT - DT_DELTA, 1, 3},
{LOW_B, UDATPG_DAYPERIOD_FIELD, DT_LONG - DT_DELTA, 4, 0},
{LOW_B, UDATPG_DAYPERIOD_FIELD, DT_NARROW - DT_DELTA, 5, 0}, // b needs to be closer to a than to B, so we make this 3*DT_DELTA
{CAP_B, UDATPG_DAYPERIOD_FIELD, DT_SHORT - 3*DT_DELTA, 1, 3},
{CAP_B, UDATPG_DAYPERIOD_FIELD, DT_LONG - 3*DT_DELTA, 4, 0},
{CAP_B, UDATPG_DAYPERIOD_FIELD, DT_NARROW - 3*DT_DELTA, 5, 0},
{CAP_H, UDATPG_HOUR_FIELD, DT_NUMERIC + 10*DT_DELTA, 1, 2}, // 24 hour
{LOW_K, UDATPG_HOUR_FIELD, DT_NUMERIC + 11*DT_DELTA, 1, 2}, // 24 hour
{LOW_H, UDATPG_HOUR_FIELD, DT_NUMERIC, 1, 2}, // 12 hour
{CAP_K, UDATPG_HOUR_FIELD, DT_NUMERIC + DT_DELTA, 1, 2}, // 12 hour // The C code has had versions of the following 3, keep & update. Should not need these, but... // Without these, certain tests using e.g. staticGetSkeleton fail because j/J in patterns // get skipped instead of mapped to the right hour chars, for example in // DateFormatTest::TestPatternFromSkeleton // IntlTestDateTimePatternGeneratorAPI:: testStaticGetSkeleton // DateIntervalFormatTest::testTicket11985 // Need to investigate better handling of jJC replacement e.g. in staticGetSkeleton.
{CAP_J, UDATPG_HOUR_FIELD, DT_NUMERIC + 5*DT_DELTA, 1, 2}, // 12/24 hour no AM/PM
{LOW_J, UDATPG_HOUR_FIELD, DT_NUMERIC + 6*DT_DELTA, 1, 6}, // 12/24 hour
{CAP_C, UDATPG_HOUR_FIELD, DT_NUMERIC + 7*DT_DELTA, 1, 6}, // 12/24 hour with preferred dayPeriods for 12
{0, UDATPG_FIELD_COUNT, 0, 0, 0} , // last row of dtTypes[]
};
staticconstchar* const CLDR_FIELD_APPEND[] = { "Era", "Year", "Quarter", "Month", "Week", "*", "Day-Of-Week", "*", "*", "Day", "DayPeriod", // The UDATPG_x_FIELD constants and these fields have a different order than in ICU4J "Hour", "Minute", "Second", "FractionalSecond", "Timezone"
};
staticconstchar* const CLDR_FIELD_NAME[UDATPG_FIELD_COUNT] = { "era", "year", "quarter", "month", "week", "weekOfMonth", "weekday", "dayOfYear", "weekdayOfMonth", "day", "dayperiod", // The UDATPG_x_FIELD constants and these fields have a different order than in ICU4J "hour", "minute", "second", "fractionalSecond", "zone"
};
// Value deleter for hashmap.
U_CFUNC void U_CALLCONV deleteAllowedHourFormats(void *ptr) {
uprv_free(ptr);
}
// Close hashmap at cleanup.
U_CFUNC UBool U_CALLCONV allowedHourFormatsCleanup() {
uhash_close(localeToAllowedHourFormatsMap); returntrue;
}
enum AllowedHourFormat{
ALLOWED_HOUR_FORMAT_UNKNOWN = -1,
ALLOWED_HOUR_FORMAT_h,
ALLOWED_HOUR_FORMAT_H,
ALLOWED_HOUR_FORMAT_K, // Added ICU-20383, used by JP
ALLOWED_HOUR_FORMAT_k, // Added ICU-20383, not currently used
ALLOWED_HOUR_FORMAT_hb,
ALLOWED_HOUR_FORMAT_hB,
ALLOWED_HOUR_FORMAT_Kb, // Added ICU-20383, not currently used
ALLOWED_HOUR_FORMAT_KB, // Added ICU-20383, not currently used // ICU-20383 The following are unlikely and not currently used
ALLOWED_HOUR_FORMAT_Hb,
ALLOWED_HOUR_FORMAT_HB
};
} // namespace
void
DateTimePatternGenerator::initData(const Locale& locale, UErrorCode &status, UBool skipStdPatterns) { //const char *baseLangName = locale.getBaseName(); // unused if (U_FAILURE(status)) { return; } if (locale.isBogus()) {
status = U_ILLEGAL_ARGUMENT_ERROR; return;
}
skipMatcher = nullptr;
fAvailableFormatKeyHash=nullptr;
addCanonicalItems(status); if (!skipStdPatterns) { // skip to prevent circular dependency when called from SimpleDateFormat::construct
addICUPatterns(locale, status);
}
addCLDRData(locale, status);
setDateTimeFromCalendar(locale, status);
setDecimalSymbols(locale, status);
umtx_initOnce(initOnce, loadAllowedHourFormatsData, status);
getAllowedHourFormats(locale, status); // If any of the above methods failed then the object is in an invalid state.
internalErrorCode = status;
} // DateTimePatternGenerator::initData
LocalUResourceBundlePointer rb(ures_openDirect(nullptr, "supplementalData", &status)); if (U_FAILURE(status)) { return; }
AllowedHourFormatsSink sink; // TODO: Currently in the enumeration each table allocates a new array. // Try to reduce the number of memory allocations. Consider storing a // UVector32 with the concatenation of all of the sub-arrays, put the start index // into the hashmap, store 6 single-value sub-arrays right at the beginning of the // vector (at index enum*2) for easy data sharing, copy sub-arrays into runtime // object. Remember to clean up the vector, too.
ures_getAllItemsWithFallback(rb.getAlias(), "timeData", sink, status);
}
Locale maxLocale; // must be here for correct lifetime if (*language == '\0' || *country == '\0') {
maxLocale = locale;
UErrorCode localStatus = U_ZERO_ERROR;
maxLocale.addLikelySubtags(localStatus); if (U_SUCCESS(localStatus)) {
language = maxLocale.getLanguage();
country = maxLocale.getCountry();
}
} if (*language == '\0') { // Unexpected, but fail gracefully
language = "und";
} if (*country == '\0') {
country = "001";
}
// We need to check if there is an hour cycle on locale char buffer[8];
int32_t count = locale.getKeywordValue("hours", buffer, sizeof(buffer), status);
// Check if the region has an alias if (allowedFormats == nullptr) {
UErrorCode localStatus = U_ZERO_ERROR; const Region* region = Region::getInstance(country, localStatus); if (U_SUCCESS(localStatus)) {
country = region->getRegionCode(); // the real region code
allowedFormats = getAllowedHourFormatsLangCountry(language, country, status);
}
}
if (allowedFormats != nullptr) { // Lookup is successful // Here allowedFormats points to a list consisting of key for preferredFormat, // followed by one or more keys for allowedFormats, then followed by ALLOWED_HOUR_FORMAT_UNKNOWN. if (!fDefaultHourFormatChar) { switch (allowedFormats[0]) { case ALLOWED_HOUR_FORMAT_h: fDefaultHourFormatChar = LOW_H; break; case ALLOWED_HOUR_FORMAT_H: fDefaultHourFormatChar = CAP_H; break; case ALLOWED_HOUR_FORMAT_K: fDefaultHourFormatChar = CAP_K; break; case ALLOWED_HOUR_FORMAT_k: fDefaultHourFormatChar = LOW_K; break; default: fDefaultHourFormatChar = CAP_H; break;
}
}
for (int32_t i = 0; i < UPRV_LENGTHOF(fAllowedHourFormats); ++i) {
fAllowedHourFormats[i] = allowedFormats[i + 1]; if (fAllowedHourFormats[i] == ALLOWED_HOUR_FORMAT_UNKNOWN) { break;
}
}
} else { // Lookup failed, twice if (!fDefaultHourFormatChar) {
fDefaultHourFormatChar = CAP_H;
}
fAllowedHourFormats[0] = ALLOWED_HOUR_FORMAT_H;
fAllowedHourFormats[1] = ALLOWED_HOUR_FORMAT_UNKNOWN;
}
}
UDateFormatHourCycle
DateTimePatternGenerator::getDefaultHourCycle(UErrorCode& status) const { if (U_FAILURE(status)) { return UDAT_HOUR_CYCLE_23;
} if (fDefaultHourFormatChar == 0) { // We need to return something, but the caller should ignore it // anyways since the returned status is a failure.
status = U_UNSUPPORTED_ERROR; return UDAT_HOUR_CYCLE_23;
} switch (fDefaultHourFormatChar) { case CAP_K: return UDAT_HOUR_CYCLE_11; case LOW_H: return UDAT_HOUR_CYCLE_12; case CAP_H: return UDAT_HOUR_CYCLE_23; case LOW_K: return UDAT_HOUR_CYCLE_24; default:
UPRV_UNREACHABLE_EXIT;
}
}
LocalUResourceBundlePointer rb(ures_open(nullptr, locale.getBaseName(), &status));
CharString calendarTypeToUse; // to be filled in with the type to use, if all goes well
getCalendarTypeToUse(locale, calendarTypeToUse, status);
// HACK to get around the fact that the old SimpleDateFormat code (actually, Calendar::getCalendarTypeForLocale() ) // returns "gregorian" for ja_JP_TRADITIONAL instead of "japanese" if (uprv_strcmp(locale.getBaseName(), "ja_JP_TRADITIONAL") == 0) {
calendarTypeToUse.clear().append("gregorian", status);
}
void
DateTimePatternGenerator::getCalendarTypeToUse(const Locale& locale, CharString& destination, UErrorCode& err) {
destination.clear().append(DT_DateTimeGregorianTag, -1, err); // initial default if ( U_SUCCESS(err) ) {
UErrorCode localStatus = U_ZERO_ERROR; char localeWithCalendarKey[ULOC_LOCALE_IDENTIFIER_CAPACITY]; // obtain a locale that always has the calendar key value that should be used
ures_getFunctionalEquivalent(
localeWithCalendarKey,
ULOC_LOCALE_IDENTIFIER_CAPACITY,
nullptr, "calendar", "calendar",
locale.getName(),
nullptr, false,
&localStatus);
localeWithCalendarKey[ULOC_LOCALE_IDENTIFIER_CAPACITY-1] = 0; // ensure null termination // now get the calendar key value from that locale // (the call to ures_getFunctionalEquivalent() above might fail, and if it does, localeWithCalendarKey // won't contain a `calendar` keyword. If this happens, the line below will stomp on `destination`, // so we have to check the return code before overwriting `destination`.) if (U_SUCCESS(localStatus)) {
destination = ulocimp_getKeywordValue(localeWithCalendarKey, "calendar", localStatus);
} // If the input locale was invalid, don't fail with missing resource error, instead // continue with default of Gregorian. if (U_FAILURE(localStatus) && localStatus != U_MISSING_RESOURCE_ERROR) {
err = localStatus;
}
}
}
void
DateTimePatternGenerator::consumeShortTimePattern(const UnicodeString& shortTimePattern,
UErrorCode& status) { if (U_FAILURE(status)) { return; } // ICU-20383 No longer set fDefaultHourFormatChar to the hour format character from // this pattern; instead it is set from localeToAllowedHourFormatsMap which now // includes entries for both preferred and allowed formats.
// HACK for hh:ss
hackTimes(shortTimePattern, status);
}
struct DateTimePatternGenerator::AppendItemFormatsSink : public ResourceSink {
// Destination for data, modified via setters.
DateTimePatternGenerator& dtpg;
virtualvoid put(constchar *key, ResourceValue &value, UBool /*isRoot*/,
UErrorCode &errorCode) override { const UnicodeString formatKey(key, -1, US_INV); if (!dtpg.isAvailableFormatSet(formatKey) ) {
dtpg.setAvailableFormat(formatKey, errorCode); // Add pattern with its associated skeleton. Override any duplicate // derived from std patterns, but not a previous availableFormats entry: const UnicodeString& formatValue = value.getUnicodeString(errorCode);
conflictingPattern.remove();
dtpg.addPatternWithSkeleton(formatValue, &formatKey, true, conflictingPattern, errorCode);
}
}
};
// Virtual destructors must be defined out of line.
DateTimePatternGenerator::AppendItemFormatsSink::~AppendItemFormatsSink() {}
DateTimePatternGenerator::AppendItemNamesSink::~AppendItemNamesSink() {}
DateTimePatternGenerator::AvailableFormatsSink::~AvailableFormatsSink() {}
LocalUResourceBundlePointer rb(ures_open(nullptr, locale.getName(), &errorCode)); if (U_FAILURE(errorCode)) { return; }
CharString calendarTypeToUse; // to be filled in with the type to use, if all goes well
getCalendarTypeToUse(locale, calendarTypeToUse, errorCode); if (U_FAILURE(errorCode)) { return; }
// Local err to ignore resource not found exceptions
UErrorCode err = U_ZERO_ERROR;
void
DateTimePatternGenerator::getAppendName(UDateTimePatternField field, UnicodeString& value) {
value = SINGLE_QUOTE;
value += fieldDisplayNames[field][UDATPG_WIDTH_APPENDITEM];
value += SINGLE_QUOTE;
}
void
DateTimePatternGenerator::setDateTimeFormat(UDateFormatStyle style, const UnicodeString& dtFormat, UErrorCode& status) { if (U_FAILURE(status)) { return;
} if (style < UDAT_FULL || style > UDAT_SHORT) {
status = U_ILLEGAL_ARGUMENT_ERROR; return;
}
dateTimeFormat[style] = dtFormat; // Note for the following: getTerminatedBuffer() can re-allocate the UnicodeString // buffer so we do this here before clients request a const ref to the UnicodeString // or its buffer.
dateTimeFormat[style].getTerminatedBuffer(); // NUL-terminate for the C API.
}
// For DateTimePatternGenerator::addPatternWithSkeleton - // If skeletonToUse is specified, then an availableFormats entry is being added. In this case: // 1. We pass that skeleton to matcher.set instead of having it derive a skeleton from the pattern. // 2. If the new entry's skeleton or basePattern does match an existing entry but that entry also had a skeleton specified // (i.e. it was also from availableFormats), then the new entry does not override it regardless of the value of the override // parameter. This prevents later availableFormats entries from a parent locale overriding earlier ones from the actual // specified locale. However, availableFormats entries *should* override entries with matching skeleton whose skeleton was // derived (i.e. entries derived from the standard date/time patters for the specified locale). // 3. When adding the pattern (patternMap->add), we set a new boolean to indicate that the added entry had a // specified skeleton (which sets a new field in the PtnElem in the PatternMap).
UDateTimePatternConflict
DateTimePatternGenerator::addPatternWithSkeleton( const UnicodeString& pattern, const UnicodeString* skeletonToUse,
UBool override,
UnicodeString& conflictingPattern,
UErrorCode& status)
{ if (U_FAILURE(internalErrorCode)) {
status = internalErrorCode; return UDATPG_NO_CONFLICT;
}
DateTimeMatcher matcher; if ( skeletonToUse == nullptr ) {
matcher.set(pattern, fp, skeleton);
matcher.getBasePattern(basePattern);
} else {
matcher.set(*skeletonToUse, fp, skeleton); // no longer trims skeleton fields to max len 3, per #7930
matcher.getBasePattern(basePattern); // or perhaps instead: basePattern = *skeletonToUse;
} // We only care about base conflicts - and replacing the pattern associated with a base - if: // 1. the conflicting previous base pattern did *not* have an explicit skeleton; in that case the previous // base + pattern combination was derived from either (a) a canonical item, (b) a standard format, or // (c) a pattern specified programmatically with a previous call to addPattern (which would only happen // if we are getting here from a subsequent call to addPattern). // 2. a skeleton is specified for the current pattern, but override=false; in that case we are checking // availableFormats items from root, which should not override any previous entry with the same base.
UBool entryHadSpecifiedSkeleton; const UnicodeString *duplicatePattern = patternMap->getPatternFromBasePattern(basePattern, entryHadSpecifiedSkeleton); if (duplicatePattern != nullptr && (!entryHadSpecifiedSkeleton || (skeletonToUse != nullptr && !override))) {
conflictingStatus = UDATPG_BASE_CONFLICT;
conflictingPattern = *duplicatePattern; if (!override) { return conflictingStatus;
}
} // The only time we get here with override=true and skeletonToUse!=null is when adding availableFormats // items from CLDR data. In that case, we don't want an item from a parent locale to replace an item with // same skeleton from the specified locale, so skip the current item if skeletonWasSpecified is true for // the previously-specified conflicting item. const PtnSkeleton* entrySpecifiedSkeleton = nullptr;
duplicatePattern = patternMap->getPatternFromSkeleton(skeleton, &entrySpecifiedSkeleton); if (duplicatePattern != nullptr ) {
conflictingStatus = UDATPG_CONFLICT;
conflictingPattern = *duplicatePattern; if (!override || (skeletonToUse != nullptr && entrySpecifiedSkeleton != nullptr)) { return conflictingStatus;
}
}
patternMap->add(basePattern, skeleton, pattern, skeletonToUse != nullptr, status); if(U_FAILURE(status)) { return conflictingStatus;
}
PatternMapIterator it(status); if (U_FAILURE(status)) { return nullptr; }
for (it.set(*patternMap); it.hasNext(); ) {
DateTimeMatcher trial = it.next(); if (trial.equals(skipMatcher)) { continue;
}
int32_t distance=source.getDistance(trial, includeMask, tempInfo); // Because we iterate over a map the order is undefined. Can change between implementations, // versions, and will very likely be different between Java and C/C++. // So if we have patterns with the same distance we also look at the missingFieldMask, // and we favour the smallest one. Because the field is a bitmask this technically means we // favour differences in the "least significant fields". For example we prefer the one with differences // in seconds field vs one with difference in the hours field. if (distance<bestDistance || (distance==bestDistance && bestMissingFieldMask<tempInfo.missingFieldMask)) {
bestDistance=distance;
bestMissingFieldMask=tempInfo.missingFieldMask;
bestPattern=patternMap->getPatternFromSkeleton(*trial.getSkeletonPtr(), &specifiedSkeleton);
missingFields->setTo(tempInfo); if (distance==0) { break;
}
}
}
// If the best raw match had a specified skeleton and that skeleton was requested by the caller, // then return it too. This generally happens when the caller needs to pass that skeleton // through to adjustFieldTypes so the latter can do a better job. if (bestPattern && specifiedSkeletonPtr) {
*specifiedSkeletonPtr = specifiedSkeleton;
} return bestPattern;
}
UnicodeString
DateTimePatternGenerator::adjustFieldTypes(const UnicodeString& pattern, const PtnSkeleton* specifiedSkeleton,
int32_t flags,
UDateTimePatternMatchOptions options) {
UnicodeString newPattern;
fp->set(pattern); for (int32_t i=0; i < fp->itemNumber; i++) {
UnicodeString field = fp->items[i]; if ( fp->isQuoteLiteral(field) ) {
// handle day periods - with #13183, no longer need special handling here, integrated with normal types
if ((flags & kDTPGFixFractionalSeconds) != 0 && typeValue == UDATPG_SECOND_FIELD) {
field += decimal;
dtMatcher->skeleton.original.appendFieldTo(UDATPG_FRACTIONAL_SECOND_FIELD, field);
} elseif (dtMatcher->skeleton.type[typeValue]!=0) { // Here: // - "reqField" is the field from the originally requested skeleton after replacement // of metacharacters 'j', 'C' and 'J', with length "reqFieldLen". // - "field" is the field from the found pattern. // // The adjusted field should consist of characters from the originally requested // skeleton, except in the case of UDATPG_MONTH_FIELD or // UDATPG_WEEKDAY_FIELD or UDATPG_YEAR_FIELD, in which case it should consist // of characters from the found pattern. In some cases of UDATPG_HOUR_FIELD, // there is adjustment following the "defaultHourFormatChar". There is explanation // how it is done below. // // The length of the adjusted field (adjFieldLen) should match that in the originally // requested skeleton, except that in the following cases the length of the adjusted field // should match that in the found pattern (i.e. the length of this pattern field should // not be adjusted): // 1. typeValue is UDATPG_HOUR_FIELD/MINUTE/SECOND and the corresponding bit in options is // not set (ticket #7180). Note, we may want to implement a similar change for other // numeric fields (MM, dd, etc.) so the default behavior is to get locale preference for // field length, but options bits can be used to override this. // 2. There is a specified skeleton for the found pattern and one of the following is true: // a) The length of the field in the skeleton (skelFieldLen) is equal to reqFieldLen. // b) The pattern field is numeric and the skeleton field is not, or vice versa.
char16_t reqFieldChar = dtMatcher->skeleton.original.getFieldChar(typeValue);
int32_t reqFieldLen = dtMatcher->skeleton.original.getFieldLength(typeValue); if (reqFieldChar == CAP_E && reqFieldLen < 3)
reqFieldLen = 3; // 1-3 for E are equivalent to 3 for c,e
int32_t adjFieldLen = reqFieldLen; if ( (typeValue==UDATPG_HOUR_FIELD && (options & UDATPG_MATCH_HOUR_FIELD_LENGTH)==0) ||
(typeValue==UDATPG_MINUTE_FIELD && (options & UDATPG_MATCH_MINUTE_FIELD_LENGTH)==0) ||
(typeValue==UDATPG_SECOND_FIELD && (options & UDATPG_MATCH_SECOND_FIELD_LENGTH)==0) ) {
adjFieldLen = field.length();
} elseif (specifiedSkeleton && reqFieldChar != LOW_C && reqFieldChar != LOW_E) { // (we skip this section for 'c' and 'e' because unlike the other characters considered in this function, // they have no minimum field length-- 'E' and 'EE' are equivalent to 'EEE', but 'e' and 'ee' are not // equivalent to 'eee' -- see the entries for "week day" in // https://www.unicode.org/reports/tr35/tr35-dates.html#Date_Field_Symbol_Table for more info)
int32_t skelFieldLen = specifiedSkeleton->original.getFieldLength(typeValue);
UBool patFieldIsNumeric = (row->type > 0);
UBool skelFieldIsNumeric = (specifiedSkeleton->type[typeValue] > 0); if (skelFieldLen == reqFieldLen || (patFieldIsNumeric && !skelFieldIsNumeric) || (skelFieldIsNumeric && !patFieldIsNumeric)) { // don't adjust the field length in the found pattern
adjFieldLen = field.length();
}
}
char16_t c = (typeValue!= UDATPG_HOUR_FIELD
&& typeValue!= UDATPG_MONTH_FIELD
&& typeValue!= UDATPG_WEEKDAY_FIELD
&& (typeValue!= UDATPG_YEAR_FIELD || reqFieldChar==CAP_Y))
? reqFieldChar
: field.charAt(0); if (c == CAP_E && adjFieldLen < 3) {
c = LOW_E;
} if (typeValue == UDATPG_HOUR_FIELD && fDefaultHourFormatChar != 0) { // The adjustment here is required to match spec (https://www.unicode.org/reports/tr35/tr35-dates.html#dfst-hour). // It is necessary to match the hour-cycle preferred by the Locale. // Given that, we need to do the following adjustments: // 1. When hour-cycle is h11 it should replace 'h' by 'K'. // 2. When hour-cycle is h23 it should replace 'H' by 'k'. // 3. When hour-cycle is h24 it should replace 'k' by 'H'. // 4. When hour-cycle is h12 it should replace 'K' by 'h'.
PatternMap::PatternMap() { for (int32_t i=0; i < MAX_PATTERN_ENTRIES; ++i ) {
boot[i] = nullptr;
}
isDupAllowed = true;
}
void
PatternMap::copyFrom(const PatternMap& other, UErrorCode& status) { if (U_FAILURE(status)) { return;
}
this->isDupAllowed = other.isDupAllowed; for (int32_t bootIndex = 0; bootIndex < MAX_PATTERN_ENTRIES; ++bootIndex) {
PtnElem *curElem, *otherElem, *prevElem=nullptr;
otherElem = other.boot[bootIndex]; while (otherElem != nullptr) {
LocalPointer<PtnElem> newElem(new PtnElem(otherElem->basePattern, otherElem->pattern), status); if (U_FAILURE(status)) { return; // out of memory
}
newElem->skeleton.adoptInsteadAndCheckErrorCode(new PtnSkeleton(*(otherElem->skeleton)), status); if (U_FAILURE(status)) { return; // out of memory
}
newElem->skeletonWasSpecified = otherElem->skeletonWasSpecified;
// Release ownership from the LocalPointer of the PtnElem object. // The PtnElem will now be owned by either the boot (for the first entry in the linked-list) // or owned by the previous PtnElem object in the linked-list.
curElem = newElem.orphan();
// the baseChar must be A-Z or a-z if ((baseChar >= CAP_A) && (baseChar <= CAP_Z)) {
baseElem = boot[baseChar-CAP_A];
} else { if ((baseChar >=LOW_A) && (baseChar <= LOW_Z)) {
baseElem = boot[26+baseChar-LOW_A];
} else {
status = U_ILLEGAL_CHARACTER; return;
}
}
if (baseElem == nullptr) {
LocalPointer<PtnElem> newElem(new PtnElem(basePattern, value), status); if (U_FAILURE(status)) { return; // out of memory
}
newElem->skeleton.adoptInsteadAndCheckErrorCode(new PtnSkeleton(skeleton), status); if (U_FAILURE(status)) { return; // out of memory
}
newElem->skeletonWasSpecified = skeletonWasSpecified; if (baseChar >= LOW_A) {
boot[26 + (baseChar - LOW_A)] = newElem.orphan(); // the boot array now owns the PtnElem.
} else {
boot[baseChar - CAP_A] = newElem.orphan(); // the boot array now owns the PtnElem.
}
} if ( baseElem != nullptr ) {
curElem = getDuplicateElem(basePattern, skeleton, baseElem);
if (curElem == nullptr) { // add new element to the list.
curElem = baseElem; while( curElem -> next != nullptr )
{
curElem = curElem->next.getAlias();
}
LocalPointer<PtnElem> newElem(new PtnElem(basePattern, value), status); if (U_FAILURE(status)) { return; // out of memory
}
newElem->skeleton.adoptInsteadAndCheckErrorCode(new PtnSkeleton(skeleton), status); if (U_FAILURE(status)) { return; // out of memory
}
newElem->skeletonWasSpecified = skeletonWasSpecified;
curElem->next.adoptInstead(newElem.orphan());
curElem = curElem->next.getAlias();
} else { // Pattern exists in the list already. if ( !isDupAllowed ) { return;
} // Overwrite the value.
curElem->pattern = value; // It was a bug that we were not doing the following previously, // though that bug hid other problems by making things partly work.
curElem->skeletonWasSpecified = skeletonWasSpecified;
}
}
} // PatternMap::add
// Find the pattern from the given basePattern string. const UnicodeString *
PatternMap::getPatternFromBasePattern(const UnicodeString& basePattern, UBool& skeletonWasSpecified) const { // key to search for
PtnElem *curElem;
if ((curElem=getHeader(basePattern.charAt(0)))==nullptr) { return nullptr; // no match
}
do { if ( basePattern.compare(curElem->basePattern)==0 ) {
skeletonWasSpecified = curElem->skeletonWasSpecified; return &(curElem->pattern);
}
curElem = curElem->next.getAlias();
} while (curElem != nullptr);
// Find the pattern from the given skeleton. // At least when this is called from getBestRaw & addPattern (in which case specifiedSkeletonPtr is non-nullptr), // the comparison should be based on skeleton.original (which is unique and tied to the distance measurement in bestRaw) // and not skeleton.baseOriginal (which is not unique); otherwise we may pick a different skeleton than the one with the // optimum distance value in getBestRaw. When this is called from public getRedundants (specifiedSkeletonPtr is nullptr), // for now it will continue to compare based on baseOriginal so as not to change the behavior unnecessarily. const UnicodeString *
PatternMap::getPatternFromSkeleton(const PtnSkeleton& skeleton, const PtnSkeleton** specifiedSkeletonPtr) const { // key to search for
PtnElem *curElem;
if (specifiedSkeletonPtr) {
*specifiedSkeletonPtr = nullptr;
}
// find boot entry
char16_t baseChar = skeleton.getFirstChar(); if ((curElem=getHeader(baseChar))==nullptr) { return nullptr; // no match
}
do {
UBool equal; if (specifiedSkeletonPtr != nullptr) { // called from DateTimePatternGenerator::getBestRaw or addPattern, use original
equal = curElem->skeleton->original == skeleton.original;
} else { // called from DateTimePatternGenerator::getRedundants, use baseOriginal
equal = curElem->skeleton->baseOriginal == skeleton.baseOriginal;
} if (equal) { if (specifiedSkeletonPtr && curElem->skeletonWasSpecified) {
*specifiedSkeletonPtr = curElem->skeleton.getAlias();
} return &(curElem->pattern);
}
curElem = curElem->next.getAlias();
} while (curElem != nullptr);
// find any key existing in the mapping table already. // return true if there is an existing key, otherwise return false.
PtnElem*
PatternMap::getDuplicateElem( const UnicodeString &basePattern, const PtnSkeleton &skeleton,
PtnElem *baseElem) {
PtnElem *curElem;
if ( baseElem == nullptr ) { return nullptr;
} else {
curElem = baseElem;
} do { if ( basePattern.compare(curElem->basePattern)==0 ) {
UBool isEqual = true; for (int32_t i = 0; i < UDATPG_FIELD_COUNT; ++i) { if (curElem->skeleton->type[i] != skeleton.type[i] ) {
isEqual = false; break;
}
} if (isEqual) { return curElem;
}
}
curElem = curElem->next.getAlias();
} while( curElem != nullptr );
// #20739, we have a skeleton with minutes and milliseconds, but no seconds // // Theoretically we would need to check and fix all fields with "gaps": // for example year-day (no month), month-hour (no day), and so on, All the possible field combinations. // Plus some smartness: year + hour => should we add month, or add day-of-year? // What about month + day-of-week, or month + am/pm indicator. // I think beyond a certain point we should not try to fix bad developer input and try guessing what they mean. // Garbage in, garbage out. if (!skeletonResult.original.isFieldEmpty(UDATPG_MINUTE_FIELD)
&& !skeletonResult.original.isFieldEmpty(UDATPG_FRACTIONAL_SECOND_FIELD)
&& skeletonResult.original.isFieldEmpty(UDATPG_SECOND_FIELD)) { // Force the use of seconds for (i = 0; dtTypes[i].patternChar != 0; i++) { if (dtTypes[i].field == UDATPG_SECOND_FIELD) { // first entry for UDATPG_SECOND_FIELD
skeletonResult.original.populate(UDATPG_SECOND_FIELD, dtTypes[i].patternChar, dtTypes[i].minLen);
skeletonResult.baseOriginal.populate(UDATPG_SECOND_FIELD, dtTypes[i].patternChar, dtTypes[i].minLen); // We add value.length, same as above, when type is first initialized. // The value we want to "fake" here is "s", and 1 means "s".length()
int16_t subField = dtTypes[i].type;
skeletonResult.type[UDATPG_SECOND_FIELD] = (subField > 0) ? subField + 1 : subField; break;
}
}
}
// #13183, handle special behavior for day period characters (a, b, B) if (!skeletonResult.original.isFieldEmpty(UDATPG_HOUR_FIELD)) { if (skeletonResult.original.getFieldChar(UDATPG_HOUR_FIELD)==LOW_H || skeletonResult.original.getFieldChar(UDATPG_HOUR_FIELD)==CAP_K) { // We have a skeleton with 12-hour-cycle format if (skeletonResult.original.isFieldEmpty(UDATPG_DAYPERIOD_FIELD)) { // But we do not have a day period in the skeleton; add the default DAYPERIOD (currently "a") for (i = 0; dtTypes[i].patternChar != 0; i++) { if ( dtTypes[i].field == UDATPG_DAYPERIOD_FIELD ) { // first entry for UDATPG_DAYPERIOD_FIELD
skeletonResult.original.populate(UDATPG_DAYPERIOD_FIELD, dtTypes[i].patternChar, dtTypes[i].minLen);
skeletonResult.baseOriginal.populate(UDATPG_DAYPERIOD_FIELD, dtTypes[i].patternChar, dtTypes[i].minLen);
skeletonResult.type[UDATPG_DAYPERIOD_FIELD] = dtTypes[i].type;
skeletonResult.addedDefaultDayPeriod = true; break;
}
}
}
} else { // Skeleton has 24-hour-cycle hour format and has dayPeriod, delete dayPeriod (i.e. ignore it)
skeletonResult.original.clearField(UDATPG_DAYPERIOD_FIELD);
skeletonResult.baseOriginal.clearField(UDATPG_DAYPERIOD_FIELD);
skeletonResult.type[UDATPG_DAYPERIOD_FIELD] = NONE;
}
}
copyFrom(skeletonResult);
}
void
DateTimeMatcher::getBasePattern(UnicodeString &result ) {
result.remove(); // Reset the result first.
skeleton.baseOriginal.appendTo(result);
}
FormatParser::FormatParser () {
status = START;
itemNumber = 0;
}
FormatParser::~FormatParser () {
}
// Find the next token with the starting position and length // Note: the startPos may
FormatParser::TokenStatus
FormatParser::setTokens(const UnicodeString& pattern, int32_t startPos, int32_t *len) {
int32_t curLoc = startPos; if ( curLoc >= pattern.length()) { return DONE;
} // check the current char is between A-Z or a-z do {
char16_t c=pattern.charAt(curLoc); if ( (c>=CAP_A && c<=CAP_Z) || (c>=LOW_A && c<=LOW_Z) ) {
curLoc++;
} else {
startPos = curLoc;
*len=1; return ADD_TOKEN;
}
if ( pattern.charAt(curLoc)!= pattern.charAt(startPos) ) { break; // not the same token
}
} while(curLoc <= pattern.length());
*len = curLoc-startPos; return ADD_TOKEN;
}
void
FormatParser::set(const UnicodeString& pattern) {
int32_t startPos = 0;
TokenStatus result = START;
int32_t len = 0;
itemNumber = 0;
do {
result = setTokens( pattern, startPos, &len ); if ( result == ADD_TOKEN )
{
items[itemNumber++] = UnicodeString(pattern, startPos, len );
startPos += len;
} else { break;
}
} while (result==ADD_TOKEN && itemNumber < MAX_DT_TOKEN);
}
// This function assumes the current itemIndex points to the quote literal. // Please call isQuoteLiteral prior to this function. void
FormatParser::getQuoteLiteral(UnicodeString& quote, int32_t *itemIndex) {
int32_t i = *itemIndex;
quote.remove(); if (items[i].charAt(0)==SINGLE_QUOTE) {
quote += items[i];
++i;
} while ( i < itemNumber ) { if ( items[i].charAt(0)==SINGLE_QUOTE ) { if ( (i+1<itemNumber) && (items[i+1].charAt(0)==SINGLE_QUOTE)) { // two single quotes e.g. 'o''clock'
quote += items[i++];
quote += items[i++]; continue;
} else {
quote += items[i]; break;
}
} else {
quote += items[i];
}
++i;
}
*itemIndex=i;
}
UnicodeString
PtnSkeleton::getSkeleton() const {
UnicodeString result;
result = original.appendTo(result);
int32_t pos; if (addedDefaultDayPeriod && (pos = result.indexOf(LOW_A)) >= 0) { // for backward compatibility: if DateTimeMatcher.set added a single 'a' that // was not in the provided skeleton, remove it here before returning skeleton.
result.remove(pos, 1);
} return result;
}
UnicodeString
PtnSkeleton::getBaseSkeleton() const {
UnicodeString result;
result = baseOriginal.appendTo(result);
int32_t pos; if (addedDefaultDayPeriod && (pos = result.indexOf(LOW_A)) >= 0) { // for backward compatibility: if DateTimeMatcher.set added a single 'a' that // was not in the provided skeleton, remove it here before returning skeleton.
result.remove(pos, 1);
} return result;
}
pos=0;
fSkeletons.adoptInsteadAndCheckErrorCode(new UVector(status), status); if (U_FAILURE(status)) { return;
}
for (bootIndex=0; bootIndex<MAX_PATTERN_ENTRIES; ++bootIndex ) {
curElem = patternMap.boot[bootIndex]; while (curElem!=nullptr) { switch(type) { case DT_BASESKELETON:
s=curElem->basePattern; break; case DT_PATTERN:
s=curElem->pattern; break; case DT_SKELETON:
curSkeleton=curElem->skeleton.getAlias();
s=curSkeleton->getSkeleton(); break;
} if ( !isCanonicalItem(s) ) {
LocalPointer<UnicodeString> newElem(s.clone(), status); if (U_FAILURE(status)) { return;
}
fSkeletons->addElement(newElem.getAlias(), status); if (U_FAILURE(status)) {
fSkeletons.adoptInstead(nullptr); return;
}
newElem.orphan(); // fSkeletons vector now owns the UnicodeString (although it // does not use a deleter function to manage the ownership).
}
curElem = curElem->next.getAlias();
}
} if ((bootIndex==MAX_PATTERN_ENTRIES) && (curElem!=nullptr) ) {
status = U_BUFFER_OVERFLOW_ERROR;
}
}
void
DTRedundantEnumeration::add(const UnicodeString& pattern, UErrorCode& status) { if (U_FAILURE(status)) { return; } if (fPatterns.isNull()) {
fPatterns.adoptInsteadAndCheckErrorCode(new UVector(status), status); if (U_FAILURE(status)) { return;
}
}
LocalPointer<UnicodeString> newElem(new UnicodeString(pattern), status); if (U_FAILURE(status)) { return;
}
fPatterns->addElement(newElem.getAlias(), status); if (U_FAILURE(status)) {
fPatterns.adoptInstead(nullptr); return;
}
newElem.orphan(); // fPatterns now owns the string, although a UVector // deleter function is not used to manage that ownership.
}
UBool
DTRedundantEnumeration::isCanonicalItem(const UnicodeString& item) const { if ( item.length() != 1 ) { returnfalse;
} for (int32_t i=0; i<UDATPG_FIELD_COUNT; ++i) { if (item.charAt(0)==Canonical_Items[i]) { returntrue;
}
} returnfalse;
}
DTRedundantEnumeration::~DTRedundantEnumeration() {
UnicodeString *s; if (fPatterns.isValid()) { for (int32_t i = 0; i < fPatterns->size(); ++i) { if ((s = static_cast<UnicodeString*>(fPatterns->elementAt(i))) != nullptr) { delete s;
}
}
}
}
U_NAMESPACE_END
#endif/* #if !UCONFIG_NO_FORMATTING */
//eof
Messung V0.5 in Prozent
¤ Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.0.73Bemerkung:
(Wie Sie bei der Firma Beratungs- und Dienstleistungen beauftragen können 2026-04-26)
¤
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.