2 ******************************************************************************
3 * Copyright (C) 1997-2014, International Business Machines
4 * Corporation and others. All Rights Reserved.
5 ******************************************************************************
6 * file name: nfrule.cpp
8 * tab size: 8 (not used)
11 * Modification history
13 * 10/11/2001 Doug Ported from ICU4J
20 #include "unicode/localpointer.h"
21 #include "unicode/rbnf.h"
22 #include "unicode/tblcoll.h"
23 #include "unicode/plurfmt.h"
24 #include "unicode/upluralrules.h"
25 #include "unicode/coleitr.h"
26 #include "unicode/uchar.h"
30 #include "patternprops.h"
34 NFRule::NFRule(const RuleBasedNumberFormat
* _rbnf
)
35 : baseValue((int32_t)0)
42 , rulePatternFormat(NULL
)
52 delete rulePatternFormat
;
55 static const UChar gLeftBracket
= 0x005b;
56 static const UChar gRightBracket
= 0x005d;
57 static const UChar gColon
= 0x003a;
58 static const UChar gZero
= 0x0030;
59 static const UChar gNine
= 0x0039;
60 static const UChar gSpace
= 0x0020;
61 static const UChar gSlash
= 0x002f;
62 static const UChar gGreaterThan
= 0x003e;
63 static const UChar gLessThan
= 0x003c;
64 static const UChar gComma
= 0x002c;
65 static const UChar gDot
= 0x002e;
66 static const UChar gTick
= 0x0027;
67 //static const UChar gMinus = 0x002d;
68 static const UChar gSemicolon
= 0x003b;
70 static const UChar gMinusX
[] = {0x2D, 0x78, 0}; /* "-x" */
71 static const UChar gXDotX
[] = {0x78, 0x2E, 0x78, 0}; /* "x.x" */
72 static const UChar gXDotZero
[] = {0x78, 0x2E, 0x30, 0}; /* "x.0" */
73 static const UChar gZeroDotX
[] = {0x30, 0x2E, 0x78, 0}; /* "0.x" */
75 static const UChar gDollarOpenParenthesis
[] = {0x24, 0x28, 0}; /* "$(" */
76 static const UChar gClosedParenthesisDollar
[] = {0x29, 0x24, 0}; /* ")$" */
78 static const UChar gLessLess
[] = {0x3C, 0x3C, 0}; /* "<<" */
79 static const UChar gLessPercent
[] = {0x3C, 0x25, 0}; /* "<%" */
80 static const UChar gLessHash
[] = {0x3C, 0x23, 0}; /* "<#" */
81 static const UChar gLessZero
[] = {0x3C, 0x30, 0}; /* "<0" */
82 static const UChar gGreaterGreater
[] = {0x3E, 0x3E, 0}; /* ">>" */
83 static const UChar gGreaterPercent
[] = {0x3E, 0x25, 0}; /* ">%" */
84 static const UChar gGreaterHash
[] = {0x3E, 0x23, 0}; /* ">#" */
85 static const UChar gGreaterZero
[] = {0x3E, 0x30, 0}; /* ">0" */
86 static const UChar gEqualPercent
[] = {0x3D, 0x25, 0}; /* "=%" */
87 static const UChar gEqualHash
[] = {0x3D, 0x23, 0}; /* "=#" */
88 static const UChar gEqualZero
[] = {0x3D, 0x30, 0}; /* "=0" */
89 static const UChar gGreaterGreaterGreater
[] = {0x3E, 0x3E, 0x3E, 0}; /* ">>>" */
91 static const UChar
* const tokenStrings
[] = {
92 gLessLess
, gLessPercent
, gLessHash
, gLessZero
,
93 gGreaterGreater
, gGreaterPercent
,gGreaterHash
, gGreaterZero
,
94 gEqualPercent
, gEqualHash
, gEqualZero
, NULL
98 NFRule::makeRules(UnicodeString
& description
,
99 const NFRuleSet
*ruleSet
,
100 const NFRule
*predecessor
,
101 const RuleBasedNumberFormat
*rbnf
,
105 // we know we're making at least one rule, so go ahead and
106 // new it up and initialize its basevalue and divisor
107 // (this also strips the rule descriptor, if any, off the
108 // descripton string)
109 NFRule
* rule1
= new NFRule(rbnf
);
112 status
= U_MEMORY_ALLOCATION_ERROR
;
115 rule1
->parseRuleDescriptor(description
, status
);
117 // check the description to see whether there's text enclosed
119 int32_t brack1
= description
.indexOf(gLeftBracket
);
120 int32_t brack2
= description
.indexOf(gRightBracket
);
122 // if the description doesn't contain a matched pair of brackets,
123 // or if it's of a type that doesn't recognize bracketed text,
124 // then leave the description alone, initialize the rule's
125 // rule text and substitutions, and return that rule
126 if (brack1
== -1 || brack2
== -1 || brack1
> brack2
127 || rule1
->getType() == kProperFractionRule
128 || rule1
->getType() == kNegativeNumberRule
) {
129 rule1
->extractSubstitutions(ruleSet
, description
, predecessor
, status
);
132 // if the description does contain a matched pair of brackets,
133 // then it's really shorthand for two rules (with one exception)
134 NFRule
* rule2
= NULL
;
137 // we'll actually only split the rule into two rules if its
138 // base value is an even multiple of its divisor (or it's one
139 // of the special rules)
140 if ((rule1
->baseValue
> 0
141 && (rule1
->baseValue
% util64_pow(rule1
->radix
, rule1
->exponent
)) == 0)
142 || rule1
->getType() == kImproperFractionRule
143 || rule1
->getType() == kMasterRule
) {
145 // if it passes that test, new up the second rule. If the
146 // rule set both rules will belong to is a fraction rule
147 // set, they both have the same base value; otherwise,
148 // increment the original rule's base value ("rule1" actually
149 // goes SECOND in the rule set's rule list)
150 rule2
= new NFRule(rbnf
);
153 status
= U_MEMORY_ALLOCATION_ERROR
;
156 if (rule1
->baseValue
>= 0) {
157 rule2
->baseValue
= rule1
->baseValue
;
158 if (!ruleSet
->isFractionRuleSet()) {
163 // if the description began with "x.x" and contains bracketed
164 // text, it describes both the improper fraction rule and
165 // the proper fraction rule
166 else if (rule1
->getType() == kImproperFractionRule
) {
167 rule2
->setType(kProperFractionRule
);
170 // if the description began with "x.0" and contains bracketed
171 // text, it describes both the master rule and the
172 // improper fraction rule
173 else if (rule1
->getType() == kMasterRule
) {
174 rule2
->baseValue
= rule1
->baseValue
;
175 rule1
->setType(kImproperFractionRule
);
178 // both rules have the same radix and exponent (i.e., the
180 rule2
->radix
= rule1
->radix
;
181 rule2
->exponent
= rule1
->exponent
;
183 // rule2's rule text omits the stuff in brackets: initalize
184 // its rule text and substitutions accordingly
185 sbuf
.append(description
, 0, brack1
);
186 if (brack2
+ 1 < description
.length()) {
187 sbuf
.append(description
, brack2
+ 1, description
.length() - brack2
- 1);
189 rule2
->extractSubstitutions(ruleSet
, sbuf
, predecessor
, status
);
192 // rule1's text includes the text in the brackets but omits
193 // the brackets themselves: initialize _its_ rule text and
194 // substitutions accordingly
195 sbuf
.setTo(description
, 0, brack1
);
196 sbuf
.append(description
, brack1
+ 1, brack2
- brack1
- 1);
197 if (brack2
+ 1 < description
.length()) {
198 sbuf
.append(description
, brack2
+ 1, description
.length() - brack2
- 1);
200 rule1
->extractSubstitutions(ruleSet
, sbuf
, predecessor
, status
);
202 // if we only have one rule, return it; if we have two, return
203 // a two-element array containing them (notice that rule2 goes
204 // BEFORE rule1 in the list: in all cases, rule2 OMITS the
205 // material in the brackets and rule1 INCLUDES the material
215 * This function parses the rule's rule descriptor (i.e., the base
216 * value and/or other tokens that precede the rule's rule text
217 * in the description) and sets the rule's base value, radix, and
218 * exponent according to the descriptor. (If the description doesn't
219 * include a rule descriptor, then this function sets everything to
220 * default values and the rule set sets the rule's real base value).
221 * @param description The rule's description
222 * @return If "description" included a rule descriptor, this is
223 * "description" with the descriptor and any trailing whitespace
224 * stripped off. Otherwise; it's "descriptor" unchangd.
227 NFRule::parseRuleDescriptor(UnicodeString
& description
, UErrorCode
& status
)
229 // the description consists of a rule descriptor and a rule body,
230 // separated by a colon. The rule descriptor is optional. If
231 // it's omitted, just set the base value to 0.
232 int32_t p
= description
.indexOf(gColon
);
234 setBaseValue((int32_t)0, status
);
236 // copy the descriptor out into its own string and strip it,
237 // along with any trailing whitespace, out of the original
239 UnicodeString descriptor
;
240 descriptor
.setTo(description
, 0, p
);
243 while (p
< description
.length() && PatternProps::isWhiteSpace(description
.charAt(p
))) {
246 description
.removeBetween(0, p
);
248 // check first to see if the rule descriptor matches the token
249 // for one of the special rules. If it does, set the base
250 // value to the correct identfier value
251 if (0 == descriptor
.compare(gMinusX
, 2)) {
252 setType(kNegativeNumberRule
);
254 else if (0 == descriptor
.compare(gXDotX
, 3)) {
255 setType(kImproperFractionRule
);
257 else if (0 == descriptor
.compare(gZeroDotX
, 3)) {
258 setType(kProperFractionRule
);
260 else if (0 == descriptor
.compare(gXDotZero
, 3)) {
261 setType(kMasterRule
);
264 // if the rule descriptor begins with a digit, it's a descriptor
266 // since we don't have Long.parseLong, and this isn't much work anyway,
267 // just build up the value as we encounter the digits.
268 else if (descriptor
.charAt(0) >= gZero
&& descriptor
.charAt(0) <= gNine
) {
273 // begin parsing the descriptor: copy digits
274 // into "tempValue", skip periods, commas, and spaces,
275 // stop on a slash or > sign (or at the end of the string),
276 // and throw an exception on any other character
278 while (p
< descriptor
.length()) {
279 c
= descriptor
.charAt(p
);
280 if (c
>= gZero
&& c
<= gNine
) {
281 val
= val
* ll_10
+ (int32_t)(c
- gZero
);
283 else if (c
== gSlash
|| c
== gGreaterThan
) {
286 else if (PatternProps::isWhiteSpace(c
) || c
== gComma
|| c
== gDot
) {
289 // throw new IllegalArgumentException("Illegal character in rule descriptor");
290 status
= U_PARSE_ERROR
;
296 // we have the base value, so set it
297 setBaseValue(val
, status
);
299 // if we stopped the previous loop on a slash, we're
300 // now parsing the rule's radix. Again, accumulate digits
301 // in tempValue, skip punctuation, stop on a > mark, and
302 // throw an exception on anything else
307 while (p
< descriptor
.length()) {
308 c
= descriptor
.charAt(p
);
309 if (c
>= gZero
&& c
<= gNine
) {
310 val
= val
* ll_10
+ (int32_t)(c
- gZero
);
312 else if (c
== gGreaterThan
) {
315 else if (PatternProps::isWhiteSpace(c
) || c
== gComma
|| c
== gDot
) {
318 // throw new IllegalArgumentException("Illegal character is rule descriptor");
319 status
= U_PARSE_ERROR
;
325 // tempValue now contain's the rule's radix. Set it
326 // accordingly, and recalculate the rule's exponent
327 radix
= (int32_t)val
;
329 // throw new IllegalArgumentException("Rule can't have radix of 0");
330 status
= U_PARSE_ERROR
;
333 exponent
= expectedExponent();
336 // if we stopped the previous loop on a > sign, then continue
337 // for as long as we still see > signs. For each one,
338 // decrement the exponent (unless the exponent is already 0).
339 // If we see another character before reaching the end of
340 // the descriptor, that's also a syntax error.
341 if (c
== gGreaterThan
) {
342 while (p
< descriptor
.length()) {
343 c
= descriptor
.charAt(p
);
344 if (c
== gGreaterThan
&& exponent
> 0) {
347 // throw new IllegalArgumentException("Illegal character in rule descriptor");
348 status
= U_PARSE_ERROR
;
357 // finally, if the rule body begins with an apostrophe, strip it off
358 // (this is generally used to put whitespace at the beginning of
359 // a rule's rule text)
360 if (description
.length() > 0 && description
.charAt(0) == gTick
) {
361 description
.removeBetween(0, 1);
364 // return the description with all the stuff we've just waded through
365 // stripped off the front. It now contains just the rule body.
366 // return description;
370 * Searches the rule's rule text for the substitution tokens,
371 * creates the substitutions, and removes the substitution tokens
372 * from the rule's rule text.
373 * @param owner The rule set containing this rule
374 * @param predecessor The rule preseding this one in "owners" rule list
375 * @param ownersOwner The RuleBasedFormat that owns this rule
378 NFRule::extractSubstitutions(const NFRuleSet
* ruleSet
,
379 const UnicodeString
&ruleText
,
380 const NFRule
* predecessor
,
383 if (U_FAILURE(status
)) {
386 this->ruleText
= ruleText
;
387 this->rulePatternFormat
= NULL
;
388 sub1
= extractSubstitution(ruleSet
, predecessor
, status
);
389 if (sub1
== NULL
|| sub1
->isNullSubstitution()) {
390 // Small optimization. There is no need to create a redundant NullSubstitution.
394 sub2
= extractSubstitution(ruleSet
, predecessor
, status
);
396 int32_t pluralRuleStart
= this->ruleText
.indexOf(gDollarOpenParenthesis
, -1, 0);
397 int32_t pluralRuleEnd
= (pluralRuleStart
>= 0 ? this->ruleText
.indexOf(gClosedParenthesisDollar
, -1, pluralRuleStart
) : -1);
398 if (pluralRuleEnd
>= 0) {
399 int32_t endType
= this->ruleText
.indexOf(gComma
, pluralRuleStart
);
401 status
= U_PARSE_ERROR
;
404 UnicodeString
type(this->ruleText
.tempSubString(pluralRuleStart
+ 2, endType
- pluralRuleStart
- 2));
405 UPluralType pluralType
;
406 if (type
.startsWith(UNICODE_STRING_SIMPLE("cardinal"))) {
407 pluralType
= UPLURAL_TYPE_CARDINAL
;
409 else if (type
.startsWith(UNICODE_STRING_SIMPLE("ordinal"))) {
410 pluralType
= UPLURAL_TYPE_ORDINAL
;
413 status
= U_ILLEGAL_ARGUMENT_ERROR
;
416 rulePatternFormat
= formatter
->createPluralFormat(pluralType
,
417 this->ruleText
.tempSubString(endType
+ 1, pluralRuleEnd
- endType
- 1), status
);
422 * Searches the rule's rule text for the first substitution token,
423 * creates a substitution based on it, and removes the token from
424 * the rule's rule text.
425 * @param owner The rule set containing this rule
426 * @param predecessor The rule preceding this one in the rule set's
428 * @param ownersOwner The RuleBasedNumberFormat that owns this rule
429 * @return The newly-created substitution. This is never null; if
430 * the rule text doesn't contain any substitution tokens, this will
431 * be a NullSubstitution.
434 NFRule::extractSubstitution(const NFRuleSet
* ruleSet
,
435 const NFRule
* predecessor
,
438 NFSubstitution
* result
= NULL
;
440 // search the rule's rule text for the first two characters of
441 // a substitution token
442 int32_t subStart
= indexOfAny(tokenStrings
);
443 int32_t subEnd
= subStart
;
445 // if we didn't find one, create a null substitution positioned
446 // at the end of the rule text
447 if (subStart
== -1) {
448 return NFSubstitution::makeSubstitution(ruleText
.length(), this, predecessor
,
449 ruleSet
, this->formatter
, UnicodeString(), status
);
452 // special-case the ">>>" token, since searching for the > at the
453 // end will actually find the > in the middle
454 if (ruleText
.indexOf(gGreaterGreaterGreater
, 3, 0) == subStart
) {
455 subEnd
= subStart
+ 2;
457 // otherwise the substitution token ends with the same character
460 UChar c
= ruleText
.charAt(subStart
);
461 subEnd
= ruleText
.indexOf(c
, subStart
+ 1);
462 // special case for '<%foo<<'
463 if (c
== gLessThan
&& subEnd
!= -1 && subEnd
< ruleText
.length() - 1 && ruleText
.charAt(subEnd
+1) == c
) {
464 // ordinals use "=#,##0==%abbrev=" as their rule. Notice that the '==' in the middle
465 // occurs because of the juxtaposition of two different rules. The check for '<' is a hack
466 // to get around this. Having the duplicate at the front would cause problems with
467 // rules like "<<%" to format, say, percents...
472 // if we don't find the end of the token (i.e., if we're on a single,
473 // unmatched token character), create a null substitution positioned
474 // at the end of the rule
476 return NFSubstitution::makeSubstitution(ruleText
.length(), this, predecessor
,
477 ruleSet
, this->formatter
, UnicodeString(), status
);
480 // if we get here, we have a real substitution token (or at least
481 // some text bounded by substitution token characters). Use
482 // makeSubstitution() to create the right kind of substitution
483 UnicodeString subToken
;
484 subToken
.setTo(ruleText
, subStart
, subEnd
+ 1 - subStart
);
485 result
= NFSubstitution::makeSubstitution(subStart
, this, predecessor
, ruleSet
,
486 this->formatter
, subToken
, status
);
488 // remove the substitution from the rule text
489 ruleText
.removeBetween(subStart
, subEnd
+1);
495 * Sets the rule's base value, and causes the radix and exponent
496 * to be recalculated. This is used during construction when we
497 * don't know the rule's base value until after it's been
498 * constructed. It should be used at any other time.
499 * @param The new base value for the rule.
502 NFRule::setBaseValue(int64_t newBaseValue
, UErrorCode
& status
)
504 // set the base value
505 baseValue
= newBaseValue
;
507 // if this isn't a special rule, recalculate the radix and exponent
508 // (the radix always defaults to 10; if it's supposed to be something
509 // else, it's cleaned up by the caller and the exponent is
510 // recalculated again-- the only function that does this is
511 // NFRule.parseRuleDescriptor() )
512 if (baseValue
>= 1) {
514 exponent
= expectedExponent();
516 // this function gets called on a fully-constructed rule whose
517 // description didn't specify a base value. This means it
518 // has substitutions, and some substitutions hold on to copies
519 // of the rule's divisor. Fix their copies of the divisor.
521 sub1
->setDivisor(radix
, exponent
, status
);
524 sub2
->setDivisor(radix
, exponent
, status
);
527 // if this is a special rule, its radix and exponent are basically
528 // ignored. Set them to "safe" default values
536 * This calculates the rule's exponent based on its radix and base
537 * value. This will be the highest power the radix can be raised to
538 * and still produce a result less than or equal to the base value.
541 NFRule::expectedExponent() const
543 // since the log of 0, or the log base 0 of something, causes an
544 // error, declare the exponent in these cases to be 0 (we also
545 // deal with the special-rule identifiers here)
546 if (radix
== 0 || baseValue
< 1) {
550 // we get rounding error in some cases-- for example, log 1000 / log 10
551 // gives us 1.9999999996 instead of 2. The extra logic here is to take
553 int16_t tempResult
= (int16_t)(uprv_log((double)baseValue
) / uprv_log((double)radix
));
554 int64_t temp
= util64_pow(radix
, tempResult
+ 1);
555 if (temp
<= baseValue
) {
562 * Searches the rule's rule text for any of the specified strings.
563 * @param strings An array of strings to search the rule's rule
565 * @return The index of the first match in the rule's rule text
566 * (i.e., the first substring in the rule's rule text that matches
567 * _any_ of the strings in "strings"). If none of the strings in
568 * "strings" is found in the rule's rule text, returns -1.
571 NFRule::indexOfAny(const UChar
* const strings
[]) const
574 for (int i
= 0; strings
[i
]; i
++) {
575 int32_t pos
= ruleText
.indexOf(*strings
[i
]);
576 if (pos
!= -1 && (result
== -1 || pos
< result
)) {
583 //-----------------------------------------------------------------------
585 //-----------------------------------------------------------------------
588 * Tests two rules for equality.
589 * @param that The rule to compare this one against
590 * @return True is the two rules are functionally equivalent
593 NFRule::operator==(const NFRule
& rhs
) const
595 return baseValue
== rhs
.baseValue
596 && radix
== rhs
.radix
597 && exponent
== rhs
.exponent
598 && ruleText
== rhs
.ruleText
599 && *sub1
== *rhs
.sub1
600 && *sub2
== *rhs
.sub2
;
604 * Returns a textual representation of the rule. This won't
605 * necessarily be the same as the description that this rule
606 * was created with, but it will produce the same result.
607 * @return A textual description of the rule
609 static void util_append64(UnicodeString
& result
, int64_t n
)
612 int32_t len
= util64_tou(n
, buffer
, sizeof(buffer
));
613 UnicodeString
temp(buffer
, len
);
618 NFRule::_appendRuleText(UnicodeString
& result
) const
621 case kNegativeNumberRule
: result
.append(gMinusX
, 2); break;
622 case kImproperFractionRule
: result
.append(gXDotX
, 3); break;
623 case kProperFractionRule
: result
.append(gZeroDotX
, 3); break;
624 case kMasterRule
: result
.append(gXDotZero
, 3); break;
626 // for a normal rule, write out its base value, and if the radix is
627 // something other than 10, write out the radix (with the preceding
628 // slash, of course). Then calculate the expected exponent and if
629 // if isn't the same as the actual exponent, write an appropriate
630 // number of > signs. Finally, terminate the whole thing with
632 util_append64(result
, baseValue
);
634 result
.append(gSlash
);
635 util_append64(result
, radix
);
637 int numCarets
= expectedExponent() - exponent
;
638 for (int i
= 0; i
< numCarets
; i
++) {
639 result
.append(gGreaterThan
);
643 result
.append(gColon
);
644 result
.append(gSpace
);
646 // if the rule text begins with a space, write an apostrophe
647 // (whitespace after the rule descriptor is ignored; the
648 // apostrophe is used to make the whitespace significant)
649 if (ruleText
.charAt(0) == gSpace
&& sub1
->getPos() != 0) {
650 result
.append(gTick
);
653 // now, write the rule's rule text, inserting appropriate
654 // substitution tokens in the appropriate places
655 UnicodeString ruleTextCopy
;
656 ruleTextCopy
.setTo(ruleText
);
659 sub2
->toString(temp
);
660 ruleTextCopy
.insert(sub2
->getPos(), temp
);
661 sub1
->toString(temp
);
662 ruleTextCopy
.insert(sub1
->getPos(), temp
);
664 result
.append(ruleTextCopy
);
666 // and finally, top the whole thing off with a semicolon and
668 result
.append(gSemicolon
);
671 //-----------------------------------------------------------------------
673 //-----------------------------------------------------------------------
676 * Formats the number, and inserts the resulting text into
678 * @param number The number being formatted
679 * @param toInsertInto The string where the resultant text should
681 * @param pos The position in toInsertInto where the resultant text
685 NFRule::doFormat(int64_t number
, UnicodeString
& toInsertInto
, int32_t pos
, UErrorCode
& status
) const
687 // first, insert the rule's rule text into toInsertInto at the
688 // specified position, then insert the results of the substitutions
689 // into the right places in toInsertInto (notice we do the
690 // substitutions in reverse order so that the offsets don't get
692 int32_t pluralRuleStart
= ruleText
.length();
693 int32_t lengthOffset
= 0;
694 if (!rulePatternFormat
) {
695 toInsertInto
.insert(pos
, ruleText
);
698 pluralRuleStart
= ruleText
.indexOf(gDollarOpenParenthesis
, -1, 0);
699 int pluralRuleEnd
= ruleText
.indexOf(gClosedParenthesisDollar
, -1, pluralRuleStart
);
700 int initialLength
= toInsertInto
.length();
701 if (pluralRuleEnd
< ruleText
.length() - 1) {
702 toInsertInto
.insert(pos
, ruleText
.tempSubString(pluralRuleEnd
+ 2));
704 toInsertInto
.insert(pos
,
705 rulePatternFormat
->format((int32_t)(number
/uprv_pow(radix
, exponent
)), status
));
706 if (pluralRuleStart
> 0) {
707 toInsertInto
.insert(pos
, ruleText
.tempSubString(0, pluralRuleStart
));
709 lengthOffset
= ruleText
.length() - (toInsertInto
.length() - initialLength
);
712 if (!sub2
->isNullSubstitution()) {
713 sub2
->doSubstitution(number
, toInsertInto
, pos
- (sub2
->getPos() > pluralRuleStart
? lengthOffset
: 0), status
);
715 if (!sub1
->isNullSubstitution()) {
716 sub1
->doSubstitution(number
, toInsertInto
, pos
- (sub1
->getPos() > pluralRuleStart
? lengthOffset
: 0), status
);
721 * Formats the number, and inserts the resulting text into
723 * @param number The number being formatted
724 * @param toInsertInto The string where the resultant text should
726 * @param pos The position in toInsertInto where the resultant text
730 NFRule::doFormat(double number
, UnicodeString
& toInsertInto
, int32_t pos
, UErrorCode
& status
) const
732 // first, insert the rule's rule text into toInsertInto at the
733 // specified position, then insert the results of the substitutions
734 // into the right places in toInsertInto
735 // [again, we have two copies of this routine that do the same thing
736 // so that we don't sacrifice precision in a long by casting it
738 int32_t pluralRuleStart
= ruleText
.length();
739 int32_t lengthOffset
= 0;
740 if (!rulePatternFormat
) {
741 toInsertInto
.insert(pos
, ruleText
);
744 pluralRuleStart
= ruleText
.indexOf(gDollarOpenParenthesis
, -1, 0);
745 int pluralRuleEnd
= ruleText
.indexOf(gClosedParenthesisDollar
, -1, pluralRuleStart
);
746 int initialLength
= toInsertInto
.length();
747 if (pluralRuleEnd
< ruleText
.length() - 1) {
748 toInsertInto
.insert(pos
, ruleText
.tempSubString(pluralRuleEnd
+ 2));
750 toInsertInto
.insert(pos
,
751 rulePatternFormat
->format((int32_t)(number
/uprv_pow(radix
, exponent
)), status
));
752 if (pluralRuleStart
> 0) {
753 toInsertInto
.insert(pos
, ruleText
.tempSubString(0, pluralRuleStart
));
755 lengthOffset
= ruleText
.length() - (toInsertInto
.length() - initialLength
);
758 if (!sub2
->isNullSubstitution()) {
759 sub2
->doSubstitution(number
, toInsertInto
, pos
- (sub2
->getPos() > pluralRuleStart
? lengthOffset
: 0), status
);
761 if (!sub1
->isNullSubstitution()) {
762 sub1
->doSubstitution(number
, toInsertInto
, pos
- (sub1
->getPos() > pluralRuleStart
? lengthOffset
: 0), status
);
767 * Used by the owning rule set to determine whether to invoke the
768 * rollback rule (i.e., whether this rule or the one that precedes
769 * it in the rule set's list should be used to format the number)
770 * @param The number being formatted
771 * @return True if the rule set should use the rule that precedes
772 * this one in its list; false if it should use this rule
775 NFRule::shouldRollBack(double number
) const
777 // we roll back if the rule contains a modulus substitution,
778 // the number being formatted is an even multiple of the rule's
779 // divisor, and the rule's base value is NOT an even multiple
781 // In other words, if the original description had
782 // 100: << hundred[ >>];
785 // 101: << hundred >>;
786 // internally. But when we're formatting 200, if we use the rule
787 // at 101, which would normally apply, we get "two hundred zero".
788 // To prevent this, we roll back and use the rule at 100 instead.
789 // This is the logic that makes this happen: the rule at 101 has
790 // a modulus substitution, its base value isn't an even multiple
791 // of 100, and the value we're trying to format _is_ an even
792 // multiple of 100. This is called the "rollback rule."
793 if ((sub1
->isModulusSubstitution()) || (sub2
->isModulusSubstitution())) {
794 int64_t re
= util64_pow(radix
, exponent
);
795 return uprv_fmod(number
, (double)re
) == 0 && (baseValue
% re
) != 0;
800 //-----------------------------------------------------------------------
802 //-----------------------------------------------------------------------
805 * Attempts to parse the string with this rule.
806 * @param text The string being parsed
807 * @param parsePosition On entry, the value is ignored and assumed to
808 * be 0. On exit, this has been updated with the position of the first
809 * character not consumed by matching the text against this rule
810 * (if this rule doesn't match the text at all, the parse position
811 * if left unchanged (presumably at 0) and the function returns
813 * @param isFractionRule True if this rule is contained within a
814 * fraction rule set. This is only used if the rule has no
816 * @return If this rule matched the text, this is the rule's base value
817 * combined appropriately with the results of parsing the substitutions.
818 * If nothing matched, this is new Long(0) and the parse position is
819 * left unchanged. The result will be an instance of Long if the
820 * result is an integer and Double otherwise. The result is never null.
825 static void dumpUS(FILE* f
, const UnicodeString
& us
) {
826 int len
= us
.length();
827 char* buf
= (char *)uprv_malloc((len
+1)*sizeof(char)); //new char[len+1];
829 us
.extract(0, len
, buf
);
831 fprintf(f
, "%s", buf
);
832 uprv_free(buf
); //delete[] buf;
838 NFRule::doParse(const UnicodeString
& text
,
839 ParsePosition
& parsePosition
,
840 UBool isFractionRule
,
843 UBool isDecimFmtParseable
) const
845 // internally we operate on a copy of the string being parsed
846 // (because we're going to change it) and use our own ParsePosition
848 UnicodeString
workText(text
);
850 // check to see whether the text before the first substitution
851 // matches the text at the beginning of the string being
852 // parsed. If it does, strip that off the front of workText;
853 // otherwise, dump out with a mismatch
854 UnicodeString prefix
;
855 prefix
.setTo(ruleText
, 0, sub1
->getPos());
858 fprintf(stderr
, "doParse %x ", this);
865 fprintf(stderr
, " text: '", this);
866 dumpUS(stderr
, text
);
867 fprintf(stderr
, "' prefix: '");
868 dumpUS(stderr
, prefix
);
870 stripPrefix(workText
, prefix
, pp
);
871 int32_t prefixLength
= text
.length() - workText
.length();
874 fprintf(stderr
, "' pl: %d ppi: %d s1p: %d\n", prefixLength
, pp
.getIndex(), sub1
->getPos());
877 if (pp
.getIndex() == 0 && sub1
->getPos() != 0) {
878 // commented out because ParsePosition doesn't have error index in 1.1.x
879 // restored for ICU4C port
880 parsePosition
.setErrorIndex(pp
.getErrorIndex());
885 // Detect when this rule's main job is to parse a decimal format and we're not
887 if (!isDecimFmtParseable
) {
888 // The following tries to detect a rule like "x.x: =#,##0.#=;"
889 if ( sub1
->isDecimalFormatSubstitutionOnly() && sub2
->isRuleSetSubstitutionOnly() ) {
890 parsePosition
.setErrorIndex(pp
.getErrorIndex());
896 // this is the fun part. The basic guts of the rule-matching
897 // logic is matchToDelimiter(), which is called twice. The first
898 // time it searches the input string for the rule text BETWEEN
899 // the substitutions and tries to match the intervening text
900 // in the input string with the first substitution. If that
901 // succeeds, it then calls it again, this time to look for the
902 // rule text after the second substitution and to match the
903 // intervening input text against the second substitution.
905 // For example, say we have a rule that looks like this:
906 // first << middle >> last;
907 // and input text that looks like this:
908 // first one middle two last
909 // First we use stripPrefix() to match "first " in both places and
910 // strip it off the front, leaving
911 // one middle two last
912 // Then we use matchToDelimiter() to match " middle " and try to
913 // match "one" against a substitution. If it's successful, we now
916 // We use matchToDelimiter() a second time to match " last" and
917 // try to match "two" against a substitution. If "two" matches
918 // the substitution, we have a successful parse.
920 // Since it's possible in many cases to find multiple instances
921 // of each of these pieces of rule text in the input string,
922 // we need to try all the possible combinations of these
923 // locations. This prevents us from prematurely declaring a mismatch,
924 // and makes sure we match as much input text as we can.
925 int highWaterMark
= 0;
928 double tempBaseValue
= (double)(baseValue
<= 0 ? 0 : baseValue
);
932 // our partial parse result starts out as this rule's base
933 // value. If it finds a successful match, matchToDelimiter()
934 // will compose this in some way with what it gets back from
935 // the substitution, giving us a new partial parse result
938 temp
.setTo(ruleText
, sub1
->getPos(), sub2
->getPos() - sub1
->getPos());
939 double partialResult
= matchToDelimiter(workText
, start
, tempBaseValue
,
943 // if we got a successful match (or were trying to match a
944 // null substitution), pp is now pointing at the first unmatched
945 // character. Take note of that, and try matchToDelimiter()
946 // on the input text again
947 if (pp
.getIndex() != 0 || sub1
->isNullSubstitution()) {
948 start
= pp
.getIndex();
950 UnicodeString workText2
;
951 workText2
.setTo(workText
, pp
.getIndex(), workText
.length() - pp
.getIndex());
954 // the second matchToDelimiter() will compose our previous
955 // partial result with whatever it gets back from its
956 // substitution if there's a successful match, giving us
958 temp
.setTo(ruleText
, sub2
->getPos(), ruleText
.length() - sub2
->getPos());
959 partialResult
= matchToDelimiter(workText2
, 0, partialResult
,
963 // if we got a successful match on this second
964 // matchToDelimiter() call, update the high-water mark
965 // and result (if necessary)
966 if (pp2
.getIndex() != 0 || sub2
->isNullSubstitution()) {
967 if (prefixLength
+ pp
.getIndex() + pp2
.getIndex() > highWaterMark
) {
968 highWaterMark
= prefixLength
+ pp
.getIndex() + pp2
.getIndex();
969 result
= partialResult
;
972 // commented out because ParsePosition doesn't have error index in 1.1.x
973 // restored for ICU4C port
975 int32_t temp
= pp2
.getErrorIndex() + sub1
->getPos() + pp
.getIndex();
976 if (temp
> parsePosition
.getErrorIndex()) {
977 parsePosition
.setErrorIndex(temp
);
981 // commented out because ParsePosition doesn't have error index in 1.1.x
982 // restored for ICU4C port
984 int32_t temp
= sub1
->getPos() + pp
.getErrorIndex();
985 if (temp
> parsePosition
.getErrorIndex()) {
986 parsePosition
.setErrorIndex(temp
);
989 // keep trying to match things until the outer matchToDelimiter()
990 // call fails to make a match (each time, it picks up where it
991 // left off the previous time)
992 } while (sub1
->getPos() != sub2
->getPos()
994 && pp
.getIndex() < workText
.length()
995 && pp
.getIndex() != start
);
997 // update the caller's ParsePosition with our high-water mark
998 // (i.e., it now points at the first character this function
999 // didn't match-- the ParsePosition is therefore unchanged if
1000 // we didn't match anything)
1001 parsePosition
.setIndex(highWaterMark
);
1002 // commented out because ParsePosition doesn't have error index in 1.1.x
1003 // restored for ICU4C port
1004 if (highWaterMark
> 0) {
1005 parsePosition
.setErrorIndex(0);
1008 // this is a hack for one unusual condition: Normally, whether this
1009 // rule belong to a fraction rule set or not is handled by its
1010 // substitutions. But if that rule HAS NO substitutions, then
1011 // we have to account for it here. By definition, if the matching
1012 // rule in a fraction rule set has no substitutions, its numerator
1013 // is 1, and so the result is the reciprocal of its base value.
1014 if (isFractionRule
&&
1015 highWaterMark
> 0 &&
1016 sub1
->isNullSubstitution()) {
1017 result
= 1 / result
;
1020 resVal
.setDouble(result
);
1021 return TRUE
; // ??? do we need to worry if it is a long or a double?
1025 * This function is used by parse() to match the text being parsed
1026 * against a possible prefix string. This function
1027 * matches characters from the beginning of the string being parsed
1028 * to characters from the prospective prefix. If they match, pp is
1029 * updated to the first character not matched, and the result is
1030 * the unparsed part of the string. If they don't match, the whole
1031 * string is returned, and pp is left unchanged.
1032 * @param text The string being parsed
1033 * @param prefix The text to match against
1034 * @param pp On entry, ignored and assumed to be 0. On exit, points
1035 * to the first unmatched character (assuming the whole prefix matched),
1036 * or is unchanged (if the whole prefix didn't match).
1037 * @return If things match, this is the unparsed part of "text";
1038 * if they didn't match, this is "text".
1041 NFRule::stripPrefix(UnicodeString
& text
, const UnicodeString
& prefix
, ParsePosition
& pp
) const
1043 // if the prefix text is empty, dump out without doing anything
1044 if (prefix
.length() != 0) {
1045 UErrorCode status
= U_ZERO_ERROR
;
1046 // use prefixLength() to match the beginning of
1047 // "text" against "prefix". This function returns the
1048 // number of characters from "text" that matched (or 0 if
1049 // we didn't match the whole prefix)
1050 int32_t pfl
= prefixLength(text
, prefix
, status
);
1051 if (U_FAILURE(status
)) { // Memory allocation error.
1055 // if we got a successful match, update the parse position
1056 // and strip the prefix off of "text"
1057 pp
.setIndex(pp
.getIndex() + pfl
);
1058 text
.remove(0, pfl
);
1064 * Used by parse() to match a substitution and any following text.
1065 * "text" is searched for instances of "delimiter". For each instance
1066 * of delimiter, the intervening text is tested to see whether it
1067 * matches the substitution. The longest match wins.
1068 * @param text The string being parsed
1069 * @param startPos The position in "text" where we should start looking
1071 * @param baseValue A partial parse result (often the rule's base value),
1072 * which is combined with the result from matching the substitution
1073 * @param delimiter The string to search "text" for.
1074 * @param pp Ignored and presumed to be 0 on entry. If there's a match,
1075 * on exit this will point to the first unmatched character.
1076 * @param sub If we find "delimiter" in "text", this substitution is used
1077 * to match the text between the beginning of the string and the
1078 * position of "delimiter." (If "delimiter" is the empty string, then
1079 * this function just matches against this substitution and updates
1080 * everything accordingly.)
1081 * @param upperBound When matching the substitution, it will only
1082 * consider rules with base values lower than this value.
1083 * @return If there's a match, this is the result of composing
1084 * baseValue with the result of matching the substitution. Otherwise,
1085 * this is new Long(0). It's never null. If the result is an integer,
1086 * this will be an instance of Long; otherwise, it's an instance of
1089 * !!! note {dlf} in point of fact, in the java code the caller always converts
1090 * the result to a double, so we might as well return one.
1093 NFRule::matchToDelimiter(const UnicodeString
& text
,
1096 const UnicodeString
& delimiter
,
1098 const NFSubstitution
* sub
,
1099 double upperBound
) const
1101 UErrorCode status
= U_ZERO_ERROR
;
1102 // if "delimiter" contains real (i.e., non-ignorable) text, search
1103 // it for "delimiter" beginning at "start". If that succeeds, then
1104 // use "sub"'s doParse() method to match the text before the
1105 // instance of "delimiter" we just found.
1106 if (!allIgnorable(delimiter
, status
)) {
1107 if (U_FAILURE(status
)) { //Memory allocation error.
1110 ParsePosition tempPP
;
1113 // use findText() to search for "delimiter". It returns a two-
1114 // element array: element 0 is the position of the match, and
1115 // element 1 is the number of characters that matched
1118 int32_t dPos
= findText(text
, delimiter
, startPos
, &dLen
);
1120 // if findText() succeeded, isolate the text preceding the
1121 // match, and use "sub" to match that text
1123 UnicodeString subText
;
1124 subText
.setTo(text
, 0, dPos
);
1125 if (subText
.length() > 0) {
1126 UBool success
= sub
->doParse(subText
, tempPP
, _baseValue
, upperBound
,
1127 #if UCONFIG_NO_COLLATION
1130 formatter
->isLenient(),
1134 // if the substitution could match all the text up to
1135 // where we found "delimiter", then this function has
1136 // a successful match. Bump the caller's parse position
1137 // to point to the first character after the text
1138 // that matches "delimiter", and return the result
1139 // we got from parsing the substitution.
1140 if (success
&& tempPP
.getIndex() == dPos
) {
1141 pp
.setIndex(dPos
+ dLen
);
1142 return result
.getDouble();
1144 // commented out because ParsePosition doesn't have error index in 1.1.x
1145 // restored for ICU4C port
1147 if (tempPP
.getErrorIndex() > 0) {
1148 pp
.setErrorIndex(tempPP
.getErrorIndex());
1150 pp
.setErrorIndex(tempPP
.getIndex());
1155 // if we didn't match the substitution, search for another
1156 // copy of "delimiter" in "text" and repeat the loop if
1159 dPos
= findText(text
, delimiter
, dPos
+ dLen
, &dLen
);
1161 // if we make it here, this was an unsuccessful match, and we
1162 // leave pp unchanged and return 0
1166 // if "delimiter" is empty, or consists only of ignorable characters
1167 // (i.e., is semantically empty), thwe we obviously can't search
1168 // for "delimiter". Instead, just use "sub" to parse as much of
1169 // "text" as possible.
1171 ParsePosition tempPP
;
1174 // try to match the whole string against the substitution
1175 UBool success
= sub
->doParse(text
, tempPP
, _baseValue
, upperBound
,
1176 #if UCONFIG_NO_COLLATION
1179 formatter
->isLenient(),
1182 if (success
&& (tempPP
.getIndex() != 0 || sub
->isNullSubstitution())) {
1183 // if there's a successful match (or it's a null
1184 // substitution), update pp to point to the first
1185 // character we didn't match, and pass the result from
1186 // sub.doParse() on through to the caller
1187 pp
.setIndex(tempPP
.getIndex());
1188 return result
.getDouble();
1190 // commented out because ParsePosition doesn't have error index in 1.1.x
1191 // restored for ICU4C port
1193 pp
.setErrorIndex(tempPP
.getErrorIndex());
1196 // and if we get to here, then nothing matched, so we return
1197 // 0 and leave pp alone
1203 * Used by stripPrefix() to match characters. If lenient parse mode
1204 * is off, this just calls startsWith(). If lenient parse mode is on,
1205 * this function uses CollationElementIterators to match characters in
1206 * the strings (only primary-order differences are significant in
1207 * determining whether there's a match).
1208 * @param str The string being tested
1209 * @param prefix The text we're hoping to see at the beginning
1211 * @return If "prefix" is found at the beginning of "str", this
1212 * is the number of characters in "str" that were matched (this
1213 * isn't necessarily the same as the length of "prefix" when matching
1214 * text with a collator). If there's no match, this is 0.
1217 NFRule::prefixLength(const UnicodeString
& str
, const UnicodeString
& prefix
, UErrorCode
& status
) const
1219 // if we're looking for an empty prefix, it obviously matches
1220 // zero characters. Just go ahead and return 0.
1221 if (prefix
.length() == 0) {
1225 #if !UCONFIG_NO_COLLATION
1226 // go through all this grief if we're in lenient-parse mode
1227 if (formatter
->isLenient()) {
1228 // get the formatter's collator and use it to create two
1229 // collation element iterators, one over the target string
1230 // and another over the prefix (right now, we'll throw an
1231 // exception if the collator we get back from the formatter
1232 // isn't a RuleBasedCollator, because RuleBasedCollator defines
1233 // the CollationElementIterator protocol. Hopefully, this
1234 // will change someday.)
1235 const RuleBasedCollator
* collator
= formatter
->getCollator();
1236 if (collator
== NULL
) {
1237 status
= U_MEMORY_ALLOCATION_ERROR
;
1240 LocalPointer
<CollationElementIterator
> strIter(collator
->createCollationElementIterator(str
));
1241 LocalPointer
<CollationElementIterator
> prefixIter(collator
->createCollationElementIterator(prefix
));
1242 // Check for memory allocation error.
1243 if (strIter
.isNull() || prefixIter
.isNull()) {
1244 status
= U_MEMORY_ALLOCATION_ERROR
;
1248 UErrorCode err
= U_ZERO_ERROR
;
1250 // The original code was problematic. Consider this match:
1251 // prefix = "fifty-"
1252 // string = " fifty-7"
1253 // The intent is to match string up to the '7', by matching 'fifty-' at position 1
1254 // in the string. Unfortunately, we were getting a match, and then computing where
1255 // the match terminated by rematching the string. The rematch code was using as an
1256 // initial guess the substring of string between 0 and prefix.length. Because of
1257 // the leading space and trailing hyphen (both ignorable) this was succeeding, leaving
1258 // the position before the hyphen in the string. Recursing down, we then parsed the
1259 // remaining string '-7' as numeric. The resulting number turned out as 43 (50 - 7).
1260 // This was not pretty, especially since the string "fifty-7" parsed just fine.
1262 // We have newer APIs now, so we can use calls on the iterator to determine what we
1263 // matched up to. If we terminate because we hit the last element in the string,
1264 // our match terminates at this length. If we terminate because we hit the last element
1265 // in the target, our match terminates at one before the element iterator position.
1267 // match collation elements between the strings
1268 int32_t oStr
= strIter
->next(err
);
1269 int32_t oPrefix
= prefixIter
->next(err
);
1271 while (oPrefix
!= CollationElementIterator::NULLORDER
) {
1272 // skip over ignorable characters in the target string
1273 while (CollationElementIterator::primaryOrder(oStr
) == 0
1274 && oStr
!= CollationElementIterator::NULLORDER
) {
1275 oStr
= strIter
->next(err
);
1278 // skip over ignorable characters in the prefix
1279 while (CollationElementIterator::primaryOrder(oPrefix
) == 0
1280 && oPrefix
!= CollationElementIterator::NULLORDER
) {
1281 oPrefix
= prefixIter
->next(err
);
1284 // dlf: move this above following test, if we consume the
1285 // entire target, aren't we ok even if the source was also
1286 // entirely consumed?
1288 // if skipping over ignorables brought to the end of
1289 // the prefix, we DID match: drop out of the loop
1290 if (oPrefix
== CollationElementIterator::NULLORDER
) {
1294 // if skipping over ignorables brought us to the end
1295 // of the target string, we didn't match and return 0
1296 if (oStr
== CollationElementIterator::NULLORDER
) {
1300 // match collation elements from the two strings
1301 // (considering only primary differences). If we
1302 // get a mismatch, dump out and return 0
1303 if (CollationElementIterator::primaryOrder(oStr
)
1304 != CollationElementIterator::primaryOrder(oPrefix
)) {
1307 // otherwise, advance to the next character in each string
1308 // and loop (we drop out of the loop when we exhaust
1309 // collation elements in the prefix)
1311 oStr
= strIter
->next(err
);
1312 oPrefix
= prefixIter
->next(err
);
1316 int32_t result
= strIter
->getOffset();
1317 if (oStr
!= CollationElementIterator::NULLORDER
) {
1318 --result
; // back over character that we don't want to consume;
1322 fprintf(stderr
, "prefix length: %d\n", result
);
1326 //----------------------------------------------------------------
1327 // JDK 1.2-specific API call
1328 // return strIter.getOffset();
1329 //----------------------------------------------------------------
1330 // JDK 1.1 HACK (take out for 1.2-specific code)
1332 // if we make it to here, we have a successful match. Now we
1333 // have to find out HOW MANY characters from the target string
1334 // matched the prefix (there isn't necessarily a one-to-one
1335 // mapping between collation elements and characters).
1336 // In JDK 1.2, there's a simple getOffset() call we can use.
1337 // In JDK 1.1, on the other hand, we have to go through some
1338 // ugly contortions. First, use the collator to compare the
1339 // same number of characters from the prefix and target string.
1340 // If they're equal, we're done.
1341 collator
->setStrength(Collator::PRIMARY
);
1342 if (str
.length() >= prefix
.length()) {
1344 temp
.setTo(str
, 0, prefix
.length());
1345 if (collator
->equals(temp
, prefix
)) {
1347 fprintf(stderr
, "returning: %d\n", prefix
.length());
1349 return prefix
.length();
1353 // if they're not equal, then we have to compare successively
1354 // larger and larger substrings of the target string until we
1355 // get to one that matches the prefix. At that point, we know
1356 // how many characters matched the prefix, and we can return.
1358 while (p
<= str
.length()) {
1360 temp
.setTo(str
, 0, p
);
1361 if (collator
->equals(temp
, prefix
)) {
1368 // SHOULD NEVER GET HERE!!!
1370 //----------------------------------------------------------------
1373 // If lenient parsing is turned off, forget all that crap above.
1374 // Just use String.startsWith() and be done with it.
1378 if (str
.startsWith(prefix
)) {
1379 return prefix
.length();
1387 * Searches a string for another string. If lenient parsing is off,
1388 * this just calls indexOf(). If lenient parsing is on, this function
1389 * uses CollationElementIterator to match characters, and only
1390 * primary-order differences are significant in determining whether
1392 * @param str The string to search
1393 * @param key The string to search "str" for
1394 * @param startingAt The index into "str" where the search is to
1396 * @return A two-element array of ints. Element 0 is the position
1397 * of the match, or -1 if there was no match. Element 1 is the
1398 * number of characters in "str" that matched (which isn't necessarily
1399 * the same as the length of "key")
1402 NFRule::findText(const UnicodeString
& str
,
1403 const UnicodeString
& key
,
1405 int32_t* length
) const
1407 if (rulePatternFormat
) {
1409 FieldPosition
position(UNUM_INTEGER_FIELD
);
1410 position
.setBeginIndex(startingAt
);
1411 rulePatternFormat
->parseType(str
, this, result
, position
);
1412 int start
= position
.getBeginIndex();
1414 int32_t pluralRuleStart
= ruleText
.indexOf(gDollarOpenParenthesis
, -1, 0);
1415 int32_t pluralRuleSuffix
= ruleText
.indexOf(gClosedParenthesisDollar
, -1, pluralRuleStart
) + 2;
1416 int32_t matchLen
= position
.getEndIndex() - start
;
1417 UnicodeString
prefix(ruleText
.tempSubString(0, pluralRuleStart
));
1418 UnicodeString
suffix(ruleText
.tempSubString(pluralRuleSuffix
));
1419 if (str
.compare(start
- prefix
.length(), prefix
.length(), prefix
, 0, prefix
.length()) == 0
1420 && str
.compare(start
+ matchLen
, suffix
.length(), suffix
, 0, suffix
.length()) == 0)
1422 *length
= matchLen
+ prefix
.length() + suffix
.length();
1423 return start
- prefix
.length();
1429 if (!formatter
->isLenient()) {
1430 // if lenient parsing is turned off, this is easy: just call
1431 // String.indexOf() and we're done
1432 *length
= key
.length();
1433 return str
.indexOf(key
, startingAt
);
1436 // but if lenient parsing is turned ON, we've got some work
1438 return findTextLenient(str
, key
, startingAt
, length
);
1443 NFRule::findTextLenient(const UnicodeString
& str
,
1444 const UnicodeString
& key
,
1446 int32_t* length
) const
1448 //----------------------------------------------------------------
1449 // JDK 1.1 HACK (take out of 1.2-specific code)
1451 // in JDK 1.2, CollationElementIterator provides us with an
1452 // API to map between character offsets and collation elements
1453 // and we can do this by marching through the string comparing
1454 // collation elements. We can't do that in JDK 1.1. Insted,
1455 // we have to go through this horrible slow mess:
1456 int32_t p
= startingAt
;
1459 // basically just isolate smaller and smaller substrings of
1460 // the target string (each running to the end of the string,
1461 // and with the first one running from startingAt to the end)
1462 // and then use prefixLength() to see if the search key is at
1463 // the beginning of each substring. This is excruciatingly
1464 // slow, but it will locate the key and tell use how long the
1465 // matching text was.
1467 UErrorCode status
= U_ZERO_ERROR
;
1468 while (p
< str
.length() && keyLen
== 0) {
1469 temp
.setTo(str
, p
, str
.length() - p
);
1470 keyLen
= prefixLength(temp
, key
, status
);
1471 if (U_FAILURE(status
)) {
1480 // if we make it to here, we didn't find it. Return -1 for the
1481 // location. The length should be ignored, but set it to 0,
1482 // which should be "safe"
1488 * Checks to see whether a string consists entirely of ignorable
1490 * @param str The string to test.
1491 * @return true if the string is empty of consists entirely of
1492 * characters that the number formatter's collator says are
1493 * ignorable at the primary-order level. false otherwise.
1496 NFRule::allIgnorable(const UnicodeString
& str
, UErrorCode
& status
) const
1498 // if the string is empty, we can just return true
1499 if (str
.length() == 0) {
1503 #if !UCONFIG_NO_COLLATION
1504 // if lenient parsing is turned on, walk through the string with
1505 // a collation element iterator and make sure each collation
1506 // element is 0 (ignorable) at the primary level
1507 if (formatter
->isLenient()) {
1508 const RuleBasedCollator
* collator
= formatter
->getCollator();
1509 if (collator
== NULL
) {
1510 status
= U_MEMORY_ALLOCATION_ERROR
;
1513 LocalPointer
<CollationElementIterator
> iter(collator
->createCollationElementIterator(str
));
1515 // Memory allocation error check.
1516 if (iter
.isNull()) {
1517 status
= U_MEMORY_ALLOCATION_ERROR
;
1521 UErrorCode err
= U_ZERO_ERROR
;
1522 int32_t o
= iter
->next(err
);
1523 while (o
!= CollationElementIterator::NULLORDER
1524 && CollationElementIterator::primaryOrder(o
) == 0) {
1525 o
= iter
->next(err
);
1528 return o
== CollationElementIterator::NULLORDER
;
1532 // if lenient parsing is turned off, there is no such thing as
1533 // an ignorable character: return true only if the string is empty