]> git.saurik.com Git - apple/icu.git/blame - icuSources/i18n/nfrule.cpp
ICU-511.35.tar.gz
[apple/icu.git] / icuSources / i18n / nfrule.cpp
CommitLineData
b75a7d8f
A
1/*
2******************************************************************************
4388f060 3* Copyright (C) 1997-2011, International Business Machines
b75a7d8f
A
4* Corporation and others. All Rights Reserved.
5******************************************************************************
6* file name: nfrule.cpp
7* encoding: US-ASCII
8* tab size: 8 (not used)
9* indentation:4
10*
11* Modification history
12* Date Name Comments
13* 10/11/2001 Doug Ported from ICU4J
14*/
15
16#include "nfrule.h"
17
18#if U_HAVE_RBNF
19
20#include "unicode/rbnf.h"
21#include "unicode/tblcoll.h"
22#include "unicode/coleitr.h"
23#include "unicode/uchar.h"
24#include "nfrs.h"
25#include "nfrlist.h"
26#include "nfsubs.h"
4388f060 27#include "patternprops.h"
b75a7d8f
A
28
29U_NAMESPACE_BEGIN
30
b75a7d8f
A
31NFRule::NFRule(const RuleBasedNumberFormat* _rbnf)
32 : baseValue((int32_t)0)
33 , radix(0)
34 , exponent(0)
35 , ruleText()
36 , sub1(NULL)
37 , sub2(NULL)
38 , formatter(_rbnf)
39{
40}
41
42NFRule::~NFRule()
43{
44 delete sub1;
45 delete sub2;
46}
47
48static const UChar gLeftBracket = 0x005b;
49static const UChar gRightBracket = 0x005d;
50static const UChar gColon = 0x003a;
51static const UChar gZero = 0x0030;
52static const UChar gNine = 0x0039;
53static const UChar gSpace = 0x0020;
54static const UChar gSlash = 0x002f;
55static const UChar gGreaterThan = 0x003e;
73c04bcf 56static const UChar gLessThan = 0x003c;
b75a7d8f
A
57static const UChar gComma = 0x002c;
58static const UChar gDot = 0x002e;
59static const UChar gTick = 0x0027;
73c04bcf 60//static const UChar gMinus = 0x002d;
b75a7d8f
A
61static const UChar gSemicolon = 0x003b;
62
63static const UChar gMinusX[] = {0x2D, 0x78, 0}; /* "-x" */
64static const UChar gXDotX[] = {0x78, 0x2E, 0x78, 0}; /* "x.x" */
65static const UChar gXDotZero[] = {0x78, 0x2E, 0x30, 0}; /* "x.0" */
66static const UChar gZeroDotX[] = {0x30, 0x2E, 0x78, 0}; /* "0.x" */
67
68static const UChar gLessLess[] = {0x3C, 0x3C, 0}; /* "<<" */
69static const UChar gLessPercent[] = {0x3C, 0x25, 0}; /* "<%" */
70static const UChar gLessHash[] = {0x3C, 0x23, 0}; /* "<#" */
71static const UChar gLessZero[] = {0x3C, 0x30, 0}; /* "<0" */
72static const UChar gGreaterGreater[] = {0x3E, 0x3E, 0}; /* ">>" */
73static const UChar gGreaterPercent[] = {0x3E, 0x25, 0}; /* ">%" */
74static const UChar gGreaterHash[] = {0x3E, 0x23, 0}; /* ">#" */
75static const UChar gGreaterZero[] = {0x3E, 0x30, 0}; /* ">0" */
76static const UChar gEqualPercent[] = {0x3D, 0x25, 0}; /* "=%" */
77static const UChar gEqualHash[] = {0x3D, 0x23, 0}; /* "=#" */
78static const UChar gEqualZero[] = {0x3D, 0x30, 0}; /* "=0" */
b75a7d8f
A
79static const UChar gGreaterGreaterGreater[] = {0x3E, 0x3E, 0x3E, 0}; /* ">>>" */
80
81static const UChar * const tokenStrings[] = {
82 gLessLess, gLessPercent, gLessHash, gLessZero,
83 gGreaterGreater, gGreaterPercent,gGreaterHash, gGreaterZero,
84 gEqualPercent, gEqualHash, gEqualZero, NULL
85};
86
87void
88NFRule::makeRules(UnicodeString& description,
89 const NFRuleSet *ruleSet,
90 const NFRule *predecessor,
91 const RuleBasedNumberFormat *rbnf,
92 NFRuleList& rules,
93 UErrorCode& status)
94{
95 // we know we're making at least one rule, so go ahead and
96 // new it up and initialize its basevalue and divisor
97 // (this also strips the rule descriptor, if any, off the
98 // descripton string)
99 NFRule* rule1 = new NFRule(rbnf);
100 /* test for NULL */
101 if (rule1 == 0) {
102 status = U_MEMORY_ALLOCATION_ERROR;
103 return;
104 }
105 rule1->parseRuleDescriptor(description, status);
106
107 // check the description to see whether there's text enclosed
108 // in brackets
109 int32_t brack1 = description.indexOf(gLeftBracket);
110 int32_t brack2 = description.indexOf(gRightBracket);
111
112 // if the description doesn't contain a matched pair of brackets,
113 // or if it's of a type that doesn't recognize bracketed text,
114 // then leave the description alone, initialize the rule's
115 // rule text and substitutions, and return that rule
116 if (brack1 == -1 || brack2 == -1 || brack1 > brack2
117 || rule1->getType() == kProperFractionRule
118 || rule1->getType() == kNegativeNumberRule) {
119 rule1->ruleText = description;
120 rule1->extractSubstitutions(ruleSet, predecessor, rbnf, status);
121 rules.add(rule1);
122 } else {
123 // if the description does contain a matched pair of brackets,
124 // then it's really shorthand for two rules (with one exception)
125 NFRule* rule2 = NULL;
126 UnicodeString sbuf;
127
128 // we'll actually only split the rule into two rules if its
129 // base value is an even multiple of its divisor (or it's one
130 // of the special rules)
131 if ((rule1->baseValue > 0
132 && (rule1->baseValue % util64_pow(rule1->radix, rule1->exponent)) == 0)
133 || rule1->getType() == kImproperFractionRule
134 || rule1->getType() == kMasterRule) {
135
136 // if it passes that test, new up the second rule. If the
137 // rule set both rules will belong to is a fraction rule
138 // set, they both have the same base value; otherwise,
139 // increment the original rule's base value ("rule1" actually
140 // goes SECOND in the rule set's rule list)
141 rule2 = new NFRule(rbnf);
142 /* test for NULL */
143 if (rule2 == 0) {
144 status = U_MEMORY_ALLOCATION_ERROR;
145 return;
146 }
147 if (rule1->baseValue >= 0) {
148 rule2->baseValue = rule1->baseValue;
149 if (!ruleSet->isFractionRuleSet()) {
150 ++rule1->baseValue;
151 }
152 }
153
154 // if the description began with "x.x" and contains bracketed
155 // text, it describes both the improper fraction rule and
156 // the proper fraction rule
157 else if (rule1->getType() == kImproperFractionRule) {
158 rule2->setType(kProperFractionRule);
159 }
160
161 // if the description began with "x.0" and contains bracketed
162 // text, it describes both the master rule and the
163 // improper fraction rule
164 else if (rule1->getType() == kMasterRule) {
165 rule2->baseValue = rule1->baseValue;
166 rule1->setType(kImproperFractionRule);
167 }
168
169 // both rules have the same radix and exponent (i.e., the
170 // same divisor)
171 rule2->radix = rule1->radix;
172 rule2->exponent = rule1->exponent;
173
174 // rule2's rule text omits the stuff in brackets: initalize
175 // its rule text and substitutions accordingly
176 sbuf.append(description, 0, brack1);
177 if (brack2 + 1 < description.length()) {
178 sbuf.append(description, brack2 + 1, description.length() - brack2 - 1);
179 }
180 rule2->ruleText.setTo(sbuf);
181 rule2->extractSubstitutions(ruleSet, predecessor, rbnf, status);
182 }
183
184 // rule1's text includes the text in the brackets but omits
185 // the brackets themselves: initialize _its_ rule text and
186 // substitutions accordingly
187 sbuf.setTo(description, 0, brack1);
188 sbuf.append(description, brack1 + 1, brack2 - brack1 - 1);
189 if (brack2 + 1 < description.length()) {
190 sbuf.append(description, brack2 + 1, description.length() - brack2 - 1);
191 }
192 rule1->ruleText.setTo(sbuf);
193 rule1->extractSubstitutions(ruleSet, predecessor, rbnf, status);
194
195 // if we only have one rule, return it; if we have two, return
196 // a two-element array containing them (notice that rule2 goes
197 // BEFORE rule1 in the list: in all cases, rule2 OMITS the
198 // material in the brackets and rule1 INCLUDES the material
199 // in the brackets)
200 if (rule2 != NULL) {
201 rules.add(rule2);
202 }
203 rules.add(rule1);
204 }
205}
206
207/**
208 * This function parses the rule's rule descriptor (i.e., the base
209 * value and/or other tokens that precede the rule's rule text
210 * in the description) and sets the rule's base value, radix, and
211 * exponent according to the descriptor. (If the description doesn't
212 * include a rule descriptor, then this function sets everything to
213 * default values and the rule set sets the rule's real base value).
214 * @param description The rule's description
215 * @return If "description" included a rule descriptor, this is
216 * "description" with the descriptor and any trailing whitespace
217 * stripped off. Otherwise; it's "descriptor" unchangd.
218 */
219void
220NFRule::parseRuleDescriptor(UnicodeString& description, UErrorCode& status)
221{
222 // the description consists of a rule descriptor and a rule body,
223 // separated by a colon. The rule descriptor is optional. If
224 // it's omitted, just set the base value to 0.
225 int32_t p = description.indexOf(gColon);
226 if (p == -1) {
374ca955 227 setBaseValue((int32_t)0, status);
b75a7d8f
A
228 } else {
229 // copy the descriptor out into its own string and strip it,
230 // along with any trailing whitespace, out of the original
231 // description
232 UnicodeString descriptor;
233 descriptor.setTo(description, 0, p);
234
235 ++p;
4388f060 236 while (p < description.length() && PatternProps::isWhiteSpace(description.charAt(p))) {
b75a7d8f
A
237 ++p;
238 }
239 description.removeBetween(0, p);
240
241 // check first to see if the rule descriptor matches the token
242 // for one of the special rules. If it does, set the base
243 // value to the correct identfier value
4388f060 244 if (0 == descriptor.compare(gMinusX, 2)) {
b75a7d8f
A
245 setType(kNegativeNumberRule);
246 }
4388f060 247 else if (0 == descriptor.compare(gXDotX, 3)) {
b75a7d8f
A
248 setType(kImproperFractionRule);
249 }
4388f060 250 else if (0 == descriptor.compare(gZeroDotX, 3)) {
b75a7d8f
A
251 setType(kProperFractionRule);
252 }
4388f060 253 else if (0 == descriptor.compare(gXDotZero, 3)) {
b75a7d8f
A
254 setType(kMasterRule);
255 }
256
257 // if the rule descriptor begins with a digit, it's a descriptor
258 // for a normal rule
259 // since we don't have Long.parseLong, and this isn't much work anyway,
260 // just build up the value as we encounter the digits.
261 else if (descriptor.charAt(0) >= gZero && descriptor.charAt(0) <= gNine) {
262 int64_t val = 0;
263 p = 0;
264 UChar c = gSpace;
265
266 // begin parsing the descriptor: copy digits
267 // into "tempValue", skip periods, commas, and spaces,
268 // stop on a slash or > sign (or at the end of the string),
269 // and throw an exception on any other character
270 int64_t ll_10 = 10;
271 while (p < descriptor.length()) {
272 c = descriptor.charAt(p);
273 if (c >= gZero && c <= gNine) {
274 val = val * ll_10 + (int32_t)(c - gZero);
275 }
276 else if (c == gSlash || c == gGreaterThan) {
277 break;
278 }
4388f060 279 else if (PatternProps::isWhiteSpace(c) || c == gComma || c == gDot) {
b75a7d8f
A
280 }
281 else {
282 // throw new IllegalArgumentException("Illegal character in rule descriptor");
283 status = U_PARSE_ERROR;
284 return;
285 }
286 ++p;
287 }
288
289 // we have the base value, so set it
374ca955 290 setBaseValue(val, status);
b75a7d8f
A
291
292 // if we stopped the previous loop on a slash, we're
293 // now parsing the rule's radix. Again, accumulate digits
294 // in tempValue, skip punctuation, stop on a > mark, and
295 // throw an exception on anything else
296 if (c == gSlash) {
297 val = 0;
298 ++p;
299 int64_t ll_10 = 10;
300 while (p < descriptor.length()) {
301 c = descriptor.charAt(p);
302 if (c >= gZero && c <= gNine) {
303 val = val * ll_10 + (int32_t)(c - gZero);
304 }
305 else if (c == gGreaterThan) {
306 break;
307 }
4388f060 308 else if (PatternProps::isWhiteSpace(c) || c == gComma || c == gDot) {
b75a7d8f
A
309 }
310 else {
311 // throw new IllegalArgumentException("Illegal character is rule descriptor");
312 status = U_PARSE_ERROR;
313 return;
314 }
315 ++p;
316 }
317
318 // tempValue now contain's the rule's radix. Set it
319 // accordingly, and recalculate the rule's exponent
374ca955 320 radix = (int32_t)val;
b75a7d8f
A
321 if (radix == 0) {
322 // throw new IllegalArgumentException("Rule can't have radix of 0");
323 status = U_PARSE_ERROR;
324 }
325
326 exponent = expectedExponent();
327 }
328
329 // if we stopped the previous loop on a > sign, then continue
330 // for as long as we still see > signs. For each one,
331 // decrement the exponent (unless the exponent is already 0).
332 // If we see another character before reaching the end of
333 // the descriptor, that's also a syntax error.
334 if (c == gGreaterThan) {
335 while (p < descriptor.length()) {
336 c = descriptor.charAt(p);
337 if (c == gGreaterThan && exponent > 0) {
338 --exponent;
339 } else {
340 // throw new IllegalArgumentException("Illegal character in rule descriptor");
341 status = U_PARSE_ERROR;
342 return;
343 }
344 ++p;
345 }
346 }
347 }
348 }
349
350 // finally, if the rule body begins with an apostrophe, strip it off
351 // (this is generally used to put whitespace at the beginning of
352 // a rule's rule text)
353 if (description.length() > 0 && description.charAt(0) == gTick) {
354 description.removeBetween(0, 1);
355 }
356
357 // return the description with all the stuff we've just waded through
358 // stripped off the front. It now contains just the rule body.
359 // return description;
360}
361
362/**
363* Searches the rule's rule text for the substitution tokens,
364* creates the substitutions, and removes the substitution tokens
365* from the rule's rule text.
366* @param owner The rule set containing this rule
367* @param predecessor The rule preseding this one in "owners" rule list
368* @param ownersOwner The RuleBasedFormat that owns this rule
369*/
370void
371NFRule::extractSubstitutions(const NFRuleSet* ruleSet,
372 const NFRule* predecessor,
373 const RuleBasedNumberFormat* rbnf,
374 UErrorCode& status)
375{
376 if (U_SUCCESS(status)) {
377 sub1 = extractSubstitution(ruleSet, predecessor, rbnf, status);
378 sub2 = extractSubstitution(ruleSet, predecessor, rbnf, status);
379 }
380}
381
382/**
383* Searches the rule's rule text for the first substitution token,
384* creates a substitution based on it, and removes the token from
385* the rule's rule text.
386* @param owner The rule set containing this rule
387* @param predecessor The rule preceding this one in the rule set's
388* rule list
389* @param ownersOwner The RuleBasedNumberFormat that owns this rule
390* @return The newly-created substitution. This is never null; if
391* the rule text doesn't contain any substitution tokens, this will
392* be a NullSubstitution.
393*/
394NFSubstitution *
395NFRule::extractSubstitution(const NFRuleSet* ruleSet,
396 const NFRule* predecessor,
397 const RuleBasedNumberFormat* rbnf,
398 UErrorCode& status)
399{
400 NFSubstitution* result = NULL;
401
402 // search the rule's rule text for the first two characters of
403 // a substitution token
404 int32_t subStart = indexOfAny(tokenStrings);
405 int32_t subEnd = subStart;
406
407 // if we didn't find one, create a null substitution positioned
408 // at the end of the rule text
409 if (subStart == -1) {
410 return NFSubstitution::makeSubstitution(ruleText.length(), this, predecessor,
4388f060 411 ruleSet, rbnf, UnicodeString(), status);
b75a7d8f
A
412 }
413
414 // special-case the ">>>" token, since searching for the > at the
415 // end will actually find the > in the middle
4388f060 416 if (ruleText.indexOf(gGreaterGreaterGreater, 3, 0) == subStart) {
b75a7d8f
A
417 subEnd = subStart + 2;
418
419 // otherwise the substitution token ends with the same character
420 // it began with
421 } else {
73c04bcf
A
422 UChar c = ruleText.charAt(subStart);
423 subEnd = ruleText.indexOf(c, subStart + 1);
424 // special case for '<%foo<<'
425 if (c == gLessThan && subEnd != -1 && subEnd < ruleText.length() - 1 && ruleText.charAt(subEnd+1) == c) {
426 // ordinals use "=#,##0==%abbrev=" as their rule. Notice that the '==' in the middle
427 // occurs because of the juxtaposition of two different rules. The check for '<' is a hack
428 // to get around this. Having the duplicate at the front would cause problems with
429 // rules like "<<%" to format, say, percents...
430 ++subEnd;
431 }
432 }
b75a7d8f
A
433
434 // if we don't find the end of the token (i.e., if we're on a single,
435 // unmatched token character), create a null substitution positioned
436 // at the end of the rule
437 if (subEnd == -1) {
438 return NFSubstitution::makeSubstitution(ruleText.length(), this, predecessor,
4388f060 439 ruleSet, rbnf, UnicodeString(), status);
b75a7d8f
A
440 }
441
442 // if we get here, we have a real substitution token (or at least
443 // some text bounded by substitution token characters). Use
444 // makeSubstitution() to create the right kind of substitution
445 UnicodeString subToken;
446 subToken.setTo(ruleText, subStart, subEnd + 1 - subStart);
447 result = NFSubstitution::makeSubstitution(subStart, this, predecessor, ruleSet,
448 rbnf, subToken, status);
449
450 // remove the substitution from the rule text
451 ruleText.removeBetween(subStart, subEnd+1);
452
453 return result;
454}
455
456/**
457 * Sets the rule's base value, and causes the radix and exponent
458 * to be recalculated. This is used during construction when we
459 * don't know the rule's base value until after it's been
460 * constructed. It should be used at any other time.
461 * @param The new base value for the rule.
462 */
463void
374ca955 464NFRule::setBaseValue(int64_t newBaseValue, UErrorCode& status)
b75a7d8f
A
465{
466 // set the base value
467 baseValue = newBaseValue;
468
469 // if this isn't a special rule, recalculate the radix and exponent
470 // (the radix always defaults to 10; if it's supposed to be something
471 // else, it's cleaned up by the caller and the exponent is
472 // recalculated again-- the only function that does this is
473 // NFRule.parseRuleDescriptor() )
474 if (baseValue >= 1) {
475 radix = 10;
476 exponent = expectedExponent();
477
478 // this function gets called on a fully-constructed rule whose
479 // description didn't specify a base value. This means it
480 // has substitutions, and some substitutions hold on to copies
481 // of the rule's divisor. Fix their copies of the divisor.
482 if (sub1 != NULL) {
374ca955 483 sub1->setDivisor(radix, exponent, status);
b75a7d8f
A
484 }
485 if (sub2 != NULL) {
374ca955 486 sub2->setDivisor(radix, exponent, status);
b75a7d8f
A
487 }
488
489 // if this is a special rule, its radix and exponent are basically
490 // ignored. Set them to "safe" default values
491 } else {
492 radix = 10;
493 exponent = 0;
494 }
495}
496
497/**
498* This calculates the rule's exponent based on its radix and base
499* value. This will be the highest power the radix can be raised to
500* and still produce a result less than or equal to the base value.
501*/
502int16_t
503NFRule::expectedExponent() const
504{
505 // since the log of 0, or the log base 0 of something, causes an
506 // error, declare the exponent in these cases to be 0 (we also
507 // deal with the special-rule identifiers here)
508 if (radix == 0 || baseValue < 1) {
509 return 0;
510 }
511
512 // we get rounding error in some cases-- for example, log 1000 / log 10
513 // gives us 1.9999999996 instead of 2. The extra logic here is to take
514 // that into account
515 int16_t tempResult = (int16_t)(uprv_log((double)baseValue) / uprv_log((double)radix));
516 int64_t temp = util64_pow(radix, tempResult + 1);
517 if (temp <= baseValue) {
518 tempResult += 1;
519 }
520 return tempResult;
521}
522
523/**
524 * Searches the rule's rule text for any of the specified strings.
525 * @param strings An array of strings to search the rule's rule
526 * text for
527 * @return The index of the first match in the rule's rule text
528 * (i.e., the first substring in the rule's rule text that matches
529 * _any_ of the strings in "strings"). If none of the strings in
530 * "strings" is found in the rule's rule text, returns -1.
531 */
532int32_t
533NFRule::indexOfAny(const UChar* const strings[]) const
534{
535 int result = -1;
536 for (int i = 0; strings[i]; i++) {
537 int32_t pos = ruleText.indexOf(*strings[i]);
538 if (pos != -1 && (result == -1 || pos < result)) {
539 result = pos;
540 }
541 }
542 return result;
543}
544
545//-----------------------------------------------------------------------
546// boilerplate
547//-----------------------------------------------------------------------
548
549/**
550* Tests two rules for equality.
551* @param that The rule to compare this one against
552* @return True is the two rules are functionally equivalent
553*/
554UBool
555NFRule::operator==(const NFRule& rhs) const
556{
557 return baseValue == rhs.baseValue
558 && radix == rhs.radix
559 && exponent == rhs.exponent
560 && ruleText == rhs.ruleText
561 && *sub1 == *rhs.sub1
562 && *sub2 == *rhs.sub2;
563}
564
565/**
566* Returns a textual representation of the rule. This won't
567* necessarily be the same as the description that this rule
568* was created with, but it will produce the same result.
569* @return A textual description of the rule
570*/
571static void util_append64(UnicodeString& result, int64_t n)
572{
573 UChar buffer[256];
574 int32_t len = util64_tou(n, buffer, sizeof(buffer));
575 UnicodeString temp(buffer, len);
576 result.append(temp);
577}
578
579void
73c04bcf 580NFRule::_appendRuleText(UnicodeString& result) const
b75a7d8f
A
581{
582 switch (getType()) {
4388f060
A
583 case kNegativeNumberRule: result.append(gMinusX, 2); break;
584 case kImproperFractionRule: result.append(gXDotX, 3); break;
585 case kProperFractionRule: result.append(gZeroDotX, 3); break;
586 case kMasterRule: result.append(gXDotZero, 3); break;
b75a7d8f
A
587 default:
588 // for a normal rule, write out its base value, and if the radix is
589 // something other than 10, write out the radix (with the preceding
590 // slash, of course). Then calculate the expected exponent and if
591 // if isn't the same as the actual exponent, write an appropriate
592 // number of > signs. Finally, terminate the whole thing with
593 // a colon.
594 util_append64(result, baseValue);
595 if (radix != 10) {
596 result.append(gSlash);
597 util_append64(result, radix);
598 }
599 int numCarets = expectedExponent() - exponent;
600 for (int i = 0; i < numCarets; i++) {
601 result.append(gGreaterThan);
602 }
603 break;
604 }
605 result.append(gColon);
606 result.append(gSpace);
607
608 // if the rule text begins with a space, write an apostrophe
609 // (whitespace after the rule descriptor is ignored; the
610 // apostrophe is used to make the whitespace significant)
4388f060 611 if (ruleText.charAt(0) == gSpace && sub1->getPos() != 0) {
b75a7d8f
A
612 result.append(gTick);
613 }
614
615 // now, write the rule's rule text, inserting appropriate
616 // substitution tokens in the appropriate places
617 UnicodeString ruleTextCopy;
618 ruleTextCopy.setTo(ruleText);
619
620 UnicodeString temp;
621 sub2->toString(temp);
622 ruleTextCopy.insert(sub2->getPos(), temp);
623 sub1->toString(temp);
624 ruleTextCopy.insert(sub1->getPos(), temp);
625
626 result.append(ruleTextCopy);
627
628 // and finally, top the whole thing off with a semicolon and
629 // return the result
630 result.append(gSemicolon);
631}
632
633//-----------------------------------------------------------------------
634// formatting
635//-----------------------------------------------------------------------
636
637/**
638* Formats the number, and inserts the resulting text into
639* toInsertInto.
640* @param number The number being formatted
641* @param toInsertInto The string where the resultant text should
642* be inserted
643* @param pos The position in toInsertInto where the resultant text
644* should be inserted
645*/
646void
647NFRule::doFormat(int64_t number, UnicodeString& toInsertInto, int32_t pos) const
648{
649 // first, insert the rule's rule text into toInsertInto at the
650 // specified position, then insert the results of the substitutions
651 // into the right places in toInsertInto (notice we do the
652 // substitutions in reverse order so that the offsets don't get
653 // messed up)
654 toInsertInto.insert(pos, ruleText);
655 sub2->doSubstitution(number, toInsertInto, pos);
656 sub1->doSubstitution(number, toInsertInto, pos);
657}
658
659/**
660* Formats the number, and inserts the resulting text into
661* toInsertInto.
662* @param number The number being formatted
663* @param toInsertInto The string where the resultant text should
664* be inserted
665* @param pos The position in toInsertInto where the resultant text
666* should be inserted
667*/
668void
669NFRule::doFormat(double number, UnicodeString& toInsertInto, int32_t pos) const
670{
671 // first, insert the rule's rule text into toInsertInto at the
672 // specified position, then insert the results of the substitutions
673 // into the right places in toInsertInto
674 // [again, we have two copies of this routine that do the same thing
675 // so that we don't sacrifice precision in a long by casting it
676 // to a double]
677 toInsertInto.insert(pos, ruleText);
678 sub2->doSubstitution(number, toInsertInto, pos);
679 sub1->doSubstitution(number, toInsertInto, pos);
680}
681
682/**
683* Used by the owning rule set to determine whether to invoke the
684* rollback rule (i.e., whether this rule or the one that precedes
685* it in the rule set's list should be used to format the number)
686* @param The number being formatted
687* @return True if the rule set should use the rule that precedes
688* this one in its list; false if it should use this rule
689*/
690UBool
691NFRule::shouldRollBack(double number) const
692{
693 // we roll back if the rule contains a modulus substitution,
694 // the number being formatted is an even multiple of the rule's
695 // divisor, and the rule's base value is NOT an even multiple
696 // of its divisor
697 // In other words, if the original description had
698 // 100: << hundred[ >>];
699 // that expands into
700 // 100: << hundred;
701 // 101: << hundred >>;
702 // internally. But when we're formatting 200, if we use the rule
703 // at 101, which would normally apply, we get "two hundred zero".
704 // To prevent this, we roll back and use the rule at 100 instead.
705 // This is the logic that makes this happen: the rule at 101 has
706 // a modulus substitution, its base value isn't an even multiple
707 // of 100, and the value we're trying to format _is_ an even
708 // multiple of 100. This is called the "rollback rule."
709 if ((sub1->isModulusSubstitution()) || (sub2->isModulusSubstitution())) {
710 int64_t re = util64_pow(radix, exponent);
711 return uprv_fmod(number, (double)re) == 0 && (baseValue % re) != 0;
712 }
713 return FALSE;
714}
715
716//-----------------------------------------------------------------------
717// parsing
718//-----------------------------------------------------------------------
719
720/**
721* Attempts to parse the string with this rule.
722* @param text The string being parsed
723* @param parsePosition On entry, the value is ignored and assumed to
724* be 0. On exit, this has been updated with the position of the first
725* character not consumed by matching the text against this rule
726* (if this rule doesn't match the text at all, the parse position
727* if left unchanged (presumably at 0) and the function returns
728* new Long(0)).
729* @param isFractionRule True if this rule is contained within a
730* fraction rule set. This is only used if the rule has no
731* substitutions.
732* @return If this rule matched the text, this is the rule's base value
733* combined appropriately with the results of parsing the substitutions.
734* If nothing matched, this is new Long(0) and the parse position is
735* left unchanged. The result will be an instance of Long if the
736* result is an integer and Double otherwise. The result is never null.
737*/
738#ifdef RBNF_DEBUG
739#include <stdio.h>
740
741static void dumpUS(FILE* f, const UnicodeString& us) {
742 int len = us.length();
743 char* buf = (char *)uprv_malloc((len+1)*sizeof(char)); //new char[len+1];
46f4442e
A
744 if (buf != NULL) {
745 us.extract(0, len, buf);
746 buf[len] = 0;
747 fprintf(f, "%s", buf);
748 uprv_free(buf); //delete[] buf;
749 }
b75a7d8f
A
750}
751#endif
752
753UBool
754NFRule::doParse(const UnicodeString& text,
755 ParsePosition& parsePosition,
756 UBool isFractionRule,
757 double upperBound,
729e4ab9
A
758 Formattable& resVal,
759 UBool isDecimFmtParseable) const
b75a7d8f
A
760{
761 // internally we operate on a copy of the string being parsed
762 // (because we're going to change it) and use our own ParsePosition
763 ParsePosition pp;
764 UnicodeString workText(text);
765
766 // check to see whether the text before the first substitution
767 // matches the text at the beginning of the string being
768 // parsed. If it does, strip that off the front of workText;
769 // otherwise, dump out with a mismatch
770 UnicodeString prefix;
771 prefix.setTo(ruleText, 0, sub1->getPos());
772
773#ifdef RBNF_DEBUG
774 fprintf(stderr, "doParse %x ", this);
775 {
776 UnicodeString rt;
73c04bcf 777 _appendRuleText(rt);
b75a7d8f
A
778 dumpUS(stderr, rt);
779 }
780
781 fprintf(stderr, " text: '", this);
782 dumpUS(stderr, text);
783 fprintf(stderr, "' prefix: '");
784 dumpUS(stderr, prefix);
785#endif
786 stripPrefix(workText, prefix, pp);
787 int32_t prefixLength = text.length() - workText.length();
788
789#ifdef RBNF_DEBUG
790 fprintf(stderr, "' pl: %d ppi: %d s1p: %d\n", prefixLength, pp.getIndex(), sub1->getPos());
791#endif
792
793 if (pp.getIndex() == 0 && sub1->getPos() != 0) {
794 // commented out because ParsePosition doesn't have error index in 1.1.x
795 // restored for ICU4C port
796 parsePosition.setErrorIndex(pp.getErrorIndex());
797 resVal.setLong(0);
798 return TRUE;
799 }
800
729e4ab9
A
801 // Detect when this rule's main job is to parse a decimal format and we're not
802 // supposed to.
803 if (!isDecimFmtParseable) {
804 // The following tries to detect a rule like "x.x: =#,##0.#=;"
805 if ( sub1->isDecimalFormatSubstitutionOnly() && sub2->isRuleSetSubstitutionOnly() ) {
806 parsePosition.setErrorIndex(pp.getErrorIndex());
807 resVal.setLong(0);
808 return TRUE;
809 }
810 }
811
b75a7d8f
A
812 // this is the fun part. The basic guts of the rule-matching
813 // logic is matchToDelimiter(), which is called twice. The first
814 // time it searches the input string for the rule text BETWEEN
815 // the substitutions and tries to match the intervening text
816 // in the input string with the first substitution. If that
817 // succeeds, it then calls it again, this time to look for the
818 // rule text after the second substitution and to match the
819 // intervening input text against the second substitution.
820 //
821 // For example, say we have a rule that looks like this:
822 // first << middle >> last;
823 // and input text that looks like this:
824 // first one middle two last
825 // First we use stripPrefix() to match "first " in both places and
826 // strip it off the front, leaving
827 // one middle two last
828 // Then we use matchToDelimiter() to match " middle " and try to
829 // match "one" against a substitution. If it's successful, we now
830 // have
831 // two last
832 // We use matchToDelimiter() a second time to match " last" and
833 // try to match "two" against a substitution. If "two" matches
834 // the substitution, we have a successful parse.
835 //
836 // Since it's possible in many cases to find multiple instances
837 // of each of these pieces of rule text in the input string,
838 // we need to try all the possible combinations of these
839 // locations. This prevents us from prematurely declaring a mismatch,
840 // and makes sure we match as much input text as we can.
841 int highWaterMark = 0;
842 double result = 0;
843 int start = 0;
844 double tempBaseValue = (double)(baseValue <= 0 ? 0 : baseValue);
845
846 UnicodeString temp;
847 do {
848 // our partial parse result starts out as this rule's base
849 // value. If it finds a successful match, matchToDelimiter()
850 // will compose this in some way with what it gets back from
851 // the substitution, giving us a new partial parse result
852 pp.setIndex(0);
853
854 temp.setTo(ruleText, sub1->getPos(), sub2->getPos() - sub1->getPos());
855 double partialResult = matchToDelimiter(workText, start, tempBaseValue,
856 temp, pp, sub1,
857 upperBound);
858
859 // if we got a successful match (or were trying to match a
860 // null substitution), pp is now pointing at the first unmatched
861 // character. Take note of that, and try matchToDelimiter()
862 // on the input text again
863 if (pp.getIndex() != 0 || sub1->isNullSubstitution()) {
864 start = pp.getIndex();
865
866 UnicodeString workText2;
867 workText2.setTo(workText, pp.getIndex(), workText.length() - pp.getIndex());
868 ParsePosition pp2;
869
870 // the second matchToDelimiter() will compose our previous
871 // partial result with whatever it gets back from its
872 // substitution if there's a successful match, giving us
873 // a real result
874 temp.setTo(ruleText, sub2->getPos(), ruleText.length() - sub2->getPos());
875 partialResult = matchToDelimiter(workText2, 0, partialResult,
876 temp, pp2, sub2,
877 upperBound);
878
879 // if we got a successful match on this second
880 // matchToDelimiter() call, update the high-water mark
881 // and result (if necessary)
882 if (pp2.getIndex() != 0 || sub2->isNullSubstitution()) {
883 if (prefixLength + pp.getIndex() + pp2.getIndex() > highWaterMark) {
884 highWaterMark = prefixLength + pp.getIndex() + pp2.getIndex();
885 result = partialResult;
886 }
887 }
888 // commented out because ParsePosition doesn't have error index in 1.1.x
889 // restored for ICU4C port
890 else {
891 int32_t temp = pp2.getErrorIndex() + sub1->getPos() + pp.getIndex();
892 if (temp> parsePosition.getErrorIndex()) {
893 parsePosition.setErrorIndex(temp);
894 }
895 }
896 }
897 // commented out because ParsePosition doesn't have error index in 1.1.x
898 // restored for ICU4C port
899 else {
900 int32_t temp = sub1->getPos() + pp.getErrorIndex();
901 if (temp > parsePosition.getErrorIndex()) {
902 parsePosition.setErrorIndex(temp);
903 }
904 }
905 // keep trying to match things until the outer matchToDelimiter()
906 // call fails to make a match (each time, it picks up where it
907 // left off the previous time)
908 } while (sub1->getPos() != sub2->getPos()
909 && pp.getIndex() > 0
910 && pp.getIndex() < workText.length()
911 && pp.getIndex() != start);
912
913 // update the caller's ParsePosition with our high-water mark
914 // (i.e., it now points at the first character this function
915 // didn't match-- the ParsePosition is therefore unchanged if
916 // we didn't match anything)
917 parsePosition.setIndex(highWaterMark);
918 // commented out because ParsePosition doesn't have error index in 1.1.x
919 // restored for ICU4C port
920 if (highWaterMark > 0) {
921 parsePosition.setErrorIndex(0);
922 }
923
924 // this is a hack for one unusual condition: Normally, whether this
925 // rule belong to a fraction rule set or not is handled by its
926 // substitutions. But if that rule HAS NO substitutions, then
927 // we have to account for it here. By definition, if the matching
928 // rule in a fraction rule set has no substitutions, its numerator
929 // is 1, and so the result is the reciprocal of its base value.
930 if (isFractionRule &&
931 highWaterMark > 0 &&
932 sub1->isNullSubstitution()) {
933 result = 1 / result;
934 }
935
936 resVal.setDouble(result);
937 return TRUE; // ??? do we need to worry if it is a long or a double?
938}
939
940/**
941* This function is used by parse() to match the text being parsed
942* against a possible prefix string. This function
943* matches characters from the beginning of the string being parsed
944* to characters from the prospective prefix. If they match, pp is
945* updated to the first character not matched, and the result is
946* the unparsed part of the string. If they don't match, the whole
947* string is returned, and pp is left unchanged.
948* @param text The string being parsed
949* @param prefix The text to match against
950* @param pp On entry, ignored and assumed to be 0. On exit, points
951* to the first unmatched character (assuming the whole prefix matched),
952* or is unchanged (if the whole prefix didn't match).
953* @return If things match, this is the unparsed part of "text";
954* if they didn't match, this is "text".
955*/
956void
957NFRule::stripPrefix(UnicodeString& text, const UnicodeString& prefix, ParsePosition& pp) const
958{
959 // if the prefix text is empty, dump out without doing anything
960 if (prefix.length() != 0) {
46f4442e 961 UErrorCode status = U_ZERO_ERROR;
b75a7d8f
A
962 // use prefixLength() to match the beginning of
963 // "text" against "prefix". This function returns the
964 // number of characters from "text" that matched (or 0 if
965 // we didn't match the whole prefix)
46f4442e
A
966 int32_t pfl = prefixLength(text, prefix, status);
967 if (U_FAILURE(status)) { // Memory allocation error.
968 return;
969 }
b75a7d8f
A
970 if (pfl != 0) {
971 // if we got a successful match, update the parse position
972 // and strip the prefix off of "text"
973 pp.setIndex(pp.getIndex() + pfl);
974 text.remove(0, pfl);
975 }
976 }
977}
978
979/**
980* Used by parse() to match a substitution and any following text.
981* "text" is searched for instances of "delimiter". For each instance
982* of delimiter, the intervening text is tested to see whether it
983* matches the substitution. The longest match wins.
984* @param text The string being parsed
985* @param startPos The position in "text" where we should start looking
986* for "delimiter".
987* @param baseValue A partial parse result (often the rule's base value),
988* which is combined with the result from matching the substitution
989* @param delimiter The string to search "text" for.
990* @param pp Ignored and presumed to be 0 on entry. If there's a match,
991* on exit this will point to the first unmatched character.
992* @param sub If we find "delimiter" in "text", this substitution is used
993* to match the text between the beginning of the string and the
994* position of "delimiter." (If "delimiter" is the empty string, then
995* this function just matches against this substitution and updates
996* everything accordingly.)
997* @param upperBound When matching the substitution, it will only
998* consider rules with base values lower than this value.
999* @return If there's a match, this is the result of composing
1000* baseValue with the result of matching the substitution. Otherwise,
1001* this is new Long(0). It's never null. If the result is an integer,
1002* this will be an instance of Long; otherwise, it's an instance of
1003* Double.
1004*
1005* !!! note {dlf} in point of fact, in the java code the caller always converts
1006* the result to a double, so we might as well return one.
1007*/
1008double
1009NFRule::matchToDelimiter(const UnicodeString& text,
1010 int32_t startPos,
1011 double _baseValue,
1012 const UnicodeString& delimiter,
1013 ParsePosition& pp,
1014 const NFSubstitution* sub,
1015 double upperBound) const
1016{
46f4442e 1017 UErrorCode status = U_ZERO_ERROR;
b75a7d8f
A
1018 // if "delimiter" contains real (i.e., non-ignorable) text, search
1019 // it for "delimiter" beginning at "start". If that succeeds, then
1020 // use "sub"'s doParse() method to match the text before the
1021 // instance of "delimiter" we just found.
46f4442e
A
1022 if (!allIgnorable(delimiter, status)) {
1023 if (U_FAILURE(status)) { //Memory allocation error.
1024 return 0;
1025 }
b75a7d8f
A
1026 ParsePosition tempPP;
1027 Formattable result;
1028
1029 // use findText() to search for "delimiter". It returns a two-
1030 // element array: element 0 is the position of the match, and
1031 // element 1 is the number of characters that matched
1032 // "delimiter".
1033 int32_t dLen;
1034 int32_t dPos = findText(text, delimiter, startPos, &dLen);
1035
1036 // if findText() succeeded, isolate the text preceding the
1037 // match, and use "sub" to match that text
1038 while (dPos >= 0) {
1039 UnicodeString subText;
1040 subText.setTo(text, 0, dPos);
1041 if (subText.length() > 0) {
1042 UBool success = sub->doParse(subText, tempPP, _baseValue, upperBound,
1043#if UCONFIG_NO_COLLATION
1044 FALSE,
1045#else
1046 formatter->isLenient(),
1047#endif
1048 result);
1049
1050 // if the substitution could match all the text up to
1051 // where we found "delimiter", then this function has
1052 // a successful match. Bump the caller's parse position
1053 // to point to the first character after the text
1054 // that matches "delimiter", and return the result
1055 // we got from parsing the substitution.
1056 if (success && tempPP.getIndex() == dPos) {
1057 pp.setIndex(dPos + dLen);
1058 return result.getDouble();
1059 }
1060 // commented out because ParsePosition doesn't have error index in 1.1.x
1061 // restored for ICU4C port
1062 else {
1063 if (tempPP.getErrorIndex() > 0) {
1064 pp.setErrorIndex(tempPP.getErrorIndex());
1065 } else {
1066 pp.setErrorIndex(tempPP.getIndex());
1067 }
1068 }
1069 }
1070
1071 // if we didn't match the substitution, search for another
1072 // copy of "delimiter" in "text" and repeat the loop if
1073 // we find it
1074 tempPP.setIndex(0);
1075 dPos = findText(text, delimiter, dPos + dLen, &dLen);
1076 }
1077 // if we make it here, this was an unsuccessful match, and we
1078 // leave pp unchanged and return 0
1079 pp.setIndex(0);
1080 return 0;
1081
1082 // if "delimiter" is empty, or consists only of ignorable characters
1083 // (i.e., is semantically empty), thwe we obviously can't search
1084 // for "delimiter". Instead, just use "sub" to parse as much of
1085 // "text" as possible.
1086 } else {
1087 ParsePosition tempPP;
1088 Formattable result;
1089
1090 // try to match the whole string against the substitution
1091 UBool success = sub->doParse(text, tempPP, _baseValue, upperBound,
1092#if UCONFIG_NO_COLLATION
1093 FALSE,
1094#else
1095 formatter->isLenient(),
1096#endif
1097 result);
1098 if (success && (tempPP.getIndex() != 0 || sub->isNullSubstitution())) {
1099 // if there's a successful match (or it's a null
1100 // substitution), update pp to point to the first
1101 // character we didn't match, and pass the result from
1102 // sub.doParse() on through to the caller
1103 pp.setIndex(tempPP.getIndex());
1104 return result.getDouble();
1105 }
1106 // commented out because ParsePosition doesn't have error index in 1.1.x
1107 // restored for ICU4C port
1108 else {
1109 pp.setErrorIndex(tempPP.getErrorIndex());
1110 }
1111
1112 // and if we get to here, then nothing matched, so we return
1113 // 0 and leave pp alone
1114 return 0;
1115 }
1116}
1117
1118/**
1119* Used by stripPrefix() to match characters. If lenient parse mode
1120* is off, this just calls startsWith(). If lenient parse mode is on,
1121* this function uses CollationElementIterators to match characters in
1122* the strings (only primary-order differences are significant in
1123* determining whether there's a match).
1124* @param str The string being tested
1125* @param prefix The text we're hoping to see at the beginning
1126* of "str"
1127* @return If "prefix" is found at the beginning of "str", this
1128* is the number of characters in "str" that were matched (this
1129* isn't necessarily the same as the length of "prefix" when matching
1130* text with a collator). If there's no match, this is 0.
1131*/
1132int32_t
46f4442e 1133NFRule::prefixLength(const UnicodeString& str, const UnicodeString& prefix, UErrorCode& status) const
b75a7d8f
A
1134{
1135 // if we're looking for an empty prefix, it obviously matches
1136 // zero characters. Just go ahead and return 0.
1137 if (prefix.length() == 0) {
1138 return 0;
1139 }
1140
1141#if !UCONFIG_NO_COLLATION
1142 // go through all this grief if we're in lenient-parse mode
1143 if (formatter->isLenient()) {
1144 // get the formatter's collator and use it to create two
1145 // collation element iterators, one over the target string
1146 // and another over the prefix (right now, we'll throw an
1147 // exception if the collator we get back from the formatter
1148 // isn't a RuleBasedCollator, because RuleBasedCollator defines
1149 // the CollationElementIterator protocol. Hopefully, this
1150 // will change someday.)
1151 RuleBasedCollator* collator = (RuleBasedCollator*)formatter->getCollator();
1152 CollationElementIterator* strIter = collator->createCollationElementIterator(str);
1153 CollationElementIterator* prefixIter = collator->createCollationElementIterator(prefix);
46f4442e
A
1154 // Check for memory allocation error.
1155 if (collator == NULL || strIter == NULL || prefixIter == NULL) {
1156 delete collator;
1157 delete strIter;
1158 delete prefixIter;
1159 status = U_MEMORY_ALLOCATION_ERROR;
1160 return 0;
1161 }
b75a7d8f
A
1162
1163 UErrorCode err = U_ZERO_ERROR;
1164
1165 // The original code was problematic. Consider this match:
1166 // prefix = "fifty-"
1167 // string = " fifty-7"
1168 // The intent is to match string up to the '7', by matching 'fifty-' at position 1
1169 // in the string. Unfortunately, we were getting a match, and then computing where
1170 // the match terminated by rematching the string. The rematch code was using as an
1171 // initial guess the substring of string between 0 and prefix.length. Because of
1172 // the leading space and trailing hyphen (both ignorable) this was succeeding, leaving
1173 // the position before the hyphen in the string. Recursing down, we then parsed the
1174 // remaining string '-7' as numeric. The resulting number turned out as 43 (50 - 7).
1175 // This was not pretty, especially since the string "fifty-7" parsed just fine.
1176 //
1177 // We have newer APIs now, so we can use calls on the iterator to determine what we
1178 // matched up to. If we terminate because we hit the last element in the string,
1179 // our match terminates at this length. If we terminate because we hit the last element
1180 // in the target, our match terminates at one before the element iterator position.
1181
1182 // match collation elements between the strings
1183 int32_t oStr = strIter->next(err);
1184 int32_t oPrefix = prefixIter->next(err);
1185
1186 while (oPrefix != CollationElementIterator::NULLORDER) {
1187 // skip over ignorable characters in the target string
1188 while (CollationElementIterator::primaryOrder(oStr) == 0
1189 && oStr != CollationElementIterator::NULLORDER) {
1190 oStr = strIter->next(err);
1191 }
1192
1193 // skip over ignorable characters in the prefix
1194 while (CollationElementIterator::primaryOrder(oPrefix) == 0
1195 && oPrefix != CollationElementIterator::NULLORDER) {
1196 oPrefix = prefixIter->next(err);
1197 }
1198
1199 // dlf: move this above following test, if we consume the
1200 // entire target, aren't we ok even if the source was also
1201 // entirely consumed?
1202
1203 // if skipping over ignorables brought to the end of
1204 // the prefix, we DID match: drop out of the loop
1205 if (oPrefix == CollationElementIterator::NULLORDER) {
1206 break;
1207 }
1208
1209 // if skipping over ignorables brought us to the end
1210 // of the target string, we didn't match and return 0
1211 if (oStr == CollationElementIterator::NULLORDER) {
1212 delete prefixIter;
1213 delete strIter;
1214 return 0;
1215 }
1216
1217 // match collation elements from the two strings
1218 // (considering only primary differences). If we
1219 // get a mismatch, dump out and return 0
1220 if (CollationElementIterator::primaryOrder(oStr)
1221 != CollationElementIterator::primaryOrder(oPrefix)) {
1222 delete prefixIter;
1223 delete strIter;
1224 return 0;
1225
1226 // otherwise, advance to the next character in each string
1227 // and loop (we drop out of the loop when we exhaust
1228 // collation elements in the prefix)
1229 } else {
1230 oStr = strIter->next(err);
1231 oPrefix = prefixIter->next(err);
1232 }
1233 }
1234
1235 int32_t result = strIter->getOffset();
1236 if (oStr != CollationElementIterator::NULLORDER) {
1237 --result; // back over character that we don't want to consume;
1238 }
1239
1240#ifdef RBNF_DEBUG
1241 fprintf(stderr, "prefix length: %d\n", result);
1242#endif
1243 delete prefixIter;
1244 delete strIter;
1245
1246 return result;
1247#if 0
1248 //----------------------------------------------------------------
1249 // JDK 1.2-specific API call
1250 // return strIter.getOffset();
1251 //----------------------------------------------------------------
1252 // JDK 1.1 HACK (take out for 1.2-specific code)
1253
1254 // if we make it to here, we have a successful match. Now we
1255 // have to find out HOW MANY characters from the target string
1256 // matched the prefix (there isn't necessarily a one-to-one
1257 // mapping between collation elements and characters).
1258 // In JDK 1.2, there's a simple getOffset() call we can use.
1259 // In JDK 1.1, on the other hand, we have to go through some
1260 // ugly contortions. First, use the collator to compare the
1261 // same number of characters from the prefix and target string.
1262 // If they're equal, we're done.
1263 collator->setStrength(Collator::PRIMARY);
1264 if (str.length() >= prefix.length()) {
1265 UnicodeString temp;
1266 temp.setTo(str, 0, prefix.length());
1267 if (collator->equals(temp, prefix)) {
1268#ifdef RBNF_DEBUG
1269 fprintf(stderr, "returning: %d\n", prefix.length());
1270#endif
1271 return prefix.length();
1272 }
1273 }
1274
1275 // if they're not equal, then we have to compare successively
1276 // larger and larger substrings of the target string until we
1277 // get to one that matches the prefix. At that point, we know
1278 // how many characters matched the prefix, and we can return.
1279 int32_t p = 1;
1280 while (p <= str.length()) {
1281 UnicodeString temp;
1282 temp.setTo(str, 0, p);
1283 if (collator->equals(temp, prefix)) {
1284 return p;
1285 } else {
1286 ++p;
1287 }
1288 }
1289
1290 // SHOULD NEVER GET HERE!!!
1291 return 0;
1292 //----------------------------------------------------------------
1293#endif
1294
1295 // If lenient parsing is turned off, forget all that crap above.
1296 // Just use String.startsWith() and be done with it.
1297 } else
1298#endif
1299 {
1300 if (str.startsWith(prefix)) {
1301 return prefix.length();
1302 } else {
1303 return 0;
1304 }
1305 }
1306}
1307
1308/**
1309* Searches a string for another string. If lenient parsing is off,
1310* this just calls indexOf(). If lenient parsing is on, this function
1311* uses CollationElementIterator to match characters, and only
1312* primary-order differences are significant in determining whether
1313* there's a match.
1314* @param str The string to search
1315* @param key The string to search "str" for
1316* @param startingAt The index into "str" where the search is to
1317* begin
1318* @return A two-element array of ints. Element 0 is the position
1319* of the match, or -1 if there was no match. Element 1 is the
1320* number of characters in "str" that matched (which isn't necessarily
1321* the same as the length of "key")
1322*/
1323int32_t
1324NFRule::findText(const UnicodeString& str,
1325 const UnicodeString& key,
1326 int32_t startingAt,
1327 int32_t* length) const
1328{
1329#if !UCONFIG_NO_COLLATION
1330 // if lenient parsing is turned off, this is easy: just call
1331 // String.indexOf() and we're done
1332 if (!formatter->isLenient()) {
1333 *length = key.length();
1334 return str.indexOf(key, startingAt);
1335
1336 // but if lenient parsing is turned ON, we've got some work
1337 // ahead of us
1338 } else
1339#endif
1340 {
1341 //----------------------------------------------------------------
1342 // JDK 1.1 HACK (take out of 1.2-specific code)
1343
1344 // in JDK 1.2, CollationElementIterator provides us with an
1345 // API to map between character offsets and collation elements
1346 // and we can do this by marching through the string comparing
1347 // collation elements. We can't do that in JDK 1.1. Insted,
1348 // we have to go through this horrible slow mess:
1349 int32_t p = startingAt;
1350 int32_t keyLen = 0;
1351
1352 // basically just isolate smaller and smaller substrings of
1353 // the target string (each running to the end of the string,
1354 // and with the first one running from startingAt to the end)
1355 // and then use prefixLength() to see if the search key is at
1356 // the beginning of each substring. This is excruciatingly
1357 // slow, but it will locate the key and tell use how long the
1358 // matching text was.
1359 UnicodeString temp;
46f4442e 1360 UErrorCode status = U_ZERO_ERROR;
b75a7d8f
A
1361 while (p < str.length() && keyLen == 0) {
1362 temp.setTo(str, p, str.length() - p);
46f4442e
A
1363 keyLen = prefixLength(temp, key, status);
1364 if (U_FAILURE(status)) {
1365 break;
1366 }
b75a7d8f
A
1367 if (keyLen != 0) {
1368 *length = keyLen;
1369 return p;
1370 }
1371 ++p;
1372 }
1373 // if we make it to here, we didn't find it. Return -1 for the
1374 // location. The length should be ignored, but set it to 0,
1375 // which should be "safe"
1376 *length = 0;
1377 return -1;
1378
1379 //----------------------------------------------------------------
1380 // JDK 1.2 version of this routine
1381 //RuleBasedCollator collator = (RuleBasedCollator)formatter.getCollator();
1382 //
1383 //CollationElementIterator strIter = collator.getCollationElementIterator(str);
1384 //CollationElementIterator keyIter = collator.getCollationElementIterator(key);
1385 //
1386 //int keyStart = -1;
1387 //
1388 //str.setOffset(startingAt);
1389 //
1390 //int oStr = strIter.next();
1391 //int oKey = keyIter.next();
1392 //while (oKey != CollationElementIterator.NULLORDER) {
1393 // while (oStr != CollationElementIterator.NULLORDER &&
1394 // CollationElementIterator.primaryOrder(oStr) == 0)
1395 // oStr = strIter.next();
1396 //
1397 // while (oKey != CollationElementIterator.NULLORDER &&
1398 // CollationElementIterator.primaryOrder(oKey) == 0)
1399 // oKey = keyIter.next();
1400 //
1401 // if (oStr == CollationElementIterator.NULLORDER) {
1402 // return new int[] { -1, 0 };
1403 // }
1404 //
1405 // if (oKey == CollationElementIterator.NULLORDER) {
1406 // break;
1407 // }
1408 //
1409 // if (CollationElementIterator.primaryOrder(oStr) ==
1410 // CollationElementIterator.primaryOrder(oKey)) {
1411 // keyStart = strIter.getOffset();
1412 // oStr = strIter.next();
1413 // oKey = keyIter.next();
1414 // } else {
1415 // if (keyStart != -1) {
1416 // keyStart = -1;
1417 // keyIter.reset();
1418 // } else {
1419 // oStr = strIter.next();
1420 // }
1421 // }
1422 //}
1423 //
1424 //if (oKey == CollationElementIterator.NULLORDER) {
1425 // return new int[] { keyStart, strIter.getOffset() - keyStart };
1426 //} else {
1427 // return new int[] { -1, 0 };
1428 //}
1429 }
1430}
1431
1432/**
1433* Checks to see whether a string consists entirely of ignorable
1434* characters.
1435* @param str The string to test.
1436* @return true if the string is empty of consists entirely of
1437* characters that the number formatter's collator says are
1438* ignorable at the primary-order level. false otherwise.
1439*/
1440UBool
46f4442e 1441NFRule::allIgnorable(const UnicodeString& str, UErrorCode& status) const
b75a7d8f
A
1442{
1443 // if the string is empty, we can just return true
1444 if (str.length() == 0) {
1445 return TRUE;
1446 }
1447
1448#if !UCONFIG_NO_COLLATION
1449 // if lenient parsing is turned on, walk through the string with
1450 // a collation element iterator and make sure each collation
1451 // element is 0 (ignorable) at the primary level
1452 if (formatter->isLenient()) {
1453 RuleBasedCollator* collator = (RuleBasedCollator*)(formatter->getCollator());
1454 CollationElementIterator* iter = collator->createCollationElementIterator(str);
46f4442e
A
1455
1456 // Memory allocation error check.
1457 if (collator == NULL || iter == NULL) {
1458 delete collator;
1459 delete iter;
1460 status = U_MEMORY_ALLOCATION_ERROR;
1461 return FALSE;
1462 }
b75a7d8f
A
1463
1464 UErrorCode err = U_ZERO_ERROR;
1465 int32_t o = iter->next(err);
1466 while (o != CollationElementIterator::NULLORDER
1467 && CollationElementIterator::primaryOrder(o) == 0) {
1468 o = iter->next(err);
1469 }
1470
1471 delete iter;
1472 return o == CollationElementIterator::NULLORDER;
1473 }
1474#endif
1475
1476 // if lenient parsing is turned off, there is no such thing as
1477 // an ignorable character: return true only if the string is empty
1478 return FALSE;
1479}
1480
1481U_NAMESPACE_END
1482
1483/* U_HAVE_RBNF */
1484#endif
1485
1486