1 // © 2016 and later: Unicode, Inc. and others.
2 // License & terms of use: http://www.unicode.org/copyright.html
4 ********************************************************************************
5 * Copyright (C) 1997-2013, International Business Machines
6 * Corporation and others. All Rights Reserved.
7 ********************************************************************************
11 * Modification History:
13 * Date Name Description
14 * 02/19/97 aliu Converted from java.
15 * 03/20/97 helena Finished first cut of implementation and got rid
16 * of nextDouble/previousDouble and replaced with
18 * 4/10/97 aliu Clean up. Modified to work on AIX.
19 * 8/6/97 nos Removed overloaded constructor, member var 'buffer'.
20 * 07/22/98 stephen Removed operator!= (implemented in Format)
21 ********************************************************************************
27 #include "unicode/utypes.h"
31 * \brief C++ API: Choice Format.
34 #if !UCONFIG_NO_FORMATTING
35 #ifndef U_HIDE_DEPRECATED_API
37 #include "unicode/fieldpos.h"
38 #include "unicode/format.h"
39 #include "unicode/messagepattern.h"
40 #include "unicode/numfmt.h"
41 #include "unicode/unistr.h"
43 #if U_SHOW_CPLUSPLUS_API
49 * ChoiceFormat converts between ranges of numeric values and strings for those ranges.
50 * The strings must conform to the MessageFormat pattern syntax.
52 * <p><em><code>ChoiceFormat</code> is probably not what you need.
53 * Please use <code>MessageFormat</code>
54 * with <code>plural</code> arguments for proper plural selection,
55 * and <code>select</code> arguments for simple selection among a fixed set of choices!</em></p>
57 * <p>A <code>ChoiceFormat</code> splits
58 * the real number line \htmlonly<code>-∞</code> to
59 * <code>+∞</code>\endhtmlonly into two
60 * or more contiguous ranges. Each range is mapped to a
63 * <p><code>ChoiceFormat</code> was originally intended
64 * for displaying grammatically correct
65 * plurals such as "There is one file." vs. "There are 2 files."
66 * <em>However,</em> plural rules for many languages
67 * are too complex for the capabilities of ChoiceFormat,
68 * and its requirement of specifying the precise rules for each message
69 * is unmanageable for translators.</p>
71 * <p>There are two methods of defining a <code>ChoiceFormat</code>; both
72 * are equivalent. The first is by using a string pattern. This is the
73 * preferred method in most cases. The second method is through direct
74 * specification of the arrays that logically make up the
75 * <code>ChoiceFormat</code>.</p>
77 * <p>Note: Typically, choice formatting is done (if done at all) via <code>MessageFormat</code>
78 * with a <code>choice</code> argument type,
79 * rather than using a stand-alone <code>ChoiceFormat</code>.</p>
81 * <h5>Patterns and Their Interpretation</h5>
83 * <p>The pattern string defines the range boundaries and the strings for each number range.
86 * choiceStyle = number separator message ('|' number separator message)*
87 * number = normal_number | ['-'] \htmlonly∞\endhtmlonly (U+221E, infinity)
88 * normal_number = double value (unlocalized ASCII string)
89 * separator = less_than | less_than_or_equal
91 * less_than_or_equal = '#' | \htmlonly≤\endhtmlonly (U+2264)
92 * message: see {@link MessageFormat}
94 * Pattern_White_Space between syntax elements is ignored, except
95 * around each range's sub-message.</p>
97 * <p>Each numeric sub-range extends from the current range's number
98 * to the next range's number.
99 * The number itself is included in its range if a <code>less_than_or_equal</code> sign is used,
100 * and excluded from its range (and instead included in the previous range)
101 * if a <code>less_than</code> sign is used.</p>
103 * <p>When a <code>ChoiceFormat</code> is constructed from
104 * arrays of numbers, closure flags and strings,
105 * they are interpreted just like
106 * the sequence of <code>(number separator string)</code> in an equivalent pattern string.
107 * <code>closure[i]==TRUE</code> corresponds to a <code>less_than</code> separator sign.
108 * The equivalent pattern string will be constructed automatically.</p>
110 * <p>During formatting, a number is mapped to the first range
111 * where the number is not greater than the range's upper limit.
112 * That range's message string is returned. A NaN maps to the very first range.</p>
114 * <p>During parsing, a range is selected for the longest match of
115 * any range's message. That range's number is returned, ignoring the separator/closure.
116 * Only a simple string match is performed, without parsing of arguments that
117 * might be specified in the message strings.</p>
119 * <p>Note that the first range's number is ignored in formatting
120 * but may be returned from parsing.</p>
124 * <p>Here is an example of two arrays that map the number
125 * <code>1..7</code> to the English day of the week abbreviations
126 * <code>Sun..Sat</code>. No closures array is given; this is the same as
127 * specifying all closures to be <code>FALSE</code>.</p>
129 * <pre> {1,2,3,4,5,6,7},
130 * {"Sun","Mon","Tue","Wed","Thur","Fri","Sat"}</pre>
132 * <p>Here is an example that maps the ranges [-Inf, 1), [1, 1], and (1,
133 * +Inf] to three strings. That is, the number line is split into three
134 * ranges: x < 1.0, x = 1.0, and x > 1.0.
135 * (The round parentheses in the notation above indicate an exclusive boundary,
136 * like the turned bracket in European notation: [-Inf, 1) == [-Inf, 1[ )</p>
139 * {FALSE, FALSE, TRUE},
140 * {"no files", "one file", "many files"}</pre>
142 * <p>Here is an example that shows formatting and parsing: </p>
145 * #include <unicode/choicfmt.h>
146 * #include <unicode/unistr.h>
147 * #include <iostream.h>
149 * int main(int argc, char *argv[]) {
150 * double limits[] = {1,2,3,4,5,6,7};
151 * UnicodeString monthNames[] = {
152 * "Sun","Mon","Tue","Wed","Thu","Fri","Sat"};
153 * ChoiceFormat fmt(limits, monthNames, 7);
156 * for (double x = 1.0; x <= 8.0; x += 1.0) {
157 * fmt.format(x, str);
158 * str.extract(0, str.length(), buf, 256, "");
160 * cout << x << " -> "
168 * <p><em>User subclasses are not supported.</em> While clients may write
169 * subclasses, such code will not necessarily work and will not be
170 * guaranteed to work stably from release to release.
172 * @deprecated ICU 49 Use MessageFormat instead, with plural and select arguments.
174 class U_I18N_API ChoiceFormat
: public NumberFormat
{
177 * Constructs a new ChoiceFormat from the pattern string.
179 * @param pattern Pattern used to construct object.
180 * @param status Output param to receive success code. If the
181 * pattern cannot be parsed, set to failure code.
182 * @deprecated ICU 49 Use MessageFormat instead, with plural and select arguments.
184 ChoiceFormat(const UnicodeString
& pattern
,
189 * Constructs a new ChoiceFormat with the given limits and message strings.
190 * All closure flags default to <code>FALSE</code>,
191 * equivalent to <code>less_than_or_equal</code> separators.
193 * Copies the limits and formats instead of adopting them.
195 * @param limits Array of limit values.
196 * @param formats Array of formats.
197 * @param count Size of 'limits' and 'formats' arrays.
198 * @deprecated ICU 49 Use MessageFormat instead, with plural and select arguments.
200 ChoiceFormat(const double* limits
,
201 const UnicodeString
* formats
,
205 * Constructs a new ChoiceFormat with the given limits, closure flags and message strings.
207 * Copies the limits and formats instead of adopting them.
209 * @param limits Array of limit values
210 * @param closures Array of booleans specifying whether each
211 * element of 'limits' is open or closed. If FALSE, then the
212 * corresponding limit number is a member of its range.
213 * If TRUE, then the limit number belongs to the previous range it.
214 * @param formats Array of formats
215 * @param count Size of 'limits', 'closures', and 'formats' arrays
216 * @deprecated ICU 49 Use MessageFormat instead, with plural and select arguments.
218 ChoiceFormat(const double* limits
,
219 const UBool
* closures
,
220 const UnicodeString
* formats
,
226 * @param that ChoiceFormat object to be copied from
227 * @deprecated ICU 49 Use MessageFormat instead, with plural and select arguments.
229 ChoiceFormat(const ChoiceFormat
& that
);
232 * Assignment operator.
234 * @param that ChoiceFormat object to be copied
235 * @deprecated ICU 49 Use MessageFormat instead, with plural and select arguments.
237 const ChoiceFormat
& operator=(const ChoiceFormat
& that
);
241 * @deprecated ICU 49 Use MessageFormat instead, with plural and select arguments.
243 virtual ~ChoiceFormat();
246 * Clones this Format object. The caller owns the
247 * result and must delete it when done.
249 * @return a copy of this object
250 * @deprecated ICU 49 Use MessageFormat instead, with plural and select arguments.
252 virtual Format
* clone(void) const;
255 * Returns true if the given Format objects are semantically equal.
256 * Objects of different subclasses are considered unequal.
258 * @param other ChoiceFormat object to be compared
259 * @return true if other is the same as this.
260 * @deprecated ICU 49 Use MessageFormat instead, with plural and select arguments.
262 virtual UBool
operator==(const Format
& other
) const;
266 * @param pattern The pattern to be applied.
267 * @param status Output param set to success/failure code on
268 * exit. If the pattern is invalid, this will be
269 * set to a failure result.
270 * @deprecated ICU 49 Use MessageFormat instead, with plural and select arguments.
272 virtual void applyPattern(const UnicodeString
& pattern
,
277 * @param pattern The pattern to be applied.
278 * @param parseError Struct to receive information on position
279 * of error if an error is encountered
280 * @param status Output param set to success/failure code on
281 * exit. If the pattern is invalid, this will be
282 * set to a failure result.
283 * @deprecated ICU 49 Use MessageFormat instead, with plural and select arguments.
285 virtual void applyPattern(const UnicodeString
& pattern
,
286 UParseError
& parseError
,
291 * @param pattern Output param which will receive the pattern
292 * Previous contents are deleted.
293 * @return A reference to 'pattern'
294 * @deprecated ICU 49 Use MessageFormat instead, with plural and select arguments.
296 virtual UnicodeString
& toPattern(UnicodeString
&pattern
) const;
299 * Sets the choices to be used in formatting.
300 * For details see the constructor with the same parameter list.
302 * @param limitsToCopy Contains the top value that you want
303 * parsed with that format,and should be in
304 * ascending sorted order. When formatting X,
305 * the choice will be the i, where limit[i]
306 * <= X < limit[i+1].
307 * @param formatsToCopy The format strings you want to use for each limit.
308 * @param count The size of the above arrays.
309 * @deprecated ICU 49 Use MessageFormat instead, with plural and select arguments.
311 virtual void setChoices(const double* limitsToCopy
,
312 const UnicodeString
* formatsToCopy
,
316 * Sets the choices to be used in formatting.
317 * For details see the constructor with the same parameter list.
319 * @param limits Array of limits
320 * @param closures Array of limit booleans
321 * @param formats Array of format string
322 * @param count The size of the above arrays
323 * @deprecated ICU 49 Use MessageFormat instead, with plural and select arguments.
325 virtual void setChoices(const double* limits
,
326 const UBool
* closures
,
327 const UnicodeString
* formats
,
331 * Returns NULL and 0.
332 * Before ICU 4.8, this used to return the choice limits array.
334 * @param count Will be set to 0.
336 * @deprecated ICU 4.8 Use the MessagePattern class to analyze a ChoiceFormat pattern.
338 virtual const double* getLimits(int32_t& count
) const;
341 * Returns NULL and 0.
342 * Before ICU 4.8, this used to return the limit booleans array.
344 * @param count Will be set to 0.
346 * @deprecated ICU 4.8 Use the MessagePattern class to analyze a ChoiceFormat pattern.
348 virtual const UBool
* getClosures(int32_t& count
) const;
351 * Returns NULL and 0.
352 * Before ICU 4.8, this used to return the array of choice strings.
354 * @param count Will be set to 0.
356 * @deprecated ICU 4.8 Use the MessagePattern class to analyze a ChoiceFormat pattern.
358 virtual const UnicodeString
* getFormats(int32_t& count
) const;
361 using NumberFormat::format
;
364 * Formats a double number using this object's choices.
366 * @param number The value to be formatted.
367 * @param appendTo Output parameter to receive result.
368 * Result is appended to existing contents.
369 * @param pos On input: an alignment field, if desired.
370 * On output: the offsets of the alignment field.
371 * @return Reference to 'appendTo' parameter.
372 * @deprecated ICU 49 Use MessageFormat instead, with plural and select arguments.
374 virtual UnicodeString
& format(double number
,
375 UnicodeString
& appendTo
,
376 FieldPosition
& pos
) const;
378 * Formats an int32_t number using this object's choices.
380 * @param number The value to be formatted.
381 * @param appendTo Output parameter to receive result.
382 * Result is appended to existing contents.
383 * @param pos On input: an alignment field, if desired.
384 * On output: the offsets of the alignment field.
385 * @return Reference to 'appendTo' parameter.
386 * @deprecated ICU 49 Use MessageFormat instead, with plural and select arguments.
388 virtual UnicodeString
& format(int32_t number
,
389 UnicodeString
& appendTo
,
390 FieldPosition
& pos
) const;
393 * Formats an int64_t number using this object's choices.
395 * @param number The value to be formatted.
396 * @param appendTo Output parameter to receive result.
397 * Result is appended to existing contents.
398 * @param pos On input: an alignment field, if desired.
399 * On output: the offsets of the alignment field.
400 * @return Reference to 'appendTo' parameter.
401 * @deprecated ICU 49 Use MessageFormat instead, with plural and select arguments.
403 virtual UnicodeString
& format(int64_t number
,
404 UnicodeString
& appendTo
,
405 FieldPosition
& pos
) const;
408 * Formats an array of objects using this object's choices.
410 * @param objs The array of objects to be formatted.
411 * @param cnt The size of objs.
412 * @param appendTo Output parameter to receive result.
413 * Result is appended to existing contents.
414 * @param pos On input: an alignment field, if desired.
415 * On output: the offsets of the alignment field.
416 * @param success Output param set to success/failure code on
418 * @return Reference to 'appendTo' parameter.
419 * @deprecated ICU 49 Use MessageFormat instead, with plural and select arguments.
421 virtual UnicodeString
& format(const Formattable
* objs
,
423 UnicodeString
& appendTo
,
425 UErrorCode
& success
) const;
427 using NumberFormat::parse
;
430 * Looks for the longest match of any message string on the input text and,
431 * if there is a match, sets the result object to the corresponding range's number.
433 * If no string matches, then the parsePosition is unchanged.
435 * @param text The text to be parsed.
436 * @param result Formattable to be set to the parse result.
437 * If parse fails, return contents are undefined.
438 * @param parsePosition The position to start parsing at on input.
439 * On output, moved to after the last successfully
440 * parse character. On parse failure, does not change.
441 * @deprecated ICU 49 Use MessageFormat instead, with plural and select arguments.
443 virtual void parse(const UnicodeString
& text
,
445 ParsePosition
& parsePosition
) const;
448 * Returns a unique class ID POLYMORPHICALLY. Part of ICU's "poor man's RTTI".
450 * @return The class ID for this object. All objects of a
451 * given class have the same class ID. Objects of
452 * other classes have different class IDs.
453 * @deprecated ICU 49 Use MessageFormat instead, with plural and select arguments.
455 virtual UClassID
getDynamicClassID(void) const;
458 * Returns the class ID for this class. This is useful only for
459 * comparing to a return value from getDynamicClassID(). For example:
461 * . Base* polymorphic_pointer = createPolymorphicObject();
462 * . if (polymorphic_pointer->getDynamicClassID() ==
463 * . Derived::getStaticClassID()) ...
465 * @return The class ID for all objects of this class.
466 * @deprecated ICU 49 Use MessageFormat instead, with plural and select arguments.
468 static UClassID U_EXPORT2
getStaticClassID(void);
472 * Converts a double value to a string.
473 * @param value the double number to be converted.
474 * @param string the result string.
475 * @return the converted string.
477 static UnicodeString
& dtos(double value
, UnicodeString
& string
);
479 ChoiceFormat(); // default constructor not implemented
482 * Construct a new ChoiceFormat with the limits and the corresponding formats
483 * based on the pattern.
485 * @param newPattern Pattern used to construct object.
486 * @param parseError Struct to receive information on position
487 * of error if an error is encountered.
488 * @param status Output param to receive success code. If the
489 * pattern cannot be parsed, set to failure code.
491 ChoiceFormat(const UnicodeString
& newPattern
,
492 UParseError
& parseError
,
495 friend class MessageFormat
;
497 virtual void setChoices(const double* limits
,
498 const UBool
* closures
,
499 const UnicodeString
* formats
,
501 UErrorCode
&errorCode
);
504 * Finds the ChoiceFormat sub-message for the given number.
505 * @param pattern A MessagePattern.
506 * @param partIndex the index of the first ChoiceFormat argument style part.
507 * @param number a number to be mapped to one of the ChoiceFormat argument's intervals
508 * @return the sub-message start part index.
510 static int32_t findSubMessage(const MessagePattern
&pattern
, int32_t partIndex
, double number
);
512 static double parseArgument(
513 const MessagePattern
&pattern
, int32_t partIndex
,
514 const UnicodeString
&source
, ParsePosition
&pos
);
517 * Matches the pattern string from the end of the partIndex to
518 * the beginning of the limitPartIndex,
519 * including all syntax except SKIP_SYNTAX,
520 * against the source string starting at sourceOffset.
521 * If they match, returns the length of the source string match.
522 * Otherwise returns -1.
524 static int32_t matchStringUntilLimitPart(
525 const MessagePattern
&pattern
, int32_t partIndex
, int32_t limitPartIndex
,
526 const UnicodeString
&source
, int32_t sourceOffset
);
529 * Some of the ChoiceFormat constructors do not have a UErrorCode paramater.
530 * We need _some_ way to provide one for the MessagePattern constructor.
531 * Alternatively, the MessagePattern could be a pointer field, but that is
534 UErrorCode constructorErrorCode
;
537 * The MessagePattern which contains the parsed structure of the pattern string.
539 * Starting with ICU 4.8, the MessagePattern contains a sequence of
540 * numeric/selector/message parts corresponding to the parsed pattern.
541 * For details see the MessagePattern class API docs.
543 MessagePattern msgPattern
;
546 * Docs & fields from before ICU 4.8, before MessagePattern was used.
547 * Commented out, and left only for explanation of semantics.
549 * Each ChoiceFormat divides the range -Inf..+Inf into fCount
550 * intervals. The intervals are:
552 * 0: fChoiceLimits[0]..fChoiceLimits[1]
553 * 1: fChoiceLimits[1]..fChoiceLimits[2]
555 * fCount-2: fChoiceLimits[fCount-2]..fChoiceLimits[fCount-1]
556 * fCount-1: fChoiceLimits[fCount-1]..+Inf
558 * Interval 0 is special; during formatting (mapping numbers to
559 * strings), it also contains all numbers less than
560 * fChoiceLimits[0], as well as NaN values.
562 * Interval i maps to and from string fChoiceFormats[i]. When
563 * parsing (mapping strings to numbers), then intervals map to
564 * their lower limit, that is, interval i maps to fChoiceLimit[i].
566 * The intervals may be closed, half open, or open. This affects
567 * formatting but does not affect parsing. Interval i is affected
568 * by fClosures[i] and fClosures[i+1]. If fClosures[i]
569 * is FALSE, then the value fChoiceLimits[i] is in interval i.
570 * That is, intervals i and i are:
572 * i-1: ... x < fChoiceLimits[i]
573 * i: fChoiceLimits[i] <= x ...
575 * If fClosures[i] is TRUE, then the value fChoiceLimits[i] is
576 * in interval i-1. That is, intervals i-1 and i are:
578 * i-1: ... x <= fChoiceLimits[i]
579 * i: fChoiceLimits[i] < x ...
581 * Because of the nature of interval 0, fClosures[0] has no
584 // double* fChoiceLimits;
586 // UnicodeString* fChoiceFormats;
592 #endif // U_SHOW_CPLUSPLUS_API
594 #endif // U_HIDE_DEPRECATED_API
595 #endif /* #if !UCONFIG_NO_FORMATTING */