本文整理汇总了C++中UnicodeString类的典型用法代码示例。如果您正苦于以下问题:C++ UnicodeString类的具体用法?C++ UnicodeString怎么用?C++ UnicodeString使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了UnicodeString类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: spanQuickCheckYes
virtual int32_t
spanQuickCheckYes(const UnicodeString &s, UErrorCode &) const {
return s.length();
}
示例2: switch
Transliterator* TransliteratorAlias::create(UParseError& pe,
UErrorCode& ec) {
if (U_FAILURE(ec)) {
return 0;
}
Transliterator *t = NULL;
switch (type) {
case SIMPLE:
t = Transliterator::createInstance(aliasesOrRules, UTRANS_FORWARD, pe, ec);
if(U_FAILURE(ec)){
return 0;
}
if (compoundFilter != 0)
t->adoptFilter((UnicodeSet*)compoundFilter->clone());
break;
case COMPOUND:
{
// the total number of transliterators in the compound is the total number of anonymous transliterators
// plus the total number of ID blocks-- we start by assuming the list begins and ends with an ID
// block and that each pair anonymous transliterators has an ID block between them. Then we go back
// to see whether there really are ID blocks at the beginning and end (by looking for U+FFFF, which
// marks the position where an anonymous transliterator goes) and adjust accordingly
int32_t anonymousRBTs = transes->size();
int32_t transCount = anonymousRBTs * 2 + 1;
if (!aliasesOrRules.isEmpty() && aliasesOrRules[0] == (UChar)(0xffff))
--transCount;
if (aliasesOrRules.length() >= 2 && aliasesOrRules[aliasesOrRules.length() - 1] == (UChar)(0xffff))
--transCount;
UnicodeString noIDBlock((UChar)(0xffff));
noIDBlock += ((UChar)(0xffff));
int32_t pos = aliasesOrRules.indexOf(noIDBlock);
while (pos >= 0) {
--transCount;
pos = aliasesOrRules.indexOf(noIDBlock, pos + 1);
}
UVector transliterators(ec);
UnicodeString idBlock;
int32_t blockSeparatorPos = aliasesOrRules.indexOf((UChar)(0xffff));
while (blockSeparatorPos >= 0) {
aliasesOrRules.extract(0, blockSeparatorPos, idBlock);
aliasesOrRules.remove(0, blockSeparatorPos + 1);
if (!idBlock.isEmpty())
transliterators.addElement(Transliterator::createInstance(idBlock, UTRANS_FORWARD, pe, ec), ec);
if (!transes->isEmpty())
transliterators.addElement(transes->orphanElementAt(0), ec);
blockSeparatorPos = aliasesOrRules.indexOf((UChar)(0xffff));
}
if (!aliasesOrRules.isEmpty())
transliterators.addElement(Transliterator::createInstance(aliasesOrRules, UTRANS_FORWARD, pe, ec), ec);
while (!transes->isEmpty())
transliterators.addElement(transes->orphanElementAt(0), ec);
if (U_SUCCESS(ec)) {
t = new CompoundTransliterator(ID, transliterators,
(compoundFilter ? (UnicodeSet*)(compoundFilter->clone()) : 0),
anonymousRBTs, pe, ec);
if (t == 0) {
ec = U_MEMORY_ALLOCATION_ERROR;
return 0;
}
} else {
for (int32_t i = 0; i < transliterators.size(); i++)
delete (Transliterator*)(transliterators.elementAt(i));
}
}
break;
case RULES:
U_ASSERT(FALSE); // don't call create() if isRuleBased() returns TRUE!
break;
}
return t;
}
示例3: applyPattern
/**
* Parse the pattern from the given RuleCharacterIterator. The
* iterator is advanced over the parsed pattern.
* @param chars iterator over the pattern characters. Upon return
* it will be advanced to the first character after the parsed
* pattern, or the end of the iteration if all characters are
* parsed.
* @param symbols symbol table to use to parse and dereference
* variables, or null if none.
* @param rebuiltPat the pattern that was parsed, rebuilt or
* copied from the input pattern, as appropriate.
* @param options a bit mask of zero or more of the following:
* IGNORE_SPACE, CASE.
*/
void UnicodeSet::applyPattern(RuleCharacterIterator& chars,
const SymbolTable* symbols,
UnicodeString& rebuiltPat,
uint32_t options,
UnicodeSet& (UnicodeSet::*caseClosure)(int32_t attribute),
UErrorCode& ec) {
if (U_FAILURE(ec)) return;
// Syntax characters: [ ] ^ - & { }
// Recognized special forms for chars, sets: c-c s-s s&s
int32_t opts = RuleCharacterIterator::PARSE_VARIABLES |
RuleCharacterIterator::PARSE_ESCAPES;
if ((options & USET_IGNORE_SPACE) != 0) {
opts |= RuleCharacterIterator::SKIP_WHITESPACE;
}
UnicodeString patLocal, buf;
UBool usePat = FALSE;
UnicodeSetPointer scratch;
RuleCharacterIterator::Pos backup;
// mode: 0=before [, 1=between [...], 2=after ]
// lastItem: 0=none, 1=char, 2=set
int8_t lastItem = 0, mode = 0;
UChar32 lastChar = 0;
UChar op = 0;
UBool invert = FALSE;
clear();
while (mode != 2 && !chars.atEnd()) {
U_ASSERT((lastItem == 0 && op == 0) ||
(lastItem == 1 && (op == 0 || op == HYPHEN /*'-'*/)) ||
(lastItem == 2 && (op == 0 || op == HYPHEN /*'-'*/ ||
op == INTERSECTION /*'&'*/)));
UChar32 c = 0;
UBool literal = FALSE;
UnicodeSet* nested = 0; // alias - do not delete
// -------- Check for property pattern
// setMode: 0=none, 1=unicodeset, 2=propertypat, 3=preparsed
int8_t setMode = 0;
if (resemblesPropertyPattern(chars, opts)) {
setMode = 2;
}
// -------- Parse '[' of opening delimiter OR nested set.
// If there is a nested set, use `setMode' to define how
// the set should be parsed. If the '[' is part of the
// opening delimiter for this pattern, parse special
// strings "[", "[^", "[-", and "[^-". Check for stand-in
// characters representing a nested set in the symbol
// table.
else {
// Prepare to backup if necessary
chars.getPos(backup);
c = chars.next(opts, literal, ec);
if (U_FAILURE(ec)) return;
if (c == 0x5B /*'['*/ && !literal) {
if (mode == 1) {
chars.setPos(backup); // backup
setMode = 1;
} else {
// Handle opening '[' delimiter
mode = 1;
patLocal.append((UChar) 0x5B /*'['*/);
chars.getPos(backup); // prepare to backup
c = chars.next(opts, literal, ec);
if (U_FAILURE(ec)) return;
if (c == 0x5E /*'^'*/ && !literal) {
invert = TRUE;
patLocal.append((UChar) 0x5E /*'^'*/);
chars.getPos(backup); // prepare to backup
c = chars.next(opts, literal, ec);
if (U_FAILURE(ec)) return;
}
// Fall through to handle special leading '-';
// otherwise restart loop for nested [], \p{}, etc.
if (c == HYPHEN /*'-'*/) {
//.........这里部分代码省略.........
示例4: while
/**
* If in "by digits" mode, fills in the substitution one decimal digit
* at a time using the rule set containing this substitution.
* Otherwise, uses the superclass function.
* @param number The number being formatted
* @param toInsertInto The string to insert the result of formatting
* the substitution into
* @param pos The position of the owning rule's rule text in
* toInsertInto
*/
void
FractionalPartSubstitution::doSubstitution(double number, UnicodeString& toInsertInto, int32_t _pos) const
{
// if we're not in "byDigits" mode, just use the inherited
// doSubstitution() routine
if (!byDigits) {
NFSubstitution::doSubstitution(number, toInsertInto, _pos);
// if we're in "byDigits" mode, transform the value into an integer
// by moving the decimal point eight places to the right and
// pulling digits off the right one at a time, formatting each digit
// as an integer using this substitution's owning rule set
// (this is slower, but more accurate, than doing it from the
// other end)
} else {
// int32_t numberToFormat = (int32_t)uprv_round(transformNumber(number) * uprv_pow(10, kMaxDecimalDigits));
// // this flag keeps us from formatting trailing zeros. It starts
// // out false because we're pulling from the right, and switches
// // to true the first time we encounter a non-zero digit
// UBool doZeros = FALSE;
// for (int32_t i = 0; i < kMaxDecimalDigits; i++) {
// int64_t digit = numberToFormat % 10;
// if (digit != 0 || doZeros) {
// if (doZeros && useSpaces) {
// toInsertInto.insert(_pos + getPos(), gSpace);
// }
// doZeros = TRUE;
// getRuleSet()->format(digit, toInsertInto, _pos + getPos());
// }
// numberToFormat /= 10;
// }
DigitList dl;
dl.set(number, 20, TRUE);
UBool pad = FALSE;
while (dl.fCount > (dl.fDecimalAt <= 0 ? 0 : dl.fDecimalAt)) {
if (pad && useSpaces) {
toInsertInto.insert(_pos + getPos(), gSpace);
} else {
pad = TRUE;
}
getRuleSet()->format((int64_t)(dl.fDigits[--dl.fCount] - '0'), toInsertInto, _pos + getPos());
}
while (dl.fDecimalAt < 0) {
if (pad && useSpaces) {
toInsertInto.insert(_pos + getPos(), gSpace);
} else {
pad = TRUE;
}
getRuleSet()->format((int64_t)0, toInsertInto, _pos + getPos());
++dl.fDecimalAt;
}
if (!pad) {
// hack around lack of precision in digitlist. if we would end up with
// "foo point" make sure we add a " zero" to the end.
getRuleSet()->format((int64_t)0, toInsertInto, _pos + getPos());
}
}
}
示例5: isPerlOpen
static inline UBool
isPerlOpen(const UnicodeString &pattern, int32_t pos) {
UChar c;
return pattern.charAt(pos)==BACKSLASH && ((c=pattern.charAt(pos+1))==LOWER_P || c==UPPER_P);
}
示例6: isPOSIXOpen
static inline UBool
isPOSIXOpen(const UnicodeString &pattern, int32_t pos) {
return pattern.charAt(pos)==SET_OPEN && pattern.charAt(pos+1)==COLON;
}
示例7: printUnicodeString
void printUnicodeString(const UnicodeString &s) {
char charBuf[1000];
s.extract(0, s.length(), charBuf, sizeof(charBuf)-1, 0);
charBuf[sizeof(charBuf)-1] = 0;
printf("%s", charBuf);
}
示例8: _smartAppend
/**
* Append c to buf, unless buf is empty or buf already ends in c.
*/
static void _smartAppend(UnicodeString& buf, UChar c) {
if (buf.length() != 0 &&
buf.charAt(buf.length() - 1) != c) {
buf.append(c);
}
}
示例9: BOOST_FIXTURE_TEST_CASE
BOOST_FIXTURE_TEST_CASE(test11, base_fixture_t)
{
// Тесты на ::FmtLoadStr FMTLOAD ::Format ::LoadStr ::LoadStrPart ::CutToChar ::TrimLeft ::TrimRight
{
UnicodeString str = ::FmtLoadStr(CONST_TEST_STRING, L"lalala", 42);
// BOOST_TEST_MESSAGE("str = " << W2MB(str.c_str()));
// BOOST_TEST_MESSAGE("length = " << str.size());
BOOST_CHECK(W2MB(str.c_str()) == "test string: \"lalala\" 42");
}
{
UnicodeString str2 = FMTLOAD(CONST_TEST_STRING, L"lalala", 42);
// BOOST_TEST_MESSAGE("str2 = " << W2MB(str2.c_str()));
BOOST_CHECK(W2MB(str2.c_str()) == "test string: \"lalala\" 42");
}
{
UnicodeString str2 = ::Format(L"test: %s %d", L"lalala", 42);
BOOST_TEST_MESSAGE("str2 = " << W2MB(str2.c_str()));
BOOST_CHECK_EQUAL(0, wcscmp(str2.c_str(), L"test: lalala 42"));
}
{
UnicodeString str3 = FORMAT(L"test: %s %d", L"lalala", 42);
BOOST_TEST_MESSAGE("str3 = " << W2MB(str3.c_str()));
BOOST_CHECK_EQUAL(0, wcscmp(str3.c_str(), L"test: lalala 42"));
}
{
UnicodeString str = ::TrimLeft(L"");
BOOST_TEST_MESSAGE("str = " << W2MB(str.c_str()));
BOOST_CHECK_EQUAL(0, wcscmp(str.c_str(), L""));
}
{
UnicodeString str = ::TrimLeft(L"1");
BOOST_TEST_MESSAGE("str = " << W2MB(str.c_str()));
BOOST_CHECK_EQUAL(0, wcscmp(str.c_str(), L"1"));
}
{
UnicodeString str = ::TrimLeft(L" 1");
BOOST_TEST_MESSAGE("str = " << W2MB(str.c_str()));
BOOST_CHECK_EQUAL(0, wcscmp(str.c_str(), L"1"));
}
{
UnicodeString str = ::TrimRight(L"");
BOOST_TEST_MESSAGE("str = " << W2MB(str.c_str()));
BOOST_CHECK_EQUAL(0, wcscmp(str.c_str(), L""));
}
{
UnicodeString str = ::TrimRight(L"1");
BOOST_TEST_MESSAGE("str = " << W2MB(str.c_str()));
BOOST_CHECK_EQUAL(0, wcscmp(str.c_str(), L"1"));
}
{
UnicodeString str = ::TrimRight(L"1 ");
BOOST_TEST_MESSAGE("str = " << W2MB(str.c_str()));
BOOST_CHECK_EQUAL(0, wcscmp(str.c_str(), L"1"));
}
{
// UnicodeString CutToChar(UnicodeString &Str, char Ch, bool Trim)
UnicodeString Str1 = L" part 1 | part 2 ";
UnicodeString str1 = ::CutToChar(Str1, '|', false);
BOOST_TEST_MESSAGE("str1 = '" << W2MB(str1.c_str()) << "'");
BOOST_TEST_MESSAGE("Str1 = '" << W2MB(Str1.c_str()) << "'");
// BOOST_TEST_MESSAGE("Str1 = '" << W2MB(Str1.c_str()) << "'");
// DEBUG_PRINTF(L"str1 = \"%s\"", str1.c_str());
BOOST_CHECK_EQUAL(0, wcscmp(str1.c_str(), L" part 1 "));
UnicodeString str2 = ::CutToChar(Str1, '|', true);
BOOST_TEST_MESSAGE("str2 = '" << W2MB(str2.c_str()) << "'");
BOOST_TEST_MESSAGE("Str1 = '" << W2MB(Str1.c_str()) << "'");
BOOST_CHECK_EQUAL(0, wcscmp(str2.c_str(), L" part 2"));
}
{
UnicodeString str = ::LoadStr(CONST_TEST_STRING);
BOOST_TEST_MESSAGE("str = " << W2MB(str.c_str()));
BOOST_CHECK_EQUAL(0, wcscmp(str.c_str(), L"test string: \"%s\" %d"));
}
{
UnicodeString str = ::LoadStrPart(CONST_TEST_STRING2, 1);
BOOST_TEST_MESSAGE("str = " << W2MB(str.c_str()));
BOOST_CHECK_EQUAL(0, wcscmp(str.c_str(), L"test string part 1"));
}
{
UnicodeString str = ::LoadStrPart(CONST_TEST_STRING2, 2);
BOOST_TEST_MESSAGE("str = " << W2MB(str.c_str()));
BOOST_CHECK_EQUAL(0, wcscmp(str.c_str(), L"part 2"));
}
}
示例10: uhash_open
//.........这里部分代码省略.........
continue;
}
// Create canonical map entry for this alias
entry = (CanonicalMapEntry*)uprv_malloc(sizeof(CanonicalMapEntry));
if (entry == NULL) {
status = U_MEMORY_ALLOCATION_ERROR;
goto error_cleanup;
}
entry->id = canonical;
if (territory == NULL || u_strcmp(territory, gWorld) == 0) {
entry->country = NULL;
} else {
entry->country = territory;
}
// Put this entry in the hashtable. Since this hashtable has no key deleter,
// key is treated as const, but must be passed as non-const.
uhash_put(canonicalMap, (UChar*)alias, entry, &status);
if (U_FAILURE(status)) {
goto error_cleanup;
}
}
}
// Some available Olson zones are not included in CLDR data (such as Asia/Riyadh87).
// Also, when we update Olson tzdata, new zones may be added.
// This code scans all available zones in zoneinfo.res, and if any of them are
// missing, add them to the map.
tzenum = TimeZone::createEnumeration();
numZones = tzenum->count(status);
if (U_SUCCESS(status)) {
int32_t i;
for (i = 0; i < numZones; i++) {
const UnicodeString *zone = tzenum->snext(status);
if (U_FAILURE(status)) {
// We should not get here.
status = U_ZERO_ERROR;
continue;
}
UChar zoneUChars[ZID_KEY_MAX];
int32_t zoneUCharsLen = zone->extract(zoneUChars, ZID_KEY_MAX, status) + 1; // Add one for NUL termination
if (U_FAILURE(status) || status==U_STRING_NOT_TERMINATED_WARNING) {
status = U_ZERO_ERROR;
continue; // zone id is too long to extract
}
CanonicalMapEntry *entry = (CanonicalMapEntry*)uhash_get(canonicalMap, zoneUChars);
if (entry) {
// Already included in CLDR data
continue;
}
// Not in CLDR data, but it could be new one whose alias is available
// in CLDR.
int32_t nTzdataEquivalent = TimeZone::countEquivalentIDs(*zone);
int32_t j;
for (j = 0; j < nTzdataEquivalent; j++) {
UnicodeString alias = TimeZone::getEquivalentID(*zone, j);
if (alias == *zone) {
continue;
}
UChar aliasUChars[ZID_KEY_MAX];
alias.extract(aliasUChars, ZID_KEY_MAX, status);
if (U_FAILURE(status) || status==U_STRING_NOT_TERMINATED_WARNING) {
status = U_ZERO_ERROR;
continue; // zone id is too long to extract
}
entry = (CanonicalMapEntry*)uhash_get(canonicalMap, aliasUChars);
示例11: kPATTERN
void DataDrivenFormatTest::testConvertDate(TestData *testData,
const DataMap * /* settings */, UBool fmt) {
UnicodeString kPATTERN("PATTERN="); // TODO: static
UnicodeString kMILLIS("MILLIS="); // TODO: static
UnicodeString kRELATIVE_MILLIS("RELATIVE_MILLIS="); // TODO: static
UnicodeString kRELATIVE_ADD("RELATIVE_ADD:"); // TODO: static
UErrorCode status = U_ZERO_ERROR;
SimpleDateFormat basicFmt(UnicodeString("EEE MMM dd yyyy / YYYY'-W'ww-ee"),
status);
if (U_FAILURE(status)) {
dataerrln("FAIL: Couldn't create basic SimpleDateFormat: %s",
u_errorName(status));
return;
}
const DataMap *currentCase= NULL;
// Start the processing
int n = 0;
while (testData->nextCase(currentCase, status)) {
char calLoc[256] = "";
DateTimeStyleSet styleSet;
UnicodeString pattern;
UBool usePattern = FALSE;
(void)usePattern; // Suppress unused warning.
CalendarFieldsSet fromSet;
UDate fromDate = 0;
UBool useDate = FALSE;
UDate now = Calendar::getNow();
++n;
char theCase[200];
sprintf(theCase, "case %d:", n);
UnicodeString caseString(theCase, "");
// load params
UnicodeString locale = currentCase->getString("locale", status);
if (U_FAILURE(status)) {
errln("case %d: No 'locale' line.", n);
continue;
}
UnicodeString zone = currentCase->getString("zone", status);
if (U_FAILURE(status)) {
errln("case %d: No 'zone' line.", n);
continue;
}
UnicodeString spec = currentCase->getString("spec", status);
if(U_FAILURE(status)) {
errln("case %d: No 'spec' line.", n);
continue;
}
UnicodeString date = currentCase->getString("date", status);
if(U_FAILURE(status)) {
errln("case %d: No 'date' line.", n);
continue;
}
UnicodeString expectStr= currentCase->getString("str", status);
if(U_FAILURE(status)) {
errln("case %d: No 'str' line.", n);
continue;
}
DateFormat *format = NULL;
// Process: 'locale'
locale.extract(0, locale.length(), calLoc, (const char*)0); // default codepage. Invariant codepage doesn't have '@'!
Locale loc(calLoc);
if(spec.startsWith(kPATTERN)) {
pattern = UnicodeString(spec,kPATTERN.length());
usePattern = TRUE;
format = new SimpleDateFormat(pattern, loc, status);
if(U_FAILURE(status)) {
errln("case %d: could not create SimpleDateFormat from pattern: %s", n, u_errorName(status));
continue;
}
} else {
if(styleSet.parseFrom(spec, status)<0 || U_FAILURE(status)) {
errln("case %d: could not parse spec as style fields: %s", n, u_errorName(status));
continue;
}
format = DateFormat::createDateTimeInstance((DateFormat::EStyle)styleSet.getDateStyle(), (DateFormat::EStyle)styleSet.getTimeStyle(), loc);
if(format == NULL ) {
errln("case %d: could not create SimpleDateFormat from styles.", n);
continue;
}
}
Calendar *cal = Calendar::createInstance(loc, status);
if(U_FAILURE(status)) {
errln("case %d: could not create calendar from %s", n, calLoc);
}
if (zone.length() > 0) {
TimeZone * tz = TimeZone::createTimeZone(zone);
cal->setTimeZone(*tz);
format->setTimeZone(*tz);
delete tz;
}
//.........这里部分代码省略.........
示例12: assertFalse
void QuantityFormatterTest::TestBasic() {
UErrorCode status = U_ZERO_ERROR;
#if !UCONFIG_NO_FORMATTING
QuantityFormatter fmt;
assertFalse(
"adding bad variant",
fmt.addIfAbsent("a bad variant", "{0} pounds", status));
assertEquals("adding bad variant status", (int32_t)U_ILLEGAL_ARGUMENT_ERROR, status);
status = U_ZERO_ERROR;
assertFalse(
"Adding bad pattern",
fmt.addIfAbsent("other", "{0} {1} too many placeholders", status));
assertEquals("adding bad pattern status", (int32_t)U_ILLEGAL_ARGUMENT_ERROR, status);
status = U_ZERO_ERROR;
assertFalse("isValid with no patterns", fmt.isValid());
assertTrue(
"Adding good pattern with no placeholders",
fmt.addIfAbsent("zero", "no placeholder", status));
assertTrue(
"Adding good pattern",
fmt.addIfAbsent("other", "{0} pounds", status));
assertTrue("isValid with other", fmt.isValid());
assertTrue(
"Adding good pattern",
fmt.addIfAbsent("one", "{0} pound", status));
assertEquals(
"getByVariant",
fmt.getByVariant("bad variant")->getTextWithNoArguments(),
" pounds");
assertEquals(
"getByVariant",
fmt.getByVariant("other")->getTextWithNoArguments(),
" pounds");
assertEquals(
"getByVariant",
fmt.getByVariant("one")->getTextWithNoArguments(),
" pound");
assertEquals(
"getByVariant",
fmt.getByVariant("few")->getTextWithNoArguments(),
" pounds");
// Test copy constructor
{
QuantityFormatter copied(fmt);
assertEquals(
"copied getByVariant",
copied.getByVariant("other")->getTextWithNoArguments(),
" pounds");
assertEquals(
"copied getByVariant",
copied.getByVariant("one")->getTextWithNoArguments(),
" pound");
assertEquals(
"copied getByVariant",
copied.getByVariant("few")->getTextWithNoArguments(),
" pounds");
}
// Test assignment
{
QuantityFormatter assigned;
assigned = fmt;
assertEquals(
"assigned getByVariant",
assigned.getByVariant("other")->getTextWithNoArguments(),
" pounds");
assertEquals(
"assigned getByVariant",
assigned.getByVariant("one")->getTextWithNoArguments(),
" pound");
assertEquals(
"assigned getByVariant",
assigned.getByVariant("few")->getTextWithNoArguments(),
" pounds");
}
// Test format.
{
LocalPointer<NumberFormat> numfmt(
NumberFormat::createInstance(Locale::getEnglish(), status));
LocalPointer<PluralRules> plurrule(
PluralRules::forLocale("en", status));
FieldPosition pos(FieldPosition::DONT_CARE);
UnicodeString appendTo;
assertEquals(
"format singular",
UnicodeString("1 pound"),
fmt.format(
1.0,
*numfmt,
*plurrule,
appendTo,
pos,
status), TRUE);
appendTo.remove();
assertEquals(
"format plural",
UnicodeString("2 pounds"),
//.........这里部分代码省略.........
示例13: main
int main(int argc, const char *argv[]) {
UErrorCode errorCode = U_ZERO_ERROR;
// Get the unsafeBackwardsSet
const CollationCacheEntry *rootEntry = CollationRoot::getRootCacheEntry(errorCode);
if(U_FAILURE(errorCode)) {
fprintf(stderr, "Err: %s getting root cache entry\n", u_errorName(errorCode));
return 1;
}
const UVersionInfo &version = rootEntry->tailoring->version;
const UnicodeSet *unsafeBackwardSet = rootEntry->tailoring->unsafeBackwardSet;
char verString[20];
u_versionToString(version, verString);
fprintf(stderr, "Generating data for ICU %s, Collation %s\n", U_ICU_VERSION, verString);
int32_t rangeCount = unsafeBackwardSet->getRangeCount();
#if SERIALIZE
fprintf(stderr, ".. serializing\n");
// UnicodeSet serialization
UErrorCode preflightCode = U_ZERO_ERROR;
// preflight
int32_t serializedCount = unsafeBackwardSet->serialize(NULL,0,preflightCode);
if(U_FAILURE(preflightCode) && preflightCode != U_BUFFER_OVERFLOW_ERROR) {
fprintf(stderr, "Err: %s preflighting unicode set\n", u_errorName(preflightCode));
return 1;
}
uint16_t *serializedData = new uint16_t[serializedCount];
// serialize
unsafeBackwardSet->serialize(serializedData, serializedCount, errorCode);
if(U_FAILURE(errorCode)) {
delete [] serializedData;
fprintf(stderr, "Err: %s serializing unicodeset\n", u_errorName(errorCode));
return 1;
}
#endif
#if PATTERN
fprintf(stderr,".. pattern. (Note: collationdatareader.cpp does not support this form also see #11891)\n");
// attempt to use pattern
UnicodeString pattern;
UnicodeSet set(*unsafeBackwardSet);
set.compact();
set.toPattern(pattern, FALSE);
if(U_SUCCESS(errorCode)) {
// This fails (bug# ?) - which is why this method was abandoned.
// UnicodeSet usA(pattern, errorCode);
// fprintf(stderr, "\n%s:%d: err creating set A %s\n", __FILE__, __LINE__, u_errorName(errorCode));
// return 1;
}
const UChar *buf = pattern.getBuffer();
int32_t needed = pattern.length();
// print
{
char buf2[2048];
int32_t len2 = pattern.extract(0, pattern.length(), buf2, "utf-8");
buf2[len2]=0;
fprintf(stderr,"===\n%s\n===\n", buf2);
}
const UnicodeString unsafeBackwardPattern(FALSE, buf, needed);
if(U_SUCCESS(errorCode)) {
//UnicodeSet us(unsafeBackwardPattern, errorCode);
// fprintf(stderr, "\n%s:%d: err creating set %s\n", __FILE__, __LINE__, u_errorName(errorCode));
} else {
fprintf(stderr, "Uset OK - \n");
}
#endif
// Generate the output file.
printf("// collunsafe.h\n");
printf("// %s\n", U_COPYRIGHT_STRING);
printf("\n");
printf("// To be included by collationdatareader.cpp, and generated by gencolusb.\n");
printf("// Machine generated, do not edit.\n");
printf("\n");
printf("#ifndef COLLUNSAFE_H\n"
"#define COLLUNSAFE_H\n"
"\n"
"#include \"unicode/utypes.h\"\n"
"\n"
"#define COLLUNSAFE_ICU_VERSION \"" U_ICU_VERSION "\"\n");
printf("#define COLLUNSAFE_COLL_VERSION \"%s\"\n", verString);
#if PATTERN
printf("#define COLLUNSAFE_PATTERN 1\n");
printf("static const int32_t collunsafe_len = %d;\n", needed);
printf("static const UChar collunsafe_pattern[collunsafe_len] = {\n");
for(int i=0;i<needed;i++) {
if( (i>0) && (i%8 == 0) ) {
//.........这里部分代码省略.........
示例14: slog2f
std::string GlobalizationNDK::numberToString(const std::string& args)
{
if (args.empty()) {
slog2f(0, ID_G11N, SLOG2_ERROR, "GlobalizationNDK::numberToString: no arguments provided!");
return errorInJson(UNKNOWN_ERROR, "No arguments provided!");
}
Json::Reader reader;
Json::Value root;
bool parse = reader.parse(args, root);
if (!parse) {
slog2f(0, ID_G11N, SLOG2_ERROR, "GlobalizationNDK::numberToString: invalid json data: %s",
args.c_str());
return errorInJson(PARSING_ERROR, "Invalid json data!");
}
Json::Value nv = root["number"];
if (nv.isNull()) {
slog2f(0, ID_G11N, SLOG2_ERROR, "GlobalizationNDK::numberToString: no number provided!");
return errorInJson(FORMATTING_ERROR, "No number provided!");
}
if (!nv.isNumeric()) {
slog2f(0, ID_G11N, SLOG2_ERROR, "GlobalizationNDK::numberToString: invalid number type: %d!",
nv.type());
return errorInJson(FORMATTING_ERROR, "Invalid number type!");
}
// This is the default value when no options provided.
ENumberType type = kNumberDecimal;
Json::Value options = root["options"];
std::string error;
if (!handleNumberOptions(options, type, error))
return errorInJson(PARSING_ERROR, error);
UErrorCode status = U_ZERO_ERROR;
NumberFormat* nf;
switch (type) {
case kNumberDecimal:
default:
nf = NumberFormat::createInstance(status);
break;
case kNumberCurrency:
nf = NumberFormat::createCurrencyInstance(status);
break;
case kNumberPercent:
nf = NumberFormat::createPercentInstance(status);
break;
}
if (!nf) {
slog2f(0, ID_G11N, SLOG2_ERROR, "GlobalizationNDK::numberToString: failed to create NumberFormat instance for type %d: %d",
status, type);
return errorInJson(UNKNOWN_ERROR, "Failed to create NumberFormat instance!");
}
std::auto_ptr<NumberFormat> deleter(nf);
UnicodeString result;
nf->format(nv.asDouble(), result);
std::string utf8;
result.toUTF8String(utf8);
return resultInJson(utf8);
}
示例15: U_ASSERT
//------------------------------------------------------------------------------
//
// findSetFor given a UnicodeString,
// - find the corresponding Unicode Set (uset node)
// (create one if necessary)
// - Set fLeftChild of the caller's node (should be a setRef node)
// to the uset node
// Maintain a hash table of uset nodes, so the same one is always used
// for the same string.
// If a "to adopt" set is provided and we haven't seen this key before,
// add the provided set to the hash table.
// If the string is one (32 bit) char in length, the set contains
// just one element which is the char in question.
// If the string is "any", return a set containing all chars.
//
//------------------------------------------------------------------------------
void RBBIRuleScanner::findSetFor(const UnicodeString &s, RBBINode *node, UnicodeSet *setToAdopt) {
RBBISetTableEl *el;
// First check whether we've already cached a set for this string.
// If so, just use the cached set in the new node.
// delete any set provided by the caller, since we own it.
el = (RBBISetTableEl *)uhash_get(fSetTable, &s);
if (el != NULL) {
delete setToAdopt;
node->fLeftChild = el->val;
U_ASSERT(node->fLeftChild->fType == RBBINode::uset);
return;
}
// Haven't seen this set before.
// If the caller didn't provide us with a prebuilt set,
// create a new UnicodeSet now.
if (setToAdopt == NULL) {
if (s.compare(kAny, -1) == 0) {
setToAdopt = new UnicodeSet(0x000000, 0x10ffff);
} else {
UChar32 c;
c = s.char32At(0);
setToAdopt = new UnicodeSet(c, c);
}
}
//
// Make a new uset node to refer to this UnicodeSet
// This new uset node becomes the child of the caller's setReference node.
//
RBBINode *usetNode = new RBBINode(RBBINode::uset);
if (usetNode == NULL) {
error(U_MEMORY_ALLOCATION_ERROR);
return;
}
usetNode->fInputSet = setToAdopt;
usetNode->fParent = node;
node->fLeftChild = usetNode;
usetNode->fText = s;
//
// Add the new uset node to the list of all uset nodes.
//
fRB->fUSetNodes->addElement(usetNode, *fRB->fStatus);
//
// Add the new set to the set hash table.
//
el = (RBBISetTableEl *)uprv_malloc(sizeof(RBBISetTableEl));
UnicodeString *tkey = new UnicodeString(s);
if (tkey == NULL || el == NULL || setToAdopt == NULL) {
// Delete to avoid memory leak
delete tkey;
tkey = NULL;
uprv_free(el);
el = NULL;
delete setToAdopt;
setToAdopt = NULL;
error(U_MEMORY_ALLOCATION_ERROR);
return;
}
el->key = tkey;
el->val = usetNode;
uhash_put(fSetTable, el->key, el, fRB->fStatus);
return;
}