void TCopyParamType::DoGetInfoStr( const UnicodeString & Separator, intptr_t Options, UnicodeString & Result, bool & SomeAttrIncluded, const UnicodeString & Link, UnicodeString & ScriptArgs, bool & NoScriptArgs, /*TAssemblyLanguage Language, UnicodeString & AssemblyCode,*/ bool & NoCodeProperties) const { TCopyParamType Defaults; bool SomeAttrExcluded = false; NoScriptArgs = false; NoCodeProperties = false; SomeAttrIncluded = false; #define ADD(STR, EXCEPT) \ if (FLAGCLEAR(Options, EXCEPT)) \ { \ AddToList(Result, (STR), Separator); \ SomeAttrIncluded = true; \ } \ else \ { \ SomeAttrExcluded = true; \ } bool AsciiFileMaskDiffers = (GetTransferMode() == tmAutomatic) && !(GetAsciiFileMask() == Defaults.GetAsciiFileMask()); bool TransferModeDiffers = ((GetTransferMode() != Defaults.GetTransferMode()) || AsciiFileMaskDiffers); if (FLAGCLEAR(Options, cpaIncludeMaskOnly | cpaNoTransferMode)) { // Adding Transfer type unconditionally bool FormatMask; int Ident; switch (GetTransferMode()) { case tmBinary: FormatMask = false; Ident = 2; break; case tmAscii: FormatMask = false; Ident = 3; break; case tmAutomatic: default: FormatMask = !(GetAsciiFileMask() == Defaults.GetAsciiFileMask()); Ident = FormatMask ? 4 : 5; break; } UnicodeString S = FORMAT(LoadStrPart(COPY_INFO_TRANSFER_TYPE2, 1).c_str(), LoadStrPart(COPY_INFO_TRANSFER_TYPE2, Ident).c_str()); if (FormatMask) { S = FORMAT(S.c_str(), GetAsciiFileMask().GetMasks().c_str()); } AddToList(Result, S, Separator); if (TransferModeDiffers) { ADD("", cpaIncludeMaskOnly | cpaNoTransferMode); /*ScriptArgs += RtfSwitchValue(TRANSFER_SWITCH, Link, TransferModeNames[TransferMode]); const wchar_t * TransferModeMembers[] = { L"Binary", L"Ascii", L"Automatic" }; AssemblyCode += AssemblyProperty( Language, TransferOptionsClassName, L"TransferMode", L"TransferMode", TransferModeMembers[TransferMode], false); if (AsciiFileMaskDiffers) { NoScriptArgs = true; NoCodeProperties = true; }*/ } } else { if (TransferModeDiffers) { SomeAttrExcluded = true; NoScriptArgs = true; NoCodeProperties = true; } } if (GetFileNameCase() != Defaults.GetFileNameCase()) { ADD(FORMAT(LoadStrPart(COPY_INFO_FILENAME, 1).c_str(), LoadStrPart(COPY_INFO_FILENAME, GetFileNameCase() + 2).c_str()), cpaIncludeMaskOnly); NoScriptArgs = true; NoCodeProperties = true; } if ((GetInvalidCharsReplacement() == NoReplacement) != (Defaults.GetInvalidCharsReplacement() == NoReplacement)) { DebugAssert(GetInvalidCharsReplacement() == NoReplacement); if (GetInvalidCharsReplacement() == NoReplacement) { ADD(LoadStr(COPY_INFO_DONT_REPLACE_INV_CHARS).c_str(), cpaIncludeMaskOnly); } NoScriptArgs = true; NoCodeProperties = true; } if ((GetPreserveRights() != Defaults.GetPreserveRights()) || (GetPreserveRights() && ((GetRights() != Defaults.GetRights()) || (GetAddXToDirectories() != Defaults.GetAddXToDirectories())))) { const int Except = cpaIncludeMaskOnly | cpaNoRights; if (DebugAlwaysTrue(GetPreserveRights())) { UnicodeString RightsStr = GetRights().GetText(); if (GetAddXToDirectories()) { RightsStr += L", " + LoadStr(COPY_INFO_ADD_X_TO_DIRS); } ADD(FORMAT(LoadStr(COPY_INFO_PERMISSIONS).c_str(), RightsStr.c_str()), Except); if (FLAGCLEAR(Options, Except)) { // ScriptArgs += RtfSwitchValue(PERMISSIONS_SWITCH, Link, Rights.Octal); // const UnicodeString FilePermissionsClassName = L"FilePermissions"; // const bool Inline = true; // UnicodeString FilePermissions = // AssemblyNewClassInstanceStart(Language, FilePermissionsClassName, Inline) + // AssemblyProperty(Language, FilePermissionsClassName, L"Octal", Rights.Octal, Inline) + // AssemblyNewClassInstanceEnd(Language, Inline); // AssemblyCode += AssemblyPropertyRaw(Language, TransferOptionsClassName, L"FilePermissions", FilePermissions, false); } } if ((GetAddXToDirectories() != Defaults.GetAddXToDirectories()) && FLAGCLEAR(Options, Except)) { NoScriptArgs = true; NoCodeProperties = true; } } bool APreserveTimeDirs = GetPreserveTime() && GetPreserveTimeDirs(); if ((GetPreserveTime() != Defaults.GetPreserveTime()) || (APreserveTimeDirs != Defaults.GetPreserveTimeDirs())) { bool AddPreserveTime = false; UnicodeString Str = LoadStr(GetPreserveTime() ? COPY_INFO_TIMESTAMP : COPY_INFO_DONT_PRESERVE_TIME); const int ExceptDirs = cpaNoPreserveTimeDirs; if (APreserveTimeDirs != Defaults.GetPreserveTimeDirs()) { if (DebugAlwaysTrue(GetPreserveTimeDirs())) { if (FLAGCLEAR(Options, ExceptDirs)) { Str = FMTLOAD(COPY_INFO_PRESERVE_TIME_DIRS, (Str)); AddPreserveTime = true; } } ADD("", ExceptDirs); } const int Except = cpaIncludeMaskOnly | cpaNoPreserveTime; if (GetPreserveTime() != Defaults.GetPreserveTime()) { if (FLAGCLEAR(Options, Except)) { AddPreserveTime = true; } ADD(L"", Except); } if (AddPreserveTime) { AddToList(Result, Str, Separator); } if (FLAGCLEAR(Options, Except)) { if (GetPreserveTime()) { if (GetPreserveTimeDirs() && FLAGCLEAR(Options, ExceptDirs)) { //ScriptArgs += RtfSwitchValue(PRESERVETIME_SWITCH, Link, PRESERVETIMEDIRS_SWITCH_VALUE); NoCodeProperties = true; } else { DebugFail(); // should never get here //ScriptArgs += RtfSwitch(PRESERVETIME_SWITCH, Link); } } else { // ScriptArgs += RtfSwitch(NOPRESERVETIME_SWITCH, Link); // AssemblyCode += AssemblyProperty(Language, TransferOptionsClassName, L"PreserveTimestamp", false, false); } } } if ((GetPreserveRights() || GetPreserveTime()) && (GetIgnorePermErrors() != Defaults.GetIgnorePermErrors())) { if (DebugAlwaysTrue(GetIgnorePermErrors())) { const int Except = cpaIncludeMaskOnly | cpaNoIgnorePermErrors; ADD(LoadStr(COPY_INFO_IGNORE_PERM_ERRORS), Except); if (FLAGCLEAR(Options, Except)) { NoScriptArgs = true; NoCodeProperties = true; } } } if (GetPreserveReadOnly() != Defaults.GetPreserveReadOnly()) { if (DebugAlwaysTrue(GetPreserveReadOnly())) { const int Except = cpaIncludeMaskOnly | cpaNoPreserveReadOnly; ADD(LoadStr(COPY_INFO_PRESERVE_READONLY), Except); if (FLAGCLEAR(Options, Except)) { NoScriptArgs = true; NoCodeProperties = true; } } } if (GetCalculateSize() != Defaults.GetCalculateSize()) { if (DebugAlwaysTrue(!GetCalculateSize())) { ADD(LoadStr(COPY_INFO_DONT_CALCULATE_SIZE), cpaIncludeMaskOnly); // Always false in scripting, in assembly controlled by use of FileTransferProgress } } if (GetClearArchive() != Defaults.GetClearArchive()) { if (DebugAlwaysTrue(GetClearArchive())) { const int Except = cpaIncludeMaskOnly | cpaNoClearArchive; ADD(LoadStr(COPY_INFO_CLEAR_ARCHIVE), Except); if (FLAGCLEAR(Options, Except)) { NoScriptArgs = true; NoCodeProperties = true; } } } if ((GetTransferMode() == tmAscii) || (GetTransferMode() == tmAutomatic)) { if (GetRemoveBOM() != Defaults.GetRemoveBOM()) { if (DebugAlwaysTrue(GetRemoveBOM())) { const int Except = cpaIncludeMaskOnly | cpaNoRemoveBOM | cpaNoTransferMode; ADD(LoadStr(COPY_INFO_REMOVE_BOM), Except); if (FLAGCLEAR(Options, Except)) { NoScriptArgs = true; NoCodeProperties = true; } } } if (GetRemoveCtrlZ() != Defaults.GetRemoveCtrlZ()) { if (DebugAlwaysTrue(GetRemoveCtrlZ())) { const int Except = cpaIncludeMaskOnly | cpaNoRemoveCtrlZ | cpaNoTransferMode; ADD(LoadStr(COPY_INFO_REMOVE_CTRLZ),Except); if (FLAGCLEAR(Options, Except)) { NoScriptArgs = true; NoCodeProperties = true; } } } } if (!(GetIncludeFileMask() == Defaults.GetIncludeFileMask())) { ADD(FORMAT(LoadStr(COPY_INFO_FILE_MASK).c_str(), GetIncludeFileMask().GetMasks().c_str()), cpaNoIncludeMask); // ScriptArgs += RtfSwitch(FILEMASK_SWITCH, Link, IncludeFileMask.Masks); // AssemblyCode += AssemblyProperty(Language, TransferOptionsClassName, L"FileMask", IncludeFileMask.Masks, false); } DebugAssert(FTransferSkipList.get() == nullptr); DebugAssert(FTransferResumeFile.IsEmpty()); if (GetCPSLimit() > 0) { intptr_t LimitKB = intptr_t(GetCPSLimit() / 1024); ADD(FMTLOAD(COPY_INFO_CPS_LIMIT2, (LimitKB)), cpaIncludeMaskOnly); // ScriptArgs += RtfSwitch(SPEED_SWITCH, Link, LimitKB); // AssemblyCode += AssemblyProperty(Language, TransferOptionsClassName, L"Speed", LimitKB, false); } if (GetNewerOnly() != Defaults.GetNewerOnly()) { if (DebugAlwaysTrue(GetNewerOnly())) { const int Except = cpaIncludeMaskOnly | cpaNoNewerOnly; ADD(StripHotkey(LoadStr(COPY_PARAM_NEWER_ONLY)), Except); if (FLAGCLEAR(Options, Except)) { // ScriptArgs += RtfSwitch(NEWERONLY_SWICH, Link); NoCodeProperties = true; } } } bool ResumeThresholdDiffers = ((GetResumeSupport() == rsSmart) && (GetResumeThreshold() != Defaults.GetResumeThreshold())); if (((GetResumeSupport() != Defaults.GetResumeSupport()) || ResumeThresholdDiffers) && (GetTransferMode() != tmAscii) && FLAGCLEAR(Options, cpaNoResumeSupport)) { UnicodeString Value; UnicodeString CodeState; intptr_t ResumeThresholdKB = (GetResumeThreshold() / 1024); switch (GetResumeSupport()) { case rsOff: Value = ToggleNames[ToggleOff]; CodeState = L"Off"; break; case rsOn: Value = ToggleNames[ToggleOn]; CodeState = L"On"; break; case rsSmart: Value = IntToStr(ResumeThresholdKB); break; } // ScriptArgs += RtfSwitchValue(RESUMESUPPORT_SWITCH, Link, Value); const UnicodeString ResumeSupportClassName = L"TransferResumeSupport"; const bool Inline = true; // UnicodeString ResumeSupportCode = // AssemblyNewClassInstanceStart(Language, ResumeSupportClassName, Inline); if (GetResumeSupport() == rsSmart) { // ResumeSupportCode += AssemblyProperty(Language, ResumeSupportClassName, L"Threshold", ResumeThresholdKB, Inline); } else { // ResumeSupportCode += AssemblyProperty(Language, ResumeSupportClassName, L"State", L"TransferResumeSupportState", CodeState, Inline); } // ResumeSupportCode += AssemblyNewClassInstanceEnd(Language, Inline); // AssemblyCode += AssemblyPropertyRaw(Language, TransferOptionsClassName, L"ResumeSupport", ResumeSupportCode, false); } if (SomeAttrExcluded) { Result += (Result.IsEmpty() ? UnicodeString() : Separator) + FORMAT(LoadStrPart(COPY_INFO_NOT_USABLE, 1).c_str(), LoadStrPart(COPY_INFO_NOT_USABLE, (SomeAttrIncluded ? 2 : 3)).c_str()); } else if (Result.IsEmpty()) { Result = LoadStr(COPY_INFO_DEFAULT); } #undef ADD }
UnicodeString& DefaultLocaleDisplayNames::keyDisplayName(const char* key, UnicodeString& result) const { return result = UnicodeString(key, -1, US_INV); }
void LocaleDisplayNamesImpl::initialize(void) { LocaleDisplayNamesImpl *nonConstThis = (LocaleDisplayNamesImpl *)this; nonConstThis->locale = langData.getLocale() == Locale::getRoot() ? regionData.getLocale() : langData.getLocale(); UnicodeString sep; langData.getNoFallback("localeDisplayPattern", "separator", sep); if (sep.isBogus()) { sep = UnicodeString("{0}, {1}", -1, US_INV); } UErrorCode status = U_ZERO_ERROR; separatorFormat.applyPatternMinMaxArguments(sep, 2, 2, status); UnicodeString pattern; langData.getNoFallback("localeDisplayPattern", "pattern", pattern); if (pattern.isBogus()) { pattern = UnicodeString("{0} ({1})", -1, US_INV); } format.applyPatternMinMaxArguments(pattern, 2, 2, status); if (pattern.indexOf((UChar)0xFF08) >= 0) { formatOpenParen.setTo((UChar)0xFF08); // fullwidth ( formatReplaceOpenParen.setTo((UChar)0xFF3B); // fullwidth [ formatCloseParen.setTo((UChar)0xFF09); // fullwidth ) formatReplaceCloseParen.setTo((UChar)0xFF3D); // fullwidth ] } else { formatOpenParen.setTo((UChar)0x0028); // ( formatReplaceOpenParen.setTo((UChar)0x005B); // [ formatCloseParen.setTo((UChar)0x0029); // ) formatReplaceCloseParen.setTo((UChar)0x005D); // ] } UnicodeString ktPattern; langData.get("localeDisplayPattern", "keyTypePattern", ktPattern); if (ktPattern.isBogus()) { ktPattern = UnicodeString("{0}={1}", -1, US_INV); } keyTypeFormat.applyPatternMinMaxArguments(ktPattern, 2, 2, status); uprv_memset(fCapitalization, 0, sizeof(fCapitalization)); #if !UCONFIG_NO_BREAK_ITERATION // Only get the context data if we need it! This is a const object so we know now... // Also check whether we will need a break iterator (depends on the data) UBool needBrkIter = FALSE; if (capitalizationContext == UDISPCTX_CAPITALIZATION_FOR_UI_LIST_OR_MENU || capitalizationContext == UDISPCTX_CAPITALIZATION_FOR_STANDALONE) { LocalUResourceBundlePointer resource(ures_open(NULL, locale.getName(), &status)); if (U_FAILURE(status)) { return; } CapitalizationContextSink sink(*this); ures_getAllItemsWithFallback(resource.getAlias(), "contextTransforms", sink, status); if (status == U_MISSING_RESOURCE_ERROR) { // Silently ignore. Not every locale has contextTransforms. status = U_ZERO_ERROR; } else if (U_FAILURE(status)) { return; } needBrkIter = sink.hasCapitalizationUsage; } // Get a sentence break iterator if we will need it if (needBrkIter || capitalizationContext == UDISPCTX_CAPITALIZATION_FOR_BEGINNING_OF_SENTENCE) { status = U_ZERO_ERROR; capitalizationBrkIter = BreakIterator::createSentenceInstance(locale, status); if (U_FAILURE(status)) { delete capitalizationBrkIter; capitalizationBrkIter = NULL; } } #endif }
UnicodeString& DefaultLocaleDisplayNames::languageDisplayName(const char* lang, UnicodeString& result) const { return result = UnicodeString(lang, -1, US_INV); }
UnicodeString& DefaultLocaleDisplayNames::regionDisplayName(const char* region, UnicodeString& result) const { return result = UnicodeString(region, -1, US_INV); }
UnicodeString IndexedString::getPrimaryIndexAtCharacter(int32_t Position) const { auto const Found = lookupPrimaryIndexAtCharacter(Position); return Found != Needles.end() ? Found->first : UnicodeString(); }
UnicodeString& DefaultLocaleDisplayNames::localeDisplayName(const Locale& locale, UnicodeString& result) const { return result = UnicodeString(locale.getName(), -1, US_INV); }
void CharIterTest::TestConstructionAndEqualityUChariter() { U_STRING_DECL(testText, "Now is the time for all good men to come to the aid of their country.", 69); U_STRING_DECL(testText2, "Don't bother using this string.", 31); U_STRING_INIT(testText, "Now is the time for all good men to come to the aid of their country.", 69); U_STRING_INIT(testText2, "Don't bother using this string.", 31); UnicodeString result, result4, result5; UCharCharacterIterator* test1 = new UCharCharacterIterator(testText, u_strlen(testText)); UCharCharacterIterator* test2 = new UCharCharacterIterator(testText, u_strlen(testText), 5); UCharCharacterIterator* test3 = new UCharCharacterIterator(testText, u_strlen(testText), 2, 20, 5); UCharCharacterIterator* test4 = new UCharCharacterIterator(testText2, u_strlen(testText2)); UCharCharacterIterator* test5 = (UCharCharacterIterator*)test1->clone(); UCharCharacterIterator* test6 = new UCharCharacterIterator(*test1); // j785: length=-1 will use u_strlen() UCharCharacterIterator* test7a = new UCharCharacterIterator(testText, -1); UCharCharacterIterator* test7b = new UCharCharacterIterator(testText, -1); UCharCharacterIterator* test7c = new UCharCharacterIterator(testText, -1, 2, 20, 5); // Bad parameters. UCharCharacterIterator* test8a = new UCharCharacterIterator(testText, -1, -1, 20, 5); UCharCharacterIterator* test8b = new UCharCharacterIterator(testText, -1, 2, 100, 5); UCharCharacterIterator* test8c = new UCharCharacterIterator(testText, -1, 2, 20, 100); if (test8a->startIndex() < 0) errln("Construction failed: startIndex is negative"); if (test8b->endIndex() != u_strlen(testText)) errln("Construction failed: endIndex is different from the text length"); if (test8c->getIndex() < test8c->startIndex() || test8c->endIndex() < test8c->getIndex()) errln("Construction failed: index is invalid"); if (*test1 == *test2 || *test1 == *test3 || *test1 == *test4 ) errln("Construction or operator== failed: Unequal objects compared equal"); if (*test1 != *test5 ) errln("clone() or equals() failed: Two clones tested unequal"); if (*test6 != *test1 ) errln("copy construction or equals() failed: Two copies tested unequal"); if (test1->hashCode() == test2->hashCode() || test1->hashCode() == test3->hashCode() || test1->hashCode() == test4->hashCode()) errln("hashCode() failed: different objects have same hash code"); if (test1->hashCode() != test5->hashCode()) errln("hashCode() failed: identical objects have different hash codes"); test7a->getText(result); test7b->getText(result4); test7c->getText(result5); if(result != UnicodeString(testText) || result4 != result || result5 != result) errln("error in construction"); test1->getText(result); test4->getText(result4); test5->getText(result5); if(result != result5 || result == result4) errln("getText() failed"); test5->setText(testText2, u_strlen(testText2)); test5->getText(result5); if(result == result5 || result4 != result5) errln("setText() or getText() failed"); test5->setText(testText, u_strlen(testText)); test5->getText(result5); if(result != result5 || result == result4) errln("setText() or getText() round-trip failed"); test1->setIndex(5); if (*test1 != *test2 || *test1 == *test5) errln("setIndex() failed"); test8b->setIndex32(5); if (test8b->getIndex()!=5) errln("setIndex32() failed"); *test1 = *test3; if (*test1 != *test3 || *test1 == *test5) errln("operator= failed"); delete test1; delete test2; delete test3; delete test4; delete test5; delete test6; delete test7a; delete test7b; delete test7c; delete test8a; delete test8b; delete test8c; }
void CharIterTest::TestUCharIterator() { // test string of length 8 UnicodeString s=UnicodeString("a \\U00010001b\\U0010fffdz", "").unescape(); const char *const moves= "0+++++++++" // 10 moves per line "----0-----" ">>|>>>>>>>" "<<|<<<<<<<" "22+>8>-8+2"; StringCharacterIterator sci(s), compareCI(s); UCharIterator sIter, cIter, rIter; uiter_setString(&sIter, s.getBuffer(), s.length()); uiter_setCharacterIterator(&cIter, &sci); uiter_setReplaceable(&rIter, &s); TestUCharIterator(&sIter, compareCI, moves, "uiter_setString"); compareCI.setIndex(0); TestUCharIterator(&cIter, compareCI, moves, "uiter_setCharacterIterator"); compareCI.setIndex(0); TestUCharIterator(&rIter, compareCI, moves, "uiter_setReplaceable"); // test move & getIndex some more sIter.start=2; sIter.index=3; sIter.limit=5; if( sIter.getIndex(&sIter, UITER_ZERO)!=0 || sIter.getIndex(&sIter, UITER_START)!=2 || sIter.getIndex(&sIter, UITER_CURRENT)!=3 || sIter.getIndex(&sIter, UITER_LIMIT)!=5 || sIter.getIndex(&sIter, UITER_LENGTH)!=s.length() ) { errln("error: UCharIterator(string).getIndex returns wrong index"); } if( sIter.move(&sIter, 4, UITER_ZERO)!=4 || sIter.move(&sIter, 1, UITER_START)!=3 || sIter.move(&sIter, 3, UITER_CURRENT)!=5 || sIter.move(&sIter, -1, UITER_LIMIT)!=4 || sIter.move(&sIter, -5, UITER_LENGTH)!=3 || sIter.move(&sIter, 0, UITER_CURRENT)!=sIter.getIndex(&sIter, UITER_CURRENT) || sIter.getIndex(&sIter, UITER_CURRENT)!=3 ) { errln("error: UCharIterator(string).move sets/returns wrong index"); } sci=StringCharacterIterator(s, 2, 5, 3); uiter_setCharacterIterator(&cIter, &sci); if( cIter.getIndex(&cIter, UITER_ZERO)!=0 || cIter.getIndex(&cIter, UITER_START)!=2 || cIter.getIndex(&cIter, UITER_CURRENT)!=3 || cIter.getIndex(&cIter, UITER_LIMIT)!=5 || cIter.getIndex(&cIter, UITER_LENGTH)!=s.length() ) { errln("error: UCharIterator(character iterator).getIndex returns wrong index"); } if( cIter.move(&cIter, 4, UITER_ZERO)!=4 || cIter.move(&cIter, 1, UITER_START)!=3 || cIter.move(&cIter, 3, UITER_CURRENT)!=5 || cIter.move(&cIter, -1, UITER_LIMIT)!=4 || cIter.move(&cIter, -5, UITER_LENGTH)!=3 || cIter.move(&cIter, 0, UITER_CURRENT)!=cIter.getIndex(&cIter, UITER_CURRENT) || cIter.getIndex(&cIter, UITER_CURRENT)!=3 ) { errln("error: UCharIterator(character iterator).move sets/returns wrong index"); } if(cIter.getIndex(&cIter, (enum UCharIteratorOrigin)-1) != -1) { errln("error: UCharIterator(char iter).getIndex did not return error value"); } if(cIter.move(&cIter, 0, (enum UCharIteratorOrigin)-1) != -1) { errln("error: UCharIterator(char iter).move did not return error value"); } if(rIter.getIndex(&rIter, (enum UCharIteratorOrigin)-1) != -1) { errln("error: UCharIterator(repl iter).getIndex did not return error value"); } if(rIter.move(&rIter, 0, (enum UCharIteratorOrigin)-1) != -1) { errln("error: UCharIterator(repl iter).move did not return error value"); } if(sIter.getIndex(&sIter, (enum UCharIteratorOrigin)-1) != -1) { errln("error: UCharIterator(string iter).getIndex did not return error value"); } if(sIter.move(&sIter, 0, (enum UCharIteratorOrigin)-1) != -1) { errln("error: UCharIterator(string iter).move did not return error value"); } /* Testing function coverage on bad input */ UErrorCode status = U_ZERO_ERROR; uiter_setString(&sIter, NULL, 1); uiter_setState(&sIter, 1, &status); if (status != U_UNSUPPORTED_ERROR) { errln("error: uiter_setState returned %s instead of U_UNSUPPORTED_ERROR", u_errorName(status)); } status = U_ZERO_ERROR; uiter_setState(NULL, 1, &status); if (status != U_ILLEGAL_ARGUMENT_ERROR) { errln("error: uiter_setState returned %s instead of U_ILLEGAL_ARGUMENT_ERROR", u_errorName(status)); } if (uiter_getState(&sIter) != UITER_NO_STATE) { errln("error: uiter_getState did not return UITER_NO_STATE on bad input"); } }
void DateFormatRoundTripTest::test(const Locale& loc) { UnicodeString temp; #if !INFINITE logln("Locale: " + loc.getDisplayName(temp)); #endif // Total possibilities = 24 // 4 date // 4 time // 16 date-time UBool TEST_TABLE [24];//= new boolean[24]; int32_t i = 0; for(i = 0; i < 24; ++i) TEST_TABLE[i] = TRUE; // If we have some sparseness, implement it here. Sparseness decreases // test time by eliminating some tests, up to 23. for(i = 0; i < SPARSENESS; ) { int random = (int)(randFraction() * 24); if (random >= 0 && random < 24 && TEST_TABLE[i]) { TEST_TABLE[i] = FALSE; ++i; } } int32_t itable = 0; int32_t style = 0; for(style = DateFormat::FULL; style <= DateFormat::SHORT; ++style) { if(TEST_TABLE[itable++]) { logln("Testing style " + UnicodeString(styleName((DateFormat::EStyle)style))); DateFormat *df = DateFormat::createDateInstance((DateFormat::EStyle)style, loc); if(df == NULL) { errln(UnicodeString("Could not DF::createDateInstance ") + UnicodeString(styleName((DateFormat::EStyle)style)) + " Locale: " + loc.getDisplayName(temp)); } else { test(df, loc); delete df; } } } for(style = DateFormat::FULL; style <= DateFormat::SHORT; ++style) { if (TEST_TABLE[itable++]) { logln("Testing style " + UnicodeString(styleName((DateFormat::EStyle)style))); DateFormat *df = DateFormat::createTimeInstance((DateFormat::EStyle)style, loc); if(df == NULL) { errln(UnicodeString("Could not DF::createTimeInstance ") + UnicodeString(styleName((DateFormat::EStyle)style)) + " Locale: " + loc.getDisplayName(temp)); } else { test(df, loc, TRUE); delete df; } } } for(int32_t dstyle = DateFormat::FULL; dstyle <= DateFormat::SHORT; ++dstyle) { for(int32_t tstyle = DateFormat::FULL; tstyle <= DateFormat::SHORT; ++tstyle) { if(TEST_TABLE[itable++]) { logln("Testing dstyle" + UnicodeString(styleName((DateFormat::EStyle)dstyle)) + ", tstyle" + UnicodeString(styleName((DateFormat::EStyle)tstyle)) ); DateFormat *df = DateFormat::createDateTimeInstance((DateFormat::EStyle)dstyle, (DateFormat::EStyle)tstyle, loc); if(df == NULL) { dataerrln(UnicodeString("Could not DF::createDateTimeInstance ") + UnicodeString(styleName((DateFormat::EStyle)dstyle)) + ", tstyle" + UnicodeString(styleName((DateFormat::EStyle)tstyle)) + "Locale: " + loc.getDisplayName(temp)); } else { test(df, loc); delete df; } } } } }
void DateFormatRoundTripTest::test(DateFormat *fmt, const Locale &origLocale, UBool timeOnly) { UnicodeString pat; if(fmt->getDynamicClassID() != SimpleDateFormat::getStaticClassID()) { errln("DateFormat wasn't a SimpleDateFormat"); return; } UBool isGregorian = FALSE; UErrorCode minStatus = U_ZERO_ERROR; if(fmt->getCalendar() == NULL) { errln((UnicodeString)"DateFormatRoundTripTest::test, DateFormat getCalendar() returns null for " + origLocale.getName()); return; } UDate minDate = CalendarTest::minDateOfCalendar(*fmt->getCalendar(), isGregorian, minStatus); if(U_FAILURE(minStatus)) { errln((UnicodeString)"Failure getting min date for " + origLocale.getName()); return; } //logln(UnicodeString("Min date is ") + fullFormat(minDate) + " for " + origLocale.getName()); pat = ((SimpleDateFormat*)fmt)->toPattern(pat); // NOTE TO MAINTAINER // This indexOf check into the pattern needs to be refined to ignore // quoted characters. Currently, this isn't a problem with the locale // patterns we have, but it may be a problem later. UBool hasEra = (pat.indexOf(UnicodeString("G")) != -1); UBool hasZoneDisplayName = (pat.indexOf(UnicodeString("z")) != -1) || (pat.indexOf(UnicodeString("v")) != -1) || (pat.indexOf(UnicodeString("V")) != -1); // Because patterns contain incomplete data representing the Date, // we must be careful of how we do the roundtrip. We start with // a randomly generated Date because they're easier to generate. // From this we get a string. The string is our real starting point, // because this string should parse the same way all the time. Note // that it will not necessarily parse back to the original date because // of incompleteness in patterns. For example, a time-only pattern won't // parse back to the same date. //try { for(int i = 0; i < TRIALS; ++i) { UDate *d = new UDate [DEPTH]; UnicodeString *s = new UnicodeString[DEPTH]; if(isGregorian == TRUE) { d[0] = generateDate(); } else { d[0] = generateDate(minDate); } UErrorCode status = U_ZERO_ERROR; // We go through this loop until we achieve a match or until // the maximum loop count is reached. We record the points at // which the date and the string starts to match. Once matching // starts, it should continue. int loop; int dmatch = 0; // d[dmatch].getTime() == d[dmatch-1].getTime() int smatch = 0; // s[smatch].equals(s[smatch-1]) for(loop = 0; loop < DEPTH; ++loop) { if (loop > 0) { d[loop] = fmt->parse(s[loop-1], status); failure(status, "fmt->parse", s[loop-1]+" in locale: " + origLocale.getName() + " with pattern: " + pat); status = U_ZERO_ERROR; /* any error would have been reported */ } s[loop] = fmt->format(d[loop], s[loop]); // For displaying which date is being tested //logln(s[loop] + " = " + fullFormat(d[loop])); if(s[loop].length() == 0) { errln("FAIL: fmt->format gave 0-length string in " + pat + " with number " + d[loop] + " in locale " + origLocale.getName()); } if(loop > 0) { if(smatch == 0) { UBool match = s[loop] == s[loop-1]; if(smatch == 0) { if(match) smatch = loop; } else if( ! match) errln("FAIL: String mismatch after match"); } if(dmatch == 0) { // {sfb} watch out here, this might not work UBool match = d[loop]/*.getTime()*/ == d[loop-1]/*.getTime()*/; if(dmatch == 0) { if(match) dmatch = loop; } else if( ! match) errln("FAIL: Date mismatch after match"); } if(smatch != 0 && dmatch != 0) break; } } // At this point loop == DEPTH if we've failed, otherwise loop is the // max(smatch, dmatch), that is, the index at which we have string and // date matching. // Date usually matches in 2. Exceptions handled below. int maxDmatch = 2; int maxSmatch = 1; if (dmatch > maxDmatch) { // Time-only pattern with zone information and a starting date in PST. if(timeOnly && hasZoneDisplayName) { int32_t startRaw, startDst; fmt->getTimeZone().getOffset(d[0], FALSE, startRaw, startDst, status); failure(status, "TimeZone::getOffset"); // if the start offset is greater than the offset on Jan 1, 1970 // in PST, then need one more round trip. There are two cases // fall into this category. The start date is 1) DST or // 2) LMT (GMT-07:52:58). if (startRaw + startDst > -28800000) { maxDmatch = 3; maxSmatch = 2; } } } // String usually matches in 1. Exceptions are checked for here. if(smatch > maxSmatch) { // Don't compute unless necessary UBool in0; // Starts in BC, with no era in pattern if( ! hasEra && getField(d[0], UCAL_ERA) == GregorianCalendar::BC) maxSmatch = 2; // Starts in DST, no year in pattern else if((in0=fmt->getTimeZone().inDaylightTime(d[0], status)) && ! failure(status, "gettingDaylightTime") && pat.indexOf(UnicodeString("yyyy")) == -1) maxSmatch = 2; // If we start not in DST, but transition into DST else if (!in0 && fmt->getTimeZone().inDaylightTime(d[1], status) && !failure(status, "gettingDaylightTime")) maxSmatch = 2; // Two digit year with no time zone change, // unless timezone isn't used or we aren't close to the DST changover else if (pat.indexOf(UnicodeString("y")) != -1 && pat.indexOf(UnicodeString("yyyy")) == -1 && getField(d[0], UCAL_YEAR) != getField(d[dmatch], UCAL_YEAR) && !failure(status, "error status [smatch>maxSmatch]") && ((hasZoneDisplayName && (fmt->getTimeZone().inDaylightTime(d[0], status) == fmt->getTimeZone().inDaylightTime(d[dmatch], status) || getField(d[0], UCAL_MONTH) == UCAL_APRIL || getField(d[0], UCAL_MONTH) == UCAL_OCTOBER)) || !hasZoneDisplayName) ) { maxSmatch = 2; } // If zone display name is used, fallback format might be used before 1970 else if (hasZoneDisplayName && d[0] < 0) { maxSmatch = 2; } else if (timeOnly && !isGregorian && hasZoneDisplayName && maxSmatch == 1) { int32_t startRaw, startDst; fmt->getTimeZone().getOffset(d[1], FALSE, startRaw, startDst, status); failure(status, "TimeZone::getOffset"); // If the calendar type is not Gregorian and the pattern is time only, // the calendar implementation may use a date before 1970 as day 0. // In this case, time zone offset of the default year might be // different from the one at 1970-01-01 in PST and string match requires // one more iteration. if (startRaw + startDst != -28800000) { maxSmatch = 2; } } } /* * Special case for Japanese and Buddhist (could have large negative years) * Also, Hebrew calendar need help handling leap month. */ if(dmatch > maxDmatch || smatch > maxSmatch) { const char *type = fmt->getCalendar()->getType(); if(!strcmp(type,"japanese") || (!strcmp(type,"buddhist"))) { maxSmatch = 4; maxDmatch = 4; } else if(!strcmp(type,"hebrew")) { maxSmatch = 3; maxDmatch = 3; } } // Use @v to see verbose results on successful cases UBool fail = (dmatch > maxDmatch || smatch > maxSmatch); if (optionv || fail) { if (fail) { errln(UnicodeString("\nFAIL: Pattern: ") + pat + " in Locale: " + origLocale.getName()); } else { errln(UnicodeString("\nOk: Pattern: ") + pat + " in Locale: " + origLocale.getName()); } logln("Date iters until match=%d (max allowed=%d), string iters until match=%d (max allowed=%d)", dmatch,maxDmatch, smatch, maxSmatch); for(int j = 0; j <= loop && j < DEPTH; ++j) { UnicodeString temp; FieldPosition pos(FieldPosition::DONT_CARE); errln((j>0?" P> ":" ") + fullFormat(d[j]) + " F> " + escape(s[j], temp) + UnicodeString(" d=") + d[j] + (j > 0 && d[j]/*.getTime()*/==d[j-1]/*.getTime()*/?" d==":"") + (j > 0 && s[j] == s[j-1]?" s==":"")); } } delete[] d; delete[] s; } /*} catch (ParseException e) { errln("Exception: " + e.getMessage()); logln(e.toString()); }*/ }
/*write indentation for formatting*/ static void write_tabs(FileStream* os){ int i=0; for(;i<=tabCount;i++){ write_utf8_file(os,UnicodeString(" ")); } }
U_CAPI int32_t U_EXPORT2 umsg_vformat( const UMessageFormat *fmt, UChar *result, int32_t resultLength, va_list ap, UErrorCode *status) { //check arguments if(status==0 || U_FAILURE(*status)) { return -1; } if(fmt==NULL||resultLength<0 || (resultLength>0 && result==0)) { *status=U_ILLEGAL_ARGUMENT_ERROR; return -1; } int32_t count =0; const Formattable::Type* argTypes = MessageFormatAdapter::getArgTypeList(*(const MessageFormat*)fmt, count); // Allocate at least one element. Allocating an array of length // zero causes problems on some platforms (e.g. Win32). Formattable* args = new Formattable[count ? count : 1]; // iterate through the vararg list, and get the arguments out for(int32_t i = 0; i < count; ++i) { UChar *stringVal; double tDouble=0; int32_t tInt =0; int64_t tInt64 = 0; UDate tempDate = 0; switch(argTypes[i]) { case Formattable::kDate: tempDate = va_arg(ap, UDate); args[i].setDate(tempDate); break; case Formattable::kDouble: tDouble =va_arg(ap, double); args[i].setDouble(tDouble); break; case Formattable::kLong: tInt = va_arg(ap, int32_t); args[i].setLong(tInt); break; case Formattable::kInt64: tInt64 = va_arg(ap, int64_t); args[i].setInt64(tInt64); break; case Formattable::kString: // For some reason, a temporary is needed stringVal = va_arg(ap, UChar*); if(stringVal){ args[i].setString(UnicodeString(stringVal)); }else{ *status=U_ILLEGAL_ARGUMENT_ERROR; } break; case Formattable::kArray: // throw away this argument // this is highly platform-dependent, and probably won't work // so, if you try to skip arguments in the list (and not use them) // you'll probably crash va_arg(ap, int); break; case Formattable::kObject: default: // This will never happen because MessageFormat doesn't // support kObject. When MessageFormat is changed to // understand MeasureFormats, modify this code to do the // right thing. [alan] U_ASSERT(FALSE); *status=U_ILLEGAL_ARGUMENT_ERROR; break; } } UnicodeString resultStr; FieldPosition fieldPosition(0); /* format the message */ ((const MessageFormat*)fmt)->format(args,count,resultStr,fieldPosition,*status); delete[] args; if(U_FAILURE(*status)){ return -1; } return resultStr.extract(result, resultLength, *status); }
void ICUServiceTest::testRBF() { // resource bundle factory. UErrorCode status = U_ZERO_ERROR; TestStringService service; service.registerFactory(new ICUResourceBundleFactory(), status); // list all of the resources { UErrorCode status = U_ZERO_ERROR; UVector ids(uprv_deleteUObject, uhash_compareUnicodeString, 0, status); service.getVisibleIDs(ids, status); logln("all visible ids:"); for (int i = 0; i < ids.size(); ++i) { const UnicodeString* id = (const UnicodeString*)ids[i]; logln(*id); } } // get all the display names of these resources // this should be fast since the display names were cached. { UErrorCode status = U_ZERO_ERROR; UVector names(status); service.getDisplayNames(names, Locale::getGermany(), status); logln("service display names for de_DE"); for (int i = 0; i < names.size(); ++i) { const StringPair* pair = (const StringPair*)names[i]; logln(" " + pair->displayName + " --> " + pair->id); } } service.registerFactory(new CalifornioLanguageFactory(), status); // get all the display names of these resources { logln("californio language factory:"); const char* idNames[] = { CalifornioLanguageFactory::californio, CalifornioLanguageFactory::valley, CalifornioLanguageFactory::surfer, CalifornioLanguageFactory::geek, }; int32_t count = sizeof(idNames)/sizeof(idNames[0]); for (int i = 0; i < count; ++i) { logln(UnicodeString("\n --- ") + idNames[i] + " ---"); { UErrorCode status = U_ZERO_ERROR; UVector names(status); service.getDisplayNames(names, idNames[i], status); for (int i = 0; i < names.size(); ++i) { const StringPair* pair = (const StringPair*)names[i]; logln(" " + pair->displayName + " --> " + pair->id); } } } } CalifornioLanguageFactory::cleanup(); }
/* * @test @(#)bug4117335.java 1.1 3/5/98 * * @bug 4117335 */ void DateFormatMiscTests::test4117335() { //UnicodeString bc = "\u7d00\u5143\u524d"; UChar bcC [] = { 0x7D00, 0x5143, 0x524D }; UnicodeString bc(bcC, 3, 3); //UnicodeString ad = "\u897f\u66a6"; UChar adC [] = { 0x897F, 0x66A6 }; UnicodeString ad(adC, 2, 2); //UnicodeString jstLong = "\u65e5\u672c\u6a19\u6e96\u6642"; UChar jstLongC [] = { 0x65e5, 0x672c, 0x6a19, 0x6e96, 0x6642 }; UnicodeString jstLong(jstLongC, 5, 5); UnicodeString jstShort = "JST"; UErrorCode status = U_ZERO_ERROR; DateFormatSymbols *symbols = new DateFormatSymbols(Locale::getJapan(), status); if(U_FAILURE(status)) { errln("Failure creating DateFormatSymbols, %s", u_errorName(status)); delete symbols; return; } failure(status, "new DateFormatSymbols"); int32_t eraCount = 0; const UnicodeString *eras = symbols->getEras(eraCount); logln(UnicodeString("BC = ") + eras[0]); if (eras[0] != bc) { errln("*** Should have been " + bc); //throw new Exception("Error in BC"); } logln(UnicodeString("AD = ") + eras[1]); if (eras[1] != ad) { errln("*** Should have been " + ad); //throw new Exception("Error in AD"); } int32_t rowCount, colCount; const UnicodeString **zones = symbols->getZoneStrings(rowCount, colCount); logln(UnicodeString("Long zone name = ") + zones[24][1]); if (zones[24][1] != jstLong) { errln("*** Should have been " + jstLong); //throw new Exception("Error in long TZ name"); } logln(UnicodeString("Short zone name = ") + zones[24][2]); if (zones[24][2] != jstShort) { errln("*** Should have been " + jstShort); //throw new Exception("Error in short TZ name"); } logln(UnicodeString("Long zone name = ") + zones[24][3]); if (zones[24][3] != jstLong) { errln("*** Should have been " + jstLong); //throw new Exception("Error in long TZ name"); } logln(UnicodeString("SHORT zone name = ") + zones[24][4]); if (zones[24][4] != jstShort) { errln("*** Should have been " + jstShort); //throw new Exception("Error in short TZ name"); } delete symbols; }
/** * See if the decomposition of cp2 is at segment starting at segmentPos * (with canonical rearrangment!) * If so, take the remainder, and return the equivalents */ Hashtable *CanonicalIterator::extract(Hashtable *fillinResult, UChar32 comp, const UChar *segment, int32_t segLen, int32_t segmentPos, UErrorCode &status) { //Hashtable *CanonicalIterator::extract(UChar32 comp, const UnicodeString &segment, int32_t segLen, int32_t segmentPos, UErrorCode &status) { //if (PROGRESS) printf(" extract: %s, ", UToS(Tr(UnicodeString(comp)))); //if (PROGRESS) printf("%s, %i\n", UToS(Tr(segment)), segmentPos); if (U_FAILURE(status)) { return NULL; } UnicodeString temp(comp); int32_t inputLen=temp.length(); UnicodeString decompString; nfd.normalize(temp, decompString, status); if (U_FAILURE(status)) { return NULL; } if (decompString.isBogus()) { status = U_MEMORY_ALLOCATION_ERROR; return NULL; } const UChar *decomp=decompString.getBuffer(); int32_t decompLen=decompString.length(); // See if it matches the start of segment (at segmentPos) UBool ok = FALSE; UChar32 cp; int32_t decompPos = 0; UChar32 decompCp; U16_NEXT(decomp, decompPos, decompLen, decompCp); int32_t i = segmentPos; while(i < segLen) { U16_NEXT(segment, i, segLen, cp); if (cp == decompCp) { // if equal, eat another cp from decomp //if (PROGRESS) printf(" matches: %s\n", UToS(Tr(UnicodeString(cp)))); if (decompPos == decompLen) { // done, have all decomp characters! temp.append(segment+i, segLen-i); ok = TRUE; break; } U16_NEXT(decomp, decompPos, decompLen, decompCp); } else { //if (PROGRESS) printf(" buffer: %s\n", UToS(Tr(UnicodeString(cp)))); // brute force approach temp.append(cp); /* TODO: optimize // since we know that the classes are monotonically increasing, after zero // e.g. 0 5 7 9 0 3 // we can do an optimization // there are only a few cases that work: zero, less, same, greater // if both classes are the same, we fail // if the decomp class < the segment class, we fail segClass = getClass(cp); if (decompClass <= segClass) return null; */ } } if (!ok) return NULL; // we failed, characters left over //if (PROGRESS) printf("Matches\n"); if (inputLen == temp.length()) { fillinResult->put(UnicodeString(), new UnicodeString(), status); return fillinResult; // succeed, but no remainder } // brute force approach // check to make sure result is canonically equivalent UnicodeString trial; nfd.normalize(temp, trial, status); if(U_FAILURE(status) || trial.compare(segment+segmentPos, segLen - segmentPos) != 0) { return NULL; } return getEquivalents2(fillinResult, temp.getBuffer()+inputLen, temp.length()-inputLen, status); }
/* * @bug 4097450 */ void DateFormatMiscTests::test4097450() { // // Date parse requiring 4 digit year. // UnicodeString dstring [] = { UnicodeString("97"), UnicodeString("1997"), UnicodeString("97"), UnicodeString("1997"), UnicodeString("01"), UnicodeString("2001"), UnicodeString("01"), UnicodeString("2001"), UnicodeString("1"), UnicodeString("1"), UnicodeString("11"), UnicodeString("11"), UnicodeString("111"), UnicodeString("111") }; UnicodeString dformat [] = { UnicodeString("yy"), UnicodeString("yy"), UnicodeString("yyyy"), UnicodeString("yyyy"), UnicodeString("yy"), UnicodeString("yy"), UnicodeString("yyyy"), UnicodeString("yyyy"), UnicodeString("yy"), UnicodeString("yyyy"), UnicodeString("yy"), UnicodeString("yyyy"), UnicodeString("yy"), UnicodeString("yyyy") }; /* UBool dresult [] = { TRUE, FALSE, FALSE, TRUE, TRUE, FALSE, FALSE, TRUE, FALSE, FALSE, TRUE, FALSE, FALSE, FALSE };*/ UErrorCode status = U_ZERO_ERROR; SimpleDateFormat *formatter; SimpleDateFormat *resultFormatter = new SimpleDateFormat((UnicodeString)"yyyy", status); failure(status, "new SimpleDateFormat"); logln("Format\tSource\tResult"); logln("-------\t-------\t-------"); for (int i = 0; i < 14/*dstring.length*/; i++) { log(dformat[i] + "\t" + dstring[i] + "\t"); formatter = new SimpleDateFormat(dformat[i], status); failure(status, "new SimpleDateFormat"); //try { UnicodeString str; FieldPosition pos(FieldPosition::DONT_CARE); logln(resultFormatter->format(formatter->parse(dstring[i], status), str, pos)); failure(status, "resultFormatter->format"); //if ( !dresult[i] ) System.out.print(" <-- error!"); /*} catch (ParseException exception) { //if ( dresult[i] ) System.out.print(" <-- error!"); System.out.print("exception --> " + exception); }*/ delete formatter; logln(); } delete resultFormatter; }
void DataDrivenCalendarTest::testConvert(int32_t n, const CalendarFieldsSet &fromSet, Calendar *fromCalendar, const CalendarFieldsSet &toSet, Calendar *toCalendar, UBool forward) { UErrorCode status = U_ZERO_ERROR; UnicodeString thisString = (UnicodeString)"#"+n+" "+(forward ? "forward" : "reverse")+" "+fromCalendar->getType()+"->"+toCalendar->getType(); fromCalendar->clear(); fromSet.setOnCalendar(fromCalendar, status); if (U_FAILURE(status)) { errln("FAIL: Failed to set on Source calendar: %s", u_errorName(status)); return; } CalendarFieldsSet diffSet; diffSet.clear(); // Is the calendar sane at the first? if (!fromSet.matches(fromCalendar, diffSet, status)) { UnicodeString diffs = diffSet.diffFrom(fromSet, status); errln((UnicodeString)"FAIL: "+thisString +", SOURCE calendar was not set: Differences: "+ diffs +"', status: "+ u_errorName(status)); } else if (U_FAILURE(status)) { errln("FAIL: "+thisString+" SOURCE calendar Failed to match: " +u_errorName(status)); } else { logln("PASS: "******" SOURCE calendar match."); } //logln("Set Source calendar: " + from); UDate fromTime = fromCalendar->getTime(status); if (U_FAILURE(status)) { errln("FAIL: Failed to get Source time: %s", u_errorName(status)); return; } diffSet.clear(); // Is the calendar sane after being set? if (!fromSet.matches(fromCalendar, diffSet, status)) { UnicodeString diffs = diffSet.diffFrom(fromSet, status); errln((UnicodeString)"FAIL: "+thisString +", SET SOURCE calendar was not set: Differences: "+ diffs +"', status: "+ u_errorName(status)); } else if (U_FAILURE(status)) { errln("FAIL: "+thisString+" SET SOURCE calendar Failed to match: " +u_errorName(status)); } else { logln("PASS: "******" SET SOURCE calendar match."); } toCalendar->clear(); toCalendar->setTime(fromTime, status); if (U_FAILURE(status)) { errln("FAIL: Failed to set Target time: %s", u_errorName(status)); return; } diffSet.clear(); if (!toSet.matches(toCalendar, diffSet, status)) { UnicodeString diffs = diffSet.diffFrom(toSet, status); errln((UnicodeString)"FAIL: "+thisString+", Differences: "+ diffs +"', status: "+ u_errorName(status)); SimpleDateFormat fmt(UnicodeString("EEE MMM dd yyyy G"), status); UnicodeString fromString; fmt.format(fromTime, fromString); logln("Source Time: "+fromString+", Source Calendar: " +fromCalendar->getType()); } else if (U_FAILURE(status)) { errln("FAIL: "+thisString+" Failed to match: "+u_errorName(status)); } else { logln("PASS: "******" match."); } }
seec::Maybe<IndexedString> IndexedString::from(UnicodeString const &String) { if (String.isBogus()) return seec::Maybe<IndexedString>(); UnicodeString const NeedleStart("@["); UnicodeString const NeedleEscape("@[["); UnicodeString const NeedleEnd("]"); UnicodeString CleanedString; // String with index indicators removed. std::multimap<UnicodeString, Needle> Needles; std::vector<std::pair<UnicodeString, int32_t>> IndexStack; int32_t SearchFrom = 0; // Current offset in String. int32_t FoundStart; // Position of matched index indicator. while ((FoundStart = String.indexOf(NeedleStart, SearchFrom)) != -1) { // Copy all the literal string data. CleanedString.append(String, SearchFrom, FoundStart - SearchFrom); // Check if this is an escape sequence. if (String.compare(FoundStart, NeedleEscape.length(), NeedleEscape) == 0) { CleanedString.append(NeedleStart); SearchFrom = FoundStart + NeedleEscape.length(); continue; } // Find the end of this sequence. int32_t FoundEnd = String.indexOf(NeedleEnd, SearchFrom); if (FoundEnd == -1) return seec::Maybe<IndexedString>(); if (FoundEnd == FoundStart + NeedleStart.length()) { // This is a closing sequence. if (IndexStack.size() == 0) return seec::Maybe<IndexedString>(); // Pop the starting details of the last-opened sequence. auto const Start = IndexStack.back(); IndexStack.pop_back(); // Store the needle for this sequence. Needles.insert(std::make_pair(Start.first, Needle(Start.second, CleanedString.countChar32()))); } else { // This is an opening sequence. int32_t const NameStart = FoundStart + NeedleStart.length(); int32_t const NameLength = FoundEnd - NameStart; IndexStack.emplace_back(UnicodeString(String, NameStart, NameLength), CleanedString.countChar32()); } SearchFrom = FoundEnd + NeedleEnd.length(); } // Copy all remaining literal data. CleanedString.append(String, SearchFrom, String.length() - SearchFrom); return IndexedString(std::move(CleanedString), std::move(Needles)); }
void DataDrivenCalendarTest::testConvert(TestData *testData, const DataMap *settings, UBool forward) { UErrorCode status = U_ZERO_ERROR; Calendar *toCalendar= NULL; const DataMap *currentCase= NULL; char toCalLoc[256] = ""; char fromCalLoc[256] = ""; // build to calendar UnicodeString testSetting = settings->getString("ToCalendar", status); if (U_SUCCESS(status)) { testSetting.extract(0, testSetting.length(), toCalLoc, (const char*)0); toCalendar = Calendar::createInstance(toCalLoc, status); if (U_FAILURE(status)) { dataerrln(UnicodeString("Unable to instantiate ToCalendar for ")+testSetting); return; } } CalendarFieldsSet fromSet, toSet, diffSet; SimpleDateFormat fmt(UnicodeString("EEE MMM dd yyyy / YYYY'-W'ww-ee"), status); if (U_FAILURE(status)) { errcheckln(status, "FAIL: Couldn't create SimpleDateFormat: %s", u_errorName(status)); return; } // Start the processing int n = 0; while (testData->nextCase(currentCase, status)) { ++n; Calendar *fromCalendar= NULL; UnicodeString locale = currentCase->getString("locale", status); if (U_SUCCESS(status)) { locale.extract(0, locale.length(), fromCalLoc, (const char*)0); // default codepage. Invariant codepage doesn't have '@'! fromCalendar = Calendar::createInstance(fromCalLoc, status); if (U_FAILURE(status)) { errln("Unable to instantiate fromCalendar for "+locale); return; } } else { errln("No 'locale' line."); continue; } fromSet.clear(); toSet.clear(); UnicodeString from = currentCase->getString("from", status); if (U_FAILURE(status)) { errln("No 'from' line."); continue; } fromSet.parseFrom(from, status); if (U_FAILURE(status)) { errln("Failed to parse 'from' parameter: "+from); continue; } UnicodeString to = currentCase->getString("to", status); if (U_FAILURE(status)) { errln("No 'to' line."); continue; } toSet.parseFrom(to, &fromSet, status); if (U_FAILURE(status)) { errln("Failed to parse 'to' parameter: "+to); continue; } // now, do it. if (forward) { logln((UnicodeString)"#"+n+" "+locale+"/"+from+" >>> "+toCalLoc+"/" +to); testConvert(n, fromSet, fromCalendar, toSet, toCalendar, forward); } else { logln((UnicodeString)"#"+n+" "+locale+"/"+from+" <<< "+toCalLoc+"/" +to); testConvert(n, toSet, toCalendar, fromSet, fromCalendar, forward); } delete fromCalendar; } delete toCalendar; }
UnicodeString& DefaultLocaleDisplayNames::localeDisplayName(const char* localeId, UnicodeString& result) const { return result = UnicodeString(localeId, -1, US_INV); }
void DataDrivenCalendarTest::testOps(TestData *testData, const DataMap * /*settings*/) { UErrorCode status = U_ZERO_ERROR; UBool useDate = FALSE; // TODO UnicodeString kMILLIS("MILLIS="); // TODO: static UDate fromDate = 0; // TODO UDate toDate = 0; const DataMap *currentCase= NULL; char toCalLoc[256] = ""; // TODO: static strings? const UnicodeString kADD("add", ""); const UnicodeString kROLL("roll", ""); // Get 'from' time CalendarFieldsSet fromSet, toSet, paramsSet, diffSet; SimpleDateFormat fmt(UnicodeString("EEE MMM dd yyyy / YYYY'-W'ww-ee"), status); if (U_FAILURE(status)) { dataerrln("FAIL: Couldn't create SimpleDateFormat: %s", u_errorName(status)); return; } // Start the processing int n = 0; while (testData->nextCase(currentCase, status)) { ++n; Calendar *toCalendar= NULL; Calendar *fromCalendar= NULL; // load parameters char theCase[200]; sprintf(theCase, "[case %d]", n); UnicodeString caseString(theCase, ""); // build to calendar // Headers { "locale","from","operation","params","to" } // #1 locale const char *param = "locale"; UnicodeString locale; UnicodeString testSetting = currentCase->getString(param, status); if (U_FAILURE(status)) { errln(caseString+": Unable to get param '"+param+"' " + UnicodeString(" - ")); continue; } testSetting.extract(0, testSetting.length(), toCalLoc, (const char*)0); fromCalendar = Calendar::createInstance(toCalLoc, status); if (U_FAILURE(status)) { errln(caseString+": Unable to instantiate calendar for " +testSetting); continue; } fromSet.clear(); // #2 'from' info param = "from"; UnicodeString from = testSetting=currentCase->getString(param, status); if (U_FAILURE(status)) { errln(caseString+": Unable to get parameter '"+param+"' " + UnicodeString(" - ")); continue; } if(from.startsWith(kMILLIS)){ UnicodeString millis = UnicodeString(from, kMILLIS.length()); useDate = TRUE; fromDate = udbg_stod(millis); } else if(fromSet.parseFrom(testSetting, status)<0 || U_FAILURE(status)){ errln(caseString+": Failed to parse '"+param+"' parameter: " +testSetting); continue; } // #4 'operation' info param = "operation"; UnicodeString operation = testSetting=currentCase->getString(param, status); if (U_FAILURE(status)) { errln(caseString+": Unable to get parameter '"+param+"' " + UnicodeString(" - ")); continue; } if (U_FAILURE(status)) { errln(caseString+": Failed to parse '"+param+"' parameter: " +testSetting); continue; } paramsSet.clear(); // #3 'params' info param = "params"; UnicodeString params = testSetting =currentCase->getString(param, status); if (U_FAILURE(status)) { errln(caseString+": Unable to get parameter '"+param+"' " + UnicodeString(" - ")); continue; } paramsSet.parseFrom(testSetting, status); // parse with inheritance. if (U_FAILURE(status)) { errln(caseString+": Failed to parse '"+param+"' parameter: " +testSetting); continue; } toSet.clear(); // #4 'to' info param = "to"; UnicodeString to = testSetting=currentCase->getString(param, status); if (U_FAILURE(status)) { errln(caseString+": Unable to get parameter '"+param+"' " + UnicodeString(" - ")); continue; } if(to.startsWith(kMILLIS)){ UnicodeString millis = UnicodeString(to, kMILLIS.length()); useDate = TRUE; toDate = udbg_stod(millis); } else if(toSet.parseFrom(testSetting, &fromSet, status)<0 || U_FAILURE(status)){ errln(caseString+": Failed to parse '"+param+"' parameter: " +testSetting); continue; } UnicodeString caseContentsString = locale+": from "+from+": " +operation +" [[[ "+params+" ]]] >>> "+to; logln(caseString+": "+caseContentsString); // ------ // now, do it. /// prepare calendar if(useDate){ fromCalendar->setTime(fromDate, status); if (U_FAILURE(status)) { errln(caseString+" FAIL: Failed to set time on Source calendar: " + u_errorName(status)); return; } } else { fromSet.setOnCalendar(fromCalendar, status); if (U_FAILURE(status)) { errln(caseString+" FAIL: Failed to set on Source calendar: " + u_errorName(status)); return; } } diffSet.clear(); // Is the calendar sane after being set? if (!fromSet.matches(fromCalendar, diffSet, status)) { UnicodeString diffs = diffSet.diffFrom(fromSet, status); errln((UnicodeString)"FAIL: "+caseString +", SET SOURCE calendar was not set: Differences: "+ diffs +"', status: "+ u_errorName(status)); } else if (U_FAILURE(status)) { errln("FAIL: "+caseString+" SET SOURCE calendar Failed to match: " +u_errorName(status)); } else { logln("PASS: "******" SET SOURCE calendar match."); } // to calendar - copy of from calendar toCalendar = fromCalendar->clone(); /// perform op for (int q=0; q<UCAL_FIELD_COUNT; q++) { if (paramsSet.isSet((UCalendarDateFields)q)) { if (operation == kROLL) { toCalendar->roll((UCalendarDateFields)q, paramsSet.get((UCalendarDateFields)q), status); } else if (operation == kADD) { toCalendar->add((UCalendarDateFields)q, paramsSet.get((UCalendarDateFields)q), status); } else { errln(caseString+ " FAIL: unknown operation "+ operation); } logln(operation + " of "+ paramsSet.get((UCalendarDateFields)q) +" -> "+u_errorName(status)); } } if (U_FAILURE(status)) { errln(caseString+" FAIL: after "+operation+" of "+params+" -> " +u_errorName(status)); continue; } // now - what's the result? diffSet.clear(); if(useDate){ if(!(toCalendar->getTime(status)==toDate) || U_FAILURE(status)){ errln("FAIL: "+caseString+" Match operation had an error: " +u_errorName(status)); }else{ logln(caseString + " SUCCESS: got=expected="+toDate); logln("PASS: "******" matched!"); } } else if (!toSet.matches(toCalendar, diffSet, status)) { UnicodeString diffs = diffSet.diffFrom(toSet, status); errln((UnicodeString)"FAIL: "+caseString+" - , "+caseContentsString +" Differences: "+ diffs +"', status: " + u_errorName(status)); }else if (U_FAILURE(status)) { errln("FAIL: "+caseString+" Match operation had an error: " +u_errorName(status)); }else { logln("PASS: "******" matched!"); } delete fromCalendar; delete toCalendar; } }
UnicodeString& DefaultLocaleDisplayNames::scriptDisplayName(const char* script, UnicodeString& result) const { return result = UnicodeString(script, -1, US_INV); }
NormalizerConformanceTest::NormalizerConformanceTest() : normalizer(UnicodeString(), UNORM_NFC) {}
UnicodeString& DefaultLocaleDisplayNames::variantDisplayName(const char* variant, UnicodeString& result) const { return result = UnicodeString(variant, -1, US_INV); }
void CasePropsBuilder::setProps(const UniProps &props, const UnicodeSet &newValues, UErrorCode &errorCode) { if(U_FAILURE(errorCode) || newValues.containsNone(relevantProps)) { return; } UChar32 start=props.start; UChar32 end=props.end; /* default: map to self */ int32_t delta=0; uint32_t type; if(props.binProps[UCHAR_LOWERCASE]) { type=UCASE_LOWER; } else if(props.binProps[UCHAR_UPPERCASE]) { type=UCASE_UPPER; } else if(props.getIntProp(UCHAR_GENERAL_CATEGORY)==U_TITLECASE_LETTER) { type=UCASE_TITLE; } else { type=UCASE_NONE; } uint32_t value=type; UBool hasMapping=FALSE; if(props.suc>=0) { /* uppercase mapping as delta if the character is lowercase */ hasMapping=TRUE; if(type==UCASE_LOWER) { delta=props.suc-start; } else { value|=UCASE_EXCEPTION; } } if(props.slc>=0) { /* lowercase mapping as delta if the character is uppercase or titlecase */ hasMapping=TRUE; if(type>=UCASE_UPPER) { delta=props.slc-start; } else { value|=UCASE_EXCEPTION; } } if(props.stc>=0) { hasMapping=TRUE; } if(props.suc!=props.stc) { value|=UCASE_EXCEPTION; } if(!props.lc.isEmpty() || !props.uc.isEmpty() || !props.tc.isEmpty() || newValues.contains(PPUCD_CONDITIONAL_CASE_MAPPINGS) ) { hasMapping=TRUE; value|=UCASE_EXCEPTION; } if( (props.scf>=0 && props.scf!=props.slc) || (!props.cf.isEmpty() && props.cf!=UnicodeString(props.scf)) || newValues.contains(PPUCD_TURKIC_CASE_FOLDING) ) { hasMapping=TRUE; value|=UCASE_EXCEPTION; } // Simple case folding falls back to simple lowercasing. // If there is no case folding but there is a lowercase mapping, // then add a case folding mapping to the code point. // For example: Cherokee uppercase syllables since Unicode 8. // (Full case folding falls back to simple case folding, // not to full lowercasing, so we need not also handle it specially // for such cases.) UChar32 scf=props.scf; if(scf<0 && props.slc>=0) { scf=start; hasMapping=TRUE; value|=UCASE_EXCEPTION; } if(delta<UCASE_MIN_DELTA || UCASE_MAX_DELTA<delta) { value|=UCASE_EXCEPTION; } if(props.binProps[UCHAR_SOFT_DOTTED]) { value|=UCASE_SOFT_DOTTED; } int32_t cc=props.getIntProp(UCHAR_CANONICAL_COMBINING_CLASS); if(cc!=0) { if(props.binProps[UCHAR_SOFT_DOTTED]) { fprintf(stderr, "genprops error: a soft-dotted character has ccc!=0\n"); errorCode=U_ILLEGAL_ARGUMENT_ERROR; return; } if(cc==230) { value|=UCASE_ABOVE; } else { value|=UCASE_OTHER_ACCENT; } } if(props.binProps[UCHAR_CASE_IGNORABLE]) { value|=UCASE_IGNORABLE; } if((hasMapping || (value&UCASE_EXCEPTION)) && start!=end) { fprintf(stderr, "genprops error: range %04lX..%04lX has case mappings " "or reasons for data structure exceptions\n", (long)start, (long)end); errorCode=U_ILLEGAL_ARGUMENT_ERROR; return; } /* handle exceptions */ if(value&UCASE_EXCEPTION) { /* simply store exceptions for later processing and encoding */ if(excPropsCount==MAX_EXC_COUNT) { fprintf(stderr, "genprops error: casepropsbuilder: too many exceptions\n"); errorCode=U_INDEX_OUTOFBOUNDS_ERROR; return; } ExcProps *newExcProps=new ExcProps(props); if(newExcProps==NULL) { fprintf(stderr, "genprops error: casepropsbuilder out of memory allocating " "exceptions properties\n"); errorCode=U_MEMORY_ALLOCATION_ERROR; return; } newExcProps->props.scf=scf; newExcProps->hasConditionalCaseMappings=newValues.contains(PPUCD_CONDITIONAL_CASE_MAPPINGS); newExcProps->hasTurkicCaseFolding=newValues.contains(PPUCD_TURKIC_CASE_FOLDING); value|=(uint32_t)excPropsCount<<UGENCASE_EXC_SHIFT; excProps[excPropsCount++]=newExcProps; } else { /* store the simple case mapping delta */ value|=((uint32_t)delta<<UCASE_DELTA_SHIFT)&UCASE_DELTA_MASK; } utrie2_setRange32(pTrie, start, end, value, TRUE, &errorCode); if(U_FAILURE(errorCode)) { fprintf(stderr, "genprops error: unable to set case mapping values: %s\n", u_errorName(errorCode)); return; } if(hasMapping) { /* update the case-sensitive set */ caseSensitive.add(start); if(scf>=0) { caseSensitive.add(scf); } if(props.slc>=0) { caseSensitive.add(props.slc); } if(props.suc>=0) { caseSensitive.add(props.suc); } if(props.stc>=0) { caseSensitive.add(props.stc); } caseSensitive.addAll(props.cf); caseSensitive.addAll(props.lc); caseSensitive.addAll(props.uc); caseSensitive.addAll(props.tc); /* update maxFullLength */ if(props.cf.length()>maxFullLength) { maxFullLength=props.cf.length(); } if(props.lc.length()>maxFullLength) { maxFullLength=props.lc.length(); } if(props.uc.length()>maxFullLength) { maxFullLength=props.uc.length(); } if(props.tc.length()>maxFullLength) { maxFullLength=props.tc.length(); } } /* add the multi-character case folding to the "unfold" data */ if(props.cf.hasMoreChar32Than(0, 0x7fffffff, 1)) { addUnfolding(start, props.cf, errorCode); } }
UnicodeString& DefaultLocaleDisplayNames::keyValueDisplayName(const char* /* key */, const char* value, UnicodeString& result) const { return result = UnicodeString(value, -1, US_INV); }
/* * @bug 4099975 */ void DateFormatMiscTests::test4099975() { /** * Test Constructor SimpleDateFormat::SimpleDateFormat (const UnicodeString & pattern, * const DateFormatSymbols & formatData, UErrorCode & status ) * The DateFormatSymbols object is NOT adopted; Modifying the original DateFormatSymbols * should not change the SimpleDateFormat's behavior. */ UDate d = Calendar::getNow(); { UErrorCode status = U_ZERO_ERROR; DateFormatSymbols* symbols = new DateFormatSymbols(Locale::getUS(), status); failure(status, "new DateFormatSymbols"); SimpleDateFormat *df = new SimpleDateFormat(UnicodeString("E hh:mm"), *symbols, status); failure(status, "new SimpleDateFormat"); UnicodeString format0; format0 = df->format(d, format0); UnicodeString localizedPattern0; localizedPattern0 = df->toLocalizedPattern(localizedPattern0, status); failure(status, "df->toLocalizedPattern"); symbols->setLocalPatternChars(UnicodeString("abcdefghijklmonpqr")); // change value of field UnicodeString format1; format1 = df->format(d, format1); if (format0 != format1) { errln(UnicodeString("Formats are different. format0: ") + format0 + UnicodeString("; format1: ") + format1); } UnicodeString localizedPattern1; localizedPattern1 = df->toLocalizedPattern(localizedPattern1, status); failure(status, "df->toLocalizedPattern"); if (localizedPattern0 != localizedPattern1) { errln(UnicodeString("Pattern has been changed. localizedPattern0: ") + localizedPattern0 + UnicodeString("; localizedPattern1: ") + localizedPattern1); } delete symbols; delete df; } /* * Test void SimpleDateFormat::setDateFormatSymbols ( const DateFormatSymbols & newFormatSymbols ) * Modifying the original DateFormatSymbols should not change the SimpleDateFormat's behavior. */ { UErrorCode status = U_ZERO_ERROR; DateFormatSymbols* symbols = new DateFormatSymbols(Locale::getUS(), status); failure(status, "new DateFormatSymbols"); SimpleDateFormat *df = new SimpleDateFormat(UnicodeString("E hh:mm"), status); failure(status, "new SimpleDateFormat"); df->setDateFormatSymbols(*symbols); UnicodeString format0; format0 = df->format(d, format0); UnicodeString localizedPattern0; localizedPattern0 = df->toLocalizedPattern(localizedPattern0, status); failure(status, "df->toLocalizedPattern"); symbols->setLocalPatternChars(UnicodeString("abcdefghijklmonpqr")); // change value of field UnicodeString format1; format1 = df->format(d, format1); if (format0 != format1) { errln(UnicodeString("Formats are different. format0: ") + format0 + UnicodeString("; format1: ") + format1); } UnicodeString localizedPattern1; localizedPattern1 = df->toLocalizedPattern(localizedPattern1, status); failure(status, "df->toLocalizedPattern"); if (localizedPattern0 != localizedPattern1) { errln(UnicodeString("Pattern has been changed. localizedPattern0: ") + localizedPattern0 + UnicodeString("; localizedPattern1: ") + localizedPattern1); } delete symbols; delete df; } //Test the pointer version of the constructor (and the adoptDateFormatSymbols method) { UErrorCode status = U_ZERO_ERROR; DateFormatSymbols* symbols = new DateFormatSymbols(Locale::getUS(), status); failure(status, "new DateFormatSymbols"); SimpleDateFormat *df = new SimpleDateFormat(UnicodeString("E hh:mm"), symbols, status); failure(status, "new SimpleDateFormat"); UnicodeString format0; format0 = df->format(d, format0); UnicodeString localizedPattern0; localizedPattern0 = df->toLocalizedPattern(localizedPattern0, status); failure(status, "df->toLocalizedPattern"); symbols->setLocalPatternChars(UnicodeString("abcdefghijklmonpqr")); // change value of field UnicodeString format1; format1 = df->format(d, format1); if (format0 != format1) { errln(UnicodeString("Formats are different. format0: ") + format0 + UnicodeString("; format1: ") + format1); } UnicodeString localizedPattern1; localizedPattern1 = df->toLocalizedPattern(localizedPattern1, status); failure(status, "df->toLocalizedPattern"); if (localizedPattern0 == localizedPattern1) { errln(UnicodeString("Pattern should have been changed. localizedPattern0: ") + localizedPattern0 + UnicodeString("; localizedPattern1: ") + localizedPattern1); } //delete symbols; the caller is no longer responsible for deleting the symbols delete df; } // { UErrorCode status = U_ZERO_ERROR; DateFormatSymbols* symbols = new DateFormatSymbols(Locale::getUS(), status); failure(status, "new DateFormatSymbols"); SimpleDateFormat *df = new SimpleDateFormat(UnicodeString("E hh:mm"), status); failure(status, "new SimpleDateFormat"); df-> adoptDateFormatSymbols(symbols); UnicodeString format0; format0 = df->format(d, format0); UnicodeString localizedPattern0; localizedPattern0 = df->toLocalizedPattern(localizedPattern0, status); failure(status, "df->toLocalizedPattern"); symbols->setLocalPatternChars(UnicodeString("abcdefghijklmonpqr")); // change value of field UnicodeString format1; format1 = df->format(d, format1); if (format0 != format1) { errln(UnicodeString("Formats are different. format0: ") + format0 + UnicodeString("; format1: ") + format1); } UnicodeString localizedPattern1; localizedPattern1 = df->toLocalizedPattern(localizedPattern1, status); failure(status, "df->toLocalizedPattern"); if (localizedPattern0 == localizedPattern1) { errln(UnicodeString("Pattern should have been changed. localizedPattern0: ") + localizedPattern0 + UnicodeString("; localizedPattern1: ") + localizedPattern1); } //delete symbols; the caller is no longer responsible for deleting the symbols delete df; } }
UnicodeString& LocaleDisplayNamesImpl::localeDisplayName(const Locale& loc, UnicodeString& result) const { if (loc.isBogus()) { result.setToBogus(); return result; } UnicodeString resultName; const char* lang = loc.getLanguage(); if (uprv_strlen(lang) == 0) { lang = "root"; } const char* script = loc.getScript(); const char* country = loc.getCountry(); const char* variant = loc.getVariant(); UBool hasScript = uprv_strlen(script) > 0; UBool hasCountry = uprv_strlen(country) > 0; UBool hasVariant = uprv_strlen(variant) > 0; if (dialectHandling == ULDN_DIALECT_NAMES) { char buffer[ULOC_FULLNAME_CAPACITY]; do { // loop construct is so we can break early out of search if (hasScript && hasCountry) { ncat(buffer, ULOC_FULLNAME_CAPACITY, lang, "_", script, "_", country, (char *)0); localeIdName(buffer, resultName); if (!resultName.isBogus()) { hasScript = FALSE; hasCountry = FALSE; break; } } if (hasScript) { ncat(buffer, ULOC_FULLNAME_CAPACITY, lang, "_", script, (char *)0); localeIdName(buffer, resultName); if (!resultName.isBogus()) { hasScript = FALSE; break; } } if (hasCountry) { ncat(buffer, ULOC_FULLNAME_CAPACITY, lang, "_", country, (char*)0); localeIdName(buffer, resultName); if (!resultName.isBogus()) { hasCountry = FALSE; break; } } } while (FALSE); } if (resultName.isBogus() || resultName.isEmpty()) { localeIdName(lang, resultName); } UnicodeString resultRemainder; UnicodeString temp; UErrorCode status = U_ZERO_ERROR; if (hasScript) { resultRemainder.append(scriptDisplayName(script, temp, TRUE)); } if (hasCountry) { appendWithSep(resultRemainder, regionDisplayName(country, temp, TRUE)); } if (hasVariant) { appendWithSep(resultRemainder, variantDisplayName(variant, temp, TRUE)); } resultRemainder.findAndReplace(formatOpenParen, formatReplaceOpenParen); resultRemainder.findAndReplace(formatCloseParen, formatReplaceCloseParen); LocalPointer<StringEnumeration> e(loc.createKeywords(status)); if (e.isValid() && U_SUCCESS(status)) { UnicodeString temp2; char value[ULOC_KEYWORD_AND_VALUES_CAPACITY]; // sigh, no ULOC_VALUE_CAPACITY const char* key; while ((key = e->next((int32_t *)0, status)) != NULL) { value[0] = 0; loc.getKeywordValue(key, value, ULOC_KEYWORD_AND_VALUES_CAPACITY, status); if (U_FAILURE(status) || status == U_STRING_NOT_TERMINATED_WARNING) { return result; } keyDisplayName(key, temp, TRUE); temp.findAndReplace(formatOpenParen, formatReplaceOpenParen); temp.findAndReplace(formatCloseParen, formatReplaceCloseParen); keyValueDisplayName(key, value, temp2, TRUE); temp2.findAndReplace(formatOpenParen, formatReplaceOpenParen); temp2.findAndReplace(formatCloseParen, formatReplaceCloseParen); if (temp2 != UnicodeString(value, -1, US_INV)) { appendWithSep(resultRemainder, temp2); } else if (temp != UnicodeString(key, -1, US_INV)) { UnicodeString temp3; keyTypeFormat.format(temp, temp2, temp3, status); appendWithSep(resultRemainder, temp3); } else { appendWithSep(resultRemainder, temp) .append((UChar)0x3d /* = */) .append(temp2); } } } if (!resultRemainder.isEmpty()) { format.format(resultName, resultRemainder, result.remove(), status); return adjustForUsageAndContext(kCapContextUsageLanguage, result); } result = resultName; return adjustForUsageAndContext(kCapContextUsageLanguage, result); }
// test APIs that are not otherwise used - improve test coverage void BasicNormalizerTest::TestNormalizerAPI() { // instantiate a Normalizer from a CharacterIterator UnicodeString s=UnicodeString("a\\u0308\\uac00\\U0002f800", "").unescape(); s.append(s); // make s a bit longer and more interesting StringCharacterIterator iter(s); Normalizer norm(iter, UNORM_NFC); if(norm.next()!=0xe4) { dataerrln("error in Normalizer(CharacterIterator).next()"); } // test copy constructor Normalizer copy(norm); if(copy.next()!=0xac00) { dataerrln("error in Normalizer(Normalizer(CharacterIterator)).next()"); } // test clone(), ==, and hashCode() Normalizer *clone=copy.clone(); if(*clone!=copy) { errln("error in Normalizer(Normalizer(CharacterIterator)).clone()!=copy"); } // clone must have the same hashCode() if(clone->hashCode()!=copy.hashCode()) { errln("error in Normalizer(Normalizer(CharacterIterator)).clone()->hashCode()!=copy.hashCode()"); } if(clone->next()!=0x4e3d) { dataerrln("error in Normalizer(Normalizer(CharacterIterator)).clone()->next()"); } // position changed, must change hashCode() if(clone->hashCode()==copy.hashCode()) { errln("error in Normalizer(Normalizer(CharacterIterator)).clone()->next().hashCode()==copy.hashCode()"); } delete clone; clone=0; // test compose() and decompose() UnicodeString tel, nfkc, nfkd; tel=UnicodeString(1, (UChar32)0x2121, 10); tel.insert(1, (UChar)0x301); UErrorCode errorCode=U_ZERO_ERROR; Normalizer::compose(tel, TRUE, 0, nfkc, errorCode); Normalizer::decompose(tel, TRUE, 0, nfkd, errorCode); if(U_FAILURE(errorCode)) { dataerrln("error in Normalizer::(de)compose(): %s", u_errorName(errorCode)); } else if( nfkc!=UnicodeString("TE\\u0139TELTELTELTELTELTELTELTELTEL", "").unescape() || nfkd!=UnicodeString("TEL\\u0301TELTELTELTELTELTELTELTELTEL", "").unescape() ) { errln("error in Normalizer::(de)compose(): wrong result(s)"); } // test setIndex() norm.setIndexOnly(3); if(norm.current()!=0x4e3d) { dataerrln("error in Normalizer(CharacterIterator).setIndex(3)"); } // test setText(CharacterIterator) and getText() UnicodeString out, out2; errorCode=U_ZERO_ERROR; copy.setText(iter, errorCode); if(U_FAILURE(errorCode)) { errln("error Normalizer::setText() failed: %s", u_errorName(errorCode)); } else { copy.getText(out); iter.getText(out2); if( out!=out2 || copy.startIndex()!=iter.startIndex() || copy.endIndex()!=iter.endIndex() ) { errln("error in Normalizer::setText() or Normalizer::getText()"); } } // test setText(UChar *), getUMode() and setMode() errorCode=U_ZERO_ERROR; copy.setText(s.getBuffer()+1, s.length()-1, errorCode); copy.setMode(UNORM_NFD); if(copy.getUMode()!=UNORM_NFD) { errln("error in Normalizer::setMode() or Normalizer::getUMode()"); } if(copy.next()!=0x308 || copy.next()!=0x1100) { dataerrln("error in Normalizer::setText(UChar *) or Normalizer::setMode()"); } // test setText(UChar *, length=-1) errorCode=U_ZERO_ERROR; // NUL-terminate s s.append((UChar)0); // append NUL s.truncate(s.length()-1); // undo length change copy.setText(s.getBuffer()+1, -1, errorCode); if(copy.endIndex()!=s.length()-1) { errln("error in Normalizer::setText(UChar *, -1)"); } // test setOption() and getOption() copy.setOption(0xaa0000, TRUE); copy.setOption(0x20000, FALSE); if(!copy.getOption(0x880000) || copy.getOption(0x20000)) { errln("error in Normalizer::setOption() or Normalizer::getOption()"); } // test last()/previous() with an internal buffer overflow errorCode=U_ZERO_ERROR; copy.setText(UnicodeString(1000, (UChar32)0x308, 1000), errorCode); if(copy.last()!=0x308) { errln("error in Normalizer(1000*U+0308).last()"); } // test UNORM_NONE norm.setMode(UNORM_NONE); if(norm.first()!=0x61 || norm.next()!=0x308 || norm.last()!=0x2f800) { errln("error in Normalizer(UNORM_NONE).first()/next()/last()"); } Normalizer::normalize(s, UNORM_NONE, 0, out, status); if(out!=s) { errln("error in Normalizer::normalize(UNORM_NONE)"); } // test that the same string can be used as source and destination s.setTo((UChar)0xe4); Normalizer::normalize(s, UNORM_NFD, 0, s, status); if(s.charAt(1)!=0x308) { dataerrln("error in Normalizer::normalize(UNORM_NFD, self)"); } Normalizer::normalize(s, UNORM_NFC, 0, s, status); if(s.charAt(0)!=0xe4) { dataerrln("error in Normalizer::normalize(UNORM_NFC, self)"); } Normalizer::decompose(s, FALSE, 0, s, status); if(s.charAt(1)!=0x308) { dataerrln("error in Normalizer::decompose(self)"); } Normalizer::compose(s, FALSE, 0, s, status); if(s.charAt(0)!=0xe4) { dataerrln("error in Normalizer::compose(self)"); } Normalizer::concatenate(s, s, s, UNORM_NFC, 0, status); if(s.charAt(1)!=0xe4) { dataerrln("error in Normalizer::decompose(self)"); } }