Upload Kmake

This commit is contained in:
Gorochu
2026-05-26 23:36:42 -07:00
parent ba051b2f74
commit 555ec72358
41615 changed files with 13344630 additions and 1 deletions

View File

@ -0,0 +1,766 @@
// © 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
/*
*******************************************************************************
*
* Copyright (C) 2011-2014 International Business Machines
* Corporation and others. All Rights Reserved.
*
*******************************************************************************
*/
#ifndef INDEXCHARS_H
#define INDEXCHARS_H
#include "unicode/utypes.h"
#if U_SHOW_CPLUSPLUS_API
#include "unicode/uobject.h"
#include "unicode/locid.h"
#include "unicode/unistr.h"
#if !UCONFIG_NO_COLLATION
/**
* \file
* \brief C++ API: Index Characters
*/
U_CDECL_BEGIN
/**
* Constants for Alphabetic Index Label Types.
* The form of these enum constants anticipates having a plain C API
* for Alphabetic Indexes that will also use them.
* @stable ICU 4.8
*/
typedef enum UAlphabeticIndexLabelType {
/**
* Normal Label, typically the starting letter of the names
* in the bucket with this label.
* @stable ICU 4.8
*/
U_ALPHAINDEX_NORMAL = 0,
/**
* Underflow Label. The bucket with this label contains names
* in scripts that sort before any of the bucket labels in this index.
* @stable ICU 4.8
*/
U_ALPHAINDEX_UNDERFLOW = 1,
/**
* Inflow Label. The bucket with this label contains names
* in scripts that sort between two of the bucket labels in this index.
* Inflow labels are created when an index contains normal labels for
* multiple scripts, and skips other scripts that sort between some of the
* included scripts.
* @stable ICU 4.8
*/
U_ALPHAINDEX_INFLOW = 2,
/**
* Overflow Label. The bucket with this label contains names in scripts
* that sort after all of the bucket labels in this index.
* @stable ICU 4.8
*/
U_ALPHAINDEX_OVERFLOW = 3
} UAlphabeticIndexLabelType;
struct UHashtable;
U_CDECL_END
U_NAMESPACE_BEGIN
// Forward Declarations
class BucketList;
class Collator;
class RuleBasedCollator;
class StringEnumeration;
class UnicodeSet;
class UVector;
/**
* AlphabeticIndex supports the creation of a UI index appropriate for a given language.
* It can support either direct use, or use with a client that doesn't support localized collation.
* The following is an example of what an index might look like in a UI:
*
* <pre>
* <b>... A B C D E F G H I J K L M N O P Q R S T U V W X Y Z ...</b>
*
* <b>A</b>
* Addison
* Albertson
* Azensky
* <b>B</b>
* Baker
* ...
* </pre>
*
* The class can generate a list of labels for use as a UI "index", that is, a list of
* clickable characters (or character sequences) that allow the user to see a segment
* (bucket) of a larger "target" list. That is, each label corresponds to a bucket in
* the target list, where everything in the bucket is greater than or equal to the character
* (according to the locale's collation). Strings can be added to the index;
* they will be in sorted order in the right bucket.
* <p>
* The class also supports having buckets for strings before the first (underflow),
* after the last (overflow), and between scripts (inflow). For example, if the index
* is constructed with labels for Russian and English, Greek characters would fall
* into an inflow bucket between the other two scripts.
* <p>
* The AlphabeticIndex class is not intended for public subclassing.
*
* <p><em>Note:</em> If you expect to have a lot of ASCII or Latin characters
* as well as characters from the user's language,
* then it is a good idea to call addLabels(Locale::getEnglish(), status).</p>
*
* <h2>Direct Use</h2>
* <p>The following shows an example of building an index directly.
* The "show..." methods below are just to illustrate usage.
*
* <pre>
* // Create a simple index. "Item" is assumed to be an application
* // defined type that the application's UI and other processing knows about,
* // and that has a name.
*
* UErrorCode status = U_ZERO_ERROR;
* AlphabeticIndex index = new AlphabeticIndex(desiredLocale, status);
* index->addLabels(additionalLocale, status);
* for (Item *item in some source of Items ) {
* index->addRecord(item->name(), item, status);
* }
* ...
* // Show index at top. We could skip or gray out empty buckets
*
* while (index->nextBucket(status)) {
* if (showAll || index->getBucketRecordCount() != 0) {
* showLabelAtTop(UI, index->getBucketLabel());
* }
* }
* ...
* // Show the buckets with their contents, skipping empty buckets
*
* index->resetBucketIterator(status);
* while (index->nextBucket(status)) {
* if (index->getBucketRecordCount() != 0) {
* showLabelInList(UI, index->getBucketLabel());
* while (index->nextRecord(status)) {
* showIndexedItem(UI, static_cast<Item *>(index->getRecordData()))
* </pre>
*
* The caller can build different UIs using this class.
* For example, an index character could be omitted or grayed-out
* if its bucket is empty. Small buckets could also be combined based on size, such as:
*
* <pre>
* <b>... A-F G-N O-Z ...</b>
* </pre>
*
* <h2>Client Support</h2>
* <p>Callers can also use the AlphabeticIndex::ImmutableIndex, or the AlphabeticIndex itself,
* to support sorting on a client that doesn't support AlphabeticIndex functionality.
*
* <p>The ImmutableIndex is both immutable and thread-safe.
* The corresponding AlphabeticIndex methods are not thread-safe because
* they "lazily" build the index buckets.
* <ul>
* <li>ImmutableIndex.getBucket(index) provides random access to all
* buckets and their labels and label types.
* <li>The AlphabeticIndex bucket iterator or ImmutableIndex.getBucket(0..getBucketCount-1)
* can be used to get a list of the labels,
* such as "...", "A", "B",..., and send that list to the client.
* <li>When the client has a new name, it sends that name to the server.
* The server needs to call the following methods,
* and communicate the bucketIndex and collationKey back to the client.
*
* <pre>
* int32_t bucketIndex = index.getBucketIndex(name, status);
* const UnicodeString &label = immutableIndex.getBucket(bucketIndex)->getLabel(); // optional
* int32_t skLength = collator.getSortKey(name, sk, skCapacity);
* </pre>
*
* <li>The client would put the name (and associated information) into its bucket for bucketIndex. The sort key sk is a
* sequence of bytes that can be compared with a binary compare, and produce the right localized result.</li>
* </ul>
*
* @stable ICU 4.8
*/
class U_I18N_API AlphabeticIndex: public UObject {
public:
/**
* An index "bucket" with a label string and type.
* It is referenced by getBucketIndex(),
* and returned by ImmutableIndex.getBucket().
*
* The Bucket class is not intended for public subclassing.
* @stable ICU 51
*/
class U_I18N_API Bucket : public UObject {
public:
/**
* Destructor.
* @stable ICU 51
*/
virtual ~Bucket();
/**
* Returns the label string.
*
* @return the label string for the bucket
* @stable ICU 51
*/
const UnicodeString &getLabel() const { return label_; }
/**
* Returns whether this bucket is a normal, underflow, overflow, or inflow bucket.
*
* @return the bucket label type
* @stable ICU 51
*/
UAlphabeticIndexLabelType getLabelType() const { return labelType_; }
private:
friend class AlphabeticIndex;
friend class BucketList;
UnicodeString label_;
UnicodeString lowerBoundary_;
UAlphabeticIndexLabelType labelType_;
Bucket *displayBucket_;
int32_t displayIndex_;
UVector *records_; // Records are owned by the inputList_ vector.
Bucket(const UnicodeString &label, // Parameter strings are copied.
const UnicodeString &lowerBoundary,
UAlphabeticIndexLabelType type);
};
/**
* Immutable, thread-safe version of AlphabeticIndex.
* This class provides thread-safe methods for bucketing,
* and random access to buckets and their properties,
* but does not offer adding records to the index.
*
* The ImmutableIndex class is not intended for public subclassing.
*
* @stable ICU 51
*/
class U_I18N_API ImmutableIndex : public UObject {
public:
/**
* Destructor.
* @stable ICU 51
*/
virtual ~ImmutableIndex();
/**
* Returns the number of index buckets and labels, including underflow/inflow/overflow.
*
* @return the number of index buckets
* @stable ICU 51
*/
int32_t getBucketCount() const;
/**
* Finds the index bucket for the given name and returns the number of that bucket.
* Use getBucket() to get the bucket's properties.
*
* @param name the string to be sorted into an index bucket
* @param errorCode Error code, will be set with the reason if the
* operation fails.
* @return the bucket number for the name
* @stable ICU 51
*/
int32_t getBucketIndex(const UnicodeString &name, UErrorCode &errorCode) const;
/**
* Returns the index-th bucket. Returns nullptr if the index is out of range.
*
* @param index bucket number
* @return the index-th bucket
* @stable ICU 51
*/
const Bucket *getBucket(int32_t index) const;
private:
friend class AlphabeticIndex;
ImmutableIndex(BucketList *bucketList, Collator *collatorPrimaryOnly)
: buckets_(bucketList), collatorPrimaryOnly_(collatorPrimaryOnly) {}
BucketList *buckets_;
Collator *collatorPrimaryOnly_;
};
/**
* Construct an AlphabeticIndex object for the specified locale. If the locale's
* data does not include index characters, a set of them will be
* synthesized based on the locale's exemplar characters. The locale
* determines the sorting order for both the index characters and the
* user item names appearing under each Index character.
*
* @param locale the desired locale.
* @param status Error code, will be set with the reason if the construction
* of the AlphabeticIndex object fails.
* @stable ICU 4.8
*/
AlphabeticIndex(const Locale &locale, UErrorCode &status);
/**
* Construct an AlphabeticIndex that uses a specific collator.
*
* The index will be created with no labels; the addLabels() function must be called
* after creation to add the desired labels to the index.
*
* The index adopts the collator, and is responsible for deleting it.
* The caller should make no further use of the collator after creating the index.
*
* @param collator The collator to use to order the contents of this index.
* @param status Error code, will be set with the reason if the
* operation fails.
* @stable ICU 51
*/
AlphabeticIndex(RuleBasedCollator *collator, UErrorCode &status);
/**
* Add Labels to this Index. The labels are additions to those
* that are already in the index; they do not replace the existing
* ones.
* @param additions The additional characters to add to the index, such as A-Z.
* @param status Error code, will be set with the reason if the
* operation fails.
* @return this, for chaining
* @stable ICU 4.8
*/
virtual AlphabeticIndex &addLabels(const UnicodeSet &additions, UErrorCode &status);
/**
* Add the index characters from a Locale to the index. The labels
* are added to those that are already in the index; they do not replace the
* existing index characters. The collation order for this index is not
* changed; it remains that of the locale that was originally specified
* when creating this Index.
*
* @param locale The locale whose index characters are to be added.
* @param status Error code, will be set with the reason if the
* operation fails.
* @return this, for chaining
* @stable ICU 4.8
*/
virtual AlphabeticIndex &addLabels(const Locale &locale, UErrorCode &status);
/**
* Destructor
* @stable ICU 4.8
*/
virtual ~AlphabeticIndex();
/**
* Builds an immutable, thread-safe version of this instance, without data records.
*
* @return an immutable index instance
* @stable ICU 51
*/
ImmutableIndex *buildImmutableIndex(UErrorCode &errorCode);
/**
* Get the Collator that establishes the ordering of the items in this index.
* Ownership of the collator remains with the AlphabeticIndex instance.
*
* The returned collator is a reference to the internal collator used by this
* index. It may be safely used to compare the names of items or to get
* sort keys for names. However if any settings need to be changed,
* or other non-const methods called, a cloned copy must be made first.
*
* @return The collator
* @stable ICU 4.8
*/
virtual const RuleBasedCollator &getCollator() const;
/**
* Get the default label used for abbreviated buckets *between* other index characters.
* For example, consider the labels when Latin (X Y Z) and Greek (Α Β Γ) are used:
*
* X Y Z ... Α Β Γ.
*
* @return inflow label
* @stable ICU 4.8
*/
virtual const UnicodeString &getInflowLabel() const;
/**
* Set the default label used for abbreviated buckets <i>between</i> other index characters.
* An inflow label will be automatically inserted if two otherwise-adjacent label characters
* are from different scripts, e.g. Latin and Cyrillic, and a third script, e.g. Greek,
* sorts between the two. The default inflow character is an ellipsis (...)
*
* @param inflowLabel the new Inflow label.
* @param status Error code, will be set with the reason if the operation fails.
* @return this
* @stable ICU 4.8
*/
virtual AlphabeticIndex &setInflowLabel(const UnicodeString &inflowLabel, UErrorCode &status);
/**
* Get the special label used for items that sort after the last normal label,
* and that would not otherwise have an appropriate label.
*
* @return the overflow label
* @stable ICU 4.8
*/
virtual const UnicodeString &getOverflowLabel() const;
/**
* Set the label used for items that sort after the last normal label,
* and that would not otherwise have an appropriate label.
*
* @param overflowLabel the new overflow label.
* @param status Error code, will be set with the reason if the operation fails.
* @return this
* @stable ICU 4.8
*/
virtual AlphabeticIndex &setOverflowLabel(const UnicodeString &overflowLabel, UErrorCode &status);
/**
* Get the special label used for items that sort before the first normal label,
* and that would not otherwise have an appropriate label.
*
* @return underflow label
* @stable ICU 4.8
*/
virtual const UnicodeString &getUnderflowLabel() const;
/**
* Set the label used for items that sort before the first normal label,
* and that would not otherwise have an appropriate label.
*
* @param underflowLabel the new underflow label.
* @param status Error code, will be set with the reason if the operation fails.
* @return this
* @stable ICU 4.8
*/
virtual AlphabeticIndex &setUnderflowLabel(const UnicodeString &underflowLabel, UErrorCode &status);
/**
* Get the limit on the number of labels permitted in the index.
* The number does not include over, under and inflow labels.
*
* @return maxLabelCount maximum number of labels.
* @stable ICU 4.8
*/
virtual int32_t getMaxLabelCount() const;
/**
* Set a limit on the number of labels permitted in the index.
* The number does not include over, under and inflow labels.
* Currently, if the number is exceeded, then every
* nth item is removed to bring the count down.
* A more sophisticated mechanism may be available in the future.
*
* @param maxLabelCount the maximum number of labels.
* @param status error code
* @return This, for chaining
* @stable ICU 4.8
*/
virtual AlphabeticIndex &setMaxLabelCount(int32_t maxLabelCount, UErrorCode &status);
/**
* Add a record to the index. Each record will be associated with an index Bucket
* based on the record's name. The list of records for each bucket will be sorted
* based on the collation ordering of the names in the index's locale.
* Records with duplicate names are permitted; they will be kept in the order
* that they were added.
*
* @param name The display name for the Record. The Record will be placed in
* a bucket based on this name.
* @param data An optional pointer to user data associated with this
* item. When iterating the contents of a bucket, both the
* data pointer the name will be available for each Record.
* @param status Error code, will be set with the reason if the operation fails.
* @return This, for chaining.
* @stable ICU 4.8
*/
virtual AlphabeticIndex &addRecord(const UnicodeString &name, const void *data, UErrorCode &status);
/**
* Remove all Records from the Index. The set of Buckets, which define the headings under
* which records are classified, is not altered.
*
* @param status Error code, will be set with the reason if the operation fails.
* @return This, for chaining.
* @stable ICU 4.8
*/
virtual AlphabeticIndex &clearRecords(UErrorCode &status);
/** Get the number of labels in this index.
* Note: may trigger lazy index construction.
*
* @param status Error code, will be set with the reason if the operation fails.
* @return The number of labels in this index, including any under, over or
* in-flow labels.
* @stable ICU 4.8
*/
virtual int32_t getBucketCount(UErrorCode &status);
/** Get the total number of Records in this index, that is, the number
* of <name, data> pairs added.
*
* @param status Error code, will be set with the reason if the operation fails.
* @return The number of records in this index, that is, the total number
* of (name, data) items added with addRecord().
* @stable ICU 4.8
*/
virtual int32_t getRecordCount(UErrorCode &status);
/**
* Given the name of a record, return the zero-based index of the Bucket
* in which the item should appear. The name need not be in the index.
* A Record will not be added to the index by this function.
* Bucket numbers are zero-based, in Bucket iteration order.
*
* @param itemName The name whose bucket position in the index is to be determined.
* @param status Error code, will be set with the reason if the operation fails.
* @return The bucket number for this name.
* @stable ICU 4.8
*
*/
virtual int32_t getBucketIndex(const UnicodeString &itemName, UErrorCode &status);
/**
* Get the zero based index of the current Bucket from an iteration
* over the Buckets of this index. Return -1 if no iteration is in process.
* @return the index of the current Bucket
* @stable ICU 4.8
*/
virtual int32_t getBucketIndex() const;
/**
* Advance the iteration over the Buckets of this index. Return false if
* there are no more Buckets.
*
* @param status Error code, will be set with the reason if the operation fails.
* U_ENUM_OUT_OF_SYNC_ERROR will be reported if the index is modified while
* an enumeration of its contents are in process.
*
* @return true if success, false if at end of iteration
* @stable ICU 4.8
*/
virtual UBool nextBucket(UErrorCode &status);
/**
* Return the name of the Label of the current bucket from an iteration over the buckets.
* If the iteration is before the first Bucket (nextBucket() has not been called),
* or after the last, return an empty string.
*
* @return the bucket label.
* @stable ICU 4.8
*/
virtual const UnicodeString &getBucketLabel() const;
/**
* Return the type of the label for the current Bucket (selected by the
* iteration over Buckets.)
*
* @return the label type.
* @stable ICU 4.8
*/
virtual UAlphabeticIndexLabelType getBucketLabelType() const;
/**
* Get the number of <name, data> Records in the current Bucket.
* If the current bucket iteration position is before the first label or after the
* last, return 0.
*
* @return the number of Records.
* @stable ICU 4.8
*/
virtual int32_t getBucketRecordCount() const;
/**
* Reset the Bucket iteration for this index. The next call to nextBucket()
* will restart the iteration at the first label.
*
* @param status Error code, will be set with the reason if the operation fails.
* @return this, for chaining.
* @stable ICU 4.8
*/
virtual AlphabeticIndex &resetBucketIterator(UErrorCode &status);
/**
* Advance to the next record in the current Bucket.
* When nextBucket() is called, Record iteration is reset to just before the
* first Record in the new Bucket.
*
* @param status Error code, will be set with the reason if the operation fails.
* U_ENUM_OUT_OF_SYNC_ERROR will be reported if the index is modified while
* an enumeration of its contents are in process.
* @return true if successful, false when the iteration advances past the last item.
* @stable ICU 4.8
*/
virtual UBool nextRecord(UErrorCode &status);
/**
* Get the name of the current Record.
* Return an empty string if the Record iteration position is before first
* or after the last.
*
* @return The name of the current index item.
* @stable ICU 4.8
*/
virtual const UnicodeString &getRecordName() const;
/**
* Return the data pointer of the Record currently being iterated over.
* Return nullptr if the current iteration position before the first item in this Bucket,
* or after the last.
*
* @return The current Record's data pointer.
* @stable ICU 4.8
*/
virtual const void *getRecordData() const;
/**
* Reset the Record iterator position to before the first Record in the current Bucket.
*
* @return This, for chaining.
* @stable ICU 4.8
*/
virtual AlphabeticIndex &resetRecordIterator();
private:
/**
* No Copy constructor.
* @internal (private)
*/
AlphabeticIndex(const AlphabeticIndex &other) = delete;
/**
* No assignment.
*/
AlphabeticIndex &operator =(const AlphabeticIndex & /*other*/) { return *this;}
/**
* No Equality operators.
* @internal (private)
*/
virtual bool operator==(const AlphabeticIndex& other) const;
/**
* Inequality operator.
* @internal (private)
*/
virtual bool operator!=(const AlphabeticIndex& other) const;
// Common initialization, for use from all constructors.
void init(const Locale *locale, UErrorCode &status);
/**
* This method is called to get the index exemplars. Normally these come from the locale directly,
* but if they aren't available, we have to synthesize them.
*/
void addIndexExemplars(const Locale &locale, UErrorCode &status);
/**
* Add Chinese index characters from the tailoring.
*/
UBool addChineseIndexCharacters(UErrorCode &errorCode);
UVector *firstStringsInScript(UErrorCode &status);
static UnicodeString separated(const UnicodeString &item);
/**
* Determine the best labels to use.
* This is based on the exemplars, but we also process to make sure that they are unique,
* and sort differently, and that the overall list is small enough.
*/
void initLabels(UVector &indexCharacters, UErrorCode &errorCode) const;
BucketList *createBucketList(UErrorCode &errorCode) const;
void initBuckets(UErrorCode &errorCode);
void clearBuckets();
void internalResetBucketIterator();
public:
// The Record is declared public only to allow access from
// implementation code written in plain C.
// It is not intended for public use.
#ifndef U_HIDE_INTERNAL_API
/**
* A (name, data) pair, to be sorted by name into one of the index buckets.
* The user data is not used by the index implementation.
* \cond
* @internal
*/
struct Record: public UMemory {
const UnicodeString name_;
const void *data_;
Record(const UnicodeString &name, const void *data);
~Record();
};
/** \endcond */
#endif /* U_HIDE_INTERNAL_API */
private:
/**
* Holds all user records before they are distributed into buckets.
* Type of contents is (Record *)
* @internal (private)
*/
UVector *inputList_;
int32_t labelsIterIndex_; // Index of next item to return.
int32_t itemsIterIndex_;
Bucket *currentBucket_; // While an iteration of the index in underway,
// point to the bucket for the current label.
// nullptr when no iteration underway.
int32_t maxLabelCount_; // Limit on # of labels permitted in the index.
UnicodeSet *initialLabels_; // Initial (unprocessed) set of Labels. Union
// of those explicitly set by the user plus
// those from locales. Raw values, before
// crunching into bucket labels.
UVector *firstCharsInScripts_; // The first character from each script,
// in collation order.
RuleBasedCollator *collator_;
RuleBasedCollator *collatorPrimaryOnly_;
// Lazy evaluated: null means that we have not built yet.
BucketList *buckets_;
UnicodeString inflowLabel_;
UnicodeString overflowLabel_;
UnicodeString underflowLabel_;
UnicodeString overflowComparisonString_;
UnicodeString emptyString_;
};
U_NAMESPACE_END
#endif // !UCONFIG_NO_COLLATION
#endif /* U_SHOW_CPLUSPLUS_API */
#endif

View File

@ -0,0 +1,248 @@
// © 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
/*
*******************************************************************************
* Copyright (C) 2007-2013, International Business Machines Corporation and
* others. All Rights Reserved.
*******************************************************************************
*/
#ifndef BASICTZ_H
#define BASICTZ_H
/**
* \file
* \brief C++ API: ICU TimeZone base class
*/
#include "unicode/utypes.h"
#if U_SHOW_CPLUSPLUS_API
#if !UCONFIG_NO_FORMATTING
#include "unicode/timezone.h"
#include "unicode/tzrule.h"
#include "unicode/tztrans.h"
U_NAMESPACE_BEGIN
// forward declarations
class UVector;
/**
* <code>BasicTimeZone</code> is an abstract class extending <code>TimeZone</code>.
* This class provides some additional methods to access time zone transitions and rules.
* All ICU <code>TimeZone</code> concrete subclasses extend this class.
* @stable ICU 3.8
*/
class U_I18N_API BasicTimeZone: public TimeZone {
public:
/**
* Destructor.
* @stable ICU 3.8
*/
virtual ~BasicTimeZone();
/**
* Clones this object polymorphically.
* The caller owns the result and should delete it when done.
* @return clone, or nullptr if an error occurred
* @stable ICU 3.8
*/
virtual BasicTimeZone* clone() const override = 0;
/**
* Gets the first time zone transition after the base time.
* @param base The base time.
* @param inclusive Whether the base time is inclusive or not.
* @param result Receives the first transition after the base time.
* @return true if the transition is found.
* @stable ICU 3.8
*/
virtual UBool getNextTransition(UDate base, UBool inclusive, TimeZoneTransition& result) const = 0;
/**
* Gets the most recent time zone transition before the base time.
* @param base The base time.
* @param inclusive Whether the base time is inclusive or not.
* @param result Receives the most recent transition before the base time.
* @return true if the transition is found.
* @stable ICU 3.8
*/
virtual UBool getPreviousTransition(UDate base, UBool inclusive, TimeZoneTransition& result) const = 0;
/**
* Checks if the time zone has equivalent transitions in the time range.
* This method returns true when all of transition times, from/to standard
* offsets and DST savings used by this time zone match the other in the
* time range.
* @param tz The <code>BasicTimeZone</code> object to be compared with.
* @param start The start time of the evaluated time range (inclusive)
* @param end The end time of the evaluated time range (inclusive)
* @param ignoreDstAmount
* When true, any transitions with only daylight saving amount
* changes will be ignored, except either of them is zero.
* For example, a transition from rawoffset 3:00/dstsavings 1:00
* to rawoffset 2:00/dstsavings 2:00 is excluded from the comparison,
* but a transition from rawoffset 2:00/dstsavings 1:00 to
* rawoffset 3:00/dstsavings 0:00 is included.
* @param ec Output param to filled in with a success or an error.
* @return true if the other time zone has the equivalent transitions in the
* time range.
* @stable ICU 3.8
*/
virtual UBool hasEquivalentTransitions(const BasicTimeZone& tz, UDate start, UDate end,
UBool ignoreDstAmount, UErrorCode& ec) const;
/**
* Returns the number of <code>TimeZoneRule</code>s which represents time transitions,
* for this time zone, that is, all <code>TimeZoneRule</code>s for this time zone except
* <code>InitialTimeZoneRule</code>. The return value range is 0 or any positive value.
* @param status Receives error status code.
* @return The number of <code>TimeZoneRule</code>s representing time transitions.
* @stable ICU 3.8
*/
virtual int32_t countTransitionRules(UErrorCode& status) const = 0;
/**
* Gets the <code>InitialTimeZoneRule</code> and the set of <code>TimeZoneRule</code>
* which represent time transitions for this time zone. On successful return,
* the argument initial points to non-nullptr <code>InitialTimeZoneRule</code> and
* the array trsrules is filled with 0 or multiple <code>TimeZoneRule</code>
* instances up to the size specified by trscount. The results are referencing the
* rule instance held by this time zone instance. Therefore, after this time zone
* is destructed, they are no longer available.
* @param initial Receives the initial timezone rule
* @param trsrules Receives the timezone transition rules
* @param trscount On input, specify the size of the array 'transitions' receiving
* the timezone transition rules. On output, actual number of
* rules filled in the array will be set.
* @param status Receives error status code.
* @stable ICU 3.8
*/
virtual void getTimeZoneRules(const InitialTimeZoneRule*& initial,
const TimeZoneRule* trsrules[], int32_t& trscount, UErrorCode& status) const = 0;
/**
* Gets the set of time zone rules valid at the specified time. Some known external time zone
* implementations are not capable to handle historic time zone rule changes. Also some
* implementations can only handle certain type of rule definitions.
* If this time zone does not use any daylight saving time within about 1 year from the specified
* time, only the <code>InitialTimeZone</code> is returned. Otherwise, the rule for standard
* time and daylight saving time transitions are returned in addition to the
* <code>InitialTimeZoneRule</code>. The standard and daylight saving time transition rules are
* represented by <code>AnnualTimeZoneRule</code> with <code>DateTimeRule::DOW</code> for its date
* rule and <code>DateTimeRule::WALL_TIME</code> for its time rule. Because daylight saving time
* rule is changing time to time in many time zones and also mapping a transition time rule to
* different type is lossy transformation, the set of rules returned by this method may be valid
* for short period of time.
* The time zone rule objects returned by this method is owned by the caller, so the caller is
* responsible for deleting them after use.
* @param date The date used for extracting time zone rules.
* @param initial Receives the <code>InitialTimeZone</code>, always not nullptr.
* @param std Receives the <code>AnnualTimeZoneRule</code> for standard time transitions.
* When this time time zone does not observe daylight saving times around the
* specified date, nullptr is set.
* @param dst Receives the <code>AnnualTimeZoneRule</code> for daylight saving time
* transitions. When this time zone does not observer daylight saving times
* around the specified date, nullptr is set.
* @param status Receives error status code.
* @stable ICU 3.8
*/
virtual void getSimpleRulesNear(UDate date, InitialTimeZoneRule*& initial,
AnnualTimeZoneRule*& std, AnnualTimeZoneRule*& dst, UErrorCode& status) const;
/**
* Get time zone offsets from local wall time.
* @stable ICU 69
*/
virtual void getOffsetFromLocal(
UDate date, UTimeZoneLocalOption nonExistingTimeOpt,
UTimeZoneLocalOption duplicatedTimeOpt, int32_t& rawOffset,
int32_t& dstOffset, UErrorCode& status) const;
#ifndef U_HIDE_INTERNAL_API
/**
* The time type option bit flags used by getOffsetFromLocal
* @internal
*/
enum {
kStandard = 0x01,
kDaylight = 0x03,
kFormer = 0x04, /* UCAL_TZ_LOCAL_FORMER */
kLatter = 0x0C /* UCAL_TZ_LOCAL_LATTER */
};
/**
* Get time zone offsets from local wall time.
* @internal
*/
void getOffsetFromLocal(UDate date, int32_t nonExistingTimeOpt, int32_t duplicatedTimeOpt,
int32_t& rawOffset, int32_t& dstOffset, UErrorCode& status) const;
#endif /* U_HIDE_INTERNAL_API */
protected:
#ifndef U_HIDE_INTERNAL_API
/**
* A time type option bit mask used by getOffsetFromLocal.
* @internal
*/
static constexpr int32_t kStdDstMask = kDaylight;
/**
* A time type option bit mask used by getOffsetFromLocal.
* @internal
*/
static constexpr int32_t kFormerLatterMask = kLatter;
#endif /* U_HIDE_INTERNAL_API */
/**
* Default constructor.
* @stable ICU 3.8
*/
BasicTimeZone();
/**
* Construct a timezone with a given ID.
* @param id a system time zone ID
* @stable ICU 3.8
*/
BasicTimeZone(const UnicodeString &id);
/**
* Copy constructor.
* @param source the object to be copied.
* @stable ICU 3.8
*/
BasicTimeZone(const BasicTimeZone& source);
/**
* Copy assignment.
* @stable ICU 3.8
*/
BasicTimeZone& operator=(const BasicTimeZone&) = default;
/**
* Gets the set of TimeZoneRule instances applicable to the specified time and after.
* @param start The start date used for extracting time zone rules
* @param initial Output parameter, receives the InitialTimeZone.
* Always not nullptr (except in case of error)
* @param transitionRules Output parameter, a UVector of transition rules.
* May be nullptr, if there are no transition rules.
* The caller owns the returned vector; the UVector owns the rules.
* @param status Receives error status code
*/
void getTimeZoneRulesAfter(UDate start, InitialTimeZoneRule*& initial, UVector*& transitionRules,
UErrorCode& status) const;
};
U_NAMESPACE_END
#endif /* #if !UCONFIG_NO_FORMATTING */
#endif /* U_SHOW_CPLUSPLUS_API */
#endif // BASICTZ_H
//eof

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,601 @@
// © 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
/*
********************************************************************************
* Copyright (C) 1997-2013, International Business Machines
* Corporation and others. All Rights Reserved.
********************************************************************************
*
* File CHOICFMT.H
*
* Modification History:
*
* Date Name Description
* 02/19/97 aliu Converted from java.
* 03/20/97 helena Finished first cut of implementation and got rid
* of nextDouble/previousDouble and replaced with
* boolean array.
* 4/10/97 aliu Clean up. Modified to work on AIX.
* 8/6/97 nos Removed overloaded constructor, member var 'buffer'.
* 07/22/98 stephen Removed operator!= (implemented in Format)
********************************************************************************
*/
#ifndef CHOICFMT_H
#define CHOICFMT_H
#include "unicode/utypes.h"
#if U_SHOW_CPLUSPLUS_API
/**
* \file
* \brief C++ API: Choice Format.
*/
#if !UCONFIG_NO_FORMATTING
#include "unicode/fieldpos.h"
#include "unicode/format.h"
#include "unicode/messagepattern.h"
#include "unicode/numfmt.h"
#include "unicode/unistr.h"
#ifndef U_HIDE_DEPRECATED_API
U_NAMESPACE_BEGIN
class MessageFormat;
/**
* ChoiceFormat converts between ranges of numeric values and strings for those ranges.
* The strings must conform to the MessageFormat pattern syntax.
*
* <p><em><code>ChoiceFormat</code> is probably not what you need.
* Please use <code>MessageFormat</code>
* with <code>plural</code> arguments for proper plural selection,
* and <code>select</code> arguments for simple selection among a fixed set of choices!</em></p>
*
* <p>A <code>ChoiceFormat</code> splits
* the real number line \htmlonly<code>-&#x221E;</code> to
* <code>+&#x221E;</code>\endhtmlonly into two
* or more contiguous ranges. Each range is mapped to a
* string.</p>
*
* <p><code>ChoiceFormat</code> was originally intended
* for displaying grammatically correct
* plurals such as &quot;There is one file.&quot; vs. &quot;There are 2 files.&quot;
* <em>However,</em> plural rules for many languages
* are too complex for the capabilities of ChoiceFormat,
* and its requirement of specifying the precise rules for each message
* is unmanageable for translators.</p>
*
* <p>There are two methods of defining a <code>ChoiceFormat</code>; both
* are equivalent. The first is by using a string pattern. This is the
* preferred method in most cases. The second method is through direct
* specification of the arrays that logically make up the
* <code>ChoiceFormat</code>.</p>
*
* <p>Note: Typically, choice formatting is done (if done at all) via <code>MessageFormat</code>
* with a <code>choice</code> argument type,
* rather than using a stand-alone <code>ChoiceFormat</code>.</p>
*
* <h5>Patterns and Their Interpretation</h5>
*
* <p>The pattern string defines the range boundaries and the strings for each number range.
* Syntax:
* <pre>
* choiceStyle = number separator message ('|' number separator message)*
* number = normal_number | ['-'] \htmlonly&#x221E;\endhtmlonly (U+221E, infinity)
* normal_number = double value (unlocalized ASCII string)
* separator = less_than | less_than_or_equal
* less_than = '<'
* less_than_or_equal = '#' | \htmlonly&#x2264;\endhtmlonly (U+2264)
* message: see {@link MessageFormat}
* </pre>
* Pattern_White_Space between syntax elements is ignored, except
* around each range's sub-message.</p>
*
* <p>Each numeric sub-range extends from the current range's number
* to the next range's number.
* The number itself is included in its range if a <code>less_than_or_equal</code> sign is used,
* and excluded from its range (and instead included in the previous range)
* if a <code>less_than</code> sign is used.</p>
*
* <p>When a <code>ChoiceFormat</code> is constructed from
* arrays of numbers, closure flags and strings,
* they are interpreted just like
* the sequence of <code>(number separator string)</code> in an equivalent pattern string.
* <code>closure[i]==true</code> corresponds to a <code>less_than</code> separator sign.
* The equivalent pattern string will be constructed automatically.</p>
*
* <p>During formatting, a number is mapped to the first range
* where the number is not greater than the range's upper limit.
* That range's message string is returned. A NaN maps to the very first range.</p>
*
* <p>During parsing, a range is selected for the longest match of
* any range's message. That range's number is returned, ignoring the separator/closure.
* Only a simple string match is performed, without parsing of arguments that
* might be specified in the message strings.</p>
*
* <p>Note that the first range's number is ignored in formatting
* but may be returned from parsing.</p>
*
* <h5>Examples</h5>
*
* <p>Here is an example of two arrays that map the number
* <code>1..7</code> to the English day of the week abbreviations
* <code>Sun..Sat</code>. No closures array is given; this is the same as
* specifying all closures to be <code>false</code>.</p>
*
* <pre> {1,2,3,4,5,6,7},
* {&quot;Sun&quot;,&quot;Mon&quot;,&quot;Tue&quot;,&quot;Wed&quot;,&quot;Thur&quot;,&quot;Fri&quot;,&quot;Sat&quot;}</pre>
*
* <p>Here is an example that maps the ranges [-Inf, 1), [1, 1], and (1,
* +Inf] to three strings. That is, the number line is split into three
* ranges: x &lt; 1.0, x = 1.0, and x &gt; 1.0.
* (The round parentheses in the notation above indicate an exclusive boundary,
* like the turned bracket in European notation: [-Inf, 1) == [-Inf, 1[ )</p>
*
* <pre> {0, 1, 1},
* {false, false, true},
* {&quot;no files&quot;, &quot;one file&quot;, &quot;many files&quot;}</pre>
*
* <p>Here is an example that shows formatting and parsing: </p>
*
* \code
* #include <unicode/choicfmt.h>
* #include <unicode/unistr.h>
* #include <iostream.h>
*
* int main(int argc, char *argv[]) {
* double limits[] = {1,2,3,4,5,6,7};
* UnicodeString monthNames[] = {
* "Sun","Mon","Tue","Wed","Thu","Fri","Sat"};
* ChoiceFormat fmt(limits, monthNames, 7);
* UnicodeString str;
* char buf[256];
* for (double x = 1.0; x <= 8.0; x += 1.0) {
* fmt.format(x, str);
* str.extract(0, str.length(), buf, 256, "");
* str.truncate(0);
* cout << x << " -> "
* << buf << endl;
* }
* cout << endl;
* return 0;
* }
* \endcode
*
* <p><em>User subclasses are not supported.</em> While clients may write
* subclasses, such code will not necessarily work and will not be
* guaranteed to work stably from release to release.
*
* @deprecated ICU 49 Use MessageFormat instead, with plural and select arguments.
*/
class U_I18N_API ChoiceFormat: public NumberFormat {
public:
/**
* Constructs a new ChoiceFormat from the pattern string.
*
* @param pattern Pattern used to construct object.
* @param status Output param to receive success code. If the
* pattern cannot be parsed, set to failure code.
* @deprecated ICU 49 Use MessageFormat instead, with plural and select arguments.
*/
ChoiceFormat(const UnicodeString& pattern,
UErrorCode& status);
/**
* Constructs a new ChoiceFormat with the given limits and message strings.
* All closure flags default to <code>false</code>,
* equivalent to <code>less_than_or_equal</code> separators.
*
* Copies the limits and formats instead of adopting them.
*
* @param limits Array of limit values.
* @param formats Array of formats.
* @param count Size of 'limits' and 'formats' arrays.
* @deprecated ICU 49 Use MessageFormat instead, with plural and select arguments.
*/
ChoiceFormat(const double* limits,
const UnicodeString* formats,
int32_t count );
/**
* Constructs a new ChoiceFormat with the given limits, closure flags and message strings.
*
* Copies the limits and formats instead of adopting them.
*
* @param limits Array of limit values
* @param closures Array of booleans specifying whether each
* element of 'limits' is open or closed. If false, then the
* corresponding limit number is a member of its range.
* If true, then the limit number belongs to the previous range it.
* @param formats Array of formats
* @param count Size of 'limits', 'closures', and 'formats' arrays
* @deprecated ICU 49 Use MessageFormat instead, with plural and select arguments.
*/
ChoiceFormat(const double* limits,
const UBool* closures,
const UnicodeString* formats,
int32_t count);
/**
* Copy constructor.
*
* @param that ChoiceFormat object to be copied from
* @deprecated ICU 49 Use MessageFormat instead, with plural and select arguments.
*/
ChoiceFormat(const ChoiceFormat& that);
/**
* Assignment operator.
*
* @param that ChoiceFormat object to be copied
* @deprecated ICU 49 Use MessageFormat instead, with plural and select arguments.
*/
const ChoiceFormat& operator=(const ChoiceFormat& that);
/**
* Destructor.
* @deprecated ICU 49 Use MessageFormat instead, with plural and select arguments.
*/
virtual ~ChoiceFormat();
/**
* Clones this Format object. The caller owns the
* result and must delete it when done.
*
* @return a copy of this object
* @deprecated ICU 49 Use MessageFormat instead, with plural and select arguments.
*/
virtual ChoiceFormat* clone() const override;
/**
* Returns true if the given Format objects are semantically equal.
* Objects of different subclasses are considered unequal.
*
* @param other ChoiceFormat object to be compared
* @return true if other is the same as this.
* @deprecated ICU 49 Use MessageFormat instead, with plural and select arguments.
*/
virtual bool operator==(const Format& other) const override;
/**
* Sets the pattern.
* @param pattern The pattern to be applied.
* @param status Output param set to success/failure code on
* exit. If the pattern is invalid, this will be
* set to a failure result.
* @deprecated ICU 49 Use MessageFormat instead, with plural and select arguments.
*/
virtual void applyPattern(const UnicodeString& pattern,
UErrorCode& status);
/**
* Sets the pattern.
* @param pattern The pattern to be applied.
* @param parseError Struct to receive information on position
* of error if an error is encountered
* @param status Output param set to success/failure code on
* exit. If the pattern is invalid, this will be
* set to a failure result.
* @deprecated ICU 49 Use MessageFormat instead, with plural and select arguments.
*/
virtual void applyPattern(const UnicodeString& pattern,
UParseError& parseError,
UErrorCode& status);
/**
* Gets the pattern.
*
* @param pattern Output param which will receive the pattern
* Previous contents are deleted.
* @return A reference to 'pattern'
* @deprecated ICU 49 Use MessageFormat instead, with plural and select arguments.
*/
virtual UnicodeString& toPattern(UnicodeString &pattern) const;
/**
* Sets the choices to be used in formatting.
* For details see the constructor with the same parameter list.
*
* @param limitsToCopy Contains the top value that you want
* parsed with that format,and should be in
* ascending sorted order. When formatting X,
* the choice will be the i, where limit[i]
* &lt;= X &lt; limit[i+1].
* @param formatsToCopy The format strings you want to use for each limit.
* @param count The size of the above arrays.
* @deprecated ICU 49 Use MessageFormat instead, with plural and select arguments.
*/
virtual void setChoices(const double* limitsToCopy,
const UnicodeString* formatsToCopy,
int32_t count );
/**
* Sets the choices to be used in formatting.
* For details see the constructor with the same parameter list.
*
* @param limits Array of limits
* @param closures Array of limit booleans
* @param formats Array of format string
* @param count The size of the above arrays
* @deprecated ICU 49 Use MessageFormat instead, with plural and select arguments.
*/
virtual void setChoices(const double* limits,
const UBool* closures,
const UnicodeString* formats,
int32_t count);
/**
* Returns nullptr and 0.
* Before ICU 4.8, this used to return the choice limits array.
*
* @param count Will be set to 0.
* @return nullptr
* @deprecated ICU 4.8 Use the MessagePattern class to analyze a ChoiceFormat pattern.
*/
virtual const double* getLimits(int32_t& count) const;
/**
* Returns nullptr and 0.
* Before ICU 4.8, this used to return the limit booleans array.
*
* @param count Will be set to 0.
* @return nullptr
* @deprecated ICU 4.8 Use the MessagePattern class to analyze a ChoiceFormat pattern.
*/
virtual const UBool* getClosures(int32_t& count) const;
/**
* Returns nullptr and 0.
* Before ICU 4.8, this used to return the array of choice strings.
*
* @param count Will be set to 0.
* @return nullptr
* @deprecated ICU 4.8 Use the MessagePattern class to analyze a ChoiceFormat pattern.
*/
virtual const UnicodeString* getFormats(int32_t& count) const;
using NumberFormat::format;
/**
* Formats a double number using this object's choices.
*
* @param number The value to be formatted.
* @param appendTo Output parameter to receive result.
* Result is appended to existing contents.
* @param pos On input: an alignment field, if desired.
* On output: the offsets of the alignment field.
* @return Reference to 'appendTo' parameter.
* @deprecated ICU 49 Use MessageFormat instead, with plural and select arguments.
*/
virtual UnicodeString& format(double number,
UnicodeString& appendTo,
FieldPosition& pos) const override;
/**
* Formats an int32_t number using this object's choices.
*
* @param number The value to be formatted.
* @param appendTo Output parameter to receive result.
* Result is appended to existing contents.
* @param pos On input: an alignment field, if desired.
* On output: the offsets of the alignment field.
* @return Reference to 'appendTo' parameter.
* @deprecated ICU 49 Use MessageFormat instead, with plural and select arguments.
*/
virtual UnicodeString& format(int32_t number,
UnicodeString& appendTo,
FieldPosition& pos) const override;
/**
* Formats an int64_t number using this object's choices.
*
* @param number The value to be formatted.
* @param appendTo Output parameter to receive result.
* Result is appended to existing contents.
* @param pos On input: an alignment field, if desired.
* On output: the offsets of the alignment field.
* @return Reference to 'appendTo' parameter.
* @deprecated ICU 49 Use MessageFormat instead, with plural and select arguments.
*/
virtual UnicodeString& format(int64_t number,
UnicodeString& appendTo,
FieldPosition& pos) const override;
/**
* Formats an array of objects using this object's choices.
*
* @param objs The array of objects to be formatted.
* @param cnt The size of objs.
* @param appendTo Output parameter to receive result.
* Result is appended to existing contents.
* @param pos On input: an alignment field, if desired.
* On output: the offsets of the alignment field.
* @param success Output param set to success/failure code on
* exit.
* @return Reference to 'appendTo' parameter.
* @deprecated ICU 49 Use MessageFormat instead, with plural and select arguments.
*/
virtual UnicodeString& format(const Formattable* objs,
int32_t cnt,
UnicodeString& appendTo,
FieldPosition& pos,
UErrorCode& success) const;
using NumberFormat::parse;
/**
* Looks for the longest match of any message string on the input text and,
* if there is a match, sets the result object to the corresponding range's number.
*
* If no string matches, then the parsePosition is unchanged.
*
* @param text The text to be parsed.
* @param result Formattable to be set to the parse result.
* If parse fails, return contents are undefined.
* @param parsePosition The position to start parsing at on input.
* On output, moved to after the last successfully
* parse character. On parse failure, does not change.
* @deprecated ICU 49 Use MessageFormat instead, with plural and select arguments.
*/
virtual void parse(const UnicodeString& text,
Formattable& result,
ParsePosition& parsePosition) const override;
/**
* Returns a unique class ID POLYMORPHICALLY. Part of ICU's "poor man's RTTI".
*
* @return The class ID for this object. All objects of a
* given class have the same class ID. Objects of
* other classes have different class IDs.
* @deprecated ICU 49 Use MessageFormat instead, with plural and select arguments.
*/
virtual UClassID getDynamicClassID() const override;
/**
* Returns the class ID for this class. This is useful only for
* comparing to a return value from getDynamicClassID(). For example:
* <pre>
* . Base* polymorphic_pointer = createPolymorphicObject();
* . if (polymorphic_pointer->getDynamicClassID() ==
* . Derived::getStaticClassID()) ...
* </pre>
* @return The class ID for all objects of this class.
* @deprecated ICU 49 Use MessageFormat instead, with plural and select arguments.
*/
static UClassID U_EXPORT2 getStaticClassID();
private:
/**
* Converts a double value to a string.
* @param value the double number to be converted.
* @param string the result string.
* @return the converted string.
*/
static UnicodeString& dtos(double value, UnicodeString& string);
ChoiceFormat() = delete; // default constructor not implemented
/**
* Construct a new ChoiceFormat with the limits and the corresponding formats
* based on the pattern.
*
* @param newPattern Pattern used to construct object.
* @param parseError Struct to receive information on position
* of error if an error is encountered.
* @param status Output param to receive success code. If the
* pattern cannot be parsed, set to failure code.
*/
ChoiceFormat(const UnicodeString& newPattern,
UParseError& parseError,
UErrorCode& status);
friend class MessageFormat;
virtual void setChoices(const double* limits,
const UBool* closures,
const UnicodeString* formats,
int32_t count,
UErrorCode &errorCode);
/**
* Finds the ChoiceFormat sub-message for the given number.
* @param pattern A MessagePattern.
* @param partIndex the index of the first ChoiceFormat argument style part.
* @param number a number to be mapped to one of the ChoiceFormat argument's intervals
* @return the sub-message start part index.
*/
static int32_t findSubMessage(const MessagePattern &pattern, int32_t partIndex, double number);
static double parseArgument(
const MessagePattern &pattern, int32_t partIndex,
const UnicodeString &source, ParsePosition &pos);
/**
* Matches the pattern string from the end of the partIndex to
* the beginning of the limitPartIndex,
* including all syntax except SKIP_SYNTAX,
* against the source string starting at sourceOffset.
* If they match, returns the length of the source string match.
* Otherwise returns -1.
*/
static int32_t matchStringUntilLimitPart(
const MessagePattern &pattern, int32_t partIndex, int32_t limitPartIndex,
const UnicodeString &source, int32_t sourceOffset);
/**
* Some of the ChoiceFormat constructors do not have a UErrorCode parameter.
* We need _some_ way to provide one for the MessagePattern constructor.
* Alternatively, the MessagePattern could be a pointer field, but that is
* not nice either.
*/
UErrorCode constructorErrorCode;
/**
* The MessagePattern which contains the parsed structure of the pattern string.
*
* Starting with ICU 4.8, the MessagePattern contains a sequence of
* numeric/selector/message parts corresponding to the parsed pattern.
* For details see the MessagePattern class API docs.
*/
MessagePattern msgPattern;
/**
* Docs & fields from before ICU 4.8, before MessagePattern was used.
* Commented out, and left only for explanation of semantics.
* --------
* Each ChoiceFormat divides the range -Inf..+Inf into fCount
* intervals. The intervals are:
*
* 0: fChoiceLimits[0]..fChoiceLimits[1]
* 1: fChoiceLimits[1]..fChoiceLimits[2]
* ...
* fCount-2: fChoiceLimits[fCount-2]..fChoiceLimits[fCount-1]
* fCount-1: fChoiceLimits[fCount-1]..+Inf
*
* Interval 0 is special; during formatting (mapping numbers to
* strings), it also contains all numbers less than
* fChoiceLimits[0], as well as NaN values.
*
* Interval i maps to and from string fChoiceFormats[i]. When
* parsing (mapping strings to numbers), then intervals map to
* their lower limit, that is, interval i maps to fChoiceLimit[i].
*
* The intervals may be closed, half open, or open. This affects
* formatting but does not affect parsing. Interval i is affected
* by fClosures[i] and fClosures[i+1]. If fClosures[i]
* is false, then the value fChoiceLimits[i] is in interval i.
* That is, intervals i and i are:
*
* i-1: ... x < fChoiceLimits[i]
* i: fChoiceLimits[i] <= x ...
*
* If fClosures[i] is true, then the value fChoiceLimits[i] is
* in interval i-1. That is, intervals i-1 and i are:
*
* i-1: ... x <= fChoiceLimits[i]
* i: fChoiceLimits[i] < x ...
*
* Because of the nature of interval 0, fClosures[0] has no
* effect.
*/
// double* fChoiceLimits;
// UBool* fClosures;
// UnicodeString* fChoiceFormats;
// int32_t fCount;
};
U_NAMESPACE_END
#endif // U_HIDE_DEPRECATED_API
#endif /* #if !UCONFIG_NO_FORMATTING */
#endif /* U_SHOW_CPLUSPLUS_API */
#endif // CHOICFMT_H
//eof

View File

@ -0,0 +1,411 @@
// © 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
/*
******************************************************************************
* Copyright (C) 1997-2014, International Business Machines
* Corporation and others. All Rights Reserved.
******************************************************************************
*/
/**
* \file
* \brief C++ API: Collation Element Iterator.
*/
/**
* File coleitr.h
*
* Created by: Helena Shih
*
* Modification History:
*
* Date Name Description
*
* 8/18/97 helena Added internal API documentation.
* 08/03/98 erm Synched with 1.2 version CollationElementIterator.java
* 12/10/99 aliu Ported Thai collation support from Java.
* 01/25/01 swquek Modified into a C++ wrapper calling C APIs (ucoliter.h)
* 02/19/01 swquek Removed CollationElementsIterator() since it is
* private constructor and no calls are made to it
* 2012-2014 markus Rewritten in C++ again.
*/
#ifndef COLEITR_H
#define COLEITR_H
#include "unicode/utypes.h"
#if U_SHOW_CPLUSPLUS_API
#if !UCONFIG_NO_COLLATION
#include "unicode/unistr.h"
#include "unicode/uobject.h"
struct UCollationElements;
struct UHashtable;
U_NAMESPACE_BEGIN
struct CollationData;
class CharacterIterator;
class CollationIterator;
class RuleBasedCollator;
class UCollationPCE;
class UVector32;
/**
* The CollationElementIterator class is used as an iterator to walk through
* each character of an international string. Use the iterator to return the
* ordering priority of the positioned character. The ordering priority of a
* character, which we refer to as a key, defines how a character is collated in
* the given collation object.
* For example, consider the following in Slovak and in traditional Spanish collation:
* <pre>
* "ca" -> the first key is key('c') and second key is key('a').
* "cha" -> the first key is key('ch') and second key is key('a').</pre>
* And in German phonebook collation,
* <pre> \htmlonly "&#x00E6;b"-> the first key is key('a'), the second key is key('e'), and
* the third key is key('b'). \endhtmlonly </pre>
* The key of a character, is an integer composed of primary order(short),
* secondary order(char), and tertiary order(char). Java strictly defines the
* size and signedness of its primitive data types. Therefore, the static
* functions primaryOrder(), secondaryOrder(), and tertiaryOrder() return
* int32_t to ensure the correctness of the key value.
* <p>Example of the iterator usage: (without error checking)
* <pre>
* \code
* void CollationElementIterator_Example()
* {
* UnicodeString str = "This is a test";
* UErrorCode success = U_ZERO_ERROR;
* RuleBasedCollator* rbc =
* (RuleBasedCollator*) RuleBasedCollator::createInstance(success);
* CollationElementIterator* c =
* rbc->createCollationElementIterator( str );
* int32_t order = c->next(success);
* c->reset();
* order = c->previous(success);
* delete c;
* delete rbc;
* }
* \endcode
* </pre>
* <p>
* The method next() returns the collation order of the next character based on
* the comparison level of the collator. The method previous() returns the
* collation order of the previous character based on the comparison level of
* the collator. The Collation Element Iterator moves only in one direction
* between calls to reset(), setOffset(), or setText(). That is, next()
* and previous() can not be inter-used. Whenever previous() is to be called after
* next() or vice versa, reset(), setOffset() or setText() has to be called first
* to reset the status, shifting pointers to either the end or the start of
* the string (reset() or setText()), or the specified position (setOffset()).
* Hence at the next call of next() or previous(), the first or last collation order,
* or collation order at the specified position will be returned. If a change of
* direction is done without one of these calls, the result is undefined.
* <p>
* The result of a forward iterate (next()) and reversed result of the backward
* iterate (previous()) on the same string are equivalent, if collation orders
* with the value 0 are ignored.
* Character based on the comparison level of the collator. A collation order
* consists of primary order, secondary order and tertiary order. The data
* type of the collation order is <strong>int32_t</strong>.
*
* Note, CollationElementIterator should not be subclassed.
* @see Collator
* @see RuleBasedCollator
* @version 1.8 Jan 16 2001
*/
class U_I18N_API CollationElementIterator final : public UObject {
public:
// CollationElementIterator public data member ------------------------------
enum {
/**
* NULLORDER indicates that an error has occurred while processing
* @stable ICU 2.0
*/
NULLORDER = static_cast<int32_t>(0xffffffff)
};
// CollationElementIterator public constructor/destructor -------------------
/**
* Copy constructor.
*
* @param other the object to be copied from
* @stable ICU 2.0
*/
CollationElementIterator(const CollationElementIterator& other);
/**
* Destructor
* @stable ICU 2.0
*/
virtual ~CollationElementIterator();
// CollationElementIterator public methods ----------------------------------
/**
* Returns true if "other" is the same as "this"
*
* @param other the object to be compared
* @return true if "other" is the same as "this"
* @stable ICU 2.0
*/
bool operator==(const CollationElementIterator& other) const;
/**
* Returns true if "other" is not the same as "this".
*
* @param other the object to be compared
* @return true if "other" is not the same as "this"
* @stable ICU 2.0
*/
bool operator!=(const CollationElementIterator& other) const;
/**
* Resets the cursor to the beginning of the string.
* @stable ICU 2.0
*/
void reset();
/**
* Gets the ordering priority of the next character in the string.
* @param status the error code status.
* @return the next character's ordering. otherwise returns NULLORDER if an
* error has occurred or if the end of string has been reached
* @stable ICU 2.0
*/
int32_t next(UErrorCode& status);
/**
* Get the ordering priority of the previous collation element in the string.
* @param status the error code status.
* @return the previous element's ordering. otherwise returns NULLORDER if an
* error has occurred or if the start of string has been reached
* @stable ICU 2.0
*/
int32_t previous(UErrorCode& status);
/**
* Gets the primary order of a collation order.
* @param order the collation order
* @return the primary order of a collation order.
* @stable ICU 2.0
*/
static inline int32_t primaryOrder(int32_t order);
/**
* Gets the secondary order of a collation order.
* @param order the collation order
* @return the secondary order of a collation order.
* @stable ICU 2.0
*/
static inline int32_t secondaryOrder(int32_t order);
/**
* Gets the tertiary order of a collation order.
* @param order the collation order
* @return the tertiary order of a collation order.
* @stable ICU 2.0
*/
static inline int32_t tertiaryOrder(int32_t order);
/**
* Return the maximum length of any expansion sequences that end with the
* specified comparison order.
* @param order a collation order returned by previous or next.
* @return maximum size of the expansion sequences ending with the collation
* element or 1 if collation element does not occur at the end of any
* expansion sequence
* @stable ICU 2.0
*/
int32_t getMaxExpansion(int32_t order) const;
/**
* Gets the comparison order in the desired strength. Ignore the other
* differences.
* @param order The order value
* @stable ICU 2.0
*/
int32_t strengthOrder(int32_t order) const;
/**
* Sets the source string.
* @param str the source string.
* @param status the error code status.
* @stable ICU 2.0
*/
void setText(const UnicodeString& str, UErrorCode& status);
/**
* Sets the source string.
* @param str the source character iterator.
* @param status the error code status.
* @stable ICU 2.0
*/
void setText(CharacterIterator& str, UErrorCode& status);
/**
* Checks if a comparison order is ignorable.
* @param order the collation order.
* @return true if a character is ignorable, false otherwise.
* @stable ICU 2.0
*/
static inline UBool isIgnorable(int32_t order);
/**
* Gets the offset of the currently processed character in the source string.
* @return the offset of the character.
* @stable ICU 2.0
*/
int32_t getOffset() const;
/**
* Sets the offset of the currently processed character in the source string.
* @param newOffset the new offset.
* @param status the error code status.
* @return the offset of the character.
* @stable ICU 2.0
*/
void setOffset(int32_t newOffset, UErrorCode& status);
/**
* ICU "poor man's RTTI", returns a UClassID for the actual class.
*
* @stable ICU 2.2
*/
virtual UClassID getDynamicClassID() const override;
/**
* ICU "poor man's RTTI", returns a UClassID for this class.
*
* @stable ICU 2.2
*/
static UClassID U_EXPORT2 getStaticClassID();
#ifndef U_HIDE_INTERNAL_API
/** @internal */
static inline CollationElementIterator *fromUCollationElements(UCollationElements *uc) {
return reinterpret_cast<CollationElementIterator *>(uc);
}
/** @internal */
static inline const CollationElementIterator *fromUCollationElements(const UCollationElements *uc) {
return reinterpret_cast<const CollationElementIterator *>(uc);
}
/** @internal */
inline UCollationElements *toUCollationElements() {
return reinterpret_cast<UCollationElements *>(this);
}
/** @internal */
inline const UCollationElements *toUCollationElements() const {
return reinterpret_cast<const UCollationElements *>(this);
}
#endif // U_HIDE_INTERNAL_API
private:
friend class RuleBasedCollator;
friend class UCollationPCE;
/**
* CollationElementIterator constructor. This takes the source string and the
* collation object. The cursor will walk thru the source string based on the
* predefined collation rules. If the source string is empty, NULLORDER will
* be returned on the calls to next().
* @param sourceText the source string.
* @param order the collation object.
* @param status the error code status.
*/
CollationElementIterator(const UnicodeString& sourceText,
const RuleBasedCollator* order, UErrorCode& status);
// Note: The constructors should take settings & tailoring, not a collator,
// to avoid circular dependencies.
// However, for operator==() we would need to be able to compare tailoring data for equality
// without making CollationData or CollationTailoring depend on TailoredSet.
// (See the implementation of RuleBasedCollator::operator==().)
// That might require creating an intermediate class that would be used
// by both CollationElementIterator and RuleBasedCollator
// but only contain the part of RBC== related to data and rules.
/**
* CollationElementIterator constructor. This takes the source string and the
* collation object. The cursor will walk thru the source string based on the
* predefined collation rules. If the source string is empty, NULLORDER will
* be returned on the calls to next().
* @param sourceText the source string.
* @param order the collation object.
* @param status the error code status.
*/
CollationElementIterator(const CharacterIterator& sourceText,
const RuleBasedCollator* order, UErrorCode& status);
/**
* Assignment operator
*
* @param other the object to be copied
*/
const CollationElementIterator&
operator=(const CollationElementIterator& other);
CollationElementIterator() = delete; // default constructor not implemented
/** Normalizes dir_=1 (just after setOffset()) to dir_=0 (just after reset()). */
inline int8_t normalizeDir() const { return dir_ == 1 ? 0 : dir_; }
static UHashtable *computeMaxExpansions(const CollationData *data, UErrorCode &errorCode);
static int32_t getMaxExpansion(const UHashtable *maxExpansions, int32_t order);
// CollationElementIterator private data members ----------------------------
CollationIterator *iter_; // owned
const RuleBasedCollator *rbc_; // aliased
uint32_t otherHalf_;
/**
* <0: backwards; 0: just after reset() (previous() begins from end);
* 1: just after setOffset(); >1: forward
*/
int8_t dir_;
/**
* Stores offsets from expansions and from unsafe-backwards iteration,
* so that getOffset() returns intermediate offsets for the CEs
* that are consistent with forward iteration.
*/
UVector32 *offsets_;
UnicodeString string_;
};
// CollationElementIterator inline method definitions --------------------------
inline int32_t CollationElementIterator::primaryOrder(int32_t order)
{
return (order >> 16) & 0xffff;
}
inline int32_t CollationElementIterator::secondaryOrder(int32_t order)
{
return (order >> 8) & 0xff;
}
inline int32_t CollationElementIterator::tertiaryOrder(int32_t order)
{
return order & 0xff;
}
inline UBool CollationElementIterator::isIgnorable(int32_t order)
{
return (order & 0xffff0000) == 0;
}
U_NAMESPACE_END
#endif /* #if !UCONFIG_NO_COLLATION */
#endif /* U_SHOW_CPLUSPLUS_API */
#endif

1387
deps/icu-small/source/i18n/unicode/coll.h vendored Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,196 @@
// © 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
/*
********************************************************************************
* Copyright (C) 2012-2016, International Business Machines
* Corporation and others. All Rights Reserved.
********************************************************************************
*
* File COMPACTDECIMALFORMAT.H
********************************************************************************
*/
#ifndef __COMPACT_DECIMAL_FORMAT_H__
#define __COMPACT_DECIMAL_FORMAT_H__
#include "unicode/utypes.h"
#if U_SHOW_CPLUSPLUS_API
/**
* \file
* \brief C++ API: Compatibility APIs for compact decimal number formatting.
*/
#if !UCONFIG_NO_FORMATTING
#include "unicode/decimfmt.h"
struct UHashtable;
U_NAMESPACE_BEGIN
class PluralRules;
/**
* **IMPORTANT:** New users are strongly encouraged to see if
* numberformatter.h fits their use case. Although not deprecated, this header
* is provided for backwards compatibility only.
*
* -----------------------------------------------------------------------------
*
* The CompactDecimalFormat produces abbreviated numbers, suitable for display in
* environments will limited real estate. For example, 'Hits: 1.2B' instead of
* 'Hits: 1,200,000,000'. The format will be appropriate for the given language,
* such as "1,2 Mrd." for German.
*
* For numbers under 1000 trillion (under 10^15, such as 123,456,789,012,345),
* the result will be short for supported languages. However, the result may
* sometimes exceed 7 characters, such as when there are combining marks or thin
* characters. In such cases, the visual width in fonts should still be short.
*
* By default, there are 3 significant digits. After creation, if more than
* three significant digits are set (with setMaximumSignificantDigits), or if a
* fixed number of digits are set (with setMaximumIntegerDigits or
* setMaximumFractionDigits), then result may be wider.
*
* At this time, parsing is not supported, and will produce a U_UNSUPPORTED_ERROR.
* Resetting the pattern prefixes or suffixes is not supported; the method calls
* are ignored.
*
* @stable ICU 51
*/
class U_I18N_API CompactDecimalFormat : public DecimalFormat {
public:
/**
* Returns a compact decimal instance for specified locale.
*
* **NOTE:** New users are strongly encouraged to use
* `number::NumberFormatter` instead of NumberFormat.
* @param inLocale the given locale.
* @param style whether to use short or long style.
* @param status error code returned here.
* @stable ICU 51
*/
static CompactDecimalFormat* U_EXPORT2 createInstance(
const Locale& inLocale, UNumberCompactStyle style, UErrorCode& status);
/**
* Copy constructor.
*
* @param source the DecimalFormat object to be copied from.
* @stable ICU 51
*/
CompactDecimalFormat(const CompactDecimalFormat& source);
/**
* Destructor.
* @stable ICU 51
*/
~CompactDecimalFormat() override;
/**
* Assignment operator.
*
* @param rhs the DecimalFormat object to be copied.
* @stable ICU 51
*/
CompactDecimalFormat& operator=(const CompactDecimalFormat& rhs);
/**
* Clone this Format object polymorphically. The caller owns the
* result and should delete it when done.
*
* @return a polymorphic copy of this CompactDecimalFormat.
* @stable ICU 51
*/
CompactDecimalFormat* clone() const override;
using DecimalFormat::format;
/**
* CompactDecimalFormat does not support parsing. This implementation
* does nothing.
* @param text Unused.
* @param result Does not change.
* @param parsePosition Does not change.
* @see Formattable
* @stable ICU 51
*/
void parse(const UnicodeString& text, Formattable& result,
ParsePosition& parsePosition) const override;
/**
* CompactDecimalFormat does not support parsing. This implementation
* sets status to U_UNSUPPORTED_ERROR
*
* @param text Unused.
* @param result Does not change.
* @param status Always set to U_UNSUPPORTED_ERROR.
* @stable ICU 51
*/
void parse(const UnicodeString& text, Formattable& result, UErrorCode& status) const override;
#ifndef U_HIDE_INTERNAL_API
/**
* Parses text from the given string as a currency amount. Unlike
* the parse() method, this method will attempt to parse a generic
* currency name, searching for a match of this object's locale's
* currency display names, or for a 3-letter ISO currency code.
* This method will fail if this format is not a currency format,
* that is, if it does not contain the currency pattern symbol
* (U+00A4) in its prefix or suffix. This implementation always returns
* nullptr.
*
* @param text the string to parse
* @param pos input-output position; on input, the position within text
* to match; must have 0 <= pos.getIndex() < text.length();
* on output, the position after the last matched character.
* If the parse fails, the position in unchanged upon output.
* @return if parse succeeds, a pointer to a newly-created CurrencyAmount
* object (owned by the caller) containing information about
* the parsed currency; if parse fails, this is nullptr.
* @internal
*/
CurrencyAmount* parseCurrency(const UnicodeString& text, ParsePosition& pos) const override;
#endif /* U_HIDE_INTERNAL_API */
/**
* Return the class ID for this class. This is useful only for
* comparing to a return value from getDynamicClassID(). For example:
* <pre>
* . Base* polymorphic_pointer = createPolymorphicObject();
* . if (polymorphic_pointer->getDynamicClassID() ==
* . Derived::getStaticClassID()) ...
* </pre>
* @return The class ID for all objects of this class.
* @stable ICU 51
*/
static UClassID U_EXPORT2 getStaticClassID();
/**
* Returns a unique class ID POLYMORPHICALLY. Pure virtual override.
* This method is to implement a simple version of RTTI, since not all
* C++ compilers support genuine RTTI. Polymorphic operator==() and
* clone() methods call this method.
*
* @return The class ID for this object. All objects of a
* given class have the same class ID. Objects of
* other classes have different class IDs.
* @stable ICU 51
*/
UClassID getDynamicClassID() const override;
private:
CompactDecimalFormat(const Locale& inLocale, UNumberCompactStyle style, UErrorCode& status);
};
U_NAMESPACE_END
#endif /* #if !UCONFIG_NO_FORMATTING */
#endif /* U_SHOW_CPLUSPLUS_API */
#endif // __COMPACT_DECIMAL_FORMAT_H__
//eof

View File

@ -0,0 +1,133 @@
// © 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
/*
**********************************************************************
* Copyright (c) 2004-2006, International Business Machines
* Corporation and others. All Rights Reserved.
**********************************************************************
* Author: Alan Liu
* Created: April 26, 2004
* Since: ICU 3.0
**********************************************************************
*/
#ifndef __CURRENCYAMOUNT_H__
#define __CURRENCYAMOUNT_H__
#include "unicode/utypes.h"
#if U_SHOW_CPLUSPLUS_API
#if !UCONFIG_NO_FORMATTING
#include "unicode/measure.h"
#include "unicode/currunit.h"
/**
* \file
* \brief C++ API: Currency Amount Object.
*/
U_NAMESPACE_BEGIN
/**
*
* A currency together with a numeric amount, such as 200 USD.
*
* @author Alan Liu
* @stable ICU 3.0
*/
class U_I18N_API CurrencyAmount: public Measure {
public:
/**
* Construct an object with the given numeric amount and the given
* ISO currency code.
* @param amount a numeric object; amount.isNumeric() must be true
* @param isoCode the 3-letter ISO 4217 currency code; must not be
* nullptr and must have length 3
* @param ec input-output error code. If the amount or the isoCode
* is invalid, then this will be set to a failing value.
* @stable ICU 3.0
*/
CurrencyAmount(const Formattable& amount, ConstChar16Ptr isoCode,
UErrorCode &ec);
/**
* Construct an object with the given numeric amount and the given
* ISO currency code.
* @param amount the amount of the given currency
* @param isoCode the 3-letter ISO 4217 currency code; must not be
* nullptr and must have length 3
* @param ec input-output error code. If the isoCode is invalid,
* then this will be set to a failing value.
* @stable ICU 3.0
*/
CurrencyAmount(double amount, ConstChar16Ptr isoCode,
UErrorCode &ec);
/**
* Copy constructor
* @stable ICU 3.0
*/
CurrencyAmount(const CurrencyAmount& other);
/**
* Assignment operator
* @stable ICU 3.0
*/
CurrencyAmount& operator=(const CurrencyAmount& other);
/**
* Return a polymorphic clone of this object. The result will
* have the same class as returned by getDynamicClassID().
* @stable ICU 3.0
*/
virtual CurrencyAmount* clone() const override;
/**
* Destructor
* @stable ICU 3.0
*/
virtual ~CurrencyAmount();
/**
* Returns a unique class ID for this object POLYMORPHICALLY.
* This method implements a simple form of RTTI used by ICU.
* @return The class ID for this object. All objects of a given
* class have the same class ID. Objects of other classes have
* different class IDs.
* @stable ICU 3.0
*/
virtual UClassID getDynamicClassID() const override;
/**
* Returns the class ID for this class. This is used to compare to
* the return value of getDynamicClassID().
* @return The class ID for all objects of this class.
* @stable ICU 3.0
*/
static UClassID U_EXPORT2 getStaticClassID();
/**
* Return the currency unit object of this object.
* @stable ICU 3.0
*/
const CurrencyUnit& getCurrency() const;
/**
* Return the ISO currency code of this object.
* @stable ICU 3.0
*/
inline const char16_t* getISOCurrency() const;
};
inline const char16_t* CurrencyAmount::getISOCurrency() const {
return getCurrency().getISOCurrency();
}
U_NAMESPACE_END
#endif // !UCONFIG_NO_FORMATTING
#endif /* U_SHOW_CPLUSPLUS_API */
#endif // __CURRENCYAMOUNT_H__

View File

@ -0,0 +1,274 @@
// © 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
/*
*******************************************************************************
* Copyright (C) 2009-2015, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
*/
#ifndef CURRPINF_H
#define CURRPINF_H
#include "unicode/utypes.h"
#if U_SHOW_CPLUSPLUS_API
/**
* \file
* \brief C++ API: Currency Plural Information used by Decimal Format
*/
#if !UCONFIG_NO_FORMATTING
#include "unicode/unistr.h"
U_NAMESPACE_BEGIN
class Locale;
class PluralRules;
class Hashtable;
/**
* This class represents the information needed by
* DecimalFormat to format currency plural,
* such as "3.00 US dollars" or "1.00 US dollar".
* DecimalFormat creates for itself an instance of
* CurrencyPluralInfo from its locale data.
* If you need to change any of these symbols, you can get the
* CurrencyPluralInfo object from your
* DecimalFormat and modify it.
*
* Following are the information needed for currency plural format and parse:
* locale information,
* plural rule of the locale,
* currency plural pattern of the locale.
*
* @stable ICU 4.2
*/
class U_I18N_API CurrencyPluralInfo : public UObject {
public:
/**
* Create a CurrencyPluralInfo object for the default locale.
* @param status output param set to success/failure code on exit
* @stable ICU 4.2
*/
CurrencyPluralInfo(UErrorCode& status);
/**
* Create a CurrencyPluralInfo object for the given locale.
* @param locale the locale
* @param status output param set to success/failure code on exit
* @stable ICU 4.2
*/
CurrencyPluralInfo(const Locale& locale, UErrorCode& status);
/**
* Copy constructor
*
* @stable ICU 4.2
*/
CurrencyPluralInfo(const CurrencyPluralInfo& info);
/**
* Assignment operator
*
* @stable ICU 4.2
*/
CurrencyPluralInfo& operator=(const CurrencyPluralInfo& info);
/**
* Destructor
*
* @stable ICU 4.2
*/
virtual ~CurrencyPluralInfo();
/**
* Equal operator.
*
* @stable ICU 4.2
*/
bool operator==(const CurrencyPluralInfo& info) const;
/**
* Not equal operator
*
* @stable ICU 4.2
*/
bool operator!=(const CurrencyPluralInfo& info) const;
/**
* Clone
*
* @stable ICU 4.2
*/
CurrencyPluralInfo* clone() const;
/**
* Gets plural rules of this locale, used for currency plural format
*
* @return plural rule
* @stable ICU 4.2
*/
const PluralRules* getPluralRules() const;
/**
* Given a plural count, gets currency plural pattern of this locale,
* used for currency plural format
*
* @param pluralCount currency plural count
* @param result output param to receive the pattern
* @return a currency plural pattern based on plural count
* @stable ICU 4.2
*/
UnicodeString& getCurrencyPluralPattern(const UnicodeString& pluralCount,
UnicodeString& result) const;
/**
* Get locale
*
* @return locale
* @stable ICU 4.2
*/
const Locale& getLocale() const;
/**
* Set plural rules.
* The plural rule is set when CurrencyPluralInfo
* instance is created.
* You can call this method to reset plural rules only if you want
* to modify the default plural rule of the locale.
*
* @param ruleDescription new plural rule description
* @param status output param set to success/failure code on exit
* @stable ICU 4.2
*/
void setPluralRules(const UnicodeString& ruleDescription,
UErrorCode& status);
/**
* Set currency plural pattern.
* The currency plural pattern is set when CurrencyPluralInfo
* instance is created.
* You can call this method to reset currency plural pattern only if
* you want to modify the default currency plural pattern of the locale.
*
* @param pluralCount the plural count for which the currency pattern will
* be overridden.
* @param pattern the new currency plural pattern
* @param status output param set to success/failure code on exit
* @stable ICU 4.2
*/
void setCurrencyPluralPattern(const UnicodeString& pluralCount,
const UnicodeString& pattern,
UErrorCode& status);
/**
* Set locale
*
* @param loc the new locale to set
* @param status output param set to success/failure code on exit
* @stable ICU 4.2
*/
void setLocale(const Locale& loc, UErrorCode& status);
/**
* ICU "poor man's RTTI", returns a UClassID for the actual class.
*
* @stable ICU 4.2
*/
virtual UClassID getDynamicClassID() const override;
/**
* ICU "poor man's RTTI", returns a UClassID for this class.
*
* @stable ICU 4.2
*/
static UClassID U_EXPORT2 getStaticClassID();
private:
friend class DecimalFormat;
friend class DecimalFormatImpl;
void initialize(const Locale& loc, UErrorCode& status);
void setupCurrencyPluralPattern(const Locale& loc, UErrorCode& status);
/*
* delete hash table
*
* @param hTable hash table to be deleted
*/
void deleteHash(Hashtable* hTable);
/*
* initialize hash table
*
* @param status output param set to success/failure code on exit
* @return hash table initialized
*/
Hashtable* initHash(UErrorCode& status);
/**
* copy hash table
*
* @param source the source to copy from
* @param target the target to copy to
* @param status error code
*/
void copyHash(const Hashtable* source, Hashtable* target, UErrorCode& status);
//-------------------- private data member ---------------------
// map from plural count to currency plural pattern, for example
// a plural pattern defined in "CurrencyUnitPatterns" is
// "one{{0} {1}}", in which "one" is a plural count
// and "{0} {1}" is a currency plural pattern".
// The currency plural pattern saved in this mapping is the pattern
// defined in "CurrencyUnitPattern" by replacing
// {0} with the number format pattern,
// and {1} with 3 currency sign.
Hashtable* fPluralCountToCurrencyUnitPattern;
/*
* The plural rule is used to format currency plural name,
* for example: "3.00 US Dollars".
* If there are 3 currency signs in the currency pattern,
* the 3 currency signs will be replaced by currency plural name.
*/
PluralRules* fPluralRules;
// locale
Locale* fLocale;
private:
/**
* An internal status variable used to indicate that the object is in an 'invalid' state.
* Used by copy constructor, the assignment operator and the clone method.
*/
UErrorCode fInternalStatus;
};
inline bool
CurrencyPluralInfo::operator!=(const CurrencyPluralInfo& info) const {
return !operator==(info);
}
U_NAMESPACE_END
#endif /* #if !UCONFIG_NO_FORMATTING */
#endif /* U_SHOW_CPLUSPLUS_API */
#endif // _CURRPINFO
//eof

View File

@ -0,0 +1,146 @@
// © 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
/*
**********************************************************************
* Copyright (c) 2004-2014, International Business Machines
* Corporation and others. All Rights Reserved.
**********************************************************************
* Author: Alan Liu
* Created: April 26, 2004
* Since: ICU 3.0
**********************************************************************
*/
#ifndef __CURRENCYUNIT_H__
#define __CURRENCYUNIT_H__
#include "unicode/utypes.h"
#if U_SHOW_CPLUSPLUS_API
#if !UCONFIG_NO_FORMATTING
#include "unicode/measunit.h"
/**
* \file
* \brief C++ API: Currency Unit Information.
*/
U_NAMESPACE_BEGIN
/**
* A unit of currency, such as USD (U.S. dollars) or JPY (Japanese
* yen). This class is a thin wrapper over a char16_t string that
* subclasses MeasureUnit, for use with Measure and MeasureFormat.
*
* @author Alan Liu
* @stable ICU 3.0
*/
class U_I18N_API CurrencyUnit: public MeasureUnit {
public:
/**
* Default constructor. Initializes currency code to "XXX" (no currency).
* @stable ICU 60
*/
CurrencyUnit();
/**
* Construct an object with the given ISO currency code.
*
* @param isoCode the 3-letter ISO 4217 currency code; must have
* length 3 and need not be NUL-terminated. If nullptr, the currency
* is initialized to the unknown currency XXX.
* @param ec input-output error code. If the isoCode is invalid,
* then this will be set to a failing value.
* @stable ICU 3.0
*/
CurrencyUnit(ConstChar16Ptr isoCode, UErrorCode &ec);
/**
* Construct an object with the given ISO currency code.
*
* @param isoCode the 3-letter ISO 4217 currency code; must have
* length 3. If invalid, the currency is initialized to XXX.
* @param ec input-output error code. If the isoCode is invalid,
* then this will be set to a failing value.
* @stable ICU 64
*/
CurrencyUnit(StringPiece isoCode, UErrorCode &ec);
/**
* Copy constructor
* @stable ICU 3.0
*/
CurrencyUnit(const CurrencyUnit& other);
/**
* Copy constructor from MeasureUnit. This constructor allows you to
* restore a CurrencyUnit that was sliced to MeasureUnit.
*
* @param measureUnit The MeasureUnit to copy from.
* @param ec Set to a failing value if the MeasureUnit is not a currency.
* @stable ICU 60
*/
CurrencyUnit(const MeasureUnit& measureUnit, UErrorCode &ec);
/**
* Assignment operator
* @stable ICU 3.0
*/
CurrencyUnit& operator=(const CurrencyUnit& other);
/**
* Return a polymorphic clone of this object. The result will
* have the same class as returned by getDynamicClassID().
* @stable ICU 3.0
*/
virtual CurrencyUnit* clone() const override;
/**
* Destructor
* @stable ICU 3.0
*/
virtual ~CurrencyUnit();
/**
* Returns a unique class ID for this object POLYMORPHICALLY.
* This method implements a simple form of RTTI used by ICU.
* @return The class ID for this object. All objects of a given
* class have the same class ID. Objects of other classes have
* different class IDs.
* @stable ICU 3.0
*/
virtual UClassID getDynamicClassID() const override;
/**
* Returns the class ID for this class. This is used to compare to
* the return value of getDynamicClassID().
* @return The class ID for all objects of this class.
* @stable ICU 3.0
*/
static UClassID U_EXPORT2 getStaticClassID();
/**
* Return the ISO currency code of this object.
* @stable ICU 3.0
*/
inline const char16_t* getISOCurrency() const;
private:
/**
* The ISO 4217 code of this object.
*/
char16_t isoCode[4];
};
inline const char16_t* CurrencyUnit::getISOCurrency() const {
return isoCode;
}
U_NAMESPACE_END
#endif // !UCONFIG_NO_FORMATTING
#endif /* U_SHOW_CPLUSPLUS_API */
#endif // __CURRENCYUNIT_H__

View File

@ -0,0 +1,968 @@
// © 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
/*
********************************************************************************
* Copyright (C) 1997-2016, International Business Machines
* Corporation and others. All Rights Reserved.
********************************************************************************
*
* File DATEFMT.H
*
* Modification History:
*
* Date Name Description
* 02/19/97 aliu Converted from java.
* 04/01/97 aliu Added support for centuries.
* 07/23/98 stephen JDK 1.2 sync
* 11/15/99 weiv Added support for week of year/day of week formatting
********************************************************************************
*/
#ifndef DATEFMT_H
#define DATEFMT_H
#include "unicode/utypes.h"
#if U_SHOW_CPLUSPLUS_API
#if !UCONFIG_NO_FORMATTING
#include "unicode/udat.h"
#include "unicode/calendar.h"
#include "unicode/numfmt.h"
#include "unicode/format.h"
#include "unicode/locid.h"
#include "unicode/enumset.h"
#include "unicode/udisplaycontext.h"
/**
* \file
* \brief C++ API: Abstract class for converting dates.
*/
U_NAMESPACE_BEGIN
class TimeZone;
class DateTimePatternGenerator;
/**
* \cond
* Export an explicit template instantiation. (See digitlst.h, datefmt.h, and others.)
* (When building DLLs for Windows this is required.)
*/
#if U_PF_WINDOWS <= U_PLATFORM && U_PLATFORM <= U_PF_CYGWIN && !defined(U_IN_DOXYGEN)
template class U_I18N_API EnumSet<UDateFormatBooleanAttribute,
0,
UDAT_BOOLEAN_ATTRIBUTE_COUNT>;
#endif
/** \endcond */
/**
* DateFormat is an abstract class for a family of classes that convert dates and
* times from their internal representations to textual form and back again in a
* language-independent manner. Converting from the internal representation (milliseconds
* since midnight, January 1, 1970) to text is known as "formatting," and converting
* from text to millis is known as "parsing." We currently define only one concrete
* subclass of DateFormat: SimpleDateFormat, which can handle pretty much all normal
* date formatting and parsing actions.
* <P>
* DateFormat helps you to format and parse dates for any locale. Your code can
* be completely independent of the locale conventions for months, days of the
* week, or even the calendar format: lunar vs. solar.
* <P>
* To format a date for the current Locale, use one of the static factory
* methods:
* <pre>
* \code
* DateFormat* dfmt = DateFormat::createDateInstance();
* UDate myDate = Calendar::getNow();
* UnicodeString myString;
* myString = dfmt->format( myDate, myString );
* \endcode
* </pre>
* If you are formatting multiple numbers, it is more efficient to get the
* format and use it multiple times so that the system doesn't have to fetch the
* information about the local language and country conventions multiple times.
* <pre>
* \code
* DateFormat* df = DateFormat::createDateInstance();
* UnicodeString myString;
* UDate myDateArr[] = { 0.0, 100000000.0, 2000000000.0 }; // test values
* for (int32_t i = 0; i < 3; ++i) {
* myString.remove();
* cout << df->format( myDateArr[i], myString ) << endl;
* }
* \endcode
* </pre>
* To get specific fields of a date, you can use UFieldPosition to
* get specific fields.
* <pre>
* \code
* DateFormat* dfmt = DateFormat::createDateInstance();
* FieldPosition pos(DateFormat::YEAR_FIELD);
* UnicodeString myString;
* myString = dfmt->format( myDate, myString );
* cout << myString << endl;
* cout << pos.getBeginIndex() << "," << pos. getEndIndex() << endl;
* \endcode
* </pre>
* To format a date for a different Locale, specify it in the call to
* createDateInstance().
* <pre>
* \code
* DateFormat* df =
* DateFormat::createDateInstance( DateFormat::SHORT, Locale::getFrance());
* \endcode
* </pre>
* You can use a DateFormat to parse also.
* <pre>
* \code
* UErrorCode status = U_ZERO_ERROR;
* UDate myDate = df->parse(myString, status);
* \endcode
* </pre>
* Use createDateInstance() to produce the normal date format for that country.
* There are other static factory methods available. Use createTimeInstance()
* to produce the normal time format for that country. Use createDateTimeInstance()
* to produce a DateFormat that formats both date and time. You can pass in
* different options to these factory methods to control the length of the
* result; from SHORT to MEDIUM to LONG to FULL. The exact result depends on the
* locale, but generally:
* <ul type=round>
* <li> SHORT is completely numeric, such as 12/13/52 or 3:30pm
* <li> MEDIUM is longer, such as Jan 12, 1952
* <li> LONG is longer, such as January 12, 1952 or 3:30:32pm
* <li> FULL is pretty completely specified, such as
* Tuesday, April 12, 1952 AD or 3:30:42pm PST.
* </ul>
* You can also set the time zone on the format if you wish. If you want even
* more control over the format or parsing, (or want to give your users more
* control), you can try casting the DateFormat you get from the factory methods
* to a SimpleDateFormat. This will work for the majority of countries; just
* remember to check getDynamicClassID() before carrying out the cast.
* <P>
* You can also use forms of the parse and format methods with ParsePosition and
* FieldPosition to allow you to
* <ul type=round>
* <li> Progressively parse through pieces of a string.
* <li> Align any particular field, or find out where it is for selection
* on the screen.
* </ul>
*
* <p><em>User subclasses are not supported.</em> While clients may write
* subclasses, such code will not necessarily work and will not be
* guaranteed to work stably from release to release.
*/
class U_I18N_API DateFormat : public Format {
public:
/**
* Constants for various style patterns. These reflect the order of items in
* the DateTimePatterns resource. There are 4 time patterns, 4 date patterns,
* the default date-time pattern, and 4 date-time patterns. Each block of 4 values
* in the resource occurs in the order full, long, medium, short.
* @stable ICU 2.4
*/
enum EStyle
{
kNone = -1,
kFull = 0,
kLong = 1,
kMedium = 2,
kShort = 3,
kDateOffset = kShort + 1,
// kFull + kDateOffset = 4
// kLong + kDateOffset = 5
// kMedium + kDateOffset = 6
// kShort + kDateOffset = 7
kDateTime = 8,
// Default DateTime
kDateTimeOffset = kDateTime + 1,
// kFull + kDateTimeOffset = 9
// kLong + kDateTimeOffset = 10
// kMedium + kDateTimeOffset = 11
// kShort + kDateTimeOffset = 12
// relative dates
kRelative = (1 << 7),
kFullRelative = (kFull | kRelative),
kLongRelative = kLong | kRelative,
kMediumRelative = kMedium | kRelative,
kShortRelative = kShort | kRelative,
kDefault = kMedium,
/**
* These constants are provided for backwards compatibility only.
* Please use the C++ style constants defined above.
*/
FULL = kFull,
LONG = kLong,
MEDIUM = kMedium,
SHORT = kShort,
DEFAULT = kDefault,
DATE_OFFSET = kDateOffset,
NONE = kNone,
DATE_TIME = kDateTime
};
/**
* Destructor.
* @stable ICU 2.0
*/
virtual ~DateFormat();
/**
* Clones this object polymorphically.
* The caller owns the result and should delete it when done.
* @return clone, or nullptr if an error occurred
* @stable ICU 2.0
*/
virtual DateFormat* clone() const override = 0;
/**
* Equality operator. Returns true if the two formats have the same behavior.
* @stable ICU 2.0
*/
virtual bool operator==(const Format&) const override;
using Format::format;
/**
* Format an object to produce a string. This method handles Formattable
* objects with a UDate type. If a the Formattable object type is not a Date,
* then it returns a failing UErrorCode.
*
* @param obj The object to format. Must be a Date.
* @param appendTo Output parameter to receive result.
* Result is appended to existing contents.
* @param pos On input: an alignment field, if desired.
* On output: the offsets of the alignment field.
* @param status Output param filled with success/failure status.
* @return Reference to 'appendTo' parameter.
* @stable ICU 2.0
*/
virtual UnicodeString& format(const Formattable& obj,
UnicodeString& appendTo,
FieldPosition& pos,
UErrorCode& status) const override;
/**
* Format an object to produce a string. This method handles Formattable
* objects with a UDate type. If a the Formattable object type is not a Date,
* then it returns a failing UErrorCode.
*
* @param obj The object to format. Must be a Date.
* @param appendTo Output parameter to receive result.
* Result is appended to existing contents.
* @param posIter On return, can be used to iterate over positions
* of fields generated by this format call. Field values
* are defined in UDateFormatField. Can be nullptr.
* @param status Output param filled with success/failure status.
* @return Reference to 'appendTo' parameter.
* @stable ICU 4.4
*/
virtual UnicodeString& format(const Formattable& obj,
UnicodeString& appendTo,
FieldPositionIterator* posIter,
UErrorCode& status) const override;
/**
* Formats a date into a date/time string. This is an abstract method which
* concrete subclasses must implement.
* <P>
* On input, the FieldPosition parameter may have its "field" member filled with
* an enum value specifying a field. On output, the FieldPosition will be filled
* in with the text offsets for that field.
* <P> For example, given a time text
* "1996.07.10 AD at 15:08:56 PDT", if the given fieldPosition.field is
* UDAT_YEAR_FIELD, the offsets fieldPosition.beginIndex and
* statfieldPositionus.getEndIndex will be set to 0 and 4, respectively.
* <P> Notice
* that if the same time field appears more than once in a pattern, the status will
* be set for the first occurrence of that time field. For instance,
* formatting a UDate to the time string "1 PM PDT (Pacific Daylight Time)"
* using the pattern "h a z (zzzz)" and the alignment field
* DateFormat::TIMEZONE_FIELD, the offsets fieldPosition.beginIndex and
* fieldPosition.getEndIndex will be set to 5 and 8, respectively, for the first
* occurrence of the timezone pattern character 'z'.
*
* @param cal Calendar set to the date and time to be formatted
* into a date/time string. When the calendar type is
* different from the internal calendar held by this
* DateFormat instance, the date and the time zone will
* be inherited from the input calendar, but other calendar
* field values will be calculated by the internal calendar.
* @param appendTo Output parameter to receive result.
* Result is appended to existing contents.
* @param fieldPosition On input: an alignment field, if desired (see examples above)
* On output: the offsets of the alignment field (see examples above)
* @return Reference to 'appendTo' parameter.
* @stable ICU 2.1
*/
virtual UnicodeString& format( Calendar& cal,
UnicodeString& appendTo,
FieldPosition& fieldPosition) const = 0;
/**
* Formats a date into a date/time string. Subclasses should implement this method.
*
* @param cal Calendar set to the date and time to be formatted
* into a date/time string. When the calendar type is
* different from the internal calendar held by this
* DateFormat instance, the date and the time zone will
* be inherited from the input calendar, but other calendar
* field values will be calculated by the internal calendar.
* @param appendTo Output parameter to receive result.
* Result is appended to existing contents.
* @param posIter On return, can be used to iterate over positions
* of fields generated by this format call. Field values
* are defined in UDateFormatField. Can be nullptr.
* @param status error status.
* @return Reference to 'appendTo' parameter.
* @stable ICU 4.4
*/
virtual UnicodeString& format(Calendar& cal,
UnicodeString& appendTo,
FieldPositionIterator* posIter,
UErrorCode& status) const;
/**
* Formats a UDate into a date/time string.
* <P>
* On input, the FieldPosition parameter may have its "field" member filled with
* an enum value specifying a field. On output, the FieldPosition will be filled
* in with the text offsets for that field.
* <P> For example, given a time text
* "1996.07.10 AD at 15:08:56 PDT", if the given fieldPosition.field is
* UDAT_YEAR_FIELD, the offsets fieldPosition.beginIndex and
* statfieldPositionus.getEndIndex will be set to 0 and 4, respectively.
* <P> Notice
* that if the same time field appears more than once in a pattern, the status will
* be set for the first occurrence of that time field. For instance,
* formatting a UDate to the time string "1 PM PDT (Pacific Daylight Time)"
* using the pattern "h a z (zzzz)" and the alignment field
* DateFormat::TIMEZONE_FIELD, the offsets fieldPosition.beginIndex and
* fieldPosition.getEndIndex will be set to 5 and 8, respectively, for the first
* occurrence of the timezone pattern character 'z'.
*
* @param date UDate to be formatted into a date/time string.
* @param appendTo Output parameter to receive result.
* Result is appended to existing contents.
* @param fieldPosition On input: an alignment field, if desired (see examples above)
* On output: the offsets of the alignment field (see examples above)
* @return Reference to 'appendTo' parameter.
* @stable ICU 2.0
*/
UnicodeString& format( UDate date,
UnicodeString& appendTo,
FieldPosition& fieldPosition) const;
/**
* Formats a UDate into a date/time string.
*
* @param date UDate to be formatted into a date/time string.
* @param appendTo Output parameter to receive result.
* Result is appended to existing contents.
* @param posIter On return, can be used to iterate over positions
* of fields generated by this format call. Field values
* are defined in UDateFormatField. Can be nullptr.
* @param status error status.
* @return Reference to 'appendTo' parameter.
* @stable ICU 4.4
*/
UnicodeString& format(UDate date,
UnicodeString& appendTo,
FieldPositionIterator* posIter,
UErrorCode& status) const;
/**
* Formats a UDate into a date/time string. If there is a problem, you won't
* know, using this method. Use the overloaded format() method which takes a
* FieldPosition& to detect formatting problems.
*
* @param date The UDate value to be formatted into a string.
* @param appendTo Output parameter to receive result.
* Result is appended to existing contents.
* @return Reference to 'appendTo' parameter.
* @stable ICU 2.0
*/
UnicodeString& format(UDate date, UnicodeString& appendTo) const;
/**
* Parse a date/time string. For example, a time text "07/10/96 4:5 PM, PDT"
* will be parsed into a UDate that is equivalent to Date(837039928046).
* Parsing begins at the beginning of the string and proceeds as far as
* possible. Assuming no parse errors were encountered, this function
* doesn't return any information about how much of the string was consumed
* by the parsing. If you need that information, use the version of
* parse() that takes a ParsePosition.
* <P>
* By default, parsing is lenient: If the input is not in the form used by
* this object's format method but can still be parsed as a date, then the
* parse succeeds. Clients may insist on strict adherence to the format by
* calling setLenient(false).
* @see DateFormat::setLenient(boolean)
* <P>
* Note that the normal date formats associated with some calendars - such
* as the Chinese lunar calendar - do not specify enough fields to enable
* dates to be parsed unambiguously. In the case of the Chinese lunar
* calendar, while the year within the current 60-year cycle is specified,
* the number of such cycles since the start date of the calendar (in the
* ERA field of the Calendar object) is not normally part of the format,
* and parsing may assume the wrong era. For cases such as this it is
* recommended that clients parse using the method
* parse(const UnicodeString&, Calendar& cal, ParsePosition&)
* with the Calendar passed in set to the current date, or to a date
* within the era/cycle that should be assumed if absent in the format.
*
* @param text The date/time string to be parsed into a UDate value.
* @param status Output param to be set to success/failure code. If
* 'text' cannot be parsed, it will be set to a failure
* code.
* @return The parsed UDate value, if successful.
* @stable ICU 2.0
*/
virtual UDate parse( const UnicodeString& text,
UErrorCode& status) const;
/**
* Parse a date/time string beginning at the given parse position. For
* example, a time text "07/10/96 4:5 PM, PDT" will be parsed into a Date
* that is equivalent to Date(837039928046).
* <P>
* By default, parsing is lenient: If the input is not in the form used by
* this object's format method but can still be parsed as a date, then the
* parse succeeds. Clients may insist on strict adherence to the format by
* calling setLenient(false).
* @see DateFormat::setLenient(boolean)
*
* @param text The date/time string to be parsed.
* @param cal A Calendar set on input to the date and time to be used for
* missing values in the date/time string being parsed, and set
* on output to the parsed date/time. When the calendar type is
* different from the internal calendar held by this DateFormat
* instance, the internal calendar will be cloned to a work
* calendar set to the same milliseconds and time zone as the
* cal parameter, field values will be parsed based on the work
* calendar, then the result (milliseconds and time zone) will
* be set in this calendar.
* @param pos On input, the position at which to start parsing; on
* output, the position at which parsing terminated, or the
* start position if the parse failed.
* @stable ICU 2.1
*/
virtual void parse( const UnicodeString& text,
Calendar& cal,
ParsePosition& pos) const = 0;
/**
* Parse a date/time string beginning at the given parse position. For
* example, a time text "07/10/96 4:5 PM, PDT" will be parsed into a Date
* that is equivalent to Date(837039928046).
* <P>
* By default, parsing is lenient: If the input is not in the form used by
* this object's format method but can still be parsed as a date, then the
* parse succeeds. Clients may insist on strict adherence to the format by
* calling setLenient(false).
* @see DateFormat::setLenient(boolean)
* <P>
* Note that the normal date formats associated with some calendars - such
* as the Chinese lunar calendar - do not specify enough fields to enable
* dates to be parsed unambiguously. In the case of the Chinese lunar
* calendar, while the year within the current 60-year cycle is specified,
* the number of such cycles since the start date of the calendar (in the
* ERA field of the Calendar object) is not normally part of the format,
* and parsing may assume the wrong era. For cases such as this it is
* recommended that clients parse using the method
* parse(const UnicodeString&, Calendar& cal, ParsePosition&)
* with the Calendar passed in set to the current date, or to a date
* within the era/cycle that should be assumed if absent in the format.
*
* @param text The date/time string to be parsed into a UDate value.
* @param pos On input, the position at which to start parsing; on
* output, the position at which parsing terminated, or the
* start position if the parse failed.
* @return A valid UDate if the input could be parsed.
* @stable ICU 2.0
*/
UDate parse( const UnicodeString& text,
ParsePosition& pos) const;
/**
* Parse a string to produce an object. This methods handles parsing of
* date/time strings into Formattable objects with UDate types.
* <P>
* Before calling, set parse_pos.index to the offset you want to start
* parsing at in the source. After calling, parse_pos.index is the end of
* the text you parsed. If error occurs, index is unchanged.
* <P>
* When parsing, leading whitespace is discarded (with a successful parse),
* while trailing whitespace is left as is.
* <P>
* See Format::parseObject() for more.
*
* @param source The string to be parsed into an object.
* @param result Formattable to be set to the parse result.
* If parse fails, return contents are undefined.
* @param parse_pos The position to start parsing at. Upon return
* this param is set to the position after the
* last character successfully parsed. If the
* source is not parsed successfully, this param
* will remain unchanged.
* @stable ICU 2.0
*/
virtual void parseObject(const UnicodeString& source,
Formattable& result,
ParsePosition& parse_pos) const override;
/**
* Create a default date/time formatter that uses the SHORT style for both
* the date and the time.
*
* @return A date/time formatter which the caller owns.
* @stable ICU 2.0
*/
static DateFormat* U_EXPORT2 createInstance();
/**
* Creates a time formatter with the given formatting style for the given
* locale.
*
* @param style The given formatting style. For example,
* SHORT for "h:mm a" in the US locale. Relative
* time styles are not currently supported.
* @param aLocale The given locale.
* @return A time formatter which the caller owns.
* @stable ICU 2.0
*/
static DateFormat* U_EXPORT2 createTimeInstance(EStyle style = kDefault,
const Locale& aLocale = Locale::getDefault());
/**
* Creates a date formatter with the given formatting style for the given
* const locale.
*
* @param style The given formatting style. For example, SHORT for "M/d/yy" in the
* US locale. As currently implemented, relative date formatting only
* affects a limited range of calendar days before or after the
* current date, based on the CLDR &lt;field type="day"&gt;/&lt;relative&gt; data:
* For example, in English, "Yesterday", "Today", and "Tomorrow".
* Outside of this range, dates are formatted using the corresponding
* non-relative style.
* @param aLocale The given locale.
* @return A date formatter which the caller owns.
* @stable ICU 2.0
*/
static DateFormat* U_EXPORT2 createDateInstance(EStyle style = kDefault,
const Locale& aLocale = Locale::getDefault());
/**
* Creates a date/time formatter with the given formatting styles for the
* given locale.
*
* @param dateStyle The given formatting style for the date portion of the result.
* For example, SHORT for "M/d/yy" in the US locale. As currently
* implemented, relative date formatting only affects a limited range
* of calendar days before or after the current date, based on the
* CLDR &lt;field type="day"&gt;/&lt;relative&gt; data: For example, in English,
* "Yesterday", "Today", and "Tomorrow". Outside of this range, dates
* are formatted using the corresponding non-relative style.
* @param timeStyle The given formatting style for the time portion of the result.
* For example, SHORT for "h:mm a" in the US locale. Relative
* time styles are not currently supported.
* @param aLocale The given locale.
* @return A date/time formatter which the caller owns.
* @stable ICU 2.0
*/
static DateFormat* U_EXPORT2 createDateTimeInstance(EStyle dateStyle = kDefault,
EStyle timeStyle = kDefault,
const Locale& aLocale = Locale::getDefault());
#ifndef U_HIDE_INTERNAL_API
/**
* Returns the best pattern given a skeleton and locale.
* @param locale the locale
* @param skeleton the skeleton
* @param status ICU error returned here
* @return the best pattern.
* @internal For ICU use only.
*/
static UnicodeString getBestPattern(
const Locale &locale,
const UnicodeString &skeleton,
UErrorCode &status);
#endif /* U_HIDE_INTERNAL_API */
/**
* Creates a date/time formatter for the given skeleton and
* default locale.
*
* @param skeleton The skeleton e.g "yMMMMd." Fields in the skeleton can
* be in any order, and this method uses the locale to
* map the skeleton to a pattern that includes locale
* specific separators with the fields in the appropriate
* order for that locale.
* @param status Any error returned here.
* @return A date/time formatter which the caller owns.
* @stable ICU 55
*/
static DateFormat* U_EXPORT2 createInstanceForSkeleton(
const UnicodeString& skeleton,
UErrorCode &status);
/**
* Creates a date/time formatter for the given skeleton and locale.
*
* @param skeleton The skeleton e.g "yMMMMd." Fields in the skeleton can
* be in any order, and this method uses the locale to
* map the skeleton to a pattern that includes locale
* specific separators with the fields in the appropriate
* order for that locale.
* @param locale The given locale.
* @param status Any error returned here.
* @return A date/time formatter which the caller owns.
* @stable ICU 55
*/
static DateFormat* U_EXPORT2 createInstanceForSkeleton(
const UnicodeString& skeleton,
const Locale &locale,
UErrorCode &status);
/**
* Creates a date/time formatter for the given skeleton and locale.
*
* @param calendarToAdopt the calendar returned DateFormat is to use.
* @param skeleton The skeleton e.g "yMMMMd." Fields in the skeleton can
* be in any order, and this method uses the locale to
* map the skeleton to a pattern that includes locale
* specific separators with the fields in the appropriate
* order for that locale.
* @param locale The given locale.
* @param status Any error returned here.
* @return A date/time formatter which the caller owns.
* @stable ICU 55
*/
static DateFormat* U_EXPORT2 createInstanceForSkeleton(
Calendar *calendarToAdopt,
const UnicodeString& skeleton,
const Locale &locale,
UErrorCode &status);
/**
* Gets the set of locales for which DateFormats are installed.
* @param count Filled in with the number of locales in the list that is returned.
* @return the set of locales for which DateFormats are installed. The caller
* does NOT own this list and must not delete it.
* @stable ICU 2.0
*/
static const Locale* U_EXPORT2 getAvailableLocales(int32_t& count);
/**
* Returns whether both date/time parsing in the encapsulated Calendar object and DateFormat whitespace &
* numeric processing is lenient.
* @stable ICU 2.0
*/
virtual UBool isLenient() const;
/**
* Specifies whether date/time parsing is to be lenient. With
* lenient parsing, the parser may use heuristics to interpret inputs that
* do not precisely match this object's format. Without lenient parsing,
* inputs must match this object's format more closely.
*
* Note: ICU 53 introduced finer grained control of leniency (and added
* new control points) making the preferred method a combination of
* setCalendarLenient() & setBooleanAttribute() calls.
* This method supports prior functionality but may not support all
* future leniency control & behavior of DateFormat. For control of pre 53 leniency,
* Calendar and DateFormat whitespace & numeric tolerance, this method is safe to
* use. However, mixing leniency control via this method and modification of the
* newer attributes via setBooleanAttribute() may produce undesirable
* results.
*
* @param lenient True specifies date/time interpretation to be lenient.
* @see Calendar::setLenient
* @stable ICU 2.0
*/
virtual void setLenient(UBool lenient);
/**
* Returns whether date/time parsing in the encapsulated Calendar object processing is lenient.
* @stable ICU 53
*/
virtual UBool isCalendarLenient() const;
/**
* Specifies whether encapsulated Calendar date/time parsing is to be lenient. With
* lenient parsing, the parser may use heuristics to interpret inputs that
* do not precisely match this object's format. Without lenient parsing,
* inputs must match this object's format more closely.
* @param lenient when true, parsing is lenient
* @see com.ibm.icu.util.Calendar#setLenient
* @stable ICU 53
*/
virtual void setCalendarLenient(UBool lenient);
/**
* Gets the calendar associated with this date/time formatter.
* The calendar is owned by the formatter and must not be modified.
* Also, the calendar does not reflect the results of a parse operation.
* To parse to a calendar, use {@link #parse(const UnicodeString&, Calendar& cal, ParsePosition&) const parse(const UnicodeString&, Calendar& cal, ParsePosition&)}
* @return the calendar associated with this date/time formatter.
* @stable ICU 2.0
*/
virtual const Calendar* getCalendar() const;
/**
* Set the calendar to be used by this date format. Initially, the default
* calendar for the specified or default locale is used. The caller should
* not delete the Calendar object after it is adopted by this call.
* Adopting a new calendar will change to the default symbols.
*
* @param calendarToAdopt Calendar object to be adopted.
* @stable ICU 2.0
*/
virtual void adoptCalendar(Calendar* calendarToAdopt);
/**
* Set the calendar to be used by this date format. Initially, the default
* calendar for the specified or default locale is used.
*
* @param newCalendar Calendar object to be set.
* @stable ICU 2.0
*/
virtual void setCalendar(const Calendar& newCalendar);
/**
* Gets the number formatter which this date/time formatter uses to format
* and parse the numeric portions of the pattern.
* @return the number formatter which this date/time formatter uses.
* @stable ICU 2.0
*/
virtual const NumberFormat* getNumberFormat() const;
/**
* Allows you to set the number formatter. The caller should
* not delete the NumberFormat object after it is adopted by this call.
* @param formatToAdopt NumberFormat object to be adopted.
* @stable ICU 2.0
*/
virtual void adoptNumberFormat(NumberFormat* formatToAdopt);
/**
* Allows you to set the number formatter.
* @param newNumberFormat NumberFormat object to be set.
* @stable ICU 2.0
*/
virtual void setNumberFormat(const NumberFormat& newNumberFormat);
/**
* Returns a reference to the TimeZone used by this DateFormat's calendar.
* @return the time zone associated with the calendar of DateFormat.
* @stable ICU 2.0
*/
virtual const TimeZone& getTimeZone() const;
/**
* Sets the time zone for the calendar of this DateFormat object. The caller
* no longer owns the TimeZone object and should not delete it after this call.
* @param zoneToAdopt the TimeZone to be adopted.
* @stable ICU 2.0
*/
virtual void adoptTimeZone(TimeZone* zoneToAdopt);
/**
* Sets the time zone for the calendar of this DateFormat object.
* @param zone the new time zone.
* @stable ICU 2.0
*/
virtual void setTimeZone(const TimeZone& zone);
/**
* Set a particular UDisplayContext value in the formatter, such as
* UDISPCTX_CAPITALIZATION_FOR_STANDALONE.
* @param value The UDisplayContext value to set.
* @param status Input/output status. If at entry this indicates a failure
* status, the function will do nothing; otherwise this will be
* updated with any new status from the function.
* @stable ICU 53
*/
virtual void setContext(UDisplayContext value, UErrorCode& status);
/**
* Get the formatter's UDisplayContext value for the specified UDisplayContextType,
* such as UDISPCTX_TYPE_CAPITALIZATION.
* @param type The UDisplayContextType whose value to return
* @param status Input/output status. If at entry this indicates a failure
* status, the function will do nothing; otherwise this will be
* updated with any new status from the function.
* @return The UDisplayContextValue for the specified type.
* @stable ICU 53
*/
virtual UDisplayContext getContext(UDisplayContextType type, UErrorCode& status) const;
/**
* Sets an boolean attribute on this DateFormat.
* May return U_UNSUPPORTED_ERROR if this instance does not support
* the specified attribute.
* @param attr the attribute to set
* @param newvalue new value
* @param status the error type
* @return *this - for chaining (example: format.setAttribute(...).setAttribute(...) )
* @stable ICU 53
*/
virtual DateFormat& U_EXPORT2 setBooleanAttribute(UDateFormatBooleanAttribute attr,
UBool newvalue,
UErrorCode &status);
/**
* Returns a boolean from this DateFormat
* May return U_UNSUPPORTED_ERROR if this instance does not support
* the specified attribute.
* @param attr the attribute to set
* @param status the error type
* @return the attribute value. Undefined if there is an error.
* @stable ICU 53
*/
virtual UBool U_EXPORT2 getBooleanAttribute(UDateFormatBooleanAttribute attr, UErrorCode &status) const;
protected:
/**
* Default constructor. Creates a DateFormat with no Calendar or NumberFormat
* associated with it. This constructor depends on the subclasses to fill in
* the calendar and numberFormat fields.
* @stable ICU 2.0
*/
DateFormat();
/**
* Copy constructor.
* @stable ICU 2.0
*/
DateFormat(const DateFormat&);
/**
* Default assignment operator.
* @stable ICU 2.0
*/
DateFormat& operator=(const DateFormat&);
/**
* The calendar that DateFormat uses to produce the time field values needed
* to implement date/time formatting. Subclasses should generally initialize
* this to the default calendar for the locale associated with this DateFormat.
* @stable ICU 2.4
*/
Calendar* fCalendar;
/**
* The number formatter that DateFormat uses to format numbers in dates and
* times. Subclasses should generally initialize this to the default number
* format for the locale associated with this DateFormat.
* @stable ICU 2.4
*/
NumberFormat* fNumberFormat;
private:
/**
* Gets the date/time formatter with the given formatting styles for the
* given locale.
* @param dateStyle the given date formatting style.
* @param timeStyle the given time formatting style.
* @param inLocale the given locale.
* @return a date/time formatter, or 0 on failure.
*/
static DateFormat* U_EXPORT2 create(EStyle timeStyle, EStyle dateStyle, const Locale& inLocale);
/**
* enum set of active boolean attributes for this instance
*/
EnumSet<UDateFormatBooleanAttribute, 0, UDAT_BOOLEAN_ATTRIBUTE_COUNT> fBoolFlags;
UDisplayContext fCapitalizationContext;
friend class DateFmtKeyByStyle;
public:
#ifndef U_HIDE_OBSOLETE_API
/**
* Field selector for FieldPosition for DateFormat fields.
* @obsolete ICU 3.4 use UDateFormatField instead, since this API will be
* removed in that release
*/
enum EField
{
// Obsolete; use UDateFormatField instead
kEraField = UDAT_ERA_FIELD,
kYearField = UDAT_YEAR_FIELD,
kMonthField = UDAT_MONTH_FIELD,
kDateField = UDAT_DATE_FIELD,
kHourOfDay1Field = UDAT_HOUR_OF_DAY1_FIELD,
kHourOfDay0Field = UDAT_HOUR_OF_DAY0_FIELD,
kMinuteField = UDAT_MINUTE_FIELD,
kSecondField = UDAT_SECOND_FIELD,
kMillisecondField = UDAT_FRACTIONAL_SECOND_FIELD,
kDayOfWeekField = UDAT_DAY_OF_WEEK_FIELD,
kDayOfYearField = UDAT_DAY_OF_YEAR_FIELD,
kDayOfWeekInMonthField = UDAT_DAY_OF_WEEK_IN_MONTH_FIELD,
kWeekOfYearField = UDAT_WEEK_OF_YEAR_FIELD,
kWeekOfMonthField = UDAT_WEEK_OF_MONTH_FIELD,
kAmPmField = UDAT_AM_PM_FIELD,
kHour1Field = UDAT_HOUR1_FIELD,
kHour0Field = UDAT_HOUR0_FIELD,
kTimezoneField = UDAT_TIMEZONE_FIELD,
kYearWOYField = UDAT_YEAR_WOY_FIELD,
kDOWLocalField = UDAT_DOW_LOCAL_FIELD,
kExtendedYearField = UDAT_EXTENDED_YEAR_FIELD,
kJulianDayField = UDAT_JULIAN_DAY_FIELD,
kMillisecondsInDayField = UDAT_MILLISECONDS_IN_DAY_FIELD,
// Obsolete; use UDateFormatField instead
ERA_FIELD = UDAT_ERA_FIELD,
YEAR_FIELD = UDAT_YEAR_FIELD,
MONTH_FIELD = UDAT_MONTH_FIELD,
DATE_FIELD = UDAT_DATE_FIELD,
HOUR_OF_DAY1_FIELD = UDAT_HOUR_OF_DAY1_FIELD,
HOUR_OF_DAY0_FIELD = UDAT_HOUR_OF_DAY0_FIELD,
MINUTE_FIELD = UDAT_MINUTE_FIELD,
SECOND_FIELD = UDAT_SECOND_FIELD,
MILLISECOND_FIELD = UDAT_FRACTIONAL_SECOND_FIELD,
DAY_OF_WEEK_FIELD = UDAT_DAY_OF_WEEK_FIELD,
DAY_OF_YEAR_FIELD = UDAT_DAY_OF_YEAR_FIELD,
DAY_OF_WEEK_IN_MONTH_FIELD = UDAT_DAY_OF_WEEK_IN_MONTH_FIELD,
WEEK_OF_YEAR_FIELD = UDAT_WEEK_OF_YEAR_FIELD,
WEEK_OF_MONTH_FIELD = UDAT_WEEK_OF_MONTH_FIELD,
AM_PM_FIELD = UDAT_AM_PM_FIELD,
HOUR1_FIELD = UDAT_HOUR1_FIELD,
HOUR0_FIELD = UDAT_HOUR0_FIELD,
TIMEZONE_FIELD = UDAT_TIMEZONE_FIELD
};
#endif /* U_HIDE_OBSOLETE_API */
};
U_NAMESPACE_END
#endif /* #if !UCONFIG_NO_FORMATTING */
#endif /* U_SHOW_CPLUSPLUS_API */
#endif // _DATEFMT
//eof

View File

@ -0,0 +1,615 @@
// © 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
/*
********************************************************************************
* Copyright (C) 1997-2016, International Business Machines
* Corporation and others. All Rights Reserved.
********************************************************************************
*
* File DCFMTSYM.H
*
* Modification History:
*
* Date Name Description
* 02/19/97 aliu Converted from java.
* 03/18/97 clhuang Updated per C++ implementation.
* 03/27/97 helena Updated to pass the simple test after code review.
* 08/26/97 aliu Added currency/intl currency symbol support.
* 07/22/98 stephen Changed to match C++ style
* currencySymbol -> fCurrencySymbol
* Constants changed from CAPS to kCaps
* 06/24/99 helena Integrated Alan's NF enhancements and Java2 bug fixes
* 09/22/00 grhoten Marked deprecation tags with a pointer to replacement
* functions.
********************************************************************************
*/
#ifndef DCFMTSYM_H
#define DCFMTSYM_H
#include "unicode/utypes.h"
#if U_SHOW_CPLUSPLUS_API
#if !UCONFIG_NO_FORMATTING
#include "unicode/uchar.h"
#include "unicode/uobject.h"
#include "unicode/locid.h"
#include "unicode/numsys.h"
#include "unicode/unum.h"
#include "unicode/unistr.h"
/**
* \file
* \brief C++ API: Symbols for formatting numbers.
*/
U_NAMESPACE_BEGIN
class CharString;
/**
* This class represents the set of symbols needed by DecimalFormat
* to format numbers. DecimalFormat creates for itself an instance of
* DecimalFormatSymbols from its locale data. If you need to change any
* of these symbols, you can get the DecimalFormatSymbols object from
* your DecimalFormat and modify it.
* <P>
* Here are the special characters used in the parts of the
* subpattern, with notes on their usage.
* <pre>
* \code
* Symbol Meaning
* 0 a digit
* # a digit, zero shows as absent
* . placeholder for decimal separator
* , placeholder for grouping separator.
* ; separates formats.
* - default negative prefix.
* % divide by 100 and show as percentage
* X any other characters can be used in the prefix or suffix
* ' used to quote special characters in a prefix or suffix.
* \endcode
* </pre>
* [Notes]
* <P>
* If there is no explicit negative subpattern, - is prefixed to the
* positive form. That is, "0.00" alone is equivalent to "0.00;-0.00".
* <P>
* The grouping separator is commonly used for thousands, but in some
* countries for ten-thousands. The interval is a constant number of
* digits between the grouping characters, such as 100,000,000 or 1,0000,0000.
* If you supply a pattern with multiple grouping characters, the interval
* between the last one and the end of the integer is the one that is
* used. So "#,##,###,####" == "######,####" == "##,####,####".
*/
class U_I18N_API DecimalFormatSymbols : public UObject {
public:
/**
* Constants for specifying a number format symbol.
* @stable ICU 2.0
*/
enum ENumberFormatSymbol {
/** The decimal separator */
kDecimalSeparatorSymbol,
/** The grouping separator */
kGroupingSeparatorSymbol,
/** The pattern separator */
kPatternSeparatorSymbol,
/** The percent sign */
kPercentSymbol,
/** Zero*/
kZeroDigitSymbol,
/** Character representing a digit in the pattern */
kDigitSymbol,
/** The minus sign */
kMinusSignSymbol,
/** The plus sign */
kPlusSignSymbol,
/** The currency symbol */
kCurrencySymbol,
/** The international currency symbol */
kIntlCurrencySymbol,
/** The monetary separator */
kMonetarySeparatorSymbol,
/** The exponential symbol */
kExponentialSymbol,
/** Per mill symbol - replaces kPermillSymbol */
kPerMillSymbol,
/** Escape padding character */
kPadEscapeSymbol,
/** Infinity symbol */
kInfinitySymbol,
/** Nan symbol */
kNaNSymbol,
/** Significant digit symbol
* @stable ICU 3.0 */
kSignificantDigitSymbol,
/** The monetary grouping separator
* @stable ICU 3.6
*/
kMonetaryGroupingSeparatorSymbol,
/** One
* @stable ICU 4.6
*/
kOneDigitSymbol,
/** Two
* @stable ICU 4.6
*/
kTwoDigitSymbol,
/** Three
* @stable ICU 4.6
*/
kThreeDigitSymbol,
/** Four
* @stable ICU 4.6
*/
kFourDigitSymbol,
/** Five
* @stable ICU 4.6
*/
kFiveDigitSymbol,
/** Six
* @stable ICU 4.6
*/
kSixDigitSymbol,
/** Seven
* @stable ICU 4.6
*/
kSevenDigitSymbol,
/** Eight
* @stable ICU 4.6
*/
kEightDigitSymbol,
/** Nine
* @stable ICU 4.6
*/
kNineDigitSymbol,
/** Multiplication sign.
* @stable ICU 54
*/
kExponentMultiplicationSymbol,
#ifndef U_HIDE_INTERNAL_API
/** Approximately sign.
* @internal
*/
kApproximatelySignSymbol,
#endif /* U_HIDE_INTERNAL_API */
/** count symbol constants */
kFormatSymbolCount = kExponentMultiplicationSymbol + 2
};
/**
* Create a DecimalFormatSymbols object for the given locale.
*
* @param locale The locale to get symbols for.
* @param status Input/output parameter, set to success or
* failure code upon return.
* @stable ICU 2.0
*/
DecimalFormatSymbols(const Locale& locale, UErrorCode& status);
/**
* Creates a DecimalFormatSymbols instance for the given locale with digits and symbols
* corresponding to the given NumberingSystem.
*
* This constructor behaves equivalently to the normal constructor called with a locale having a
* "numbers=xxxx" keyword specifying the numbering system by name.
*
* In this constructor, the NumberingSystem argument will be used even if the locale has its own
* "numbers=xxxx" keyword.
*
* @param locale The locale to get symbols for.
* @param ns The numbering system.
* @param status Input/output parameter, set to success or
* failure code upon return.
* @stable ICU 60
*/
DecimalFormatSymbols(const Locale& locale, const NumberingSystem& ns, UErrorCode& status);
/**
* Create a DecimalFormatSymbols object for the default locale.
* This constructor will not fail. If the resource file data is
* not available, it will use hard-coded last-resort data and
* set status to U_USING_FALLBACK_ERROR.
*
* @param status Input/output parameter, set to success or
* failure code upon return.
* @stable ICU 2.0
*/
DecimalFormatSymbols(UErrorCode& status);
/**
* Creates a DecimalFormatSymbols object with last-resort data.
* Intended for callers who cache the symbols data and
* set all symbols on the resulting object.
*
* The last-resort symbols are similar to those for the root data,
* except that the grouping separators are empty,
* the NaN symbol is U+FFFD rather than "NaN",
* and the CurrencySpacing patterns are empty.
*
* @param status Input/output parameter, set to success or
* failure code upon return.
* @return last-resort symbols
* @stable ICU 52
*/
static DecimalFormatSymbols* createWithLastResortData(UErrorCode& status);
/**
* Copy constructor.
* @stable ICU 2.0
*/
DecimalFormatSymbols(const DecimalFormatSymbols&);
/**
* Assignment operator.
* @stable ICU 2.0
*/
DecimalFormatSymbols& operator=(const DecimalFormatSymbols&);
/**
* Destructor.
* @stable ICU 2.0
*/
virtual ~DecimalFormatSymbols();
/**
* Return true if another object is semantically equal to this one.
*
* @param other the object to be compared with.
* @return true if another object is semantically equal to this one.
* @stable ICU 2.0
*/
bool operator==(const DecimalFormatSymbols& other) const;
/**
* Return true if another object is semantically unequal to this one.
*
* @param other the object to be compared with.
* @return true if another object is semantically unequal to this one.
* @stable ICU 2.0
*/
bool operator!=(const DecimalFormatSymbols& other) const { return !operator==(other); }
/**
* Get one of the format symbols by its enum constant.
* Each symbol is stored as a string so that graphemes
* (characters with modifier letters) can be used.
*
* @param symbol Constant to indicate a number format symbol.
* @return the format symbols by the param 'symbol'
* @stable ICU 2.0
*/
inline UnicodeString getSymbol(ENumberFormatSymbol symbol) const;
/**
* Set one of the format symbols by its enum constant.
* Each symbol is stored as a string so that graphemes
* (characters with modifier letters) can be used.
*
* @param symbol Constant to indicate a number format symbol.
* @param value value of the format symbol
* @param propagateDigits If false, setting the zero digit will not automatically set 1-9.
* The default behavior is to automatically set 1-9 if zero is being set and the value
* it is being set to corresponds to a known Unicode zero digit.
* @stable ICU 2.0
*/
void setSymbol(ENumberFormatSymbol symbol, const UnicodeString &value, const UBool propagateDigits);
#ifndef U_HIDE_INTERNAL_API
/**
* Loads symbols for the specified currency into this instance.
*
* This method is internal. If you think it should be public, file a ticket.
*
* @internal
*/
void setCurrency(const char16_t* currency, UErrorCode& status);
#endif // U_HIDE_INTERNAL_API
/**
* Returns the locale for which this object was constructed.
* @stable ICU 2.6
*/
inline Locale getLocale() const;
/**
* Returns the locale for this object. Two flavors are available:
* valid and actual locale.
* @stable ICU 2.8
*/
Locale getLocale(ULocDataLocaleType type, UErrorCode& status) const;
/**
* Get pattern string for 'CurrencySpacing' that can be applied to
* currency format.
* This API gets the CurrencySpacing data from ResourceBundle. The pattern can
* be empty if there is no data from current locale and its parent locales.
*
* @param type : UNUM_CURRENCY_MATCH, UNUM_CURRENCY_SURROUNDING_MATCH or UNUM_CURRENCY_INSERT.
* @param beforeCurrency : true if the pattern is for before currency symbol.
* false if the pattern is for after currency symbol.
* @param status: Input/output parameter, set to success or
* failure code upon return.
* @return pattern string for currencyMatch, surroundingMatch or spaceInsert.
* Return empty string if there is no data for this locale and its parent
* locales.
* @stable ICU 4.8
*/
const UnicodeString& getPatternForCurrencySpacing(UCurrencySpacing type,
UBool beforeCurrency,
UErrorCode& status) const;
/**
* Set pattern string for 'CurrencySpacing' that can be applied to
* currency format.
*
* @param type : UNUM_CURRENCY_MATCH, UNUM_CURRENCY_SURROUNDING_MATCH or UNUM_CURRENCY_INSERT.
* @param beforeCurrency : true if the pattern is for before currency symbol.
* false if the pattern is for after currency symbol.
* @param pattern : pattern string to override current setting.
* @stable ICU 4.8
*/
void setPatternForCurrencySpacing(UCurrencySpacing type,
UBool beforeCurrency,
const UnicodeString& pattern);
/**
* ICU "poor man's RTTI", returns a UClassID for the actual class.
*
* @stable ICU 2.2
*/
virtual UClassID getDynamicClassID() const override;
/**
* ICU "poor man's RTTI", returns a UClassID for this class.
*
* @stable ICU 2.2
*/
static UClassID U_EXPORT2 getStaticClassID();
private:
DecimalFormatSymbols();
/**
* Initializes the symbols from the LocaleElements resource bundle.
* Note: The organization of LocaleElements badly needs to be
* cleaned up.
*
* @param locale The locale to get symbols for.
* @param success Input/output parameter, set to success or
* failure code upon return.
* @param useLastResortData determine if use last resort data
* @param ns The NumberingSystem to use; otherwise, fall
* back to the locale.
*/
void initialize(const Locale& locale, UErrorCode& success,
UBool useLastResortData = false, const NumberingSystem* ns = nullptr);
/**
* Initialize the symbols with default values.
*/
void initialize();
public:
#ifndef U_HIDE_INTERNAL_API
/**
* @internal For ICU use only
*/
inline UBool isCustomCurrencySymbol() const {
return fIsCustomCurrencySymbol;
}
/**
* @internal For ICU use only
*/
inline UBool isCustomIntlCurrencySymbol() const {
return fIsCustomIntlCurrencySymbol;
}
/**
* @internal For ICU use only
*/
inline UChar32 getCodePointZero() const {
return fCodePointZero;
}
#endif /* U_HIDE_INTERNAL_API */
/**
* _Internal_ function - more efficient version of getSymbol,
* returning a const reference to one of the symbol strings.
* The returned reference becomes invalid when the symbol is changed
* or when the DecimalFormatSymbols are destroyed.
* Note: moved \#ifndef U_HIDE_INTERNAL_API after this, since this is needed for inline in DecimalFormat
*
* This is not currently stable API, but if you think it should be stable,
* post a comment on the following ticket and the ICU team will take a look:
* https://unicode-org.atlassian.net/browse/ICU-13580
*
* @param symbol Constant to indicate a number format symbol.
* @return the format symbol by the param 'symbol'
* @internal
*/
inline const UnicodeString& getConstSymbol(ENumberFormatSymbol symbol) const;
#ifndef U_HIDE_INTERNAL_API
/**
* Returns the const UnicodeString reference, like getConstSymbol,
* corresponding to the digit with the given value. This is equivalent
* to accessing the symbol from getConstSymbol with the corresponding
* key, such as kZeroDigitSymbol or kOneDigitSymbol.
*
* This is not currently stable API, but if you think it should be stable,
* post a comment on the following ticket and the ICU team will take a look:
* https://unicode-org.atlassian.net/browse/ICU-13580
*
* @param digit The digit, an integer between 0 and 9 inclusive.
* If outside the range 0 to 9, the zero digit is returned.
* @return the format symbol for the given digit.
* @internal This API is currently for ICU use only.
*/
inline const UnicodeString& getConstDigitSymbol(int32_t digit) const;
/**
* Returns that pattern stored in currency info. Internal API for use by NumberFormat API.
* @internal
*/
inline const char16_t* getCurrencyPattern() const;
/**
* Returns the numbering system with which this DecimalFormatSymbols was initialized.
* @internal
*/
inline const char* getNumberingSystemName() const;
#endif /* U_HIDE_INTERNAL_API */
private:
/**
* Private symbol strings.
* They are either loaded from a resource bundle or otherwise owned.
* setSymbol() clones the symbol string.
* Readonly aliases can only come from a resource bundle, so that we can always
* use fastCopyFrom() with them.
*
* If DecimalFormatSymbols becomes subclassable and the status of fSymbols changes
* from private to protected,
* or when fSymbols can be set any other way that allows them to be readonly aliases
* to non-resource bundle strings,
* then regular UnicodeString copies must be used instead of fastCopyFrom().
*
*/
UnicodeString fSymbols[kFormatSymbolCount];
/**
* Non-symbol variable for getConstSymbol(). Always empty.
*/
UnicodeString fNoSymbol;
/**
* Dealing with code points is faster than dealing with strings when formatting. Because of
* this, we maintain a value containing the zero code point that is used whenever digitStrings
* represents a sequence of ten code points in order.
*
* <p>If the value stored here is positive, it means that the code point stored in this value
* corresponds to the digitStrings array, and codePointZero can be used instead of the
* digitStrings array for the purposes of efficient formatting; if -1, then digitStrings does
* *not* contain a sequence of code points, and it must be used directly.
*
* <p>It is assumed that codePointZero always shadows the value in digitStrings. codePointZero
* should never be set directly; rather, it should be updated only when digitStrings mutates.
* That is, the flow of information is digitStrings -> codePointZero, not the other way.
*/
UChar32 fCodePointZero;
Locale locale;
CharString* actualLocale = nullptr;
CharString* validLocale = nullptr;
const char16_t* currPattern = nullptr;
UnicodeString currencySpcBeforeSym[UNUM_CURRENCY_SPACING_COUNT];
UnicodeString currencySpcAfterSym[UNUM_CURRENCY_SPACING_COUNT];
UBool fIsCustomCurrencySymbol;
UBool fIsCustomIntlCurrencySymbol;
char nsName[kInternalNumSysNameCapacity+1] = {};
};
// -------------------------------------
inline UnicodeString
DecimalFormatSymbols::getSymbol(ENumberFormatSymbol symbol) const {
const UnicodeString *strPtr;
if(symbol < kFormatSymbolCount) {
strPtr = &fSymbols[symbol];
} else {
strPtr = &fNoSymbol;
}
return *strPtr;
}
// See comments above for this function. Not hidden with #ifdef U_HIDE_INTERNAL_API
inline const UnicodeString &
DecimalFormatSymbols::getConstSymbol(ENumberFormatSymbol symbol) const {
const UnicodeString *strPtr;
if(symbol < kFormatSymbolCount) {
strPtr = &fSymbols[symbol];
} else {
strPtr = &fNoSymbol;
}
return *strPtr;
}
#ifndef U_HIDE_INTERNAL_API
inline const UnicodeString& DecimalFormatSymbols::getConstDigitSymbol(int32_t digit) const {
if (digit < 0 || digit > 9) {
digit = 0;
}
if (digit == 0) {
return fSymbols[kZeroDigitSymbol];
}
ENumberFormatSymbol key = static_cast<ENumberFormatSymbol>(kOneDigitSymbol + digit - 1);
return fSymbols[key];
}
#endif /* U_HIDE_INTERNAL_API */
// -------------------------------------
inline void
DecimalFormatSymbols::setSymbol(ENumberFormatSymbol symbol, const UnicodeString &value, const UBool propagateDigits = true) {
if (symbol == kCurrencySymbol) {
fIsCustomCurrencySymbol = true;
}
else if (symbol == kIntlCurrencySymbol) {
fIsCustomIntlCurrencySymbol = true;
}
if(symbol<kFormatSymbolCount) {
fSymbols[symbol]=value;
}
// If the zero digit is being set to a known zero digit according to Unicode,
// then we automatically set the corresponding 1-9 digits
// Also record updates to fCodePointZero. Be conservative if in doubt.
if (symbol == kZeroDigitSymbol) {
UChar32 sym = value.char32At(0);
if ( propagateDigits && u_charDigitValue(sym) == 0 && value.countChar32() == 1 ) {
fCodePointZero = sym;
for ( int8_t i = 1 ; i<= 9 ; i++ ) {
sym++;
fSymbols[static_cast<int>(kOneDigitSymbol) + i - 1] = UnicodeString(sym);
}
} else {
fCodePointZero = -1;
}
} else if (symbol >= kOneDigitSymbol && symbol <= kNineDigitSymbol) {
fCodePointZero = -1;
}
}
// -------------------------------------
inline Locale
DecimalFormatSymbols::getLocale() const {
return locale;
}
#ifndef U_HIDE_INTERNAL_API
inline const char16_t*
DecimalFormatSymbols::getCurrencyPattern() const {
return currPattern;
}
inline const char*
DecimalFormatSymbols::getNumberingSystemName() const {
return nsName;
}
#endif /* U_HIDE_INTERNAL_API */
U_NAMESPACE_END
#endif /* #if !UCONFIG_NO_FORMATTING */
#endif /* U_SHOW_CPLUSPLUS_API */
#endif // _DCFMTSYM
//eof

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,270 @@
// © 2022 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
#ifndef __DISPLAYOPTIONS_H__
#define __DISPLAYOPTIONS_H__
#include "unicode/utypes.h"
#if U_SHOW_CPLUSPLUS_API
#if !UCONFIG_NO_FORMATTING
/**
* \file
* \brief C++ API: Display options class
*
* This class is designed as a more modern version of the UDisplayContext mechanism.
*/
#include "unicode/udisplayoptions.h"
#include "unicode/uversion.h"
U_NAMESPACE_BEGIN
/**
* Represents all the display options that are supported by CLDR such as grammatical case, noun
* class, ... etc. It currently supports enums, but may be extended in the future to have other
* types of data. It replaces a DisplayContext[] as a method parameter.
*
* NOTE: This class is Immutable, and uses a Builder interface.
*
* For example:
* ```
* DisplayOptions x =
* DisplayOptions::builder().
* .setGrammaticalCase(UDISPOPT_GRAMMATICAL_CASE_DATIVE)
* .setPluralCategory(UDISPOPT_PLURAL_CATEGORY_FEW)
* .build();
* ```
*
* @stable ICU 72
*/
class U_I18N_API DisplayOptions {
public:
/**
* Responsible for building `DisplayOptions`.
*
* @stable ICU 72
*/
class U_I18N_API Builder {
public:
/**
* Sets the grammatical case.
*
* @param grammaticalCase The grammatical case.
* @return Builder
* @stable ICU 72
*/
Builder &setGrammaticalCase(UDisplayOptionsGrammaticalCase grammaticalCase) {
this->grammaticalCase = grammaticalCase;
return *this;
}
/**
* Sets the noun class.
*
* @param nounClass The noun class.
* @return Builder
* @stable ICU 72
*/
Builder &setNounClass(UDisplayOptionsNounClass nounClass) {
this->nounClass = nounClass;
return *this;
}
/**
* Sets the plural category.
*
* @param pluralCategory The plural category.
* @return Builder
* @stable ICU 72
*/
Builder &setPluralCategory(UDisplayOptionsPluralCategory pluralCategory) {
this->pluralCategory = pluralCategory;
return *this;
}
/**
* Sets the capitalization.
*
* @param capitalization The capitalization.
* @return Builder
* @stable ICU 72
*/
Builder &setCapitalization(UDisplayOptionsCapitalization capitalization) {
this->capitalization = capitalization;
return *this;
}
/**
* Sets the dialect handling.
*
* @param nameStyle The name style.
* @return Builder
* @stable ICU 72
*/
Builder &setNameStyle(UDisplayOptionsNameStyle nameStyle) {
this->nameStyle = nameStyle;
return *this;
}
/**
* Sets the display length.
*
* @param displayLength The display length.
* @return Builder
* @stable ICU 72
*/
Builder &setDisplayLength(UDisplayOptionsDisplayLength displayLength) {
this->displayLength = displayLength;
return *this;
}
/**
* Sets the substitute handling.
*
* @param substituteHandling The substitute handling.
* @return Builder
* @stable ICU 72
*/
Builder &setSubstituteHandling(UDisplayOptionsSubstituteHandling substituteHandling) {
this->substituteHandling = substituteHandling;
return *this;
}
/**
* Builds the display options.
*
* @return DisplayOptions
* @stable ICU 72
*/
DisplayOptions build() { return DisplayOptions(*this); }
private:
friend DisplayOptions;
Builder();
Builder(const DisplayOptions &displayOptions);
UDisplayOptionsGrammaticalCase grammaticalCase;
UDisplayOptionsNounClass nounClass;
UDisplayOptionsPluralCategory pluralCategory;
UDisplayOptionsCapitalization capitalization;
UDisplayOptionsNameStyle nameStyle;
UDisplayOptionsDisplayLength displayLength;
UDisplayOptionsSubstituteHandling substituteHandling;
};
/**
* Creates a builder with the `UNDEFINED` values for all the parameters.
*
* @return Builder
* @stable ICU 72
*/
static Builder builder();
/**
* Creates a builder with the same parameters from this object.
*
* @return Builder
* @stable ICU 72
*/
Builder copyToBuilder() const;
/**
* Gets the grammatical case.
*
* @return UDisplayOptionsGrammaticalCase
* @stable ICU 72
*/
UDisplayOptionsGrammaticalCase getGrammaticalCase() const { return grammaticalCase; }
/**
* Gets the noun class.
*
* @return UDisplayOptionsNounClass
* @stable ICU 72
*/
UDisplayOptionsNounClass getNounClass() const { return nounClass; }
/**
* Gets the plural category.
*
* @return UDisplayOptionsPluralCategory
* @stable ICU 72
*/
UDisplayOptionsPluralCategory getPluralCategory() const { return pluralCategory; }
/**
* Gets the capitalization.
*
* @return UDisplayOptionsCapitalization
* @stable ICU 72
*/
UDisplayOptionsCapitalization getCapitalization() const { return capitalization; }
/**
* Gets the dialect handling.
*
* @return UDisplayOptionsNameStyle
* @stable ICU 72
*/
UDisplayOptionsNameStyle getNameStyle() const { return nameStyle; }
/**
* Gets the display length.
*
* @return UDisplayOptionsDisplayLength
* @stable ICU 72
*/
UDisplayOptionsDisplayLength getDisplayLength() const { return displayLength; }
/**
* Gets the substitute handling.
*
* @return UDisplayOptionsSubstituteHandling
* @stable ICU 72
*/
UDisplayOptionsSubstituteHandling getSubstituteHandling() const { return substituteHandling; }
/**
* Copies the DisplayOptions.
*
* @param other The options to copy.
* @stable ICU 72
*/
DisplayOptions &operator=(const DisplayOptions &other) = default;
/**
* Moves the DisplayOptions.
*
* @param other The options to move from.
* @stable ICU 72
*/
DisplayOptions &operator=(DisplayOptions &&other) noexcept = default;
/**
* Copies the DisplayOptions.
*
* @param other The options to copy.
* @stable ICU 72
*/
DisplayOptions(const DisplayOptions &other) = default;
private:
DisplayOptions(const Builder &builder);
UDisplayOptionsGrammaticalCase grammaticalCase;
UDisplayOptionsNounClass nounClass;
UDisplayOptionsPluralCategory pluralCategory;
UDisplayOptionsCapitalization capitalization;
UDisplayOptionsNameStyle nameStyle;
UDisplayOptionsDisplayLength displayLength;
UDisplayOptionsSubstituteHandling substituteHandling;
};
U_NAMESPACE_END
#endif /* #if !UCONFIG_NO_FORMATTING */
#endif /* U_SHOW_CPLUSPLUS_API */
#endif // __DISPLAYOPTIONS_H__

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,524 @@
// © 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
/*
*******************************************************************************
* Copyright (C) 2008-2016, International Business Machines Corporation and
* others. All Rights Reserved.
*******************************************************************************
*
* File DTITVINF.H
*
*******************************************************************************
*/
#ifndef __DTITVINF_H__
#define __DTITVINF_H__
#include "unicode/utypes.h"
#if U_SHOW_CPLUSPLUS_API
/**
* \file
* \brief C++ API: Date/Time interval patterns for formatting date/time interval
*/
#if !UCONFIG_NO_FORMATTING
#include "unicode/udat.h"
#include "unicode/locid.h"
#include "unicode/ucal.h"
#include "unicode/dtptngen.h"
U_NAMESPACE_BEGIN
/**
* DateIntervalInfo is a public class for encapsulating localizable
* date time interval patterns. It is used by DateIntervalFormat.
*
* <P>
* For most users, ordinary use of DateIntervalFormat does not need to create
* DateIntervalInfo object directly.
* DateIntervalFormat will take care of it when creating a date interval
* formatter when user pass in skeleton and locale.
*
* <P>
* For power users, who want to create their own date interval patterns,
* or want to re-set date interval patterns, they could do so by
* directly creating DateIntervalInfo and manipulating it.
*
* <P>
* Logically, the interval patterns are mappings
* from (skeleton, the_largest_different_calendar_field)
* to (date_interval_pattern).
*
* <P>
* A skeleton
* <ol>
* <li>
* only keeps the field pattern letter and ignores all other parts
* in a pattern, such as space, punctuations, and string literals.
* <li>
* hides the order of fields.
* <li>
* might hide a field's pattern letter length.
*
* For those non-digit calendar fields, the pattern letter length is
* important, such as MMM, MMMM, and MMMMM; EEE and EEEE,
* and the field's pattern letter length is honored.
*
* For the digit calendar fields, such as M or MM, d or dd, yy or yyyy,
* the field pattern length is ignored and the best match, which is defined
* in date time patterns, will be returned without honor the field pattern
* letter length in skeleton.
* </ol>
*
* <P>
* The calendar fields we support for interval formatting are:
* year, month, date, day-of-week, am-pm, hour, hour-of-day, and minute.
* Those calendar fields can be defined in the following order:
* year > month > date > am-pm > hour > minute
*
* The largest different calendar fields between 2 calendars is the
* first different calendar field in above order.
*
* For example: the largest different calendar fields between &quot;Jan 10, 2007&quot;
* and &quot;Feb 20, 2008&quot; is year.
*
* <P>
* There is a set of pre-defined static skeleton strings.
* There are pre-defined interval patterns for those pre-defined skeletons
* in locales' resource files.
* For example, for a skeleton UDAT_YEAR_ABBR_MONTH_DAY, which is &quot;yMMMd&quot;,
* in en_US, if the largest different calendar field between date1 and date2
* is &quot;year&quot;, the date interval pattern is &quot;MMM d, yyyy - MMM d, yyyy&quot;,
* such as &quot;Jan 10, 2007 - Jan 10, 2008&quot;.
* If the largest different calendar field between date1 and date2 is &quot;month&quot;,
* the date interval pattern is &quot;MMM d - MMM d, yyyy&quot;,
* such as &quot;Jan 10 - Feb 10, 2007&quot;.
* If the largest different calendar field between date1 and date2 is &quot;day&quot;,
* the date interval pattern is &quot;MMM d-d, yyyy&quot;, such as &quot;Jan 10-20, 2007&quot;.
*
* For date skeleton, the interval patterns when year, or month, or date is
* different are defined in resource files.
* For time skeleton, the interval patterns when am/pm, or hour, or minute is
* different are defined in resource files.
*
*
* <P>
* There are 2 dates in interval pattern. For most locales, the first date
* in an interval pattern is the earlier date. There might be a locale in which
* the first date in an interval pattern is the later date.
* We use fallback format for the default order for the locale.
* For example, if the fallback format is &quot;{0} - {1}&quot;, it means
* the first date in the interval pattern for this locale is earlier date.
* If the fallback format is &quot;{1} - {0}&quot;, it means the first date is the
* later date.
* For a particular interval pattern, the default order can be overridden
* by prefixing &quot;latestFirst:&quot; or &quot;earliestFirst:&quot; to the interval pattern.
* For example, if the fallback format is &quot;{0}-{1}&quot;,
* but for skeleton &quot;yMMMd&quot;, the interval pattern when day is different is
* &quot;latestFirst:d-d MMM yy&quot;, it means by default, the first date in interval
* pattern is the earlier date. But for skeleton &quot;yMMMd&quot;, when day is different,
* the first date in &quot;d-d MMM yy&quot; is the later date.
*
* <P>
* The recommended way to create a DateIntervalFormat object is to pass in
* the locale.
* By using a Locale parameter, the DateIntervalFormat object is
* initialized with the pre-defined interval patterns for a given or
* default locale.
* <P>
* Users can also create DateIntervalFormat object
* by supplying their own interval patterns.
* It provides flexibility for power users.
*
* <P>
* After a DateIntervalInfo object is created, clients may modify
* the interval patterns using setIntervalPattern function as so desired.
* Currently, users can only set interval patterns when the following
* calendar fields are different: ERA, YEAR, MONTH, DATE, DAY_OF_MONTH,
* DAY_OF_WEEK, AM_PM, HOUR, HOUR_OF_DAY, MINUTE, SECOND, and MILLISECOND.
* Interval patterns when other calendar fields are different is not supported.
* <P>
* DateIntervalInfo objects are cloneable.
* When clients obtain a DateIntervalInfo object,
* they can feel free to modify it as necessary.
* <P>
* DateIntervalInfo are not expected to be subclassed.
* Data for a calendar is loaded out of resource bundles.
* Through ICU 4.4, date interval patterns are only supported in the Gregorian
* calendar; non-Gregorian calendars are supported from ICU 4.4.1.
* @stable ICU 4.0
**/
class U_I18N_API DateIntervalInfo final : public UObject {
public:
/**
* Default constructor.
* It does not initialize any interval patterns except
* that it initialize default fall-back pattern as "{0} - {1}",
* which can be reset by setFallbackIntervalPattern().
* It should be followed by setFallbackIntervalPattern() and
* setIntervalPattern(),
* and is recommended to be used only for power users who
* wants to create their own interval patterns and use them to create
* date interval formatter.
* @param status output param set to success/failure code on exit
* @internal ICU 4.0
*/
DateIntervalInfo(UErrorCode& status);
/**
* Construct DateIntervalInfo for the given locale,
* @param locale the interval patterns are loaded from the appropriate calendar
* data (specified calendar or default calendar) in this locale.
* @param status output param set to success/failure code on exit
* @stable ICU 4.0
*/
DateIntervalInfo(const Locale& locale, UErrorCode& status);
/**
* Copy constructor.
* @stable ICU 4.0
*/
DateIntervalInfo(const DateIntervalInfo&);
/**
* Assignment operator
* @stable ICU 4.0
*/
DateIntervalInfo& operator=(const DateIntervalInfo&);
/**
* Clone this object polymorphically.
* The caller owns the result and should delete it when done.
* @return a copy of the object
* @stable ICU 4.0
*/
virtual DateIntervalInfo* clone() const;
/**
* Destructor.
* It is virtual to be safe, but it is not designed to be subclassed.
* @stable ICU 4.0
*/
virtual ~DateIntervalInfo();
/**
* Return true if another object is semantically equal to this one.
*
* @param other the DateIntervalInfo object to be compared with.
* @return true if other is semantically equal to this.
* @stable ICU 4.0
*/
virtual bool operator==(const DateIntervalInfo& other) const;
/**
* Return true if another object is semantically unequal to this one.
*
* @param other the DateIntervalInfo object to be compared with.
* @return true if other is semantically unequal to this.
* @stable ICU 4.0
*/
bool operator!=(const DateIntervalInfo& other) const;
/**
* Provides a way for client to build interval patterns.
* User could construct DateIntervalInfo by providing a list of skeletons
* and their patterns.
* <P>
* For example:
* <pre>
* UErrorCode status = U_ZERO_ERROR;
* DateIntervalInfo dIntervalInfo = new DateIntervalInfo();
* dIntervalInfo->setFallbackIntervalPattern("{0} ~ {1}");
* dIntervalInfo->setIntervalPattern("yMd", UCAL_YEAR, "'from' yyyy-M-d 'to' yyyy-M-d", status);
* dIntervalInfo->setIntervalPattern("yMMMd", UCAL_MONTH, "'from' yyyy MMM d 'to' MMM d", status);
* dIntervalInfo->setIntervalPattern("yMMMd", UCAL_DAY, "yyyy MMM d-d", status, status);
* </pre>
*
* Restriction:
* Currently, users can only set interval patterns when the following
* calendar fields are different: ERA, YEAR, MONTH, DATE, DAY_OF_MONTH,
* DAY_OF_WEEK, AM_PM, HOUR, HOUR_OF_DAY, MINUTE, SECOND and MILLISECOND.
* Interval patterns when other calendar fields are different are
* not supported.
*
* @param skeleton the skeleton on which interval pattern based
* @param lrgDiffCalUnit the largest different calendar unit.
* @param intervalPattern the interval pattern on the largest different
* calendar unit.
* For example, if lrgDiffCalUnit is
* "year", the interval pattern for en_US when year
* is different could be "'from' yyyy 'to' yyyy".
* @param status output param set to success/failure code on exit
* @stable ICU 4.0
*/
void setIntervalPattern(const UnicodeString& skeleton,
UCalendarDateFields lrgDiffCalUnit,
const UnicodeString& intervalPattern,
UErrorCode& status);
/**
* Get the interval pattern given skeleton and
* the largest different calendar field.
* @param skeleton the skeleton
* @param field the largest different calendar field
* @param result output param to receive the pattern
* @param status output param set to success/failure code on exit
* @return a reference to 'result'
* @stable ICU 4.0
*/
UnicodeString& getIntervalPattern(const UnicodeString& skeleton,
UCalendarDateFields field,
UnicodeString& result,
UErrorCode& status) const;
/**
* Get the fallback interval pattern.
* @param result output param to receive the pattern
* @return a reference to 'result'
* @stable ICU 4.0
*/
UnicodeString& getFallbackIntervalPattern(UnicodeString& result) const;
/**
* Re-set the fallback interval pattern.
*
* In construction, default fallback pattern is set as "{0} - {1}".
* And constructor taking locale as parameter will set the
* fallback pattern as what defined in the locale resource file.
*
* This method provides a way for user to replace the fallback pattern.
*
* @param fallbackPattern fall-back interval pattern.
* @param status output param set to success/failure code on exit
* @stable ICU 4.0
*/
void setFallbackIntervalPattern(const UnicodeString& fallbackPattern,
UErrorCode& status);
/** Get default order -- whether the first date in pattern is later date
or not.
* return default date ordering in interval pattern. true if the first date
* in pattern is later date, false otherwise.
* @stable ICU 4.0
*/
UBool getDefaultOrder() const;
/**
* ICU "poor man's RTTI", returns a UClassID for the actual class.
*
* @stable ICU 4.0
*/
virtual UClassID getDynamicClassID() const override;
/**
* ICU "poor man's RTTI", returns a UClassID for this class.
*
* @stable ICU 4.0
*/
static UClassID U_EXPORT2 getStaticClassID();
private:
/**
* DateIntervalFormat will need access to
* getBestSkeleton(), parseSkeleton(), enum IntervalPatternIndex,
* and calendarFieldToPatternIndex().
*
* Instead of making above public,
* make DateIntervalFormat a friend of DateIntervalInfo.
*/
friend class DateIntervalFormat;
/**
* Internal struct used to load resource bundle data.
*/
struct U_HIDDEN DateIntervalSink;
/**
* Following is for saving the interval patterns.
* We only support interval patterns on
* ERA, YEAR, MONTH, DAY, AM_PM, HOUR, MINUTE, SECOND and MILLISECOND.
*/
enum IntervalPatternIndex
{
kIPI_ERA,
kIPI_YEAR,
kIPI_MONTH,
kIPI_DATE,
kIPI_AM_PM,
kIPI_HOUR,
kIPI_MINUTE,
kIPI_SECOND,
kIPI_MILLISECOND,
kIPI_MAX_INDEX
};
public:
#ifndef U_HIDE_INTERNAL_API
/**
* Max index for stored interval patterns
* @internal ICU 4.4
*/
enum {
kMaxIntervalPatternIndex = kIPI_MAX_INDEX
};
#endif /* U_HIDE_INTERNAL_API */
private:
/**
* Initialize the DateIntervalInfo from locale
* @param locale the given locale.
* @param status output param set to success/failure code on exit
*/
void initializeData(const Locale& locale, UErrorCode& status);
/* Set Interval pattern.
*
* It sets interval pattern into the hash map.
*
* @param skeleton skeleton on which the interval pattern based
* @param lrgDiffCalUnit the largest different calendar unit.
* @param intervalPattern the interval pattern on the largest different
* calendar unit.
* @param status output param set to success/failure code on exit
*/
void setIntervalPatternInternally(const UnicodeString& skeleton,
UCalendarDateFields lrgDiffCalUnit,
const UnicodeString& intervalPattern,
UErrorCode& status);
/**given an input skeleton, get the best match skeleton
* which has pre-defined interval pattern in resource file.
* Also return the difference between the input skeleton
* and the best match skeleton.
*
* TODO (xji): set field weight or
* isolate the functionality in DateTimePatternGenerator
* @param skeleton input skeleton
* @param bestMatchDistanceInfo the difference between input skeleton
* and best match skeleton.
* 0, if there is exact match for input skeleton
* 1, if there is only field width difference between
* the best match and the input skeleton
* 2, the only field difference is 'v' and 'z'
* -1, if there is calendar field difference between
* the best match and the input skeleton
* @return best match skeleton
*/
const UnicodeString* getBestSkeleton(const UnicodeString& skeleton,
int8_t& bestMatchDistanceInfo) const;
/**
* Parse skeleton, save each field's width.
* It is used for looking for best match skeleton,
* and adjust pattern field width.
* @param skeleton skeleton to be parsed
* @param skeletonFieldWidth parsed skeleton field width
*/
static void U_EXPORT2 parseSkeleton(const UnicodeString& skeleton,
int32_t* skeletonFieldWidth);
/**
* Check whether one field width is numeric while the other is string.
*
* TODO (xji): make it general
*
* @param fieldWidth one field width
* @param anotherFieldWidth another field width
* @param patternLetter pattern letter char
* @return true if one field width is numeric and the other is string,
* false otherwise.
*/
static UBool U_EXPORT2 stringNumeric(int32_t fieldWidth,
int32_t anotherFieldWidth,
char patternLetter);
/**
* Convert calendar field to the interval pattern index in
* hash table.
*
* Since we only support the following calendar fields:
* ERA, YEAR, MONTH, DATE, DAY_OF_MONTH, DAY_OF_WEEK,
* AM_PM, HOUR, HOUR_OF_DAY, MINUTE, SECOND, and MILLISECOND.
* We reserve only 4 interval patterns for a skeleton.
*
* @param field calendar field
* @param status output param set to success/failure code on exit
* @return interval pattern index in hash table
*/
static IntervalPatternIndex U_EXPORT2 calendarFieldToIntervalIndex(
UCalendarDateFields field,
UErrorCode& status);
/**
* delete hash table (of type fIntervalPatterns).
*
* @param hTable hash table to be deleted
*/
void deleteHash(Hashtable* hTable);
/**
* initialize hash table (of type fIntervalPatterns).
*
* @param status output param set to success/failure code on exit
* @return hash table initialized
*/
Hashtable* initHash(UErrorCode& status);
/**
* copy hash table (of type fIntervalPatterns).
*
* @param source the source to copy from
* @param target the target to copy to
* @param status output param set to success/failure code on exit
*/
void copyHash(const Hashtable* source, Hashtable* target, UErrorCode& status);
// data members
// fallback interval pattern
UnicodeString fFallbackIntervalPattern;
// default order
UBool fFirstDateInPtnIsLaterDate;
// HashMap<UnicodeString, UnicodeString[kIPI_MAX_INDEX]>
// HashMap( skeleton, pattern[largest_different_field] )
Hashtable* fIntervalPatterns;
};// end class DateIntervalInfo
inline bool
DateIntervalInfo::operator!=(const DateIntervalInfo& other) const {
return !operator==(other);
}
U_NAMESPACE_END
#endif
#endif /* U_SHOW_CPLUSPLUS_API */
#endif

View File

@ -0,0 +1,653 @@
// © 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
/*
*******************************************************************************
* Copyright (C) 2007-2016, International Business Machines Corporation and
* others. All Rights Reserved.
*******************************************************************************
*
* File DTPTNGEN.H
*
*******************************************************************************
*/
#ifndef __DTPTNGEN_H__
#define __DTPTNGEN_H__
#include "unicode/utypes.h"
#if U_SHOW_CPLUSPLUS_API
#include "unicode/datefmt.h"
#include "unicode/locid.h"
#include "unicode/udat.h"
#include "unicode/udatpg.h"
#include "unicode/unistr.h"
U_NAMESPACE_BEGIN
/**
* \file
* \brief C++ API: Date/Time Pattern Generator
*/
class CharString;
class Hashtable;
class FormatParser;
class DateTimeMatcher;
class DistanceInfo;
class PatternMap;
class PtnSkeleton;
class SharedDateTimePatternGenerator;
/**
* This class provides flexible generation of date format patterns, like "yy-MM-dd".
* The user can build up the generator by adding successive patterns. Once that
* is done, a query can be made using a "skeleton", which is a pattern which just
* includes the desired fields and lengths. The generator will return the "best fit"
* pattern corresponding to that skeleton.
* <p>The main method people will use is getBestPattern(String skeleton),
* since normally this class is pre-built with data from a particular locale.
* However, generators can be built directly from other data as well.
* <p><i>Issue: may be useful to also have a function that returns the list of
* fields in a pattern, in order, since we have that internally.
* That would be useful for getting the UI order of field elements.</i>
* @stable ICU 3.8
**/
class U_I18N_API DateTimePatternGenerator : public UObject {
public:
/**
* Construct a flexible generator according to default locale.
* @param status Output param set to success/failure code on exit,
* which must not indicate a failure before the function call.
* @stable ICU 3.8
*/
static DateTimePatternGenerator* U_EXPORT2 createInstance(UErrorCode& status);
/**
* Construct a flexible generator according to data for a given locale.
* @param uLocale
* @param status Output param set to success/failure code on exit,
* which must not indicate a failure before the function call.
* @stable ICU 3.8
*/
static DateTimePatternGenerator* U_EXPORT2 createInstance(const Locale& uLocale, UErrorCode& status);
#ifndef U_HIDE_INTERNAL_API
/**
* For ICU use only. Skips loading the standard date/time patterns (which is done via DateFormat).
*
* @internal
*/
static DateTimePatternGenerator* U_EXPORT2 createInstanceNoStdPat(const Locale& uLocale, UErrorCode& status);
#endif /* U_HIDE_INTERNAL_API */
/**
* Create an empty generator, to be constructed with addPattern(...) etc.
* @param status Output param set to success/failure code on exit,
* which must not indicate a failure before the function call.
* @stable ICU 3.8
*/
static DateTimePatternGenerator* U_EXPORT2 createEmptyInstance(UErrorCode& status);
/**
* Destructor.
* @stable ICU 3.8
*/
virtual ~DateTimePatternGenerator();
/**
* Clone DateTimePatternGenerator object. Clients are responsible for
* deleting the DateTimePatternGenerator object cloned.
* @stable ICU 3.8
*/
DateTimePatternGenerator* clone() const;
/**
* Return true if another object is semantically equal to this one.
*
* @param other the DateTimePatternGenerator object to be compared with.
* @return true if other is semantically equal to this.
* @stable ICU 3.8
*/
bool operator==(const DateTimePatternGenerator& other) const;
/**
* Return true if another object is semantically unequal to this one.
*
* @param other the DateTimePatternGenerator object to be compared with.
* @return true if other is semantically unequal to this.
* @stable ICU 3.8
*/
bool operator!=(const DateTimePatternGenerator& other) const;
/**
* Utility to return a unique skeleton from a given pattern. For example,
* both "MMM-dd" and "dd/MMM" produce the skeleton "MMMdd".
*
* @param pattern Input pattern, such as "dd/MMM"
* @param status Output param set to success/failure code on exit,
* which must not indicate a failure before the function call.
* @return skeleton such as "MMMdd"
* @stable ICU 56
*/
static UnicodeString staticGetSkeleton(const UnicodeString& pattern, UErrorCode& status);
/**
* Utility to return a unique skeleton from a given pattern. For example,
* both "MMM-dd" and "dd/MMM" produce the skeleton "MMMdd".
* getSkeleton() works exactly like staticGetSkeleton().
* Use staticGetSkeleton() instead of getSkeleton().
*
* @param pattern Input pattern, such as "dd/MMM"
* @param status Output param set to success/failure code on exit,
* which must not indicate a failure before the function call.
* @return skeleton such as "MMMdd"
* @stable ICU 3.8
*/
UnicodeString getSkeleton(const UnicodeString& pattern, UErrorCode& status); /* {
The function is commented out because it is a stable API calling a draft API.
After staticGetSkeleton becomes stable, staticGetSkeleton can be used and
these comments and the definition of getSkeleton in dtptngen.cpp should be removed.
return staticGetSkeleton(pattern, status);
}*/
/**
* Utility to return a unique base skeleton from a given pattern. This is
* the same as the skeleton, except that differences in length are minimized
* so as to only preserve the difference between string and numeric form. So
* for example, both "MMM-dd" and "d/MMM" produce the skeleton "MMMd"
* (notice the single d).
*
* @param pattern Input pattern, such as "dd/MMM"
* @param status Output param set to success/failure code on exit,
* which must not indicate a failure before the function call.
* @return base skeleton, such as "MMMd"
* @stable ICU 56
*/
static UnicodeString staticGetBaseSkeleton(const UnicodeString& pattern, UErrorCode& status);
/**
* Utility to return a unique base skeleton from a given pattern. This is
* the same as the skeleton, except that differences in length are minimized
* so as to only preserve the difference between string and numeric form. So
* for example, both "MMM-dd" and "d/MMM" produce the skeleton "MMMd"
* (notice the single d).
* getBaseSkeleton() works exactly like staticGetBaseSkeleton().
* Use staticGetBaseSkeleton() instead of getBaseSkeleton().
*
* @param pattern Input pattern, such as "dd/MMM"
* @param status Output param set to success/failure code on exit,
* which must not indicate a failure before the function call.
* @return base skeleton, such as "MMMd"
* @stable ICU 3.8
*/
UnicodeString getBaseSkeleton(const UnicodeString& pattern, UErrorCode& status); /* {
The function is commented out because it is a stable API calling a draft API.
After staticGetBaseSkeleton becomes stable, staticGetBaseSkeleton can be used and
these comments and the definition of getBaseSkeleton in dtptngen.cpp should be removed.
return staticGetBaseSkeleton(pattern, status);
}*/
/**
* Adds a pattern to the generator. If the pattern has the same skeleton as
* an existing pattern, and the override parameter is set, then the previous
* value is overridden. Otherwise, the previous value is retained. In either
* case, the conflicting status is set and previous vale is stored in
* conflicting pattern.
* <p>
* Note that single-field patterns (like "MMM") are automatically added, and
* don't need to be added explicitly!
*
* @param pattern Input pattern, such as "dd/MMM"
* @param override When existing values are to be overridden use true,
* otherwise use false.
* @param conflictingPattern Previous pattern with the same skeleton.
* @param status Output param set to success/failure code on exit,
* which must not indicate a failure before the function call.
* @return conflicting status. The value could be UDATPG_NO_CONFLICT,
* UDATPG_BASE_CONFLICT or UDATPG_CONFLICT.
* @stable ICU 3.8
*/
UDateTimePatternConflict addPattern(const UnicodeString& pattern,
UBool override,
UnicodeString& conflictingPattern,
UErrorCode& status);
/**
* An AppendItem format is a pattern used to append a field if there is no
* good match. For example, suppose that the input skeleton is "GyyyyMMMd",
* and there is no matching pattern internally, but there is a pattern
* matching "yyyyMMMd", say "d-MM-yyyy". Then that pattern is used, plus the
* G. The way these two are conjoined is by using the AppendItemFormat for G
* (era). So if that value is, say "{0}, {1}" then the final resulting
* pattern is "d-MM-yyyy, G".
* <p>
* There are actually three available variables: {0} is the pattern so far,
* {1} is the element we are adding, and {2} is the name of the element.
* <p>
* This reflects the way that the CLDR data is organized.
*
* @param field such as UDATPG_ERA_FIELD.
* @param value pattern, such as "{0}, {1}"
* @stable ICU 3.8
*/
void setAppendItemFormat(UDateTimePatternField field, const UnicodeString& value);
/**
* Getter corresponding to setAppendItemFormat. Values below 0 or at or
* above UDATPG_FIELD_COUNT are illegal arguments.
*
* @param field such as UDATPG_ERA_FIELD.
* @return append pattern for field
* @stable ICU 3.8
*/
const UnicodeString& getAppendItemFormat(UDateTimePatternField field) const;
/**
* Sets the names of field, eg "era" in English for ERA. These are only
* used if the corresponding AppendItemFormat is used, and if it contains a
* {2} variable.
* <p>
* This reflects the way that the CLDR data is organized.
*
* @param field such as UDATPG_ERA_FIELD.
* @param value name of the field
* @stable ICU 3.8
*/
void setAppendItemName(UDateTimePatternField field, const UnicodeString& value);
/**
* Getter corresponding to setAppendItemNames. Values below 0 or at or above
* UDATPG_FIELD_COUNT are illegal arguments. Note: The more general method
* for getting date/time field display names is getFieldDisplayName.
*
* @param field such as UDATPG_ERA_FIELD.
* @return name for field
* @see getFieldDisplayName
* @stable ICU 3.8
*/
const UnicodeString& getAppendItemName(UDateTimePatternField field) const;
/**
* The general interface to get a display name for a particular date/time field,
* in one of several possible display widths.
*
* @param field The desired UDateTimePatternField, such as UDATPG_ERA_FIELD.
* @param width The desired UDateTimePGDisplayWidth, such as UDATPG_ABBREVIATED.
* @return The display name for field
* @stable ICU 61
*/
UnicodeString getFieldDisplayName(UDateTimePatternField field, UDateTimePGDisplayWidth width) const;
/**
* The DateTimeFormat is a message format pattern used to compose date and
* time patterns. The default pattern in the root locale is "{1} {0}", where
* {1} will be replaced by the date pattern and {0} will be replaced by the
* time pattern; however, other locales may specify patterns such as
* "{1}, {0}" or "{1} 'at' {0}", etc.
* <p>
* This is used when the input skeleton contains both date and time fields,
* but there is not a close match among the added patterns. For example,
* suppose that this object was created by adding "dd-MMM" and "hh:mm", and
* its datetimeFormat is the default "{1} {0}". Then if the input skeleton
* is "MMMdhmm", there is not an exact match, so the input skeleton is
* broken up into two components "MMMd" and "hmm". There are close matches
* for those two skeletons, so the result is put together with this pattern,
* resulting in "d-MMM h:mm".
*
* There are four DateTimeFormats in a DateTimePatternGenerator object,
* corresponding to date styles UDAT_FULL..UDAT_SHORT. This method sets
* all of them to the specified pattern. To set them individually, see
* setDateTimeFormat(UDateFormatStyle style, ...).
*
* @param dateTimeFormat
* message format pattern, here {1} will be replaced by the date
* pattern and {0} will be replaced by the time pattern.
* @stable ICU 3.8
*/
void setDateTimeFormat(const UnicodeString& dateTimeFormat);
/**
* Getter corresponding to setDateTimeFormat.
*
* There are four DateTimeFormats in a DateTimePatternGenerator object,
* corresponding to date styles UDAT_FULL..UDAT_SHORT. This method gets
* the style for UDAT_MEDIUM (the default). To get them individually, see
* getDateTimeFormat(UDateFormatStyle style).
*
* @return DateTimeFormat.
* @stable ICU 3.8
*/
const UnicodeString& getDateTimeFormat() const;
#if !UCONFIG_NO_FORMATTING
/**
* dateTimeFormats are message patterns used to compose combinations of date
* and time patterns. There are four length styles, corresponding to the
* inferred style of the date pattern; these are UDateFormatStyle values:
* - UDAT_FULL (for date pattern with weekday and long month), else
* - UDAT_LONG (for a date pattern with long month), else
* - UDAT_MEDIUM (for a date pattern with abbreviated month), else
* - UDAT_SHORT (for any other date pattern).
* For details on dateTimeFormats, see
* https://www.unicode.org/reports/tr35/tr35-dates.html#dateTimeFormats.
* The default pattern in the root locale for all styles is "{1} {0}".
*
* @param style
* one of DateFormat.FULL..DateFormat.SHORT. Error if out of range.
* @param dateTimeFormat
* the new dateTimeFormat to set for the the specified style
* @param status
* in/out parameter; if no failure status is already set,
* it will be set according to result of the function (e.g.
* U_ILLEGAL_ARGUMENT_ERROR for style out of range).
* @stable ICU 71
*/
void setDateTimeFormat(UDateFormatStyle style, const UnicodeString& dateTimeFormat,
UErrorCode& status);
/**
* Getter corresponding to setDateTimeFormat.
*
* @param style
* one of UDAT_FULL..UDAT_SHORT. Error if out of range.
* @param status
* in/out parameter; if no failure status is already set,
* it will be set according to result of the function (e.g.
* U_ILLEGAL_ARGUMENT_ERROR for style out of range).
* @return
* the current dateTimeFormat for the the specified style, or
* empty string in case of error. The UnicodeString reference,
* or the contents of the string, may no longer be valid if
* setDateTimeFormat is called, or the DateTimePatternGenerator
* object is deleted.
* @stable ICU 71
*/
const UnicodeString& getDateTimeFormat(UDateFormatStyle style,
UErrorCode& status) const;
#endif /* #if !UCONFIG_NO_FORMATTING */
/**
* Return the best pattern matching the input skeleton. It is guaranteed to
* have all of the fields in the skeleton.
*
* @param skeleton
* The skeleton is a pattern containing only the variable fields.
* For example, "MMMdd" and "mmhh" are skeletons.
* @param status Output param set to success/failure code on exit,
* which must not indicate a failure before the function call.
* @return bestPattern
* The best pattern found from the given skeleton.
* @stable ICU 3.8
*/
UnicodeString getBestPattern(const UnicodeString& skeleton, UErrorCode& status);
/**
* Return the best pattern matching the input skeleton. It is guaranteed to
* have all of the fields in the skeleton.
*
* @param skeleton
* The skeleton is a pattern containing only the variable fields.
* For example, "MMMdd" and "mmhh" are skeletons.
* @param options
* Options for forcing the length of specified fields in the
* returned pattern to match those in the skeleton (when this
* would not happen otherwise). For default behavior, use
* UDATPG_MATCH_NO_OPTIONS.
* @param status
* Output param set to success/failure code on exit,
* which must not indicate a failure before the function call.
* @return bestPattern
* The best pattern found from the given skeleton.
* @stable ICU 4.4
*/
UnicodeString getBestPattern(const UnicodeString& skeleton,
UDateTimePatternMatchOptions options,
UErrorCode& status);
/**
* Adjusts the field types (width and subtype) of a pattern to match what is
* in a skeleton. That is, if you supply a pattern like "d-M H:m", and a
* skeleton of "MMMMddhhmm", then the input pattern is adjusted to be
* "dd-MMMM hh:mm". This is used internally to get the best match for the
* input skeleton, but can also be used externally.
*
* @param pattern Input pattern
* @param skeleton
* The skeleton is a pattern containing only the variable fields.
* For example, "MMMdd" and "mmhh" are skeletons.
* @param status Output param set to success/failure code on exit,
* which must not indicate a failure before the function call.
* @return pattern adjusted to match the skeleton fields widths and subtypes.
* @stable ICU 3.8
*/
UnicodeString replaceFieldTypes(const UnicodeString& pattern,
const UnicodeString& skeleton,
UErrorCode& status);
/**
* Adjusts the field types (width and subtype) of a pattern to match what is
* in a skeleton. That is, if you supply a pattern like "d-M H:m", and a
* skeleton of "MMMMddhhmm", then the input pattern is adjusted to be
* "dd-MMMM hh:mm". This is used internally to get the best match for the
* input skeleton, but can also be used externally.
*
* @param pattern Input pattern
* @param skeleton
* The skeleton is a pattern containing only the variable fields.
* For example, "MMMdd" and "mmhh" are skeletons.
* @param options
* Options controlling whether the length of specified fields in the
* pattern are adjusted to match those in the skeleton (when this
* would not happen otherwise). For default behavior, use
* UDATPG_MATCH_NO_OPTIONS.
* @param status
* Output param set to success/failure code on exit,
* which must not indicate a failure before the function call.
* @return pattern adjusted to match the skeleton fields widths and subtypes.
* @stable ICU 4.4
*/
UnicodeString replaceFieldTypes(const UnicodeString& pattern,
const UnicodeString& skeleton,
UDateTimePatternMatchOptions options,
UErrorCode& status);
/**
* Return a list of all the skeletons (in canonical form) from this class.
*
* Call getPatternForSkeleton() to get the corresponding pattern.
*
* @param status Output param set to success/failure code on exit,
* which must not indicate a failure before the function call.
* @return StringEnumeration with the skeletons.
* The caller must delete the object.
* @stable ICU 3.8
*/
StringEnumeration* getSkeletons(UErrorCode& status) const;
/**
* Get the pattern corresponding to a given skeleton.
* @param skeleton
* @return pattern corresponding to a given skeleton.
* @stable ICU 3.8
*/
const UnicodeString& getPatternForSkeleton(const UnicodeString& skeleton) const;
/**
* Return a list of all the base skeletons (in canonical form) from this class.
*
* @param status Output param set to success/failure code on exit,
* which must not indicate a failure before the function call.
* @return a StringEnumeration with the base skeletons.
* The caller must delete the object.
* @stable ICU 3.8
*/
StringEnumeration* getBaseSkeletons(UErrorCode& status) const;
#ifndef U_HIDE_INTERNAL_API
/**
* Return a list of redundant patterns are those which if removed, make no
* difference in the resulting getBestPattern values. This method returns a
* list of them, to help check the consistency of the patterns used to build
* this generator.
*
* @param status Output param set to success/failure code on exit,
* which must not indicate a failure before the function call.
* @return a StringEnumeration with the redundant pattern.
* The caller must delete the object.
* @internal ICU 3.8
*/
StringEnumeration* getRedundants(UErrorCode& status);
#endif /* U_HIDE_INTERNAL_API */
/**
* The decimal value is used in formatting fractions of seconds. If the
* skeleton contains fractional seconds, then this is used with the
* fractional seconds. For example, suppose that the input pattern is
* "hhmmssSSSS", and the best matching pattern internally is "H:mm:ss", and
* the decimal string is ",". Then the resulting pattern is modified to be
* "H:mm:ss,SSSS"
*
* @param decimal
* @stable ICU 3.8
*/
void setDecimal(const UnicodeString& decimal);
/**
* Getter corresponding to setDecimal.
* @return UnicodeString corresponding to the decimal point
* @stable ICU 3.8
*/
const UnicodeString& getDecimal() const;
#if !UCONFIG_NO_FORMATTING
/**
* Get the default hour cycle for a locale. Uses the locale that the
* DateTimePatternGenerator was initially created with.
*
* Cannot be used on an empty DateTimePatternGenerator instance.
*
* @param status Output param set to success/failure code on exit, which
* which must not indicate a failure before the function call.
* Set to U_UNSUPPORTED_ERROR if used on an empty instance.
* @return the default hour cycle.
* @stable ICU 67
*/
UDateFormatHourCycle getDefaultHourCycle(UErrorCode& status) const;
#endif /* #if !UCONFIG_NO_FORMATTING */
/**
* ICU "poor man's RTTI", returns a UClassID for the actual class.
*
* @stable ICU 3.8
*/
virtual UClassID getDynamicClassID() const override;
/**
* ICU "poor man's RTTI", returns a UClassID for this class.
*
* @stable ICU 3.8
*/
static UClassID U_EXPORT2 getStaticClassID();
private:
/**
* Constructor.
*/
DateTimePatternGenerator(UErrorCode & status);
/**
* Constructor.
*/
DateTimePatternGenerator(const Locale& locale, UErrorCode & status, UBool skipStdPatterns = false);
/**
* Copy constructor.
* @param other DateTimePatternGenerator to copy
*/
DateTimePatternGenerator(const DateTimePatternGenerator& other);
/**
* Default assignment operator.
* @param other DateTimePatternGenerator to copy
*/
DateTimePatternGenerator& operator=(const DateTimePatternGenerator& other);
static const int32_t UDATPG_WIDTH_COUNT = UDATPG_NARROW + 1;
Locale pLocale; // pattern locale
FormatParser *fp;
DateTimeMatcher* dtMatcher;
DistanceInfo *distanceInfo;
PatternMap *patternMap;
UnicodeString appendItemFormats[UDATPG_FIELD_COUNT];
UnicodeString fieldDisplayNames[UDATPG_FIELD_COUNT][UDATPG_WIDTH_COUNT];
UnicodeString dateTimeFormat[4];
UnicodeString decimal;
DateTimeMatcher *skipMatcher;
Hashtable *fAvailableFormatKeyHash;
UnicodeString emptyString;
char16_t fDefaultHourFormatChar;
int32_t fAllowedHourFormats[7]; // Actually an array of AllowedHourFormat enum type, ending with UNKNOWN.
// Internal error code used for recording/reporting errors that occur during methods that do not
// have a UErrorCode parameter. For example: the Copy Constructor, or the ::clone() method.
// When this is set to an error the object is in an invalid state.
UErrorCode internalErrorCode;
/* internal flags masks for adjustFieldTypes etc. */
enum {
kDTPGNoFlags = 0,
kDTPGFixFractionalSeconds = 1,
kDTPGSkeletonUsesCapJ = 2
// with #13183, no longer need flags for b, B
};
void initData(const Locale &locale, UErrorCode &status, UBool skipStdPatterns = false);
void addCanonicalItems(UErrorCode &status);
void addICUPatterns(const Locale& locale, UErrorCode& status);
void hackTimes(const UnicodeString& hackPattern, UErrorCode& status);
void getCalendarTypeToUse(const Locale& locale, CharString& destination, UErrorCode& err);
void consumeShortTimePattern(const UnicodeString& shortTimePattern, UErrorCode& status);
void addCLDRData(const Locale& locale, UErrorCode& status);
UDateTimePatternConflict addPatternWithSkeleton(const UnicodeString& pattern, const UnicodeString * skeletonToUse, UBool override, UnicodeString& conflictingPattern, UErrorCode& status);
void initHashtable(UErrorCode& status);
void setDateTimeFromCalendar(const Locale& locale, UErrorCode& status);
void setDecimalSymbols(const Locale& locale, UErrorCode& status);
UDateTimePatternField getAppendFormatNumber(const char* field) const;
// Note for the next 3: UDateTimePGDisplayWidth is now stable ICU 61
UDateTimePatternField getFieldAndWidthIndices(const char* key, UDateTimePGDisplayWidth* widthP) const;
void setFieldDisplayName(UDateTimePatternField field, UDateTimePGDisplayWidth width, const UnicodeString& value);
UnicodeString& getMutableFieldDisplayName(UDateTimePatternField field, UDateTimePGDisplayWidth width);
void getAppendName(UDateTimePatternField field, UnicodeString& value);
UnicodeString mapSkeletonMetacharacters(const UnicodeString& patternForm, int32_t* flags, UErrorCode& status);
const UnicodeString* getBestRaw(DateTimeMatcher& source, int32_t includeMask, DistanceInfo* missingFields, UErrorCode& status, const PtnSkeleton** specifiedSkeletonPtr = nullptr);
UnicodeString adjustFieldTypes(const UnicodeString& pattern, const PtnSkeleton* specifiedSkeleton, int32_t flags, UDateTimePatternMatchOptions options = UDATPG_MATCH_NO_OPTIONS);
UnicodeString getBestAppending(int32_t missingFields, int32_t flags, UErrorCode& status, UDateTimePatternMatchOptions options = UDATPG_MATCH_NO_OPTIONS);
int32_t getTopBitNumber(int32_t foundMask) const;
void setAvailableFormat(const UnicodeString &key, UErrorCode& status);
UBool isAvailableFormatSet(const UnicodeString &key) const;
void copyHashtable(Hashtable *other, UErrorCode &status);
UBool isCanonicalItem(const UnicodeString& item) const;
static void U_CALLCONV loadAllowedHourFormatsData(UErrorCode &status);
void getAllowedHourFormats(const Locale &locale, UErrorCode &status);
struct U_HIDDEN AppendItemFormatsSink;
struct U_HIDDEN AppendItemNamesSink;
struct U_HIDDEN AvailableFormatsSink;
} ;// end class DateTimePatternGenerator
U_NAMESPACE_END
#endif /* U_SHOW_CPLUSPLUS_API */
#endif

View File

@ -0,0 +1,256 @@
// © 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
/*
*******************************************************************************
* Copyright (C) 2007-2008, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
*/
#ifndef DTRULE_H
#define DTRULE_H
#include "unicode/utypes.h"
#if U_SHOW_CPLUSPLUS_API
/**
* \file
* \brief C++ API: Rule for specifying date and time in an year
*/
#if !UCONFIG_NO_FORMATTING
#include "unicode/uobject.h"
U_NAMESPACE_BEGIN
/**
* <code>DateTimeRule</code> is a class representing a time in a year by
* a rule specified by month, day of month, day of week and
* time in the day.
*
* @stable ICU 3.8
*/
class U_I18N_API DateTimeRule : public UObject {
public:
/**
* Date rule type constants.
* @stable ICU 3.8
*/
enum DateRuleType {
DOM = 0, /**< The exact day of month,
for example, March 11. */
DOW, /**< The Nth occurrence of the day of week,
for example, 2nd Sunday in March. */
DOW_GEQ_DOM, /**< The first occurrence of the day of week on or after the day of monnth,
for example, first Sunday on or after March 8. */
DOW_LEQ_DOM /**< The last occurrence of the day of week on or before the day of month,
for example, first Sunday on or before March 14. */
};
/**
* Time rule type constants.
* @stable ICU 3.8
*/
enum TimeRuleType {
WALL_TIME = 0, /**< The local wall clock time */
STANDARD_TIME, /**< The local standard time */
UTC_TIME /**< The UTC time */
};
/**
* Constructs a <code>DateTimeRule</code> by the day of month and
* the time rule. The date rule type for an instance created by
* this constructor is <code>DOM</code>.
*
* @param month The rule month, for example, <code>Calendar::JANUARY</code>
* @param dayOfMonth The day of month, 1-based.
* @param millisInDay The milliseconds in the rule date.
* @param timeType The time type, <code>WALL_TIME</code> or <code>STANDARD_TIME</code>
* or <code>UTC_TIME</code>.
* @stable ICU 3.8
*/
DateTimeRule(int32_t month, int32_t dayOfMonth,
int32_t millisInDay, TimeRuleType timeType);
/**
* Constructs a <code>DateTimeRule</code> by the day of week and its ordinal
* number and the time rule. The date rule type for an instance created
* by this constructor is <code>DOW</code>.
*
* @param month The rule month, for example, <code>Calendar::JANUARY</code>.
* @param weekInMonth The ordinal number of the day of week. Negative number
* may be used for specifying a rule date counted from the
* end of the rule month.
* @param dayOfWeek The day of week, for example, <code>Calendar::SUNDAY</code>.
* @param millisInDay The milliseconds in the rule date.
* @param timeType The time type, <code>WALL_TIME</code> or <code>STANDARD_TIME</code>
* or <code>UTC_TIME</code>.
* @stable ICU 3.8
*/
DateTimeRule(int32_t month, int32_t weekInMonth, int32_t dayOfWeek,
int32_t millisInDay, TimeRuleType timeType);
/**
* Constructs a <code>DateTimeRule</code> by the first/last day of week
* on or after/before the day of month and the time rule. The date rule
* type for an instance created by this constructor is either
* <code>DOM_GEQ_DOM</code> or <code>DOM_LEQ_DOM</code>.
*
* @param month The rule month, for example, <code>Calendar::JANUARY</code>
* @param dayOfMonth The day of month, 1-based.
* @param dayOfWeek The day of week, for example, <code>Calendar::SUNDAY</code>.
* @param after true if the rule date is on or after the day of month.
* @param millisInDay The milliseconds in the rule date.
* @param timeType The time type, <code>WALL_TIME</code> or <code>STANDARD_TIME</code>
* or <code>UTC_TIME</code>.
* @stable ICU 3.8
*/
DateTimeRule(int32_t month, int32_t dayOfMonth, int32_t dayOfWeek, UBool after,
int32_t millisInDay, TimeRuleType timeType);
/**
* Copy constructor.
* @param source The DateTimeRule object to be copied.
* @stable ICU 3.8
*/
DateTimeRule(const DateTimeRule& source);
/**
* Destructor.
* @stable ICU 3.8
*/
~DateTimeRule();
/**
* Clone this DateTimeRule object polymorphically. The caller owns the result and
* should delete it when done.
* @return A copy of the object.
* @stable ICU 3.8
*/
DateTimeRule* clone() const;
/**
* Assignment operator.
* @param right The object to be copied.
* @stable ICU 3.8
*/
DateTimeRule& operator=(const DateTimeRule& right);
/**
* Return true if the given DateTimeRule objects are semantically equal. Objects
* of different subclasses are considered unequal.
* @param that The object to be compared with.
* @return true if the given DateTimeRule objects are semantically equal.
* @stable ICU 3.8
*/
bool operator==(const DateTimeRule& that) const;
/**
* Return true if the given DateTimeRule objects are semantically unequal. Objects
* of different subclasses are considered unequal.
* @param that The object to be compared with.
* @return true if the given DateTimeRule objects are semantically unequal.
* @stable ICU 3.8
*/
bool operator!=(const DateTimeRule& that) const;
/**
* Gets the date rule type, such as <code>DOM</code>
* @return The date rule type.
* @stable ICU 3.8
*/
DateRuleType getDateRuleType() const;
/**
* Gets the time rule type
* @return The time rule type, either <code>WALL_TIME</code> or <code>STANDARD_TIME</code>
* or <code>UTC_TIME</code>.
* @stable ICU 3.8
*/
TimeRuleType getTimeRuleType() const;
/**
* Gets the rule month.
* @return The rule month.
* @stable ICU 3.8
*/
int32_t getRuleMonth() const;
/**
* Gets the rule day of month. When the date rule type
* is <code>DOW</code>, the value is always 0.
* @return The rule day of month
* @stable ICU 3.8
*/
int32_t getRuleDayOfMonth() const;
/**
* Gets the rule day of week. When the date rule type
* is <code>DOM</code>, the value is always 0.
* @return The rule day of week.
* @stable ICU 3.8
*/
int32_t getRuleDayOfWeek() const;
/**
* Gets the ordinal number of the occurrence of the day of week
* in the month. When the date rule type is not <code>DOW</code>,
* the value is always 0.
* @return The rule day of week ordinal number in the month.
* @stable ICU 3.8
*/
int32_t getRuleWeekInMonth() const;
/**
* Gets the rule time in the rule day.
* @return The time in the rule day in milliseconds.
* @stable ICU 3.8
*/
int32_t getRuleMillisInDay() const;
private:
int32_t fMonth;
int32_t fDayOfMonth;
int32_t fDayOfWeek;
int32_t fWeekInMonth;
int32_t fMillisInDay;
DateRuleType fDateRuleType;
TimeRuleType fTimeRuleType;
public:
/**
* Return the class ID for this class. This is useful only for comparing to
* a return value from getDynamicClassID(). For example:
* <pre>
* . Base* polymorphic_pointer = createPolymorphicObject();
* . if (polymorphic_pointer->getDynamicClassID() ==
* . erived::getStaticClassID()) ...
* </pre>
* @return The class ID for all objects of this class.
* @stable ICU 3.8
*/
static UClassID U_EXPORT2 getStaticClassID();
/**
* Returns a unique class ID POLYMORPHICALLY. Pure virtual override. This
* method is to implement a simple version of RTTI, since not all C++
* compilers support genuine RTTI. Polymorphic operator==() and clone()
* methods call this method.
*
* @return The class ID for this object. All objects of a
* given class have the same class ID. Objects of
* other classes have different class IDs.
* @stable ICU 3.8
*/
virtual UClassID getDynamicClassID() const override;
};
U_NAMESPACE_END
#endif /* #if !UCONFIG_NO_FORMATTING */
#endif /* U_SHOW_CPLUSPLUS_API */
#endif // DTRULE_H
//eof

View File

@ -0,0 +1,298 @@
// © 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
/*
********************************************************************************
* Copyright (C) 1997-2006, International Business Machines
* Corporation and others. All Rights Reserved.
********************************************************************************
*
* File FIELDPOS.H
*
* Modification History:
*
* Date Name Description
* 02/25/97 aliu Converted from java.
* 03/17/97 clhuang Updated per Format implementation.
* 07/17/98 stephen Added default/copy ctors, and operators =, ==, !=
********************************************************************************
*/
// *****************************************************************************
// This file was generated from the java source file FieldPosition.java
// *****************************************************************************
#ifndef FIELDPOS_H
#define FIELDPOS_H
#include "unicode/utypes.h"
#if U_SHOW_CPLUSPLUS_API
/**
* \file
* \brief C++ API: FieldPosition identifies the fields in a formatted output.
*/
#if !UCONFIG_NO_FORMATTING
#include "unicode/uobject.h"
U_NAMESPACE_BEGIN
/**
* <code>FieldPosition</code> is a simple class used by <code>Format</code>
* and its subclasses to identify fields in formatted output. Fields are
* identified by constants, whose names typically end with <code>_FIELD</code>,
* defined in the various subclasses of <code>Format</code>. See
* <code>ERA_FIELD</code> and its friends in <code>DateFormat</code> for
* an example.
*
* <p>
* <code>FieldPosition</code> keeps track of the position of the
* field within the formatted output with two indices: the index
* of the first character of the field and the index of the last
* character of the field.
*
* <p>
* One version of the <code>format</code> method in the various
* <code>Format</code> classes requires a <code>FieldPosition</code>
* object as an argument. You use this <code>format</code> method
* to perform partial formatting or to get information about the
* formatted output (such as the position of a field).
*
* The FieldPosition class is not intended for public subclassing.
*
* <p>
* Below is an example of using <code>FieldPosition</code> to aid
* alignment of an array of formatted floating-point numbers on
* their decimal points:
* <pre>
* \code
* double doubleNum[] = {123456789.0, -12345678.9, 1234567.89, -123456.789,
* 12345.6789, -1234.56789, 123.456789, -12.3456789, 1.23456789};
* int dNumSize = (int)(sizeof(doubleNum)/sizeof(double));
*
* UErrorCode status = U_ZERO_ERROR;
* DecimalFormat* fmt = (DecimalFormat*) NumberFormat::createInstance(status);
* fmt->setDecimalSeparatorAlwaysShown(true);
*
* const int tempLen = 20;
* char temp[tempLen];
*
* for (int i=0; i<dNumSize; i++) {
* FieldPosition pos(NumberFormat::INTEGER_FIELD);
* UnicodeString buf;
* char fmtText[tempLen];
* ToCharString(fmt->format(doubleNum[i], buf, pos), fmtText);
* for (int j=0; j<tempLen; j++) temp[j] = ' '; // clear with spaces
* temp[__min(tempLen, tempLen-pos.getEndIndex())] = '\0';
* cout << temp << fmtText << endl;
* }
* delete fmt;
* \endcode
* </pre>
* <p>
* The code will generate the following output:
* <pre>
* \code
* 123,456,789.000
* -12,345,678.900
* 1,234,567.880
* -123,456.789
* 12,345.678
* -1,234.567
* 123.456
* -12.345
* 1.234
* \endcode
* </pre>
*/
class U_I18N_API FieldPosition : public UObject {
public:
/**
* DONT_CARE may be specified as the field to indicate that the
* caller doesn't need to specify a field.
* @stable ICU 2.0
*/
enum { DONT_CARE = -1 };
/**
* Creates a FieldPosition object with a non-specified field.
* @stable ICU 2.0
*/
FieldPosition()
: UObject(), fField(DONT_CARE), fBeginIndex(0), fEndIndex(0) {}
/**
* Creates a FieldPosition object for the given field. Fields are
* identified by constants, whose names typically end with _FIELD,
* in the various subclasses of Format.
*
* @see NumberFormat#INTEGER_FIELD
* @see NumberFormat#FRACTION_FIELD
* @see DateFormat#YEAR_FIELD
* @see DateFormat#MONTH_FIELD
* @stable ICU 2.0
*/
FieldPosition(int32_t field)
: UObject(), fField(field), fBeginIndex(0), fEndIndex(0) {}
/**
* Copy constructor
* @param copy the object to be copied from.
* @stable ICU 2.0
*/
FieldPosition(const FieldPosition& copy)
: UObject(copy), fField(copy.fField), fBeginIndex(copy.fBeginIndex), fEndIndex(copy.fEndIndex) {}
/**
* Destructor
* @stable ICU 2.0
*/
virtual ~FieldPosition();
/**
* Assignment operator
* @param copy the object to be copied from.
* @stable ICU 2.0
*/
FieldPosition& operator=(const FieldPosition& copy);
/**
* Equality operator.
* @param that the object to be compared with.
* @return true if the two field positions are equal, false otherwise.
* @stable ICU 2.0
*/
bool operator==(const FieldPosition& that) const;
/**
* Equality operator.
* @param that the object to be compared with.
* @return true if the two field positions are not equal, false otherwise.
* @stable ICU 2.0
*/
bool operator!=(const FieldPosition& that) const;
/**
* Clone this object.
* Clones can be used concurrently in multiple threads.
* If an error occurs, then nullptr is returned.
* The caller must delete the clone.
*
* @return a clone of this object
*
* @see getDynamicClassID
* @stable ICU 2.8
*/
FieldPosition *clone() const;
/**
* Retrieve the field identifier.
* @return the field identifier.
* @stable ICU 2.0
*/
int32_t getField() const { return fField; }
/**
* Retrieve the index of the first character in the requested field.
* @return the index of the first character in the requested field.
* @stable ICU 2.0
*/
int32_t getBeginIndex() const { return fBeginIndex; }
/**
* Retrieve the index of the character following the last character in the
* requested field.
* @return the index of the character following the last character in the
* requested field.
* @stable ICU 2.0
*/
int32_t getEndIndex() const { return fEndIndex; }
/**
* Set the field.
* @param f the new value of the field.
* @stable ICU 2.0
*/
void setField(int32_t f) { fField = f; }
/**
* Set the begin index. For use by subclasses of Format.
* @param bi the new value of the begin index
* @stable ICU 2.0
*/
void setBeginIndex(int32_t bi) { fBeginIndex = bi; }
/**
* Set the end index. For use by subclasses of Format.
* @param ei the new value of the end index
* @stable ICU 2.0
*/
void setEndIndex(int32_t ei) { fEndIndex = ei; }
/**
* ICU "poor man's RTTI", returns a UClassID for the actual class.
*
* @stable ICU 2.2
*/
virtual UClassID getDynamicClassID() const override;
/**
* ICU "poor man's RTTI", returns a UClassID for this class.
*
* @stable ICU 2.2
*/
static UClassID U_EXPORT2 getStaticClassID();
private:
/**
* Input: Desired field to determine start and end offsets for.
* The meaning depends on the subclass of Format.
*/
int32_t fField;
/**
* Output: Start offset of field in text.
* If the field does not occur in the text, 0 is returned.
*/
int32_t fBeginIndex;
/**
* Output: End offset of field in text.
* If the field does not occur in the text, 0 is returned.
*/
int32_t fEndIndex;
};
inline FieldPosition&
FieldPosition::operator=(const FieldPosition& copy)
{
fField = copy.fField;
fEndIndex = copy.fEndIndex;
fBeginIndex = copy.fBeginIndex;
return *this;
}
inline bool
FieldPosition::operator==(const FieldPosition& copy) const
{
return (fField == copy.fField &&
fEndIndex == copy.fEndIndex &&
fBeginIndex == copy.fBeginIndex);
}
inline bool
FieldPosition::operator!=(const FieldPosition& copy) const
{
return !operator==(copy);
}
U_NAMESPACE_END
#endif /* #if !UCONFIG_NO_FORMATTING */
#endif /* U_SHOW_CPLUSPLUS_API */
#endif // _FIELDPOS
//eof

View File

@ -0,0 +1,758 @@
// © 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
/*
********************************************************************************
* Copyright (C) 1997-2014, International Business Machines
* Corporation and others. All Rights Reserved.
********************************************************************************
*
* File FMTABLE.H
*
* Modification History:
*
* Date Name Description
* 02/29/97 aliu Creation.
********************************************************************************
*/
#ifndef FMTABLE_H
#define FMTABLE_H
#include "unicode/utypes.h"
#if U_SHOW_CPLUSPLUS_API
/**
* \file
* \brief C++ API: Formattable is a thin wrapper for primitive types used for formatting and parsing
*/
#if !UCONFIG_NO_FORMATTING
#include "unicode/unistr.h"
#include "unicode/stringpiece.h"
#include "unicode/uformattable.h"
U_NAMESPACE_BEGIN
class CharString;
namespace number::impl {
class DecimalQuantity;
}
/**
* Formattable objects can be passed to the Format class or
* its subclasses for formatting. Formattable is a thin wrapper
* class which interconverts between the primitive numeric types
* (double, long, etc.) as well as UDate and UnicodeString.
*
* <p>Internally, a Formattable object is a union of primitive types.
* As such, it can only store one flavor of data at a time. To
* determine what flavor of data it contains, use the getType method.
*
* <p>As of ICU 3.0, Formattable may also wrap a UObject pointer,
* which it owns. This allows an instance of any ICU class to be
* encapsulated in a Formattable. For legacy reasons and for
* efficiency, primitive numeric types are still stored directly
* within a Formattable.
*
* <p>The Formattable class is not suitable for subclassing.
*
* <p>See UFormattable for a C wrapper.
*/
class U_I18N_API Formattable : public UObject {
public:
/**
* This enum is only used to let callers distinguish between
* the Formattable(UDate) constructor and the Formattable(double)
* constructor; the compiler cannot distinguish the signatures,
* since UDate is currently typedefed to be either double or long.
* If UDate is changed later to be a bonafide class
* or struct, then we no longer need this enum.
* @stable ICU 2.4
*/
enum ISDATE { kIsDate };
/**
* Default constructor
* @stable ICU 2.4
*/
Formattable(); // Type kLong, value 0
/**
* Creates a Formattable object with a UDate instance.
* @param d the UDate instance.
* @param flag the flag to indicate this is a date. Always set it to kIsDate
* @stable ICU 2.0
*/
Formattable(UDate d, ISDATE flag);
/**
* Creates a Formattable object with a double number.
* @param d the double number.
* @stable ICU 2.0
*/
Formattable(double d);
/**
* Creates a Formattable object with a long number.
* @param l the long number.
* @stable ICU 2.0
*/
Formattable(int32_t l);
/**
* Creates a Formattable object with an int64_t number
* @param ll the int64_t number.
* @stable ICU 2.8
*/
Formattable(int64_t ll);
#if !UCONFIG_NO_CONVERSION
/**
* Creates a Formattable object with a char string pointer.
* Assumes that the char string is null terminated.
* @param strToCopy the char string.
* @stable ICU 2.0
*/
Formattable(const char* strToCopy);
#endif
/**
* Creates a Formattable object of an appropriate numeric type from a
* a decimal number in string form. The Formattable will retain the
* full precision of the input in decimal format, even when it exceeds
* what can be represented by a double or int64_t.
*
* @param number the unformatted (not localized) string representation
* of the Decimal number.
* @param status the error code. Possible errors include U_INVALID_FORMAT_ERROR
* if the format of the string does not conform to that of a
* decimal number.
* @stable ICU 4.4
*/
Formattable(StringPiece number, UErrorCode &status);
/**
* Creates a Formattable object with a UnicodeString object to copy from.
* @param strToCopy the UnicodeString string.
* @stable ICU 2.0
*/
Formattable(const UnicodeString& strToCopy);
/**
* Creates a Formattable object with a UnicodeString object to adopt from.
* @param strToAdopt the UnicodeString string.
* @stable ICU 2.0
*/
Formattable(UnicodeString* strToAdopt);
/**
* Creates a Formattable object with an array of Formattable objects.
* @param arrayToCopy the Formattable object array.
* @param count the array count.
* @stable ICU 2.0
*/
Formattable(const Formattable* arrayToCopy, int32_t count);
/**
* Creates a Formattable object that adopts the given UObject.
* @param objectToAdopt the UObject to set this object to
* @stable ICU 3.0
*/
Formattable(UObject* objectToAdopt);
/**
* Copy constructor.
* @stable ICU 2.0
*/
Formattable(const Formattable&);
/**
* Assignment operator.
* @param rhs The Formattable object to copy into this object.
* @stable ICU 2.0
*/
Formattable& operator=(const Formattable &rhs);
/**
* Equality comparison.
* @param other the object to be compared with.
* @return true if other are equal to this, false otherwise.
* @stable ICU 2.0
*/
bool operator==(const Formattable &other) const;
/**
* Equality operator.
* @param other the object to be compared with.
* @return true if other are unequal to this, false otherwise.
* @stable ICU 2.0
*/
bool operator!=(const Formattable& other) const
{ return !operator==(other); }
/**
* Destructor.
* @stable ICU 2.0
*/
virtual ~Formattable();
/**
* Clone this object.
* Clones can be used concurrently in multiple threads.
* If an error occurs, then nullptr is returned.
* The caller must delete the clone.
*
* @return a clone of this object
*
* @see getDynamicClassID
* @stable ICU 2.8
*/
Formattable *clone() const;
/**
* Selector for flavor of data type contained within a
* Formattable object. Formattable is a union of several
* different types, and at any time contains exactly one type.
* @stable ICU 2.4
*/
enum Type {
/**
* Selector indicating a UDate value. Use getDate to retrieve
* the value.
* @stable ICU 2.4
*/
kDate,
/**
* Selector indicating a double value. Use getDouble to
* retrieve the value.
* @stable ICU 2.4
*/
kDouble,
/**
* Selector indicating a 32-bit integer value. Use getLong to
* retrieve the value.
* @stable ICU 2.4
*/
kLong,
/**
* Selector indicating a UnicodeString value. Use getString
* to retrieve the value.
* @stable ICU 2.4
*/
kString,
/**
* Selector indicating an array of Formattables. Use getArray
* to retrieve the value.
* @stable ICU 2.4
*/
kArray,
/**
* Selector indicating a 64-bit integer value. Use getInt64
* to retrieve the value.
* @stable ICU 2.8
*/
kInt64,
/**
* Selector indicating a UObject value. Use getObject to
* retrieve the value.
* @stable ICU 3.0
*/
kObject
};
/**
* Gets the data type of this Formattable object.
* @return the data type of this Formattable object.
* @stable ICU 2.0
*/
Type getType() const;
/**
* Returns true if the data type of this Formattable object
* is kDouble, kLong, or kInt64
* @return true if this is a pure numeric object
* @stable ICU 3.0
*/
UBool isNumeric() const;
/**
* Gets the double value of this object. If this object is not of type
* kDouble then the result is undefined.
* @return the double value of this object.
* @stable ICU 2.0
*/
double getDouble() const { return fValue.fDouble; }
/**
* Gets the double value of this object. If this object is of type
* long, int64 or Decimal Number then a conversion is performed, with
* possible loss of precision. If the type is kObject and the
* object is a Measure, then the result of
* getNumber().getDouble(status) is returned. If this object is
* neither a numeric type nor a Measure, then 0 is returned and
* the status is set to U_INVALID_FORMAT_ERROR.
* @param status the error code
* @return the double value of this object.
* @stable ICU 3.0
*/
double getDouble(UErrorCode& status) const;
/**
* Gets the long value of this object. If this object is not of type
* kLong then the result is undefined.
* @return the long value of this object.
* @stable ICU 2.0
*/
int32_t getLong() const { return static_cast<int32_t>(fValue.fInt64); }
/**
* Gets the long value of this object. If the magnitude is too
* large to fit in a long, then the maximum or minimum long value,
* as appropriate, is returned and the status is set to
* U_INVALID_FORMAT_ERROR. If this object is of type kInt64 and
* it fits within a long, then no precision is lost. If it is of
* type kDouble, then a conversion is performed, with
* truncation of any fractional part. If the type is kObject and
* the object is a Measure, then the result of
* getNumber().getLong(status) is returned. If this object is
* neither a numeric type nor a Measure, then 0 is returned and
* the status is set to U_INVALID_FORMAT_ERROR.
* @param status the error code
* @return the long value of this object.
* @stable ICU 3.0
*/
int32_t getLong(UErrorCode& status) const;
/**
* Gets the int64 value of this object. If this object is not of type
* kInt64 then the result is undefined.
* @return the int64 value of this object.
* @stable ICU 2.8
*/
int64_t getInt64() const { return fValue.fInt64; }
/**
* Gets the int64 value of this object. If this object is of a numeric
* type and the magnitude is too large to fit in an int64, then
* the maximum or minimum int64 value, as appropriate, is returned
* and the status is set to U_INVALID_FORMAT_ERROR. If the
* magnitude fits in an int64, then a casting conversion is
* performed, with truncation of any fractional part. If the type
* is kObject and the object is a Measure, then the result of
* getNumber().getDouble(status) is returned. If this object is
* neither a numeric type nor a Measure, then 0 is returned and
* the status is set to U_INVALID_FORMAT_ERROR.
* @param status the error code
* @return the int64 value of this object.
* @stable ICU 3.0
*/
int64_t getInt64(UErrorCode& status) const;
/**
* Gets the Date value of this object. If this object is not of type
* kDate then the result is undefined.
* @return the Date value of this object.
* @stable ICU 2.0
*/
UDate getDate() const { return fValue.fDate; }
/**
* Gets the Date value of this object. If the type is not a date,
* status is set to U_INVALID_FORMAT_ERROR and the return value is
* undefined.
* @param status the error code.
* @return the Date value of this object.
* @stable ICU 3.0
*/
UDate getDate(UErrorCode& status) const;
/**
* Gets the string value of this object. If this object is not of type
* kString then the result is undefined.
* @param result Output param to receive the Date value of this object.
* @return A reference to 'result'.
* @stable ICU 2.0
*/
UnicodeString& getString(UnicodeString& result) const
{ result=*fValue.fString; return result; }
/**
* Gets the string value of this object. If the type is not a
* string, status is set to U_INVALID_FORMAT_ERROR and a bogus
* string is returned.
* @param result Output param to receive the Date value of this object.
* @param status the error code.
* @return A reference to 'result'.
* @stable ICU 3.0
*/
UnicodeString& getString(UnicodeString& result, UErrorCode& status) const;
/**
* Gets a const reference to the string value of this object. If
* this object is not of type kString then the result is
* undefined.
* @return a const reference to the string value of this object.
* @stable ICU 2.0
*/
inline const UnicodeString& getString() const;
/**
* Gets a const reference to the string value of this object. If
* the type is not a string, status is set to
* U_INVALID_FORMAT_ERROR and the result is a bogus string.
* @param status the error code.
* @return a const reference to the string value of this object.
* @stable ICU 3.0
*/
const UnicodeString& getString(UErrorCode& status) const;
/**
* Gets a reference to the string value of this object. If this
* object is not of type kString then the result is undefined.
* @return a reference to the string value of this object.
* @stable ICU 2.0
*/
inline UnicodeString& getString();
/**
* Gets a reference to the string value of this object. If the
* type is not a string, status is set to U_INVALID_FORMAT_ERROR
* and the result is a bogus string.
* @param status the error code.
* @return a reference to the string value of this object.
* @stable ICU 3.0
*/
UnicodeString& getString(UErrorCode& status);
/**
* Gets the array value and count of this object. If this object
* is not of type kArray then the result is undefined.
* @param count fill-in with the count of this object.
* @return the array value of this object.
* @stable ICU 2.0
*/
const Formattable* getArray(int32_t& count) const
{ count=fValue.fArrayAndCount.fCount; return fValue.fArrayAndCount.fArray; }
/**
* Gets the array value and count of this object. If the type is
* not an array, status is set to U_INVALID_FORMAT_ERROR, count is
* set to 0, and the result is nullptr.
* @param count fill-in with the count of this object.
* @param status the error code.
* @return the array value of this object.
* @stable ICU 3.0
*/
const Formattable* getArray(int32_t& count, UErrorCode& status) const;
/**
* Accesses the specified element in the array value of this
* Formattable object. If this object is not of type kArray then
* the result is undefined.
* @param index the specified index.
* @return the accessed element in the array.
* @stable ICU 2.0
*/
Formattable& operator[](int32_t index) { return fValue.fArrayAndCount.fArray[index]; }
/**
* Returns a pointer to the UObject contained within this
* formattable, or nullptr if this object does not contain a UObject.
* @return a UObject pointer, or nullptr
* @stable ICU 3.0
*/
const UObject* getObject() const;
/**
* Returns a numeric string representation of the number contained within this
* formattable, or nullptr if this object does not contain numeric type.
* For values obtained by parsing, the returned decimal number retains
* the full precision and range of the original input, unconstrained by
* the limits of a double floating point or a 64 bit int.
*
* This function is not thread safe, and therefore is not declared const,
* even though it is logically const.
*
* Possible errors include U_MEMORY_ALLOCATION_ERROR, and
* U_INVALID_STATE if the formattable object has not been set to
* a numeric type.
*
* @param status the error code.
* @return the unformatted string representation of a number.
* @stable ICU 4.4
*/
StringPiece getDecimalNumber(UErrorCode &status);
/**
* Sets the double value of this object and changes the type to
* kDouble.
* @param d the new double value to be set.
* @stable ICU 2.0
*/
void setDouble(double d);
/**
* Sets the long value of this object and changes the type to
* kLong.
* @param l the new long value to be set.
* @stable ICU 2.0
*/
void setLong(int32_t l);
/**
* Sets the int64 value of this object and changes the type to
* kInt64.
* @param ll the new int64 value to be set.
* @stable ICU 2.8
*/
void setInt64(int64_t ll);
/**
* Sets the Date value of this object and changes the type to
* kDate.
* @param d the new Date value to be set.
* @stable ICU 2.0
*/
void setDate(UDate d);
/**
* Sets the string value of this object and changes the type to
* kString.
* @param stringToCopy the new string value to be set.
* @stable ICU 2.0
*/
void setString(const UnicodeString& stringToCopy);
/**
* Sets the array value and count of this object and changes the
* type to kArray.
* @param array the array value.
* @param count the number of array elements to be copied.
* @stable ICU 2.0
*/
void setArray(const Formattable* array, int32_t count);
/**
* Sets and adopts the string value and count of this object and
* changes the type to kArray.
* @param stringToAdopt the new string value to be adopted.
* @stable ICU 2.0
*/
void adoptString(UnicodeString* stringToAdopt);
/**
* Sets and adopts the array value and count of this object and
* changes the type to kArray.
* @stable ICU 2.0
*/
void adoptArray(Formattable* array, int32_t count);
/**
* Sets and adopts the UObject value of this object and changes
* the type to kObject. After this call, the caller must not
* delete the given object.
* @param objectToAdopt the UObject value to be adopted
* @stable ICU 3.0
*/
void adoptObject(UObject* objectToAdopt);
/**
* Sets the the numeric value from a decimal number string, and changes
* the type to to a numeric type appropriate for the number.
* The syntax of the number is a "numeric string"
* as defined in the Decimal Arithmetic Specification, available at
* http://speleotrove.com/decimal
* The full precision and range of the input number will be retained,
* even when it exceeds what can be represented by a double or an int64.
*
* @param numberString a string representation of the unformatted decimal number.
* @param status the error code. Set to U_INVALID_FORMAT_ERROR if the
* incoming string is not a valid decimal number.
* @stable ICU 4.4
*/
void setDecimalNumber(StringPiece numberString,
UErrorCode &status);
/**
* ICU "poor man's RTTI", returns a UClassID for the actual class.
*
* @stable ICU 2.2
*/
virtual UClassID getDynamicClassID() const override;
/**
* ICU "poor man's RTTI", returns a UClassID for this class.
*
* @stable ICU 2.2
*/
static UClassID U_EXPORT2 getStaticClassID();
/**
* Convert the UFormattable to a Formattable. Internally, this is a reinterpret_cast.
* @param fmt a valid UFormattable
* @return the UFormattable as a Formattable object pointer. This is an alias to the original
* UFormattable, and so is only valid while the original argument remains in scope.
* @stable ICU 52
*/
static inline Formattable *fromUFormattable(UFormattable *fmt);
/**
* Convert the const UFormattable to a const Formattable. Internally, this is a reinterpret_cast.
* @param fmt a valid UFormattable
* @return the UFormattable as a Formattable object pointer. This is an alias to the original
* UFormattable, and so is only valid while the original argument remains in scope.
* @stable ICU 52
*/
static inline const Formattable *fromUFormattable(const UFormattable *fmt);
/**
* Convert this object pointer to a UFormattable.
* @return this object as a UFormattable pointer. This is an alias to this object,
* and so is only valid while this object remains in scope.
* @stable ICU 52
*/
inline UFormattable *toUFormattable();
/**
* Convert this object pointer to a UFormattable.
* @return this object as a UFormattable pointer. This is an alias to this object,
* and so is only valid while this object remains in scope.
* @stable ICU 52
*/
inline const UFormattable *toUFormattable() const;
#ifndef U_HIDE_DEPRECATED_API
/**
* Deprecated variant of getLong(UErrorCode&).
* @param status the error code
* @return the long value of this object.
* @deprecated ICU 3.0 use getLong(UErrorCode&) instead
*/
inline int32_t getLong(UErrorCode* status) const;
#endif /* U_HIDE_DEPRECATED_API */
#ifndef U_HIDE_INTERNAL_API
/**
* Internal function, do not use.
* TODO: figure out how to make this be non-public.
* NumberFormat::format(Formattable, ...
* needs to get at the DecimalQuantity, if it exists, for
* big decimal formatting.
* @internal
*/
number::impl::DecimalQuantity *getDecimalQuantity() const { return fDecimalQuantity;}
/**
* Export the value of this Formattable to a DecimalQuantity.
* @internal
*/
void populateDecimalQuantity(number::impl::DecimalQuantity& output, UErrorCode& status) const;
/**
* Adopt, and set value from, a DecimalQuantity
* Internal Function, do not use.
* @param dq the DecimalQuantity to be adopted
* @internal
*/
void adoptDecimalQuantity(number::impl::DecimalQuantity *dq);
/**
* Internal function to return the CharString pointer.
* @param status error code
* @return pointer to the CharString - may become invalid if the object is modified
* @internal
*/
CharString *internalGetCharString(UErrorCode &status);
#endif /* U_HIDE_INTERNAL_API */
private:
/**
* Cleans up the memory for unwanted values. For example, the adopted
* string or array objects.
*/
void dispose();
/**
* Common initialization, for use by constructors.
*/
void init();
UnicodeString* getBogus() const;
union {
UObject* fObject;
UnicodeString* fString;
double fDouble;
int64_t fInt64;
UDate fDate;
struct {
Formattable* fArray;
int32_t fCount;
} fArrayAndCount;
} fValue;
CharString *fDecimalStr;
number::impl::DecimalQuantity *fDecimalQuantity;
Type fType;
UnicodeString fBogus; // Bogus string when it's needed.
};
inline UDate Formattable::getDate(UErrorCode& status) const {
if (fType != kDate) {
if (U_SUCCESS(status)) {
status = U_INVALID_FORMAT_ERROR;
}
return 0;
}
return fValue.fDate;
}
inline const UnicodeString& Formattable::getString() const {
return *fValue.fString;
}
inline UnicodeString& Formattable::getString() {
return *fValue.fString;
}
#ifndef U_HIDE_DEPRECATED_API
inline int32_t Formattable::getLong(UErrorCode* status) const {
return getLong(*status);
}
#endif /* U_HIDE_DEPRECATED_API */
inline UFormattable* Formattable::toUFormattable() {
return reinterpret_cast<UFormattable*>(this);
}
inline const UFormattable* Formattable::toUFormattable() const {
return reinterpret_cast<const UFormattable*>(this);
}
inline Formattable* Formattable::fromUFormattable(UFormattable *fmt) {
return reinterpret_cast<Formattable *>(fmt);
}
inline const Formattable* Formattable::fromUFormattable(const UFormattable *fmt) {
return reinterpret_cast<const Formattable *>(fmt);
}
U_NAMESPACE_END
#endif /* #if !UCONFIG_NO_FORMATTING */
#endif /* U_SHOW_CPLUSPLUS_API */
#endif //_FMTABLE
//eof

View File

@ -0,0 +1,312 @@
// © 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
/*
********************************************************************************
* Copyright (C) 1997-2011, International Business Machines Corporation and others.
* All Rights Reserved.
********************************************************************************
*
* File FORMAT.H
*
* Modification History:
*
* Date Name Description
* 02/19/97 aliu Converted from java.
* 03/17/97 clhuang Updated per C++ implementation.
* 03/27/97 helena Updated to pass the simple test after code review.
********************************************************************************
*/
// *****************************************************************************
// This file was generated from the java source file Format.java
// *****************************************************************************
#ifndef FORMAT_H
#define FORMAT_H
#include "unicode/utypes.h"
#if U_SHOW_CPLUSPLUS_API
/**
* \file
* \brief C++ API: Base class for all formats.
*/
#if !UCONFIG_NO_FORMATTING
#include "unicode/unistr.h"
#include "unicode/fmtable.h"
#include "unicode/fieldpos.h"
#include "unicode/fpositer.h"
#include "unicode/parsepos.h"
#include "unicode/parseerr.h"
#include "unicode/locid.h"
U_NAMESPACE_BEGIN
class CharString;
/**
* Base class for all formats. This is an abstract base class which
* specifies the protocol for classes which convert other objects or
* values, such as numeric values and dates, and their string
* representations. In some cases these representations may be
* localized or contain localized characters or strings. For example,
* a numeric formatter such as DecimalFormat may convert a numeric
* value such as 12345 to the string "$12,345". It may also parse
* the string back into a numeric value. A date and time formatter
* like SimpleDateFormat may represent a specific date, encoded
* numerically, as a string such as "Wednesday, February 26, 1997 AD".
* <P>
* Many of the concrete subclasses of Format employ the notion of
* a pattern. A pattern is a string representation of the rules which
* govern the interconversion between values and strings. For example,
* a DecimalFormat object may be associated with the pattern
* "$#,##0.00;($#,##0.00)", which is a common US English format for
* currency values, yielding strings such as "$1,234.45" for 1234.45,
* and "($987.65)" for 987.6543. The specific syntax of a pattern
* is defined by each subclass.
* <P>
* Even though many subclasses use patterns, the notion of a pattern
* is not inherent to Format classes in general, and is not part of
* the explicit base class protocol.
* <P>
* Two complex formatting classes bear mentioning. These are
* MessageFormat and ChoiceFormat. ChoiceFormat is a subclass of
* NumberFormat which allows the user to format different number ranges
* as strings. For instance, 0 may be represented as "no files", 1 as
* "one file", and any number greater than 1 as "many files".
* MessageFormat is a formatter which utilizes other Format objects to
* format a string containing with multiple values. For instance,
* A MessageFormat object might produce the string "There are no files
* on the disk MyDisk on February 27, 1997." given the arguments 0,
* "MyDisk", and the date value of 2/27/97. See the ChoiceFormat
* and MessageFormat headers for further information.
* <P>
* If formatting is unsuccessful, a failing UErrorCode is returned when
* the Format cannot format the type of object, otherwise if there is
* something illformed about the the Unicode replacement character
* 0xFFFD is returned.
* <P>
* If there is no match when parsing, a parse failure UErrorCode is
* returned for methods which take no ParsePosition. For the method
* that takes a ParsePosition, the index parameter is left unchanged.
* <P>
* <em>User subclasses are not supported.</em> While clients may write
* subclasses, such code will not necessarily work and will not be
* guaranteed to work stably from release to release.
*/
class U_I18N_API Format : public UObject {
public:
/** Destructor
* @stable ICU 2.4
*/
virtual ~Format();
/**
* Return true if the given Format objects are semantically equal.
* Objects of different subclasses are considered unequal.
* @param other the object to be compared with.
* @return Return true if the given Format objects are semantically equal.
* Objects of different subclasses are considered unequal.
* @stable ICU 2.0
*/
virtual bool operator==(const Format& other) const = 0;
/**
* Return true if the given Format objects are not semantically
* equal.
* @param other the object to be compared with.
* @return Return true if the given Format objects are not semantically.
* @stable ICU 2.0
*/
bool operator!=(const Format& other) const { return !operator==(other); }
/**
* Clone this object polymorphically. The caller is responsible
* for deleting the result when done.
* @return A copy of the object
* @stable ICU 2.0
*/
virtual Format* clone() const = 0;
/**
* Formats an object to produce a string.
*
* @param obj The object to format.
* @param appendTo Output parameter to receive result.
* Result is appended to existing contents.
* @param status Output parameter filled in with success or failure status.
* @return Reference to 'appendTo' parameter.
* @stable ICU 2.0
*/
UnicodeString& format(const Formattable& obj,
UnicodeString& appendTo,
UErrorCode& status) const;
/**
* Format an object to produce a string. This is a pure virtual method which
* subclasses must implement. This method allows polymorphic formatting
* of Formattable objects. If a subclass of Format receives a Formattable
* object type it doesn't handle (e.g., if a numeric Formattable is passed
* to a DateFormat object) then it returns a failing UErrorCode.
*
* @param obj The object to format.
* @param appendTo Output parameter to receive result.
* Result is appended to existing contents.
* @param pos On input: an alignment field, if desired.
* On output: the offsets of the alignment field.
* @param status Output param filled with success/failure status.
* @return Reference to 'appendTo' parameter.
* @stable ICU 2.0
*/
virtual UnicodeString& format(const Formattable& obj,
UnicodeString& appendTo,
FieldPosition& pos,
UErrorCode& status) const = 0;
/**
* Format an object to produce a string. Subclasses should override this
* method. This method allows polymorphic formatting of Formattable objects.
* If a subclass of Format receives a Formattable object type it doesn't
* handle (e.g., if a numeric Formattable is passed to a DateFormat object)
* then it returns a failing UErrorCode.
*
* @param obj The object to format.
* @param appendTo Output parameter to receive result.
* Result is appended to existing contents.
* @param posIter On return, can be used to iterate over positions
* of fields generated by this format call.
* @param status Output param filled with success/failure status.
* @return Reference to 'appendTo' parameter.
* @stable ICU 4.4
*/
virtual UnicodeString& format(const Formattable& obj,
UnicodeString& appendTo,
FieldPositionIterator* posIter,
UErrorCode& status) const;
/**
* Parse a string to produce an object. This is a pure virtual
* method which subclasses must implement. This method allows
* polymorphic parsing of strings into Formattable objects.
* <P>
* Before calling, set parse_pos.index to the offset you want to
* start parsing at in the source. After calling, parse_pos.index
* is the end of the text you parsed. If error occurs, index is
* unchanged.
* <P>
* When parsing, leading whitespace is discarded (with successful
* parse), while trailing whitespace is left as is.
* <P>
* Example:
* <P>
* Parsing "_12_xy" (where _ represents a space) for a number,
* with index == 0 will result in the number 12, with
* parse_pos.index updated to 3 (just before the second space).
* Parsing a second time will result in a failing UErrorCode since
* "xy" is not a number, and leave index at 3.
* <P>
* Subclasses will typically supply specific parse methods that
* return different types of values. Since methods can't overload
* on return types, these will typically be named "parse", while
* this polymorphic method will always be called parseObject. Any
* parse method that does not take a parse_pos should set status
* to an error value when no text in the required format is at the
* start position.
*
* @param source The string to be parsed into an object.
* @param result Formattable to be set to the parse result.
* If parse fails, return contents are undefined.
* @param parse_pos The position to start parsing at. Upon return
* this param is set to the position after the
* last character successfully parsed. If the
* source is not parsed successfully, this param
* will remain unchanged.
* @stable ICU 2.0
*/
virtual void parseObject(const UnicodeString& source,
Formattable& result,
ParsePosition& parse_pos) const = 0;
/**
* Parses a string to produce an object. This is a convenience method
* which calls the pure virtual parseObject() method, and returns a
* failure UErrorCode if the ParsePosition indicates failure.
*
* @param source The string to be parsed into an object.
* @param result Formattable to be set to the parse result.
* If parse fails, return contents are undefined.
* @param status Output param to be filled with success/failure
* result code.
* @stable ICU 2.0
*/
void parseObject(const UnicodeString& source,
Formattable& result,
UErrorCode& status) const;
/** Get the locale for this format object. You can choose between valid and actual locale.
* @param type type of the locale we're looking for (valid or actual)
* @param status error code for the operation
* @return the locale
* @stable ICU 2.8
*/
Locale getLocale(ULocDataLocaleType type, UErrorCode& status) const;
#ifndef U_HIDE_INTERNAL_API
/** Get the locale for this format object. You can choose between valid and actual locale.
* @param type type of the locale we're looking for (valid or actual)
* @param status error code for the operation
* @return the locale
* @internal
*/
const char* getLocaleID(ULocDataLocaleType type, UErrorCode &status) const;
#endif /* U_HIDE_INTERNAL_API */
protected:
/** @stable ICU 2.8 */
void setLocaleIDs(const char* valid, const char* actual);
protected:
/**
* Default constructor for subclass use only. Does nothing.
* @stable ICU 2.0
*/
Format();
/**
* @stable ICU 2.0
*/
Format(const Format&); // Does nothing; for subclasses only
/**
* @stable ICU 2.0
*/
Format& operator=(const Format&); // Does nothing; for subclasses
/**
* Simple function for initializing a UParseError from a UnicodeString.
*
* @param pattern The pattern to copy into the parseError
* @param pos The position in pattern where the error occurred
* @param parseError The UParseError object to fill in
* @stable ICU 2.4
*/
static void syntaxError(const UnicodeString& pattern,
int32_t pos,
UParseError& parseError);
private:
CharString* actualLocale = nullptr;
CharString* validLocale = nullptr;
};
U_NAMESPACE_END
#endif /* #if !UCONFIG_NO_FORMATTING */
#endif /* U_SHOW_CPLUSPLUS_API */
#endif // _FORMAT
//eof

View File

@ -0,0 +1,215 @@
// © 2022 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
#ifndef __FORMATTEDNUMBER_H__
#define __FORMATTEDNUMBER_H__
#include "unicode/utypes.h"
#if U_SHOW_CPLUSPLUS_API
#if !UCONFIG_NO_FORMATTING
#include "unicode/uobject.h"
#include "unicode/formattedvalue.h"
#include "unicode/measunit.h"
#include "unicode/udisplayoptions.h"
/**
* \file
* \brief C API: Formatted number result from various number formatting functions.
*
* See also {@link icu::FormattedValue} for additional things you can do with a FormattedNumber.
*/
U_NAMESPACE_BEGIN
class FieldPositionIteratorHandler;
class SimpleDateFormat;
namespace number { // icu::number
namespace impl {
class DecimalQuantity;
class UFormattedNumberData;
struct UFormattedNumberImpl;
} // icu::number::impl
/**
* The result of a number formatting operation. This class allows the result to be exported in several data types,
* including a UnicodeString and a FieldPositionIterator.
*
* Instances of this class are immutable and thread-safe.
*
* @stable ICU 60
*/
class U_I18N_API FormattedNumber : public UMemory, public FormattedValue {
public:
/**
* Default constructor; makes an empty FormattedNumber.
* @stable ICU 64
*/
FormattedNumber()
: fData(nullptr), fErrorCode(U_INVALID_STATE_ERROR) {}
/**
* Move constructor: Leaves the source FormattedNumber in an undefined state.
* @stable ICU 62
*/
FormattedNumber(FormattedNumber&& src) noexcept;
/**
* Destruct an instance of FormattedNumber.
* @stable ICU 60
*/
virtual ~FormattedNumber() override;
/** Copying not supported; use move constructor instead. */
FormattedNumber(const FormattedNumber&) = delete;
/** Copying not supported; use move assignment instead. */
FormattedNumber& operator=(const FormattedNumber&) = delete;
/**
* Move assignment: Leaves the source FormattedNumber in an undefined state.
* @stable ICU 62
*/
FormattedNumber& operator=(FormattedNumber&& src) noexcept;
// Copybrief: this method is older than the parent method
/**
* @copybrief FormattedValue::toString()
*
* For more information, see FormattedValue::toString()
*
* @stable ICU 62
*/
UnicodeString toString(UErrorCode& status) const override;
// Copydoc: this method is new in ICU 64
/** @copydoc FormattedValue::toTempString() */
UnicodeString toTempString(UErrorCode& status) const override;
// Copybrief: this method is older than the parent method
/**
* @copybrief FormattedValue::appendTo()
*
* For more information, see FormattedValue::appendTo()
*
* @stable ICU 62
*/
Appendable &appendTo(Appendable& appendable, UErrorCode& status) const override;
// Copydoc: this method is new in ICU 64
/** @copydoc FormattedValue::nextPosition() */
UBool nextPosition(ConstrainedFieldPosition& cfpos, UErrorCode& status) const override;
/**
* Export the formatted number as a "numeric string" conforming to the
* syntax defined in the Decimal Arithmetic Specification, available at
* http://speleotrove.com/decimal
*
* This endpoint is useful for obtaining the exact number being printed
* after scaling and rounding have been applied by the number formatter.
*
* Example call site:
*
* auto decimalNumber = fn.toDecimalNumber<std::string>(status);
*
* @tparam StringClass A string class compatible with StringByteSink;
* for example, std::string.
* @param status Set if an error occurs.
* @return A StringClass containing the numeric string.
* @stable ICU 65
*/
template<typename StringClass>
inline StringClass toDecimalNumber(UErrorCode& status) const;
/**
* Gets the resolved output unit.
*
* The output unit is dependent upon the localized preferences for the usage
* specified via NumberFormatterSettings::usage(), and may be a unit with
* UMEASURE_UNIT_MIXED unit complexity (MeasureUnit::getComplexity()), such
* as "foot-and-inch" or "hour-and-minute-and-second".
*
* @return `MeasureUnit`.
* @stable ICU 68
*/
MeasureUnit getOutputUnit(UErrorCode& status) const;
/**
* Gets the noun class of the formatted output. Returns `UNDEFINED` when the noun class
* is not supported yet.
*
* @return UDisplayOptionsNounClass
* @stable ICU 72
*/
UDisplayOptionsNounClass getNounClass(UErrorCode &status) const;
#ifndef U_HIDE_INTERNAL_API
/**
* Gets the raw DecimalQuantity for plural rule selection.
* @internal
*/
void getDecimalQuantity(impl::DecimalQuantity& output, UErrorCode& status) const;
/**
* Populates the mutable builder type FieldPositionIteratorHandler.
* @internal
*/
void getAllFieldPositionsImpl(FieldPositionIteratorHandler& fpih, UErrorCode& status) const;
#endif /* U_HIDE_INTERNAL_API */
private:
// Can't use LocalPointer because UFormattedNumberData is forward-declared
impl::UFormattedNumberData *fData;
// Error code for the terminal methods
UErrorCode fErrorCode;
/**
* Internal constructor from data type. Adopts the data pointer.
* @internal (private)
*/
explicit FormattedNumber(impl::UFormattedNumberData *results)
: fData(results), fErrorCode(U_ZERO_ERROR) {}
explicit FormattedNumber(UErrorCode errorCode)
: fData(nullptr), fErrorCode(errorCode) {}
void toDecimalNumber(ByteSink& sink, UErrorCode& status) const;
// To give LocalizedNumberFormatter format methods access to this class's constructor:
friend class LocalizedNumberFormatter;
friend class SimpleNumberFormatter;
// To give C API access to internals
friend struct impl::UFormattedNumberImpl;
// To give access to the data pointer for non-heap allocation
friend class icu::SimpleDateFormat;
};
template<typename StringClass>
StringClass FormattedNumber::toDecimalNumber(UErrorCode& status) const {
StringClass result;
StringByteSink<StringClass> sink(&result);
toDecimalNumber(sink, status);
return result;
}
} // namespace number
U_NAMESPACE_END
#endif /* #if !UCONFIG_NO_FORMATTING */
#endif /* U_SHOW_CPLUSPLUS_API */
#endif // __FORMATTEDNUMBER_H__

View File

@ -0,0 +1,318 @@
// © 2018 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
#ifndef __FORMATTEDVALUE_H__
#define __FORMATTEDVALUE_H__
#include "unicode/utypes.h"
#if U_SHOW_CPLUSPLUS_API
#if !UCONFIG_NO_FORMATTING
#include "unicode/appendable.h"
#include "unicode/fpositer.h"
#include "unicode/unistr.h"
#include "unicode/uformattedvalue.h"
U_NAMESPACE_BEGIN
/**
* \file
* \brief C++ API: Abstract operations for localized strings.
*
* This file contains declarations for classes that deal with formatted strings. A number
* of APIs throughout ICU use these classes for expressing their localized output.
*/
/**
* Represents a span of a string containing a given field.
*
* This class differs from FieldPosition in the following ways:
*
* 1. It has information on the field category.
* 2. It allows you to set constraints to use when iterating over field positions.
* 3. It is used for the newer FormattedValue APIs.
*
* This class is not intended for public subclassing.
*
* @stable ICU 64
*/
class U_I18N_API ConstrainedFieldPosition : public UMemory {
public:
/**
* Initializes a ConstrainedFieldPosition.
*
* By default, the ConstrainedFieldPosition has no iteration constraints.
*
* @stable ICU 64
*/
ConstrainedFieldPosition();
/** @stable ICU 64 */
~ConstrainedFieldPosition();
/**
* Resets this ConstrainedFieldPosition to its initial state, as if it were newly created:
*
* - Removes any constraints that may have been set on the instance.
* - Resets the iteration position.
*
* @stable ICU 64
*/
void reset();
/**
* Sets a constraint on the field category.
*
* When this instance of ConstrainedFieldPosition is passed to FormattedValue#nextPosition,
* positions are skipped unless they have the given category.
*
* Any previously set constraints are cleared.
*
* For example, to loop over only the number-related fields:
*
* ConstrainedFieldPosition cfpos;
* cfpos.constrainCategory(UFIELDCATEGORY_NUMBER_FORMAT);
* while (fmtval.nextPosition(cfpos, status)) {
* // handle the number-related field position
* }
*
* Changing the constraint while in the middle of iterating over a FormattedValue
* does not generally have well-defined behavior.
*
* @param category The field category to fix when iterating.
* @stable ICU 64
*/
void constrainCategory(int32_t category);
/**
* Sets a constraint on the category and field.
*
* When this instance of ConstrainedFieldPosition is passed to FormattedValue#nextPosition,
* positions are skipped unless they have the given category and field.
*
* Any previously set constraints are cleared.
*
* For example, to loop over all grouping separators:
*
* ConstrainedFieldPosition cfpos;
* cfpos.constrainField(UFIELDCATEGORY_NUMBER_FORMAT, UNUM_GROUPING_SEPARATOR_FIELD);
* while (fmtval.nextPosition(cfpos, status)) {
* // handle the grouping separator position
* }
*
* Changing the constraint while in the middle of iterating over a FormattedValue
* does not generally have well-defined behavior.
*
* @param category The field category to fix when iterating.
* @param field The field to fix when iterating.
* @stable ICU 64
*/
void constrainField(int32_t category, int32_t field);
/**
* Gets the field category for the current position.
*
* The return value is well-defined only after
* FormattedValue#nextPosition returns true.
*
* @return The field category saved in the instance.
* @stable ICU 64
*/
inline int32_t getCategory() const {
return fCategory;
}
/**
* Gets the field for the current position.
*
* The return value is well-defined only after
* FormattedValue#nextPosition returns true.
*
* @return The field saved in the instance.
* @stable ICU 64
*/
inline int32_t getField() const {
return fField;
}
/**
* Gets the INCLUSIVE start index for the current position.
*
* The return value is well-defined only after FormattedValue#nextPosition returns true.
*
* @return The start index saved in the instance.
* @stable ICU 64
*/
inline int32_t getStart() const {
return fStart;
}
/**
* Gets the EXCLUSIVE end index stored for the current position.
*
* The return value is well-defined only after FormattedValue#nextPosition returns true.
*
* @return The end index saved in the instance.
* @stable ICU 64
*/
inline int32_t getLimit() const {
return fLimit;
}
////////////////////////////////////////////////////////////////////
//// The following methods are for FormattedValue implementers; ////
//// most users can ignore them. ////
////////////////////////////////////////////////////////////////////
/**
* Gets an int64 that FormattedValue implementations may use for storage.
*
* The initial value is zero.
*
* Users of FormattedValue should not need to call this method.
*
* @return The current iteration context from {@link #setInt64IterationContext}.
* @stable ICU 64
*/
inline int64_t getInt64IterationContext() const {
return fContext;
}
/**
* Sets an int64 that FormattedValue implementations may use for storage.
*
* Intended to be used by FormattedValue implementations.
*
* @param context The new iteration context.
* @stable ICU 64
*/
void setInt64IterationContext(int64_t context);
/**
* Determines whether a given field should be included given the
* constraints.
*
* Intended to be used by FormattedValue implementations.
*
* @param category The category to test.
* @param field The field to test.
* @stable ICU 64
*/
UBool matchesField(int32_t category, int32_t field) const;
/**
* Sets new values for the primary public getters.
*
* Intended to be used by FormattedValue implementations.
*
* It is up to the implementation to ensure that the user-requested
* constraints are satisfied. This method does not check!
*
* @param category The new field category.
* @param field The new field.
* @param start The new inclusive start index.
* @param limit The new exclusive end index.
* @stable ICU 64
*/
void setState(
int32_t category,
int32_t field,
int32_t start,
int32_t limit);
private:
int64_t fContext = 0LL;
int32_t fField = 0;
int32_t fStart = 0;
int32_t fLimit = 0;
int32_t fCategory = UFIELD_CATEGORY_UNDEFINED;
int8_t fConstraint = 0;
};
/**
* An abstract formatted value: a string with associated field attributes.
* Many formatters format to classes implementing FormattedValue.
*
* @stable ICU 64
*/
class U_I18N_API FormattedValue /* not : public UObject because this is an interface/mixin class */ {
public:
/** @stable ICU 64 */
virtual ~FormattedValue();
/**
* Returns the formatted string as a self-contained UnicodeString.
*
* If you need the string within the current scope only, consider #toTempString.
*
* @param status Set if an error occurs.
* @return a UnicodeString containing the formatted string.
*
* @stable ICU 64
*/
virtual UnicodeString toString(UErrorCode& status) const = 0;
/**
* Returns the formatted string as a read-only alias to memory owned by the FormattedValue.
*
* The return value is valid only as long as this FormattedValue is present and unchanged in
* memory. If you need the string outside the current scope, consider #toString.
*
* The buffer returned by calling UnicodeString#getBuffer() on the return value is
* guaranteed to be NUL-terminated.
*
* @param status Set if an error occurs.
* @return a temporary UnicodeString containing the formatted string.
*
* @stable ICU 64
*/
virtual UnicodeString toTempString(UErrorCode& status) const = 0;
/**
* Appends the formatted string to an Appendable.
*
* @param appendable
* The Appendable to which to append the string output.
* @param status Set if an error occurs.
* @return The same Appendable, for chaining.
*
* @stable ICU 64
* @see Appendable
*/
virtual Appendable& appendTo(Appendable& appendable, UErrorCode& status) const = 0;
/**
* Iterates over field positions in the FormattedValue. This lets you determine the position
* of specific types of substrings, like a month or a decimal separator.
*
* To loop over all field positions:
*
* ConstrainedFieldPosition cfpos;
* while (fmtval.nextPosition(cfpos, status)) {
* // handle the field position; get information from cfpos
* }
*
* @param cfpos
* The object used for iteration state. This can provide constraints to iterate over
* only one specific category or field;
* see ConstrainedFieldPosition#constrainCategory
* and ConstrainedFieldPosition#constrainField.
* @param status Set if an error occurs.
* @return true if a new occurrence of the field was found;
* false otherwise or if an error was set.
*
* @stable ICU 64
*/
virtual UBool nextPosition(ConstrainedFieldPosition& cfpos, UErrorCode& status) const = 0;
};
U_NAMESPACE_END
#endif /* #if !UCONFIG_NO_FORMATTING */
#endif /* U_SHOW_CPLUSPLUS_API */
#endif // __FORMATTEDVALUE_H__

View File

@ -0,0 +1,124 @@
// © 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
/*
********************************************************************************
* Copyright (C) 2010-2012, International Business Machines
* Corporation and others. All Rights Reserved.
********************************************************************************
*
* File attiter.h
*
* Modification History:
*
* Date Name Description
* 12/15/2009 dougfelt Created
********************************************************************************
*/
#ifndef FPOSITER_H
#define FPOSITER_H
#include "unicode/utypes.h"
#if U_SHOW_CPLUSPLUS_API
#include "unicode/uobject.h"
/**
* \file
* \brief C++ API: FieldPosition Iterator.
*/
#if UCONFIG_NO_FORMATTING
U_NAMESPACE_BEGIN
/*
* Allow the declaration of APIs with pointers to FieldPositionIterator
* even when formatting is removed from the build.
*/
class FieldPositionIterator;
U_NAMESPACE_END
#else
#include "unicode/fieldpos.h"
#include "unicode/umisc.h"
U_NAMESPACE_BEGIN
class UVector32;
/**
* FieldPositionIterator returns the field ids and their start/limit positions generated
* by a call to Format::format. See Format, NumberFormat, DecimalFormat.
* @stable ICU 4.4
*/
class U_I18N_API FieldPositionIterator : public UObject {
public:
/**
* Destructor.
* @stable ICU 4.4
*/
~FieldPositionIterator();
/**
* Constructs a new, empty iterator.
* @stable ICU 4.4
*/
FieldPositionIterator();
/**
* Copy constructor. If the copy failed for some reason, the new iterator will
* be empty.
* @stable ICU 4.4
*/
FieldPositionIterator(const FieldPositionIterator&);
/**
* Return true if another object is semantically equal to this
* one.
* <p>
* Return true if this FieldPositionIterator is at the same position in an
* equal array of run values.
* @stable ICU 4.4
*/
bool operator==(const FieldPositionIterator&) const;
/**
* Returns the complement of the result of operator==
* @param rhs The FieldPositionIterator to be compared for inequality
* @return the complement of the result of operator==
* @stable ICU 4.4
*/
bool operator!=(const FieldPositionIterator& rhs) const { return !operator==(rhs); }
/**
* If the current position is valid, updates the FieldPosition values, advances the iterator,
* and returns true, otherwise returns false.
* @stable ICU 4.4
*/
UBool next(FieldPosition& fp);
private:
/**
* Sets the data used by the iterator, and resets the position.
* Returns U_ILLEGAL_ARGUMENT_ERROR in status if the data is not valid
* (length is not a multiple of 3, or start >= limit for any run).
*/
void setData(UVector32 *adopt, UErrorCode& status);
friend class FieldPositionIteratorHandler;
UVector32 *data;
int32_t pos;
};
U_NAMESPACE_END
#endif /* #if !UCONFIG_NO_FORMATTING */
#endif /* U_SHOW_CPLUSPLUS_API */
#endif // FPOSITER_H

View File

@ -0,0 +1,122 @@
// © 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
/*
*******************************************************************************
* Copyright (C) 2008-2013, International Business Machines Corporation and
* others. All Rights Reserved.
*******************************************************************************
*
*
* File GENDER.H
*
* Modification History:*
* Date Name Description
*
********************************************************************************
*/
#ifndef _GENDER
#define _GENDER
/**
* \file
* \brief C++ API: GenderInfo computes the gender of a list.
*/
#include "unicode/utypes.h"
#if U_SHOW_CPLUSPLUS_API
#if !UCONFIG_NO_FORMATTING
#include "unicode/locid.h"
#include "unicode/ugender.h"
#include "unicode/uobject.h"
class GenderInfoTest;
U_NAMESPACE_BEGIN
/** \internal Forward Declaration */
void U_CALLCONV GenderInfo_initCache(UErrorCode &status);
/**
* GenderInfo computes the gender of a list as a whole given the gender of
* each element.
* @stable ICU 50
*/
class U_I18N_API GenderInfo : public UObject {
public:
/**
* Provides access to the predefined GenderInfo object for a given
* locale.
*
* @param locale The locale for which a <code>GenderInfo</code> object is
* returned.
* @param status Output param set to success/failure code on exit, which
* must not indicate a failure before the function call.
* @return The predefined <code>GenderInfo</code> object pointer for
* this locale. The returned object is immutable, so it is
* declared as const. Caller does not own the returned
* pointer, so it must not attempt to free it.
* @stable ICU 50
*/
static const GenderInfo* U_EXPORT2 getInstance(const Locale& locale, UErrorCode& status);
/**
* Determines the gender of a list as a whole given the gender of each
* of the elements.
*
* @param genders the gender of each element in the list.
* @param length the length of gender array.
* @param status Output param set to success/failure code on exit, which
* must not indicate a failure before the function call.
* @return the gender of the whole list.
* @stable ICU 50
*/
UGender getListGender(const UGender* genders, int32_t length, UErrorCode& status) const;
/**
* Destructor.
*
* @stable ICU 50
*/
virtual ~GenderInfo();
private:
int32_t _style;
/**
* Copy constructor. One object per locale invariant. Clients
* must never copy GenderInfo objects.
*/
GenderInfo(const GenderInfo& other) = delete;
/**
* Assignment operator. Not applicable to immutable objects.
*/
GenderInfo& operator=(const GenderInfo&) = delete;
GenderInfo();
static const GenderInfo* getNeutralInstance();
static const GenderInfo* getMixedNeutralInstance();
static const GenderInfo* getMaleTaintsInstance();
static const GenderInfo* loadInstance(const Locale& locale, UErrorCode& status);
friend class ::GenderInfoTest;
friend void U_CALLCONV GenderInfo_initCache(UErrorCode &status);
};
U_NAMESPACE_END
#endif /* #if !UCONFIG_NO_FORMATTING */
#endif /* U_SHOW_CPLUSPLUS_API */
#endif // _GENDER
//eof

View File

@ -0,0 +1,737 @@
// © 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
/*
* Copyright (C) 1997-2013, International Business Machines Corporation and others.
* All Rights Reserved.
********************************************************************************
*
* File GREGOCAL.H
*
* Modification History:
*
* Date Name Description
* 04/22/97 aliu Overhauled header.
* 07/28/98 stephen Sync with JDK 1.2
* 09/04/98 stephen Re-sync with JDK 8/31 putback
* 09/14/98 stephen Changed type of kOneDay, kOneWeek to double.
* Fixed bug in roll()
* 10/15/99 aliu Fixed j31, incorrect WEEK_OF_YEAR computation.
* Added documentation of WEEK_OF_YEAR computation.
* 10/15/99 aliu Fixed j32, cannot set date to Feb 29 2000 AD.
* {JDK bug 4210209 4209272}
* 11/07/2003 srl Update, clean up documentation.
********************************************************************************
*/
#ifndef GREGOCAL_H
#define GREGOCAL_H
#include "unicode/utypes.h"
#if U_SHOW_CPLUSPLUS_API
#if !UCONFIG_NO_FORMATTING
#include "unicode/calendar.h"
/**
* \file
* \brief C++ API: Concrete class which provides the standard calendar.
*/
U_NAMESPACE_BEGIN
/**
* Concrete class which provides the standard calendar used by most of the world.
* <P>
* The standard (Gregorian) calendar has 2 eras, BC and AD.
* <P>
* This implementation handles a single discontinuity, which corresponds by default to
* the date the Gregorian calendar was originally instituted (October 15, 1582). Not all
* countries adopted the Gregorian calendar then, so this cutover date may be changed by
* the caller.
* <P>
* Prior to the institution of the Gregorian Calendar, New Year's Day was March 25. To
* avoid confusion, this Calendar always uses January 1. A manual adjustment may be made
* if desired for dates that are prior to the Gregorian changeover and which fall
* between January 1 and March 24.
*
* <p>Values calculated for the <code>WEEK_OF_YEAR</code> field range from 1 to
* 53. Week 1 for a year is the first week that contains at least
* <code>getMinimalDaysInFirstWeek()</code> days from that year. It thus
* depends on the values of <code>getMinimalDaysInFirstWeek()</code>,
* <code>getFirstDayOfWeek()</code>, and the day of the week of January 1.
* Weeks between week 1 of one year and week 1 of the following year are
* numbered sequentially from 2 to 52 or 53 (as needed).
*
* <p>For example, January 1, 1998 was a Thursday. If
* <code>getFirstDayOfWeek()</code> is <code>MONDAY</code> and
* <code>getMinimalDaysInFirstWeek()</code> is 4 (these are the values
* reflecting ISO 8601 and many national standards), then week 1 of 1998 starts
* on December 29, 1997, and ends on January 4, 1998. If, however,
* <code>getFirstDayOfWeek()</code> is <code>SUNDAY</code>, then week 1 of 1998
* starts on January 4, 1998, and ends on January 10, 1998; the first three days
* of 1998 then are part of week 53 of 1997.
*
* <p>Example for using GregorianCalendar:
* <pre>
* \code
* // get the supported ids for GMT-08:00 (Pacific Standard Time)
* UErrorCode success = U_ZERO_ERROR;
* const StringEnumeration *ids = TimeZone::createEnumeration(-8 * 60 * 60 * 1000, success);
* // if no ids were returned, something is wrong. get out.
* if (U_FAILURE(success)) {
* return;
* }
*
* // begin output
* cout << "Current Time" << endl;
*
* // create a Pacific Standard Time time zone
* SimpleTimeZone* pdt = new SimpleTimeZone(-8 * 60 * 60 * 1000, ids->unext(nullptr, success)));
*
* // set up rules for daylight savings time
* pdt->setStartRule(UCAL_MARCH, 1, UCAL_SUNDAY, 2 * 60 * 60 * 1000);
* pdt->setEndRule(UCAL_NOVEMBER, 2, UCAL_SUNDAY, 2 * 60 * 60 * 1000);
*
* // create a GregorianCalendar with the Pacific Daylight time zone
* // and the current date and time
* Calendar* calendar = new GregorianCalendar( pdt, success );
*
* // print out a bunch of interesting things
* cout << "ERA: " << calendar->get( UCAL_ERA, success ) << endl;
* cout << "YEAR: " << calendar->get( UCAL_YEAR, success ) << endl;
* cout << "MONTH: " << calendar->get( UCAL_MONTH, success ) << endl;
* cout << "WEEK_OF_YEAR: " << calendar->get( UCAL_WEEK_OF_YEAR, success ) << endl;
* cout << "WEEK_OF_MONTH: " << calendar->get( UCAL_WEEK_OF_MONTH, success ) << endl;
* cout << "DATE: " << calendar->get( UCAL_DATE, success ) << endl;
* cout << "DAY_OF_MONTH: " << calendar->get( UCAL_DAY_OF_MONTH, success ) << endl;
* cout << "DAY_OF_YEAR: " << calendar->get( UCAL_DAY_OF_YEAR, success ) << endl;
* cout << "DAY_OF_WEEK: " << calendar->get( UCAL_DAY_OF_WEEK, success ) << endl;
* cout << "DAY_OF_WEEK_IN_MONTH: " << calendar->get( UCAL_DAY_OF_WEEK_IN_MONTH, success ) << endl;
* cout << "AM_PM: " << calendar->get( UCAL_AM_PM, success ) << endl;
* cout << "HOUR: " << calendar->get( UCAL_HOUR, success ) << endl;
* cout << "HOUR_OF_DAY: " << calendar->get( UCAL_HOUR_OF_DAY, success ) << endl;
* cout << "MINUTE: " << calendar->get( UCAL_MINUTE, success ) << endl;
* cout << "SECOND: " << calendar->get( UCAL_SECOND, success ) << endl;
* cout << "MILLISECOND: " << calendar->get( UCAL_MILLISECOND, success ) << endl;
* cout << "ZONE_OFFSET: " << (calendar->get( UCAL_ZONE_OFFSET, success )/(60*60*1000)) << endl;
* cout << "DST_OFFSET: " << (calendar->get( UCAL_DST_OFFSET, success )/(60*60*1000)) << endl;
*
* cout << "Current Time, with hour reset to 3" << endl;
* calendar->clear(UCAL_HOUR_OF_DAY); // so doesn't override
* calendar->set(UCAL_HOUR, 3);
* cout << "ERA: " << calendar->get( UCAL_ERA, success ) << endl;
* cout << "YEAR: " << calendar->get( UCAL_YEAR, success ) << endl;
* cout << "MONTH: " << calendar->get( UCAL_MONTH, success ) << endl;
* cout << "WEEK_OF_YEAR: " << calendar->get( UCAL_WEEK_OF_YEAR, success ) << endl;
* cout << "WEEK_OF_MONTH: " << calendar->get( UCAL_WEEK_OF_MONTH, success ) << endl;
* cout << "DATE: " << calendar->get( UCAL_DATE, success ) << endl;
* cout << "DAY_OF_MONTH: " << calendar->get( UCAL_DAY_OF_MONTH, success ) << endl;
* cout << "DAY_OF_YEAR: " << calendar->get( UCAL_DAY_OF_YEAR, success ) << endl;
* cout << "DAY_OF_WEEK: " << calendar->get( UCAL_DAY_OF_WEEK, success ) << endl;
* cout << "DAY_OF_WEEK_IN_MONTH: " << calendar->get( UCAL_DAY_OF_WEEK_IN_MONTH, success ) << endl;
* cout << "AM_PM: " << calendar->get( UCAL_AM_PM, success ) << endl;
* cout << "HOUR: " << calendar->get( UCAL_HOUR, success ) << endl;
* cout << "HOUR_OF_DAY: " << calendar->get( UCAL_HOUR_OF_DAY, success ) << endl;
* cout << "MINUTE: " << calendar->get( UCAL_MINUTE, success ) << endl;
* cout << "SECOND: " << calendar->get( UCAL_SECOND, success ) << endl;
* cout << "MILLISECOND: " << calendar->get( UCAL_MILLISECOND, success ) << endl;
* cout << "ZONE_OFFSET: " << (calendar->get( UCAL_ZONE_OFFSET, success )/(60*60*1000)) << endl; // in hours
* cout << "DST_OFFSET: " << (calendar->get( UCAL_DST_OFFSET, success )/(60*60*1000)) << endl; // in hours
*
* if (U_FAILURE(success)) {
* cout << "An error occurred. success=" << u_errorName(success) << endl;
* }
*
* delete ids;
* delete calendar; // also deletes pdt
* \endcode
* </pre>
* @stable ICU 2.0
*/
class U_I18N_API GregorianCalendar: public Calendar {
public:
/**
* Useful constants for GregorianCalendar and TimeZone.
* @stable ICU 2.0
*/
enum EEras {
BC,
AD
};
/**
* Constructs a default GregorianCalendar using the current time in the default time
* zone with the default locale.
*
* @param success Indicates the status of GregorianCalendar object construction.
* Returns U_ZERO_ERROR if constructed successfully.
* @stable ICU 2.0
*/
GregorianCalendar(UErrorCode& success);
/**
* Constructs a GregorianCalendar based on the current time in the given time zone
* with the default locale. Clients are no longer responsible for deleting the given
* time zone object after it's adopted.
*
* @param zoneToAdopt The given timezone.
* @param success Indicates the status of GregorianCalendar object construction.
* Returns U_ZERO_ERROR if constructed successfully.
* @stable ICU 2.0
*/
GregorianCalendar(TimeZone* zoneToAdopt, UErrorCode& success);
/**
* Constructs a GregorianCalendar based on the current time in the given time zone
* with the default locale.
*
* @param zone The given timezone.
* @param success Indicates the status of GregorianCalendar object construction.
* Returns U_ZERO_ERROR if constructed successfully.
* @stable ICU 2.0
*/
GregorianCalendar(const TimeZone& zone, UErrorCode& success);
/**
* Constructs a GregorianCalendar based on the current time in the default time zone
* with the given locale.
*
* @param aLocale The given locale.
* @param success Indicates the status of GregorianCalendar object construction.
* Returns U_ZERO_ERROR if constructed successfully.
* @stable ICU 2.0
*/
GregorianCalendar(const Locale& aLocale, UErrorCode& success);
/**
* Constructs a GregorianCalendar based on the current time in the given time zone
* with the given locale. Clients are no longer responsible for deleting the given
* time zone object after it's adopted.
*
* @param zoneToAdopt The given timezone.
* @param aLocale The given locale.
* @param success Indicates the status of GregorianCalendar object construction.
* Returns U_ZERO_ERROR if constructed successfully.
* @stable ICU 2.0
*/
GregorianCalendar(TimeZone* zoneToAdopt, const Locale& aLocale, UErrorCode& success);
/**
* Constructs a GregorianCalendar based on the current time in the given time zone
* with the given locale.
*
* @param zone The given timezone.
* @param aLocale The given locale.
* @param success Indicates the status of GregorianCalendar object construction.
* Returns U_ZERO_ERROR if constructed successfully.
* @stable ICU 2.0
*/
GregorianCalendar(const TimeZone& zone, const Locale& aLocale, UErrorCode& success);
/**
* Constructs a GregorianCalendar with the given AD date set in the default time
* zone with the default locale.
*
* @param year The value used to set the YEAR time field in the calendar.
* @param month The value used to set the MONTH time field in the calendar. Month
* value is 0-based. e.g., 0 for January.
* @param date The value used to set the DATE time field in the calendar.
* @param success Indicates the status of GregorianCalendar object construction.
* Returns U_ZERO_ERROR if constructed successfully.
* @stable ICU 2.0
*/
GregorianCalendar(int32_t year, int32_t month, int32_t date, UErrorCode& success);
/**
* Constructs a GregorianCalendar with the given AD date and time set for the
* default time zone with the default locale.
*
* @param year The value used to set the YEAR time field in the calendar.
* @param month The value used to set the MONTH time field in the calendar. Month
* value is 0-based. e.g., 0 for January.
* @param date The value used to set the DATE time field in the calendar.
* @param hour The value used to set the HOUR_OF_DAY time field in the calendar.
* @param minute The value used to set the MINUTE time field in the calendar.
* @param success Indicates the status of GregorianCalendar object construction.
* Returns U_ZERO_ERROR if constructed successfully.
* @stable ICU 2.0
*/
GregorianCalendar(int32_t year, int32_t month, int32_t date, int32_t hour, int32_t minute, UErrorCode& success);
/**
* Constructs a GregorianCalendar with the given AD date and time set for the
* default time zone with the default locale.
*
* @param year The value used to set the YEAR time field in the calendar.
* @param month The value used to set the MONTH time field in the calendar. Month
* value is 0-based. e.g., 0 for January.
* @param date The value used to set the DATE time field in the calendar.
* @param hour The value used to set the HOUR_OF_DAY time field in the calendar.
* @param minute The value used to set the MINUTE time field in the calendar.
* @param second The value used to set the SECOND time field in the calendar.
* @param success Indicates the status of GregorianCalendar object construction.
* Returns U_ZERO_ERROR if constructed successfully.
* @stable ICU 2.0
*/
GregorianCalendar(int32_t year, int32_t month, int32_t date, int32_t hour, int32_t minute, int32_t second, UErrorCode& success);
/**
* Destructor
* @stable ICU 2.0
*/
virtual ~GregorianCalendar();
/**
* Copy constructor
* @param source the object to be copied.
* @stable ICU 2.0
*/
GregorianCalendar(const GregorianCalendar& source);
/**
* Default assignment operator
* @param right the object to be copied.
* @stable ICU 2.0
*/
GregorianCalendar& operator=(const GregorianCalendar& right);
/**
* Create and return a polymorphic copy of this calendar.
* @return return a polymorphic copy of this calendar.
* @stable ICU 2.0
*/
virtual GregorianCalendar* clone() const override;
/**
* Sets the GregorianCalendar change date. This is the point when the switch from
* Julian dates to Gregorian dates occurred. Default is 00:00:00 local time, October
* 15, 1582. Previous to this time and date will be Julian dates.
*
* @param date The given Gregorian cutover date.
* @param success Output param set to success/failure code on exit.
* @stable ICU 2.0
*/
void setGregorianChange(UDate date, UErrorCode& success);
/**
* Gets the Gregorian Calendar change date. This is the point when the switch from
* Julian dates to Gregorian dates occurred. Default is 00:00:00 local time, October
* 15, 1582. Previous to this time and date will be Julian dates.
*
* @return The Gregorian cutover time for this calendar.
* @stable ICU 2.0
*/
UDate getGregorianChange() const;
/**
* Return true if the given year is a leap year. Determination of whether a year is
* a leap year is actually very complicated. We do something crude and mostly
* correct here, but for a real determination you need a lot of contextual
* information. For example, in Sweden, the change from Julian to Gregorian happened
* in a complex way resulting in missed leap years and double leap years between
* 1700 and 1753. Another example is that after the start of the Julian calendar in
* 45 B.C., the leap years did not regularize until 8 A.D. This method ignores these
* quirks, and pays attention only to the Julian onset date and the Gregorian
* cutover (which can be changed).
*
* @param year The given year.
* @return True if the given year is a leap year; false otherwise.
* @stable ICU 2.0
*/
UBool isLeapYear(int32_t year) const;
/**
* Returns true if the given Calendar object is equivalent to this
* one. Calendar override.
*
* @param other the Calendar to be compared with this Calendar
* @stable ICU 2.4
*/
virtual UBool isEquivalentTo(const Calendar& other) const override;
#ifndef U_FORCE_HIDE_DEPRECATED_API
/**
* (Overrides Calendar) Rolls up or down by the given amount in the specified field.
* For more information, see the documentation for Calendar::roll().
*
* @param field The time field.
* @param amount Indicates amount to roll.
* @param status Output param set to success/failure code on exit. If any value
* previously set in the time field is invalid, this will be set to
* an error status.
* @deprecated ICU 2.6. Use roll(UCalendarDateFields field, int32_t amount, UErrorCode& status) instead.
*/
virtual void roll(EDateFields field, int32_t amount, UErrorCode& status) override;
#endif // U_FORCE_HIDE_DEPRECATED_API
/**
* (Overrides Calendar) Rolls up or down by the given amount in the specified field.
* For more information, see the documentation for Calendar::roll().
*
* @param field The time field.
* @param amount Indicates amount to roll.
* @param status Output param set to success/failure code on exit. If any value
* previously set in the time field is invalid, this will be set to
* an error status.
* @stable ICU 2.6.
*/
virtual void roll(UCalendarDateFields field, int32_t amount, UErrorCode& status) override;
#ifndef U_HIDE_DEPRECATED_API
/**
* Return the minimum value that this field could have, given the current date.
* For the Gregorian calendar, this is the same as getMinimum() and getGreatestMinimum().
* @param field the time field.
* @return the minimum value that this field could have, given the current date.
* @deprecated ICU 2.6. Use getActualMinimum(UCalendarDateFields field) instead.
*/
int32_t getActualMinimum(EDateFields field) const;
/**
* Return the minimum value that this field could have, given the current date.
* For the Gregorian calendar, this is the same as getMinimum() and getGreatestMinimum().
* @param field the time field.
* @param status
* @return the minimum value that this field could have, given the current date.
* @deprecated ICU 2.6. Use getActualMinimum(UCalendarDateFields field) instead. (Added to ICU 3.0 for signature consistency)
*/
int32_t getActualMinimum(EDateFields field, UErrorCode& status) const;
#endif /* U_HIDE_DEPRECATED_API */
/**
* Return the minimum value that this field could have, given the current date.
* For the Gregorian calendar, this is the same as getMinimum() and getGreatestMinimum().
* @param field the time field.
* @param status error result.
* @return the minimum value that this field could have, given the current date.
* @stable ICU 3.0
*/
int32_t getActualMinimum(UCalendarDateFields field, UErrorCode &status) const override;
/**
* Return the maximum value that this field could have, given the current date.
* For example, with the date "Feb 3, 1997" and the DAY_OF_MONTH field, the actual
* maximum would be 28; for "Feb 3, 1996" it s 29. Similarly for a Hebrew calendar,
* for some years the actual maximum for MONTH is 12, and for others 13.
* @param field the time field.
* @param status returns any errors that may result from this function call.
* @return the maximum value that this field could have, given the current date.
* @stable ICU 2.6
*/
virtual int32_t getActualMaximum(UCalendarDateFields field, UErrorCode& status) const override;
public:
/**
* Override Calendar Returns a unique class ID POLYMORPHICALLY. Pure virtual
* override. This method is to implement a simple version of RTTI, since not all C++
* compilers support genuine RTTI. Polymorphic operator==() and clone() methods call
* this method.
*
* @return The class ID for this object. All objects of a given class have the
* same class ID. Objects of other classes have different class IDs.
* @stable ICU 2.0
*/
virtual UClassID getDynamicClassID() const override;
/**
* Return the class ID for this class. This is useful only for comparing to a return
* value from getDynamicClassID(). For example:
*
* Base* polymorphic_pointer = createPolymorphicObject();
* if (polymorphic_pointer->getDynamicClassID() ==
* Derived::getStaticClassID()) ...
*
* @return The class ID for all objects of this class.
* @stable ICU 2.0
*/
static UClassID U_EXPORT2 getStaticClassID();
/**
* Returns the calendar type name string for this Calendar object.
* The returned string is the legacy ICU calendar attribute value,
* for example, "gregorian" or "japanese".
*
* For more details see the Calendar::getType() documentation.
*
* @return legacy calendar type name string
* @stable ICU 49
*/
virtual const char * getType() const override;
private:
GregorianCalendar() = delete; // default constructor not implemented
protected:
/**
* Return the ERA. We need a special method for this because the
* default ERA is AD, but a zero (unset) ERA is BC.
* @return the ERA.
* @internal
*/
virtual int32_t internalGetEra() const;
/**
* Return the Julian day number of day before the first day of the
* given month in the given extended year. Subclasses should override
* this method to implement their calendar system.
* @param eyear the extended year
* @param month the zero-based month, or 0 if useMonth is false
* @param useMonth if false, compute the day before the first day of
* the given year, otherwise, compute the day before the first day of
* the given month
* @param status Fill-in parameter which receives the status of this operation.
* @return the Julian day number of the day before the first
* day of the given month and year
* @internal
*/
virtual int64_t handleComputeMonthStart(int32_t eyear, int32_t month,
UBool useMonth, UErrorCode& status) const override;
/**
* Subclasses may override this. This method calls
* handleGetMonthLength() to obtain the calendar-specific month
* length.
* @param bestField which field to use to calculate the date
* @param status Fill-in parameter which receives the status of this operation.
* @return julian day specified by calendar fields.
* @internal
*/
virtual int32_t handleComputeJulianDay(UCalendarDateFields bestField, UErrorCode& status) override;
/**
* Return the number of days in the given month of the given extended
* year of this calendar system. Subclasses should override this
* method if they can provide a more correct or more efficient
* implementation than the default implementation in Calendar.
* @internal
*/
virtual int32_t handleGetMonthLength(int32_t extendedYear, int32_t month, UErrorCode& status) const override;
/**
* Return the number of days in the given extended year of this
* calendar system. Subclasses should override this method if they can
* provide a more correct or more efficient implementation than the
* default implementation in Calendar.
* @stable ICU 2.0
*/
virtual int32_t handleGetYearLength(int32_t eyear, UErrorCode& status) const override;
/**
* return the length of the given month.
* @param month the given month.
* @param status Fill-in parameter which receives the status of this operation.
* @return the length of the given month.
* @internal
*/
virtual int32_t monthLength(int32_t month, UErrorCode& status) const;
/**
* return the length of the month according to the given year.
* @param month the given month.
* @param year the given year.
* @return the length of the month
* @internal
*/
virtual int32_t monthLength(int32_t month, int32_t year) const;
#ifndef U_HIDE_INTERNAL_API
/**
* return the length of the year field.
* @return the length of the year field
* @internal
*/
int32_t yearLength() const;
#endif /* U_HIDE_INTERNAL_API */
/**
* Return the day number with respect to the epoch. January 1, 1970 (Gregorian)
* is day zero.
* @param status Fill-in parameter which receives the status of this operation.
* @return the day number with respect to the epoch.
* @internal
*/
virtual UDate getEpochDay(UErrorCode& status);
/**
* Subclass API for defining limits of different types.
* Subclasses must implement this method to return limits for the
* following fields:
*
* <pre>UCAL_ERA
* UCAL_YEAR
* UCAL_MONTH
* UCAL_WEEK_OF_YEAR
* UCAL_WEEK_OF_MONTH
* UCAL_DATE (DAY_OF_MONTH on Java)
* UCAL_DAY_OF_YEAR
* UCAL_DAY_OF_WEEK_IN_MONTH
* UCAL_YEAR_WOY
* UCAL_EXTENDED_YEAR</pre>
*
* @param field one of the above field numbers
* @param limitType one of <code>MINIMUM</code>, <code>GREATEST_MINIMUM</code>,
* <code>LEAST_MAXIMUM</code>, or <code>MAXIMUM</code>
* @internal
*/
virtual int32_t handleGetLimit(UCalendarDateFields field, ELimitType limitType) const override;
/**
* Return the extended year defined by the current fields. This will
* use the UCAL_EXTENDED_YEAR field or the UCAL_YEAR and supra-year fields (such
* as UCAL_ERA) specific to the calendar system, depending on which set of
* fields is newer.
* @param status
* @return the extended year
* @internal
*/
virtual int32_t handleGetExtendedYear(UErrorCode& status) override;
/**
* Subclasses may override this to convert from week fields
* (YEAR_WOY and WEEK_OF_YEAR) to an extended year in the case
* where YEAR, EXTENDED_YEAR are not set.
* The Gregorian implementation assumes a yearWoy in gregorian format, according to the current era.
* @return the extended year, UCAL_EXTENDED_YEAR
* @internal
*/
virtual int32_t handleGetExtendedYearFromWeekFields(int32_t yearWoy, int32_t woy, UErrorCode& status) override;
/**
* Subclasses may override this method to compute several fields
* specific to each calendar system. These are:
*
* <ul><li>ERA
* <li>YEAR
* <li>MONTH
* <li>DAY_OF_MONTH
* <li>DAY_OF_YEAR
* <li>EXTENDED_YEAR</ul>
*
* <p>The GregorianCalendar implementation implements
* a calendar with the specified Julian/Gregorian cutover date.
* @internal
*/
virtual void handleComputeFields(int32_t julianDay, UErrorCode &status) override;
#ifndef U_HIDE_INTERNAL_API
/**
* The year in this calendar is counting from 1 backward if the era is 0.
* @return The year in era 0 of this calendar is counting backward from 1.
* @internal
*/
virtual bool isEra0CountingBackward() const override { return true; }
#endif // U_HIDE_INTERNAL_API
private:
/**
* Compute the julian day number of the given year.
* @param isGregorian if true, using Gregorian calendar, otherwise using Julian calendar
* @param year the given year.
* @param isLeap true if the year is a leap year.
* @return
*/
static double computeJulianDayOfYear(UBool isGregorian, int32_t year,
UBool& isLeap);
/**
* Validates the values of the set time fields. True if they're all valid.
* @return True if the set time fields are all valid.
*/
UBool validateFields() const;
/**
* Validates the value of the given time field. True if it's valid.
*/
UBool boundsCheck(int32_t value, UCalendarDateFields field) const;
/**
* Return the pseudo-time-stamp for two fields, given their
* individual pseudo-time-stamps. If either of the fields
* is unset, then the aggregate is unset. Otherwise, the
* aggregate is the later of the two stamps.
* @param stamp_a One given field.
* @param stamp_b Another given field.
* @return the pseudo-time-stamp for two fields
*/
int32_t aggregateStamp(int32_t stamp_a, int32_t stamp_b);
/**
* The point at which the Gregorian calendar rules are used, measured in
* milliseconds from the standard epoch. Default is October 15, 1582
* (Gregorian) 00:00:00 UTC, that is, October 4, 1582 (Julian) is followed
* by October 15, 1582 (Gregorian). This corresponds to Julian day number
* 2299161. This is measured from the standard epoch, not in Julian Days.
*/
UDate fGregorianCutover;
/**
* Julian day number of the Gregorian cutover
*/
int32_t fCutoverJulianDay;
/**
* Midnight, local time (using this Calendar's TimeZone) at or before the
* gregorianCutover. This is a pure date value with no time of day or
* timezone component.
*/
UDate fNormalizedGregorianCutover;// = gregorianCutover;
/**
* The year of the gregorianCutover, with 0 representing
* 1 BC, -1 representing 2 BC, etc.
*/
int32_t fGregorianCutoverYear;// = 1582;
/**
* Converts time as milliseconds to Julian date. The Julian date used here is not a
* true Julian date, since it is measured from midnight, not noon.
*
* @param millis The given milliseconds.
* @return The Julian date number.
*/
static double millisToJulianDay(UDate millis);
/**
* Converts Julian date to time as milliseconds. The Julian date used here is not a
* true Julian date, since it is measured from midnight, not noon.
*
* @param julian The given Julian date number.
* @return Time as milliseconds.
*/
static UDate julianDayToMillis(double julian);
/**
* Used by handleComputeJulianDay() and handleComputeMonthStart().
* Temporary field indicating whether the calendar is currently Gregorian as opposed to Julian.
*/
UBool fIsGregorian;
/**
* Used by handleComputeJulianDay() and handleComputeMonthStart().
* Temporary field indicating that the sense of the gregorian cutover should be inverted
* to handle certain calculations on and around the cutover date.
*/
UBool fInvertGregorian;
public: // internal implementation
DECLARE_OVERRIDE_SYSTEM_DEFAULT_CENTURY
};
U_NAMESPACE_END
#endif /* #if !UCONFIG_NO_FORMATTING */
#endif /* U_SHOW_CPLUSPLUS_API */
#endif // _GREGOCAL
//eof

View File

@ -0,0 +1,286 @@
// © 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
/*
*******************************************************************************
*
* Copyright (C) 2012-2016, International Business Machines
* Corporation and others. All Rights Reserved.
*
*******************************************************************************
* file name: listformatter.h
* encoding: UTF-8
* tab size: 8 (not used)
* indentation:4
*
* created on: 20120426
* created by: Umesh P. Nair
*/
#ifndef __LISTFORMATTER_H__
#define __LISTFORMATTER_H__
#include "unicode/utypes.h"
#if U_SHOW_CPLUSPLUS_API
#if !UCONFIG_NO_FORMATTING
#include "unicode/unistr.h"
#include "unicode/locid.h"
#include "unicode/formattedvalue.h"
#include "unicode/ulistformatter.h"
U_NAMESPACE_BEGIN
class FieldPositionHandler;
class FormattedListData;
class ListFormatter;
/** @internal */
class Hashtable;
/** @internal */
struct ListFormatInternal;
/* The following can't be #ifndef U_HIDE_INTERNAL_API, needed for other .h file declarations */
/**
* @internal
* \cond
*/
struct ListFormatData : public UMemory {
UnicodeString twoPattern;
UnicodeString startPattern;
UnicodeString middlePattern;
UnicodeString endPattern;
Locale locale;
ListFormatData(const UnicodeString& two, const UnicodeString& start, const UnicodeString& middle, const UnicodeString& end,
const Locale& loc) :
twoPattern(two), startPattern(start), middlePattern(middle), endPattern(end), locale(loc) {}
};
/** \endcond */
/**
* \file
* \brief C++ API: API for formatting a list.
*/
/**
* An immutable class containing the result of a list formatting operation.
*
* Instances of this class are immutable and thread-safe.
*
* When calling nextPosition():
* The fields are returned from start to end. The special field category
* UFIELD_CATEGORY_LIST_SPAN is used to indicate which argument
* was inserted at the given position. The span category will
* always occur before the corresponding instance of UFIELD_CATEGORY_LIST
* in the nextPosition() iterator.
*
* Not intended for public subclassing.
*
* @stable ICU 64
*/
class U_I18N_API FormattedList : public UMemory, public FormattedValue {
public:
/**
* Default constructor; makes an empty FormattedList.
* @stable ICU 64
*/
FormattedList() : fData(nullptr), fErrorCode(U_INVALID_STATE_ERROR) {}
/**
* Move constructor: Leaves the source FormattedList in an undefined state.
* @stable ICU 64
*/
FormattedList(FormattedList&& src) noexcept;
/**
* Destruct an instance of FormattedList.
* @stable ICU 64
*/
virtual ~FormattedList() override;
/** Copying not supported; use move constructor instead. */
FormattedList(const FormattedList&) = delete;
/** Copying not supported; use move assignment instead. */
FormattedList& operator=(const FormattedList&) = delete;
/**
* Move assignment: Leaves the source FormattedList in an undefined state.
* @stable ICU 64
*/
FormattedList& operator=(FormattedList&& src) noexcept;
/** @copydoc FormattedValue::toString() */
UnicodeString toString(UErrorCode& status) const override;
/** @copydoc FormattedValue::toTempString() */
UnicodeString toTempString(UErrorCode& status) const override;
/** @copydoc FormattedValue::appendTo() */
Appendable &appendTo(Appendable& appendable, UErrorCode& status) const override;
/** @copydoc FormattedValue::nextPosition() */
UBool nextPosition(ConstrainedFieldPosition& cfpos, UErrorCode& status) const override;
private:
FormattedListData *fData;
UErrorCode fErrorCode;
explicit FormattedList(FormattedListData *results)
: fData(results), fErrorCode(U_ZERO_ERROR) {}
explicit FormattedList(UErrorCode errorCode)
: fData(nullptr), fErrorCode(errorCode) {}
friend class ListFormatter;
};
/**
* An immutable class for formatting a list, using data from CLDR (or supplied
* separately).
*
* Example: Input data ["Alice", "Bob", "Charlie", "Delta"] will be formatted
* as "Alice, Bob, Charlie and Delta" in English.
*
* The ListFormatter class is not intended for public subclassing.
* @stable ICU 50
*/
class U_I18N_API ListFormatter : public UObject{
public:
/**
* Copy constructor.
* @stable ICU 52
*/
ListFormatter(const ListFormatter&);
/**
* Assignment operator.
* @stable ICU 52
*/
ListFormatter& operator=(const ListFormatter& other);
/**
* Creates a ListFormatter appropriate for the default locale.
*
* @param errorCode ICU error code, set if no data available for default locale.
* @return Pointer to a ListFormatter object for the default locale,
* created from internal data derived from CLDR data.
* @stable ICU 50
*/
static ListFormatter* createInstance(UErrorCode& errorCode);
/**
* Creates a ListFormatter appropriate for a locale.
*
* @param locale The locale.
* @param errorCode ICU error code, set if no data available for the given locale.
* @return A ListFormatter object created from internal data derived from
* CLDR data.
* @stable ICU 50
*/
static ListFormatter* createInstance(const Locale& locale, UErrorCode& errorCode);
/**
* Creates a ListFormatter for the given locale, list type, and style.
*
* @param locale The locale.
* @param type The type of list formatting to use.
* @param width The width of formatting to use.
* @param errorCode ICU error code, set if no data available for the given locale.
* @return A ListFormatter object created from internal data derived from CLDR data.
* @stable ICU 67
*/
static ListFormatter* createInstance(
const Locale& locale, UListFormatterType type, UListFormatterWidth width, UErrorCode& errorCode);
/**
* Destructor.
*
* @stable ICU 50
*/
virtual ~ListFormatter();
/**
* Formats a list of strings.
*
* @param items An array of strings to be combined and formatted.
* @param n_items Length of the array items.
* @param appendTo The string to which the result should be appended to.
* @param errorCode ICU error code, set if there is an error.
* @return Formatted string combining the elements of items, appended to appendTo.
* @stable ICU 50
*/
UnicodeString& format(const UnicodeString items[], int32_t n_items,
UnicodeString& appendTo, UErrorCode& errorCode) const;
/**
* Formats a list of strings to a FormattedList, which exposes field
* position information. The FormattedList contains more information than
* a FieldPositionIterator.
*
* @param items An array of strings to be combined and formatted.
* @param n_items Length of the array items.
* @param errorCode ICU error code returned here.
* @return A FormattedList containing field information.
* @stable ICU 64
*/
FormattedList formatStringsToValue(
const UnicodeString items[],
int32_t n_items,
UErrorCode& errorCode) const;
#ifndef U_HIDE_INTERNAL_API
/**
@internal for MeasureFormat
*/
UnicodeString& format(
const UnicodeString items[],
int32_t n_items,
UnicodeString& appendTo,
int32_t index,
int32_t &offset,
UErrorCode& errorCode) const;
/**
* @internal constructor made public for testing.
*/
ListFormatter(const ListFormatData &data, UErrorCode &errorCode);
/**
* @internal constructor made public for testing.
*/
ListFormatter(const ListFormatInternal* listFormatterInternal);
#endif /* U_HIDE_INTERNAL_API */
private:
/**
* Creates a ListFormatter appropriate for a locale and style.
*
* @param locale The locale.
* @param style the style, either "standard", "or", "unit", "unit-narrow", or "unit-short"
*/
static ListFormatter* createInstance(const Locale& locale, const char* style, UErrorCode& errorCode);
static void initializeHash(UErrorCode& errorCode);
static const ListFormatInternal* getListFormatInternal(const Locale& locale, const char *style, UErrorCode& errorCode);
struct U_HIDDEN ListPatternsSink;
static ListFormatInternal* loadListFormatInternal(const Locale& locale, const char* style, UErrorCode& errorCode);
ListFormatter() = delete;
ListFormatInternal* owned;
const ListFormatInternal* data;
};
U_NAMESPACE_END
#endif /* #if !UCONFIG_NO_FORMATTING */
#endif /* U_SHOW_CPLUSPLUS_API */
#endif // __LISTFORMATTER_H__

View File

@ -0,0 +1,398 @@
// © 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
/*
**********************************************************************
* Copyright (c) 2004-2016, International Business Machines
* Corporation and others. All Rights Reserved.
**********************************************************************
* Author: Alan Liu
* Created: April 20, 2004
* Since: ICU 3.0
**********************************************************************
*/
#ifndef MEASUREFORMAT_H
#define MEASUREFORMAT_H
#include "unicode/utypes.h"
#if U_SHOW_CPLUSPLUS_API
#if !UCONFIG_NO_FORMATTING
#include "unicode/format.h"
#include "unicode/udat.h"
/**
* \file
* \brief C++ API: Compatibility APIs for measure formatting.
*/
/**
* Constants for various widths.
* There are 4 widths: Wide, Short, Narrow, Numeric.
* For example, for English, when formatting "3 hours"
* Wide is "3 hours"; short is "3 hrs"; narrow is "3h";
* formatting "3 hours 17 minutes" as numeric give "3:17"
* @stable ICU 53
*/
enum UMeasureFormatWidth {
// Wide, short, and narrow must be first and in this order.
/**
* Spell out measure units.
* @stable ICU 53
*/
UMEASFMT_WIDTH_WIDE,
/**
* Abbreviate measure units.
* @stable ICU 53
*/
UMEASFMT_WIDTH_SHORT,
/**
* Use symbols for measure units when possible.
* @stable ICU 53
*/
UMEASFMT_WIDTH_NARROW,
/**
* Completely omit measure units when possible. For example, format
* '5 hours, 37 minutes' as '5:37'
* @stable ICU 53
*/
UMEASFMT_WIDTH_NUMERIC,
#ifndef U_HIDE_DEPRECATED_API
/**
* One more than the highest normal UMeasureFormatWidth value.
* @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420.
*/
UMEASFMT_WIDTH_COUNT = 4
#endif // U_HIDE_DEPRECATED_API
};
/** @stable ICU 53 */
typedef enum UMeasureFormatWidth UMeasureFormatWidth;
U_NAMESPACE_BEGIN
class Measure;
class MeasureUnit;
class NumberFormat;
class PluralRules;
class MeasureFormatCacheData;
class SharedNumberFormat;
class SharedPluralRules;
class QuantityFormatter;
class SimpleFormatter;
class ListFormatter;
class DateFormat;
/**
* <p><strong>IMPORTANT:</strong> New users are strongly encouraged to see if
* numberformatter.h fits their use case. Although not deprecated, this header
* is provided for backwards compatibility only, and has much more limited
* capabilities.
*
* @see Format
* @author Alan Liu
* @stable ICU 3.0
*/
class U_I18N_API MeasureFormat : public Format {
public:
using Format::parseObject;
using Format::format;
/**
* Constructor.
* <p>
* <strong>NOTE:</strong> New users are strongly encouraged to use
* {@link icu::number::NumberFormatter} instead of NumberFormat.
* @stable ICU 53
*/
MeasureFormat(
const Locale &locale, UMeasureFormatWidth width, UErrorCode &status);
/**
* Constructor.
* <p>
* <strong>NOTE:</strong> New users are strongly encouraged to use
* {@link icu::number::NumberFormatter} instead of NumberFormat.
* @stable ICU 53
*/
MeasureFormat(
const Locale &locale,
UMeasureFormatWidth width,
NumberFormat *nfToAdopt,
UErrorCode &status);
/**
* Copy constructor.
* @stable ICU 3.0
*/
MeasureFormat(const MeasureFormat &other);
/**
* Assignment operator.
* @stable ICU 3.0
*/
MeasureFormat &operator=(const MeasureFormat &rhs);
/**
* Destructor.
* @stable ICU 3.0
*/
virtual ~MeasureFormat();
/**
* Return true if given Format objects are semantically equal.
* @stable ICU 53
*/
virtual bool operator==(const Format &other) const override;
/**
* Clones this object polymorphically.
* @stable ICU 53
*/
virtual MeasureFormat *clone() const override;
/**
* Formats object to produce a string.
* @stable ICU 53
*/
virtual UnicodeString &format(
const Formattable &obj,
UnicodeString &appendTo,
FieldPosition &pos,
UErrorCode &status) const override;
#ifndef U_FORCE_HIDE_DRAFT_API
/**
* Parse a string to produce an object. This implementation sets
* status to U_UNSUPPORTED_ERROR.
*
* @draft ICU 53
*/
virtual void parseObject(
const UnicodeString &source,
Formattable &reslt,
ParsePosition &pos) const override;
#endif // U_FORCE_HIDE_DRAFT_API
/**
* Formats measure objects to produce a string. An example of such a
* formatted string is 3 meters, 3.5 centimeters. Measure objects appear
* in the formatted string in the same order they appear in the "measures"
* array. The NumberFormat of this object is used only to format the amount
* of the very last measure. The other amounts are formatted with zero
* decimal places while rounding toward zero.
* @param measures array of measure objects.
* @param measureCount the number of measure objects.
* @param appendTo formatted string appended here.
* @param pos the field position.
* @param status the error.
* @return appendTo reference
*
* @stable ICU 53
*/
UnicodeString &formatMeasures(
const Measure *measures,
int32_t measureCount,
UnicodeString &appendTo,
FieldPosition &pos,
UErrorCode &status) const;
/**
* Formats a single measure per unit. An example of such a
* formatted string is 3.5 meters per second.
* @param measure The measure object. In above example, 3.5 meters.
* @param perUnit The per unit. In above example, it is
* `*%MeasureUnit::createSecond(status)`.
* @param appendTo formatted string appended here.
* @param pos the field position.
* @param status the error.
* @return appendTo reference
*
* @stable ICU 55
*/
UnicodeString &formatMeasurePerUnit(
const Measure &measure,
const MeasureUnit &perUnit,
UnicodeString &appendTo,
FieldPosition &pos,
UErrorCode &status) const;
/**
* Gets the display name of the specified {@link MeasureUnit} corresponding to the current
* locale and format width.
* @param unit The unit for which to get a display name.
* @param status the error.
* @return The display name in the locale and width specified in
* the MeasureFormat constructor, or null if there is no display name available
* for the specified unit.
*
* @stable ICU 58
*/
UnicodeString getUnitDisplayName(const MeasureUnit& unit, UErrorCode &status) const;
/**
* Return a formatter for CurrencyAmount objects in the given
* locale.
* <p>
* <strong>NOTE:</strong> New users are strongly encouraged to use
* {@link icu::number::NumberFormatter} instead of NumberFormat.
* @param locale desired locale
* @param ec input-output error code
* @return a formatter object, or nullptr upon error
* @stable ICU 3.0
*/
static MeasureFormat* U_EXPORT2 createCurrencyFormat(const Locale& locale,
UErrorCode& ec);
/**
* Return a formatter for CurrencyAmount objects in the default
* locale.
* <p>
* <strong>NOTE:</strong> New users are strongly encouraged to use
* {@link icu::number::NumberFormatter} instead of NumberFormat.
* @param ec input-output error code
* @return a formatter object, or nullptr upon error
* @stable ICU 3.0
*/
static MeasureFormat* U_EXPORT2 createCurrencyFormat(UErrorCode& ec);
/**
* Return the class ID for this class. This is useful only for comparing to
* a return value from getDynamicClassID(). For example:
* <pre>
* . Base* polymorphic_pointer = createPolymorphicObject();
* . if (polymorphic_pointer->getDynamicClassID() ==
* . erived::getStaticClassID()) ...
* </pre>
* @return The class ID for all objects of this class.
* @stable ICU 53
*/
static UClassID U_EXPORT2 getStaticClassID();
/**
* Returns a unique class ID POLYMORPHICALLY. Pure virtual override. This
* method is to implement a simple version of RTTI, since not all C++
* compilers support genuine RTTI. Polymorphic operator==() and clone()
* methods call this method.
*
* @return The class ID for this object. All objects of a
* given class have the same class ID. Objects of
* other classes have different class IDs.
* @stable ICU 53
*/
virtual UClassID getDynamicClassID() const override;
protected:
/**
* Default constructor.
* @stable ICU 3.0
*/
MeasureFormat();
#ifndef U_HIDE_INTERNAL_API
/**
* ICU use only.
* Initialize or change MeasureFormat class from subclass.
* @internal.
*/
void initMeasureFormat(
const Locale &locale,
UMeasureFormatWidth width,
NumberFormat *nfToAdopt,
UErrorCode &status);
/**
* ICU use only.
* Allows subclass to change locale. Note that this method also changes
* the NumberFormat object. Returns true if locale changed; false if no
* change was made.
* @internal.
*/
UBool setMeasureFormatLocale(const Locale &locale, UErrorCode &status);
/**
* ICU use only.
* Let subclass change NumberFormat.
* @internal.
*/
void adoptNumberFormat(NumberFormat *nfToAdopt, UErrorCode &status);
/**
* ICU use only.
* @internal.
*/
const NumberFormat &getNumberFormatInternal() const;
/**
* ICU use only.
* Always returns the short form currency formatter.
* @internal.
*/
const NumberFormat& getCurrencyFormatInternal() const;
/**
* ICU use only.
* @internal.
*/
const PluralRules &getPluralRules() const;
/**
* ICU use only.
* @internal.
*/
Locale getLocale(UErrorCode &status) const;
/**
* ICU use only.
* @internal.
*/
const char *getLocaleID(UErrorCode &status) const;
#endif /* U_HIDE_INTERNAL_API */
private:
const MeasureFormatCacheData *cache;
const SharedNumberFormat *numberFormat;
const SharedPluralRules *pluralRules;
UMeasureFormatWidth fWidth;
// Declared outside of MeasureFormatSharedData because ListFormatter
// objects are relatively cheap to copy; therefore, they don't need to be
// shared across instances.
ListFormatter *listFormatter;
UnicodeString &formatMeasure(
const Measure &measure,
const NumberFormat &nf,
UnicodeString &appendTo,
FieldPosition &pos,
UErrorCode &status) const;
UnicodeString &formatMeasuresSlowTrack(
const Measure *measures,
int32_t measureCount,
UnicodeString& appendTo,
FieldPosition& pos,
UErrorCode& status) const;
UnicodeString &formatNumeric(
const Formattable *hms, // always length 3: [0] is hour; [1] is
// minute; [2] is second.
int32_t bitMap, // 1=hour set, 2=minute set, 4=second set
UnicodeString &appendTo,
UErrorCode &status) const;
};
U_NAMESPACE_END
#endif // #if !UCONFIG_NO_FORMATTING
#endif /* U_SHOW_CPLUSPLUS_API */
#endif // #ifndef MEASUREFORMAT_H

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,174 @@
// © 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
/*
**********************************************************************
* Copyright (c) 2004-2015, International Business Machines
* Corporation and others. All Rights Reserved.
**********************************************************************
* Author: Alan Liu
* Created: April 26, 2004
* Since: ICU 3.0
**********************************************************************
*/
#ifndef __MEASURE_H__
#define __MEASURE_H__
#include "unicode/utypes.h"
#if U_SHOW_CPLUSPLUS_API
/**
* \file
* \brief C++ API: MeasureUnit object.
*/
#if !UCONFIG_NO_FORMATTING
#include "unicode/fmtable.h"
U_NAMESPACE_BEGIN
class MeasureUnit;
/**
* An amount of a specified unit, consisting of a number and a Unit.
* For example, a length measure consists of a number and a length
* unit, such as feet or meters.
*
* <p>Measure objects are formatted by MeasureFormat.
*
* <p>Measure objects are immutable.
*
* @author Alan Liu
* @stable ICU 3.0
*/
class U_I18N_API Measure: public UObject {
public:
/**
* Construct an object with the given numeric amount and the given
* unit. After this call, the caller must not delete the given
* unit object.
* @param number a numeric object; amount.isNumeric() must be true
* @param adoptedUnit the unit object, which must not be nullptr
* @param ec input-output error code. If the amount or the unit
* is invalid, then this will be set to a failing value.
* @stable ICU 3.0
*/
Measure(const Formattable& number, MeasureUnit* adoptedUnit,
UErrorCode& ec);
/**
* Copy constructor
* @stable ICU 3.0
*/
Measure(const Measure& other);
/**
* Assignment operator
* @stable ICU 3.0
*/
Measure& operator=(const Measure& other);
/**
* Return a polymorphic clone of this object. The result will
* have the same class as returned by getDynamicClassID().
* @stable ICU 3.0
*/
virtual Measure* clone() const;
/**
* Destructor
* @stable ICU 3.0
*/
virtual ~Measure();
/**
* Equality operator. Return true if this object is equal
* to the given object.
* @stable ICU 3.0
*/
bool operator==(const UObject& other) const;
/**
* Inequality operator. Returns true if this object is not equal to the other object.
* @param other the object to compare with
* @return true if the objects are not equal
* @stable ICU 74
*/
inline bool operator!=(const UObject& other) const { return !operator==(other); }
/**
* Return a reference to the numeric value of this object. The
* numeric value may be of any numeric type supported by
* Formattable.
* @stable ICU 3.0
*/
inline const Formattable& getNumber() const;
/**
* Return a reference to the unit of this object.
* @stable ICU 3.0
*/
inline const MeasureUnit& getUnit() const;
/**
* Return the class ID for this class. This is useful only for comparing to
* a return value from getDynamicClassID(). For example:
* <pre>
* . Base* polymorphic_pointer = createPolymorphicObject();
* . if (polymorphic_pointer->getDynamicClassID() ==
* . erived::getStaticClassID()) ...
* </pre>
* @return The class ID for all objects of this class.
* @stable ICU 53
*/
static UClassID U_EXPORT2 getStaticClassID();
/**
* Returns a unique class ID POLYMORPHICALLY. Pure virtual override. This
* method is to implement a simple version of RTTI, since not all C++
* compilers support genuine RTTI. Polymorphic operator==() and clone()
* methods call this method.
*
* @return The class ID for this object. All objects of a
* given class have the same class ID. Objects of
* other classes have different class IDs.
* @stable ICU 53
*/
virtual UClassID getDynamicClassID() const override;
protected:
/**
* Default constructor.
* @stable ICU 3.0
*/
Measure();
private:
/**
* The numeric value of this object, e.g. 2.54 or 100.
*/
Formattable number;
/**
* The unit of this object, e.g., "millimeter" or "JPY". This is
* owned by this object.
*/
MeasureUnit* unit;
};
inline const Formattable& Measure::getNumber() const {
return number;
}
inline const MeasureUnit& Measure::getUnit() const {
return *unit;
}
U_NAMESPACE_END
#endif // !UCONFIG_NO_FORMATTING
#endif /* U_SHOW_CPLUSPLUS_API */
#endif // __MEASURE_H__

View File

@ -0,0 +1,476 @@
// © 2024 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
#include "unicode/utypes.h"
#ifndef MESSAGEFORMAT2_H
#define MESSAGEFORMAT2_H
#if U_SHOW_CPLUSPLUS_API
#if !UCONFIG_NO_NORMALIZATION
#if !UCONFIG_NO_FORMATTING
#if !UCONFIG_NO_MF2
/**
* \file
* \brief C++ API: Formats messages using the draft MessageFormat 2.0.
*/
#include "unicode/messageformat2_arguments.h"
#include "unicode/messageformat2_data_model.h"
#include "unicode/messageformat2_function_registry.h"
#include "unicode/normalizer2.h"
#include "unicode/unistr.h"
#ifndef U_HIDE_DEPRECATED_API
U_NAMESPACE_BEGIN
namespace message2 {
class Environment;
class MessageContext;
class StaticErrors;
class InternalValue;
/**
* <p>MessageFormatter is a Technical Preview API implementing MessageFormat 2.0.
*
* <p>See <a target="github" href="https://github.com/unicode-org/message-format-wg/blob/main/spec/syntax.md">the
* description of the syntax with examples and use cases</a> and the corresponding
* <a target="github" href="https://github.com/unicode-org/message-format-wg/blob/main/spec/message.abnf">ABNF</a> grammar.</p>
*
* The MessageFormatter class is mutable and movable. It is not copyable.
* (It is mutable because if it has a custom function registry, the registry may include
* `FormatterFactory` objects implementing custom formatters, which are allowed to contain
* mutable state.)
*
* @internal ICU 75 technology preview
* @deprecated This API is for technology preview only.
*/
class U_I18N_API MessageFormatter : public UObject {
// Note: This class does not currently inherit from the existing
// `Format` class.
public:
/**
* Move assignment operator:
* The source MessageFormatter will be left in a valid but undefined state.
*
* @internal ICU 75 technology preview
* @deprecated This API is for technology preview only.
*/
MessageFormatter& operator=(MessageFormatter&&) noexcept;
/**
* Destructor.
*
* @internal ICU 75 technology preview
* @deprecated This API is for technology preview only.
*/
virtual ~MessageFormatter();
/**
* Formats the message to a string, using the data model that was previously set or parsed,
* and the given `arguments` object.
*
* @param arguments Reference to message arguments
* @param status Input/output error code used to indicate syntax errors, data model
* errors, resolution errors, formatting errors, selection errors, as well
* as other errors (such as memory allocation failures). Partial output
* is still provided in the presence of most error types.
* @return The string result of formatting the message with the given arguments.
*
* @internal ICU 75 technology preview
* @deprecated This API is for technology preview only.
*/
UnicodeString formatToString(const MessageArguments& arguments, UErrorCode &status);
/**
* Not yet implemented; formats the message to a `FormattedMessage` object,
* using the data model that was previously set or parsed,
* and the given `arguments` object.
*
* @param arguments Reference to message arguments
* @param status Input/output error code used to indicate syntax errors, data model
* errors, resolution errors, formatting errors, selection errors, as well
* as other errors (such as memory allocation failures). Partial output
* is still provided in the presence of most error types.
* @return The `FormattedMessage` representing the formatted message.
*
* @internal ICU 75 technology preview
* @deprecated This API is for technology preview only.
*/
FormattedMessage format(const MessageArguments& arguments, UErrorCode &status) const {
(void) arguments;
if (U_SUCCESS(status)) {
status = U_UNSUPPORTED_ERROR;
}
return FormattedMessage(status);
}
/**
* Accesses the locale that this `MessageFormatter` object was created with.
*
* @return A reference to the locale.
*
* @internal ICU 75 technology preview
* @deprecated This API is for technology preview only.
*/
const Locale& getLocale() const { return locale; }
/**
* Serializes the data model as a string in MessageFormat 2.0 syntax.
*
* @return result A string representation of the data model.
* The string is a valid MessageFormat 2.0 message.
*
* @internal ICU 75 technology preview
* @deprecated This API is for technology preview only.
*/
UnicodeString getPattern() const;
/**
* Accesses the data model referred to by this
* `MessageFormatter` object.
*
* @return A reference to the data model.
*
* @internal ICU 75 technology preview
* @deprecated This API is for technology preview only.
*/
const MFDataModel& getDataModel() const;
/**
* Used in conjunction with the
* MessageFormatter::Builder::setErrorHandlingBehavior() method.
*
* @internal ICU 76 technology preview
* @deprecated This API is for technology preview only.
*/
typedef enum UMFErrorHandlingBehavior {
/**
* Suppress errors and return best-effort output.
*
* @internal ICU 76 technology preview
* @deprecated This API is for technology preview only.
*/
U_MF_BEST_EFFORT = 0,
/**
* Signal all MessageFormat errors using the UErrorCode
* argument.
*
* @internal ICU 76 technology preview
* @deprecated This API is for technology preview only.
*/
U_MF_STRICT
} UMFErrorHandlingBehavior;
/**
* The mutable Builder class allows each part of the MessageFormatter to be initialized
* separately; calling its `build()` method yields an immutable MessageFormatter.
*
* Not copyable or movable.
*/
class U_I18N_API Builder : public UObject {
private:
friend class MessageFormatter;
// The pattern to be parsed to generate the formatted message
UnicodeString pattern;
bool hasPattern = false;
bool hasDataModel = false;
// The data model to be used to generate the formatted message
// Initialized either by `setDataModel()`, or by the parser
// through a call to `setPattern()`
MFDataModel dataModel;
// Normalized representation of the pattern;
// ignored if `setPattern()` wasn't called
UnicodeString normalizedInput;
// Errors (internal representation of parse errors)
// Ignored if `setPattern()` wasn't called
StaticErrors* errors;
Locale locale;
// Not owned
const MFFunctionRegistry* customMFFunctionRegistry;
// Error behavior; see comment in `MessageFormatter` class
bool signalErrors = false;
void clearState();
public:
/**
* Sets the locale to use for formatting.
*
* @param locale The desired locale.
* @return A reference to the builder.
*
* @internal ICU 75 technology preview
* @deprecated This API is for technology preview only.
*/
Builder& setLocale(const Locale& locale);
/**
* Sets the pattern (contents of the message) and parses it
* into a data model. If a data model was
* previously set, it is removed.
*
* @param pattern A string in MessageFormat 2.0 syntax.
* @param parseError Struct to receive information on the position
* of an error within the pattern.
* @param status Input/output error code. If the
* pattern cannot be parsed, set to failure code.
* @return A reference to the builder.
*
* @internal ICU 75 technology preview
* @deprecated This API is for technology preview only.
*/
Builder& setPattern(const UnicodeString& pattern, UParseError& parseError, UErrorCode& status);
/**
* Sets a custom function registry.
*
* @param functionRegistry Reference to the function registry to use.
* `functionRegistry` is not copied,
* and the caller must ensure its lifetime contains
* the lifetime of the `MessageFormatter` object built by this
* builder.
* @return A reference to the builder.
*
* @internal ICU 75 technology preview
* @deprecated This API is for technology preview only.
*/
Builder& setFunctionRegistry(const MFFunctionRegistry& functionRegistry);
/**
* Sets a data model. If a pattern was previously set, it is removed.
*
* @param dataModel Data model to format. Passed by move.
* @return A reference to the builder.
*
* @internal ICU 75 technology preview
* @deprecated This API is for technology preview only.
*/
Builder& setDataModel(MFDataModel&& dataModel);
/**
* Set the error handling behavior for this formatter.
*
* "Strict" error behavior means that that formatting methods
* will set their UErrorCode arguments to signal MessageFormat
* data model, resolution, and runtime errors. Syntax errors are
* always signaled.
*
* "Best effort" error behavior means that MessageFormat errors are
* suppressed: formatting methods will _not_ set their
* UErrorCode arguments to signal MessageFormat data model,
* resolution, or runtime errors. Best-effort output
* will be returned. Syntax errors are always signaled.
* This is the default behavior.
*
* @param type An enum with type UMFErrorHandlingBehavior;
* if type == `U_MF_STRICT`, then
* errors are handled strictly.
* If type == `U_MF_BEST_EFFORT`, then
* best-effort output is returned.
*
* The default is to suppress all MessageFormat errors
* and return best-effort output.
*
* @return A reference to the builder.
*
* @internal ICU 76 technology preview
* @deprecated This API is for technology preview only.
*/
Builder& setErrorHandlingBehavior(UMFErrorHandlingBehavior type);
/**
* Constructs a new immutable MessageFormatter using the pattern or data model
* that was previously set, and the locale (if it was previously set)
* or default locale (otherwise).
*
* The builder object (`this`) can still be used after calling `build()`.
*
* @param status Input/output error code. If neither the pattern
* nor the data model is set, set to failure code.
* @return The new MessageFormatter object
*
* @internal ICU 75 technology preview
* @deprecated This API is for technology preview only.
*/
MessageFormatter build(UErrorCode& status) const;
/**
* Default constructor.
* Returns a Builder with the default locale and with no
* data model or pattern set. Either `setPattern()`
* or `setDataModel()` has to be called before calling `build()`.
*
* @param status Input/output error code.
*
* @internal ICU 75 technology preview
* @deprecated This API is for technology preview only.
*/
Builder(UErrorCode& status);
/**
* Destructor.
*
* @internal ICU 75 technology preview
* @deprecated This API is for technology preview only.
*/
virtual ~Builder();
}; // class MessageFormatter::Builder
// TODO: Shouldn't be public; only used for testing
/**
* Returns a string consisting of the input with optional spaces removed.
*
* @return A normalized string representation of the input
*
* @internal ICU 75 technology preview
* @deprecated This API is for technology preview only.
*/
const UnicodeString& getNormalizedPattern() const { return normalizedInput; }
private:
friend class Builder;
friend class Checker;
friend class MessageArguments;
friend class MessageContext;
MessageFormatter(const MessageFormatter::Builder& builder, UErrorCode &status);
MessageFormatter() = delete; // default constructor not implemented
// Do not define default assignment operator
const MessageFormatter &operator=(const MessageFormatter &) = delete;
// Selection methods
// Takes a vector of FormattedPlaceholders
void resolveSelectors(MessageContext&, const Environment& env, UErrorCode&, UVector&) const;
// Takes a vector of vectors of strings (input) and a vector of PrioritizedVariants (output)
void filterVariants(const UVector&, UVector&, UErrorCode&) const;
// Takes a vector of vectors of strings (input) and a vector of PrioritizedVariants (input/output)
void sortVariants(const UVector&, UVector&, UErrorCode&) const;
// Takes a vector of strings (input) and a vector of strings (output)
void matchSelectorKeys(const UVector&, MessageContext&, InternalValue* rv, UVector&, UErrorCode&) const;
// Takes a vector of FormattedPlaceholders (input),
// and a vector of vectors of strings (output)
void resolvePreferences(MessageContext&, UVector&, UVector&, UErrorCode&) const;
// Formatting methods
// Used for normalizing variable names and keys for comparison
UnicodeString normalizeNFC(const UnicodeString&) const;
[[nodiscard]] FormattedPlaceholder formatLiteral(const data_model::Literal&) const;
void formatPattern(MessageContext&, const Environment&, const data_model::Pattern&, UErrorCode&, UnicodeString&) const;
// Evaluates a function call
// Dispatches on argument type
[[nodiscard]] InternalValue* evalFunctionCall(FormattedPlaceholder&& argument,
MessageContext& context,
UErrorCode& status) const;
// Dispatches on function name
[[nodiscard]] InternalValue* evalFunctionCall(const FunctionName& functionName,
InternalValue* argument,
FunctionOptions&& options,
MessageContext& context,
UErrorCode& status) const;
// Formats an expression that appears in a pattern or as the definition of a local variable
[[nodiscard]] InternalValue* formatExpression(const Environment&,
const data_model::Expression&,
MessageContext&,
UErrorCode&) const;
[[nodiscard]] FunctionOptions resolveOptions(const Environment& env, const OptionMap&, MessageContext&, UErrorCode&) const;
[[nodiscard]] InternalValue* formatOperand(const Environment&, const data_model::Operand&, MessageContext&, UErrorCode&) const;
[[nodiscard]] FormattedPlaceholder evalArgument(const data_model::VariableName&, MessageContext&, UErrorCode&) const;
void formatSelectors(MessageContext& context, const Environment& env, UErrorCode &status, UnicodeString& result) const;
// Function registry methods
bool hasCustomMFFunctionRegistry() const {
return (customMFFunctionRegistry != nullptr);
}
// Precondition: custom function registry exists
// Note: this is non-const because the values in the MFFunctionRegistry are mutable
// (a FormatterFactory can have mutable state)
const MFFunctionRegistry& getCustomMFFunctionRegistry() const;
bool isCustomFormatter(const FunctionName&) const;
FormatterFactory* lookupFormatterFactory(const FunctionName&, UErrorCode& status) const;
bool isBuiltInSelector(const FunctionName&) const;
bool isBuiltInFormatter(const FunctionName&) const;
bool isCustomSelector(const FunctionName&) const;
const SelectorFactory* lookupSelectorFactory(MessageContext&, const FunctionName&, UErrorCode&) const;
bool isSelector(const FunctionName& fn) const { return isBuiltInSelector(fn) || isCustomSelector(fn); }
bool isFormatter(const FunctionName& fn) const { return isBuiltInFormatter(fn) || isCustomFormatter(fn); }
const Formatter* lookupFormatter(const FunctionName&, UErrorCode&) const;
Selector* getSelector(MessageContext&, const FunctionName&, UErrorCode&) const;
Formatter* getFormatter(const FunctionName&, UErrorCode&) const;
bool getDefaultFormatterNameByType(const UnicodeString&, FunctionName&) const;
// Checking for resolution errors
void checkDeclarations(MessageContext&, Environment*&, UErrorCode&) const;
void check(MessageContext&, const Environment&, const data_model::Expression&, UErrorCode&) const;
void check(MessageContext&, const Environment&, const data_model::Operand&, UErrorCode&) const;
void check(MessageContext&, const Environment&, const OptionMap&, UErrorCode&) const;
void initErrors(UErrorCode&);
void clearErrors() const;
void cleanup() noexcept;
// The locale this MessageFormatter was created with
/* const */ Locale locale;
// Registry for built-in functions
MFFunctionRegistry standardMFFunctionRegistry;
// Registry for custom functions; may be null if no custom registry supplied
// Note: this is *not* owned by the MessageFormatter object
// The reason for this choice is to have a non-destructive MessageFormatter::Builder,
// while also not requiring the function registry to be deeply-copyable. Making the
// function registry copyable would impose a requirement on any implementations
// of the FormatterFactory and SelectorFactory interfaces to implement a custom
// clone() method, which is necessary to avoid sharing between copies of the
// function registry (and thus double-frees)
// Not deeply immutable (the values in the function registry are mutable,
// as a FormatterFactory can have mutable state
const MFFunctionRegistry* customMFFunctionRegistry;
// Data model, representing the parsed message
MFDataModel dataModel;
// Normalized version of the input string (optional whitespace removed)
UnicodeString normalizedInput;
// Errors -- only used while parsing and checking for data model errors; then
// the MessageContext keeps track of errors
// Must be a raw pointer to avoid including the internal header file
// defining StaticErrors
// Owned by `this`
StaticErrors* errors = nullptr;
// Error handling behavior.
// If true, then formatting methods set their UErrorCode arguments
// to signal MessageFormat errors, and no useful output is returned.
// If false, then MessageFormat errors are not signaled and the
// formatting methods return best-effort output.
// The default is false.
bool signalErrors = false;
// Used for implementing normalizeNFC()
const Normalizer2* nfcNormalizer = nullptr;
}; // class MessageFormatter
} // namespace message2
U_NAMESPACE_END
#endif // U_HIDE_DEPRECATED_API
#endif /* #if !UCONFIG_NO_MF2 */
#endif /* #if !UCONFIG_NO_FORMATTING */
#endif /* #if !UCONFIG_NO_NORMALIZATION */
#endif /* U_SHOW_CPLUSPLUS_API */
#endif // MESSAGEFORMAT2_H
// eof

View File

@ -0,0 +1,144 @@
// © 2024 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
#include "unicode/utypes.h"
#ifndef MESSAGEFORMAT2_ARGUMENTS_H
#define MESSAGEFORMAT2_ARGUMENTS_H
#if U_SHOW_CPLUSPLUS_API
#if !UCONFIG_NO_NORMALIZATION
#if !UCONFIG_NO_FORMATTING
#if !UCONFIG_NO_MF2
/**
* \file
* \brief C++ API: Formats messages using the draft MessageFormat 2.0.
*/
#include "unicode/messageformat2_data_model_names.h"
#include "unicode/messageformat2_formattable.h"
#include "unicode/unistr.h"
#ifndef U_HIDE_DEPRECATED_API
#include <map>
U_NAMESPACE_BEGIN
/// @cond DOXYGEN_IGNORE
// Export an explicit template instantiation of the LocalPointer that is used as a
// data member of various MessageFormatDataModel classes.
// (When building DLLs for Windows this is required.)
// (See measunit_impl.h, datefmt.h, collationiterator.h, erarules.h and others
// for similar examples.)
#if U_PF_WINDOWS <= U_PLATFORM && U_PLATFORM <= U_PF_CYGWIN
template class U_I18N_API LocalPointerBase<UnicodeString>;
template class U_I18N_API LocalPointerBase<message2::Formattable>;
template class U_I18N_API LocalArray<UnicodeString>;
template class U_I18N_API LocalArray<message2::Formattable>;
#endif
/// @endcond
namespace message2 {
class MessageFormatter;
// Arguments
// ----------
/**
*
* The `MessageArguments` class represents the named arguments to a message.
* It is immutable and movable. It is not copyable.
*
* @internal ICU 75 technology preview
* @deprecated This API is for technology preview only.
*/
class U_I18N_API MessageArguments : public UObject {
public:
/**
* Message arguments constructor, which takes a map and returns a container
* of arguments that can be passed to a `MessageFormatter`.
*
* @param args A reference to a map from strings (argument names) to `message2::Formattable`
* objects (argument values). The keys and values of the map are copied into the result.
* @param status Input/output error code.
*
* @internal ICU 75 technology preview
* @deprecated This API is for technology preview only.
*/
MessageArguments(const std::map<UnicodeString, Formattable>& args, UErrorCode& status) {
if (U_FAILURE(status)) {
return;
}
argumentNames = LocalArray<UnicodeString>(new UnicodeString[argsLen = static_cast<int32_t>(args.size())]);
arguments = LocalArray<Formattable>(new Formattable[argsLen]);
if (!argumentNames.isValid() || !arguments.isValid()) {
status = U_MEMORY_ALLOCATION_ERROR;
return;
}
int32_t i = 0;
for (auto iter = args.begin(); iter != args.end(); ++iter) {
argumentNames[i] = iter->first;
arguments[i] = iter->second;
i++;
}
}
/**
* Move operator:
* The source MessageArguments will be left in a valid but undefined state.
*
* @internal ICU 75 technology preview
* @deprecated This API is for technology preview only.
*/
MessageArguments& operator=(MessageArguments&&) noexcept;
/**
* Default constructor.
* Returns an empty arguments mapping.
*
* @internal ICU 75 technology preview
* @deprecated This API is for technology preview only.
*/
MessageArguments() = default;
/**
* Destructor.
*
* @internal ICU 75 technology preview
* @deprecated This API is for technology preview only.
*/
virtual ~MessageArguments();
private:
friend class MessageContext;
const Formattable* getArgument(const MessageFormatter&,
const data_model::VariableName&,
UErrorCode&) const;
// Avoids using Hashtable so that code constructing a Hashtable
// doesn't have to appear in this header file
LocalArray<UnicodeString> argumentNames;
LocalArray<Formattable> arguments;
int32_t argsLen = 0;
}; // class MessageArguments
} // namespace message2
U_NAMESPACE_END
#endif // U_HIDE_DEPRECATED_API
#endif /* #if !UCONFIG_NO_MF2 */
#endif /* #if !UCONFIG_NO_FORMATTING */
#endif /* #if !UCONFIG_NO_NORMALIZATION */
#endif /* U_SHOW_CPLUSPLUS_API */
#endif // MESSAGEFORMAT2_ARGUMENTS_H
// eof

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,42 @@
// © 2024 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
#include "unicode/utypes.h"
#ifndef MESSAGEFORMAT_DATA_MODEL_NAMES_H
#define MESSAGEFORMAT_DATA_MODEL_NAMES_H
#if U_SHOW_CPLUSPLUS_API
#if !UCONFIG_NO_FORMATTING
#if !UCONFIG_NO_MF2
#include "unicode/unistr.h"
#ifndef U_HIDE_DEPRECATED_API
U_NAMESPACE_BEGIN
namespace message2 {
namespace data_model {
typedef UnicodeString VariableName;
typedef UnicodeString FunctionName;
} // namespace data_model
} // namespace message2
U_NAMESPACE_END
#endif // U_HIDE_DEPRECATED_API
#endif /* #if !UCONFIG_NO_MF2 */
#endif /* #if !UCONFIG_NO_FORMATTING */
#endif /* U_SHOW_CPLUSPLUS_API */
#endif // MESSAGEFORMAT_DATA_MODEL_NAMES_H
// eof

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,433 @@
// © 2024 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
#include "unicode/utypes.h"
#ifndef MESSAGEFORMAT2_FUNCTION_REGISTRY_H
#define MESSAGEFORMAT2_FUNCTION_REGISTRY_H
#if U_SHOW_CPLUSPLUS_API
#if !UCONFIG_NO_NORMALIZATION
#if !UCONFIG_NO_FORMATTING
#if !UCONFIG_NO_MF2
#include "unicode/messageformat2_data_model_names.h"
#include "unicode/messageformat2_formattable.h"
#ifndef U_HIDE_DEPRECATED_API
#include <map>
U_NAMESPACE_BEGIN
class Hashtable;
class UVector;
namespace message2 {
using namespace data_model;
/**
* Interface that factory classes for creating formatters must implement.
*
* @internal ICU 75 technology preview
* @deprecated This API is for technology preview only.
*/
class U_I18N_API FormatterFactory : public UObject {
// TODO: the coding guidelines say that interface classes
// shouldn't inherit from UObject, but if I change it so these
// classes don't, and the individual formatter factory classes
// inherit from public FormatterFactory, public UObject, then
// memory leaks ensue
public:
/**
* Constructs a new formatter object. This method is not const;
* formatter factories with local state may be defined.
*
* @param locale Locale to be used by the formatter.
* @param status Input/output error code.
* @return The new Formatter, which is non-null if U_SUCCESS(status).
*
* @internal ICU 75 technology preview
* @deprecated This API is for technology preview only.
*/
virtual Formatter* createFormatter(const Locale& locale, UErrorCode& status) = 0;
/**
* Destructor.
*
* @internal ICU 75 technology preview
* @deprecated This API is for technology preview only.
*/
virtual ~FormatterFactory();
/**
* Copy constructor.
*
* @internal ICU 75 technology preview
* @deprecated This API is for technology preview only.
*/
FormatterFactory& operator=(const FormatterFactory&) = delete;
}; // class FormatterFactory
/**
* Interface that factory classes for creating selectors must implement.
*
* @internal ICU 75 technology preview
* @deprecated This API is for technology preview only.
*/
class U_I18N_API SelectorFactory : public UObject {
public:
/**
* Constructs a new selector object.
*
* @param locale Locale to be used by the selector.
* @param status Input/output error code.
* @return The new selector, which is non-null if U_SUCCESS(status).
*
* @internal ICU 75 technology preview
* @deprecated This API is for technology preview only.
*/
virtual Selector* createSelector(const Locale& locale, UErrorCode& status) const = 0;
/**
* Destructor.
*
* @internal ICU 75 technology preview
* @deprecated This API is for technology preview only.
*/
virtual ~SelectorFactory();
/**
* Copy constructor.
*
* @internal ICU 75 technology preview
* @deprecated This API is for technology preview only.
*/
SelectorFactory& operator=(const SelectorFactory&) = delete;
}; // class SelectorFactory
/**
* Defines mappings from names of formatters and selectors to functions implementing them.
* The required set of formatter and selector functions is defined in the spec. Users can
* also define custom formatter and selector functions.
*
* `MFFunctionRegistry` is immutable and movable. It is not copyable.
*
* @internal ICU 75 technology preview
* @deprecated This API is for technology preview only.
*/
class U_I18N_API MFFunctionRegistry : public UObject {
private:
using FormatterMap = Hashtable; // Map from stringified function names to FormatterFactory*
using SelectorMap = Hashtable; // Map from stringified function names to SelectorFactory*
public:
/**
* Looks up a formatter factory by the name of the formatter. The result is non-const,
* since formatter factories may have local state. Returns the result by pointer
* rather than by reference since it can fail.
*
* @param formatterName Name of the desired formatter.
* @return A pointer to the `FormatterFactory` registered under `formatterName`, or null
* if no formatter was registered under that name. The pointer is not owned
* by the caller.
*
* @internal ICU 75 technology preview
* @deprecated This API is for technology preview only.
*/
FormatterFactory* getFormatter(const FunctionName& formatterName) const;
/**
* Looks up a selector factory by the name of the selector. (This returns the result by pointer
* rather than by reference since `FormatterFactory` is an abstract class.)
*
* @param selectorName Name of the desired selector.
* @return A pointer to the `SelectorFactory` registered under `selectorName`, or null
* if no formatter was registered under that name.
*
* @internal ICU 75 technology preview
* @deprecated This API is for technology preview only.
*/
const SelectorFactory* getSelector(const FunctionName& selectorName) const;
/**
* Looks up a formatter factory by a type tag. This method gets the name of the default formatter registered
* for that type. If no formatter was explicitly registered for this type, it returns false.
*
* @param formatterType Type tag for the desired `FormattableObject` type to be formatted.
* @param name Output parameter; initialized to the name of the default formatter for `formatterType`
* if one has been registered. Its value is undefined otherwise.
* @return True if and only if the function registry contains a default formatter for `formatterType`.
* If the return value is false, then the value of `name` is undefined.
*
* @internal ICU 75 technology preview
* @deprecated This API is for technology preview only.
*/
UBool getDefaultFormatterNameByType(const UnicodeString& formatterType, FunctionName& name) const;
/**
* The mutable Builder class allows each formatter and selector factory
* to be initialized separately; calling its `build()` method yields an
* immutable MFFunctionRegistry object.
*
* Builder is not copyable or movable.
*
* @internal ICU 75 technology preview
* @deprecated This API is for technology preview only.
*/
class U_I18N_API Builder : public UObject {
private:
// Must use raw pointers to avoid instantiating `LocalPointer` on an internal type
FormatterMap* formatters;
SelectorMap* selectors;
Hashtable* formattersByType;
// Do not define copy constructor/assignment operator
Builder& operator=(const Builder&) = delete;
Builder(const Builder&) = delete;
public:
/*
Notes about `adoptFormatter()`'s type signature:
Alternative considered: take a non-owned FormatterFactory*
This is unsafe.
Alternative considered: take a FormatterFactory&
This requires getFormatter() to cast the reference to a pointer,
as it must return an unowned FormatterFactory* since it can fail.
That is also unsafe, since the caller could delete the pointer.
The "TemperatureFormatter" test from the previous ICU4J version doesn't work now,
as it only works if the `formatterFactory` argument is non-owned.
If registering a non-owned FormatterFactory is desirable, this could
be re-thought.
*/
/**
* Registers a formatter factory to a given formatter name.
*
* @param formatterName Name of the formatter being registered.
* @param formatterFactory A pointer to a FormatterFactory object to use
* for creating `formatterName` formatters. This argument is adopted.
* @param errorCode Input/output error code
* @return A reference to the builder.
*
* @internal ICU 75 technology preview
* @deprecated This API is for technology preview only.
*/
Builder& adoptFormatter(const data_model::FunctionName& formatterName, FormatterFactory* formatterFactory, UErrorCode& errorCode);
/**
* Registers a formatter factory to a given type tag.
* (See `FormattableObject` for details on type tags.)
*
* @param type Tag for objects to be formatted with this formatter.
* @param functionName A reference to the name of the function to use for
* creating formatters for `formatterType` objects.
* @param errorCode Input/output error code
* @return A reference to the builder.
*
* @internal ICU 75 technology preview
* @deprecated This API is for technology preview only.
*/
Builder& setDefaultFormatterNameByType(const UnicodeString& type, const data_model::FunctionName& functionName, UErrorCode& errorCode);
/**
* Registers a selector factory to a given selector name. Adopts `selectorFactory`.
*
* @param selectorName Name of the selector being registered.
* @param selectorFactory A SelectorFactory object to use for creating `selectorName`
* selectors.
* @param errorCode Input/output error code
* @return A reference to the builder.
*
* @internal ICU 75 technology preview
* @deprecated This API is for technology preview only.
*/
Builder& adoptSelector(const data_model::FunctionName& selectorName, SelectorFactory* selectorFactory, UErrorCode& errorCode);
/**
* Creates an immutable `MFFunctionRegistry` object with the selectors and formatters
* that were previously registered. The builder cannot be used after this call.
* The `build()` method is destructive to avoid the need for a deep copy of the
* `FormatterFactory` and `SelectorFactory` objects (this would be necessary because
* `FormatterFactory` can have mutable state), which in turn would require implementors
* of those interfaces to implement a `clone()` method.
*
* @return The new MFFunctionRegistry
*
* @internal ICU 75 technology preview
* @deprecated This API is for technology preview only.
*/
MFFunctionRegistry build();
/**
* Default constructor.
* Returns a Builder with no functions registered.
*
* @param errorCode Input/output error code
*
* @internal ICU 75 technology preview
* @deprecated This API is for technology preview only.
*/
Builder(UErrorCode& errorCode);
/**
* Destructor.
*
* @internal ICU 75 technology preview
* @deprecated This API is for technology preview only.
*/
virtual ~Builder();
}; // class MFFunctionRegistry::Builder
/**
* Move assignment operator:
* The source MFFunctionRegistry will be left in a valid but undefined state.
*
* @internal ICU 75 technology preview
* @deprecated This API is for technology preview only.
*/
MFFunctionRegistry& operator=(MFFunctionRegistry&&) noexcept;
/**
* Move constructor:
* The source MFFunctionRegistry will be left in a valid but undefined state.
*
* @internal ICU 75 technology preview
* @deprecated This API is for technology preview only.
*/
MFFunctionRegistry(MFFunctionRegistry&& other) { *this = std::move(other); }
/**
* Destructor.
*
* @internal ICU 75 technology preview
* @deprecated This API is for technology preview only.
*/
virtual ~MFFunctionRegistry();
private:
friend class MessageContext;
friend class MessageFormatter;
// Do not define copy constructor or copy assignment operator
MFFunctionRegistry& operator=(const MFFunctionRegistry&) = delete;
MFFunctionRegistry(const MFFunctionRegistry&) = delete;
MFFunctionRegistry(FormatterMap* f, SelectorMap* s, Hashtable* byType);
MFFunctionRegistry() {}
// Debugging; should only be called on a function registry with
// all the standard functions registered
void checkFormatter(const char*) const;
void checkSelector(const char*) const;
void checkStandard() const;
bool hasFormatter(const data_model::FunctionName& f) const;
bool hasSelector(const data_model::FunctionName& s) const;
void cleanup() noexcept;
// Must use raw pointers to avoid instantiating `LocalPointer` on an internal type
FormatterMap* formatters = nullptr;
SelectorMap* selectors = nullptr;
// Mapping from strings (type tags) to FunctionNames
Hashtable* formattersByType = nullptr;
}; // class MFFunctionRegistry
/**
* Interface that formatter classes must implement.
*
* @internal ICU 75 technology preview
* @deprecated This API is for technology preview only.
*/
class U_I18N_API Formatter : public UObject {
public:
/**
* Formats the input passed in `context` by setting an output using one of the
* `FormattingContext` methods or indicating an error.
*
* @param toFormat Placeholder, including a source formattable value and possibly
* the output of a previous formatter applied to it; see
* `message2::FormattedPlaceholder` for details. Passed by move.
* @param options The named function options. Passed by move
* @param status Input/output error code. Should not be set directly by the
* custom formatter, which should use `FormattingContext::setFormattingWarning()`
* to signal errors. The custom formatter may pass `status` to other ICU functions
* that can signal errors using this mechanism.
*
* @return The formatted value.
*
* @internal ICU 75 technology preview
* @deprecated This API is for technology preview only.
*/
virtual FormattedPlaceholder format(FormattedPlaceholder&& toFormat,
FunctionOptions&& options,
UErrorCode& status) const = 0;
/**
* Destructor.
*
* @internal ICU 75 technology preview
* @deprecated This API is for technology preview only.
*/
virtual ~Formatter();
}; // class Formatter
/**
* Interface that selector classes must implement.
*
* @internal ICU 75 technology preview
* @deprecated This API is for technology preview only.
*/
class U_I18N_API Selector : public UObject {
public:
/**
* Compares the input to an array of keys, and returns an array of matching
* keys sorted by preference.
*
* @param toFormat The unnamed function argument; passed by move.
* @param options A reference to the named function options.
* @param keys An array of strings that are compared to the input
* (`context.getFormattableInput()`) in an implementation-specific way.
* @param keysLen The length of `keys`.
* @param prefs An array of strings with length `keysLen`. The contents of
* the array is undefined. `selectKey()` should set the contents
* of `prefs` to a subset of `keys`, with the best match placed at the lowest index.
* @param prefsLen A reference that `selectKey()` should set to the length of `prefs`,
* which must be less than or equal to `keysLen`.
* @param status Input/output error code. Should not be set directly by the
* custom selector, which should use `FormattingContext::setSelectorError()`
* to signal errors. The custom selector may pass `status` to other ICU functions
* that can signal errors using this mechanism.
*
* @internal ICU 75 technology preview
* @deprecated This API is for technology preview only.
*/
virtual void selectKey(FormattedPlaceholder&& toFormat,
FunctionOptions&& options,
const UnicodeString* keys,
int32_t keysLen,
UnicodeString* prefs,
int32_t& prefsLen,
UErrorCode& status) const = 0;
// Note: This takes array arguments because the internal MessageFormat code has to
// call this method, and can't include any code that constructs std::vectors.
/**
* Destructor.
*
* @internal ICU 75 technology preview
* @deprecated This API is for technology preview only.
*/
virtual ~Selector();
}; // class Selector
} // namespace message2
U_NAMESPACE_END
#endif // U_HIDE_DEPRECATED_API
#endif /* #if !UCONFIG_NO_MF2 */
#endif /* #if !UCONFIG_NO_FORMATTING */
#endif /* #if !UCONFIG_NO_NORMALIZATION */
#endif /* U_SHOW_CPLUSPLUS_API */
#endif // MESSAGEFORMAT2_FUNCTION_REGISTRY_H
// eof

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,86 @@
// © 2017 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
/*
*******************************************************************************
* Copyright (C) 2009-2017, International Business Machines Corporation, *
* Google, and others. All Rights Reserved. *
*******************************************************************************
*/
#ifndef __NOUNIT_H__
#define __NOUNIT_H__
#include "unicode/utypes.h"
#if U_SHOW_CPLUSPLUS_API
#if !UCONFIG_NO_FORMATTING
#include "unicode/measunit.h"
/**
* \file
* \brief C++ API: units for percent and permille
*/
U_NAMESPACE_BEGIN
/**
* Dimensionless unit for percent and permille.
* Prior to ICU 68, this namespace was a class with the same name.
* @see NumberFormatter
* @stable ICU 68
*/
namespace NoUnit {
/**
* Returns an instance for the base unit (dimensionless and no scaling).
*
* Prior to ICU 68, this function returned a NoUnit by value.
*
* Since ICU 68, this function returns the same value as the default MeasureUnit constructor.
*
* @return a MeasureUnit instance
* @stable ICU 68
*/
static inline MeasureUnit U_EXPORT2 base() {
return {};
}
/**
* Returns an instance for percent, or 1/100 of a base unit.
*
* Prior to ICU 68, this function returned a NoUnit by value.
*
* Since ICU 68, this function returns the same value as MeasureUnit::getPercent().
*
* @return a MeasureUnit instance
* @stable ICU 68
*/
static inline MeasureUnit U_EXPORT2 percent() {
return MeasureUnit::getPercent();
}
/**
* Returns an instance for permille, or 1/1000 of a base unit.
*
* Prior to ICU 68, this function returned a NoUnit by value.
*
* Since ICU 68, this function returns the same value as MeasureUnit::getPermille().
*
* @return a MeasureUnit instance
* @stable ICU 68
*/
static inline MeasureUnit U_EXPORT2 permille() {
return MeasureUnit::getPermille();
}
}
U_NAMESPACE_END
#endif /* #if !UCONFIG_NO_FORMATTING */
#endif /* U_SHOW_CPLUSPLUS_API */
#endif // __NOUNIT_H__
//eof
//

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,792 @@
// © 2018 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
#ifndef __NUMBERRANGEFORMATTER_H__
#define __NUMBERRANGEFORMATTER_H__
#include "unicode/utypes.h"
#if U_SHOW_CPLUSPLUS_API
#if !UCONFIG_NO_FORMATTING
#include <atomic>
#include "unicode/appendable.h"
#include "unicode/fieldpos.h"
#include "unicode/formattedvalue.h"
#include "unicode/fpositer.h"
#include "unicode/numberformatter.h"
#include "unicode/unumberrangeformatter.h"
/**
* \file
* \brief C++ API: Library for localized formatting of number, currency, and unit ranges.
*
* The main entrypoint to the formatting of ranges of numbers, including currencies and other units of measurement.
* <p>
* Usage example:
* <p>
* <pre>
* NumberRangeFormatter::with()
* .identityFallback(UNUM_IDENTITY_FALLBACK_APPROXIMATELY_OR_SINGLE_VALUE)
* .numberFormatterFirst(NumberFormatter::with().adoptUnit(MeasureUnit::createMeter()))
* .numberFormatterSecond(NumberFormatter::with().adoptUnit(MeasureUnit::createKilometer()))
* .locale("en-GB")
* .formatFormattableRange(750, 1.2, status)
* .toString(status);
* // => "750 m - 1.2 km"
* </pre>
* <p>
* Like NumberFormatter, NumberRangeFormatter instances (i.e., LocalizedNumberRangeFormatter
* and UnlocalizedNumberRangeFormatter) are immutable and thread-safe. This API is based on the
* <em>fluent</em> design pattern popularized by libraries such as Google's Guava.
*
* @author Shane Carr
*/
U_NAMESPACE_BEGIN
// Forward declarations:
class PluralRules;
namespace number { // icu::number
// Forward declarations:
class UnlocalizedNumberRangeFormatter;
class LocalizedNumberRangeFormatter;
class FormattedNumberRange;
namespace impl {
// Forward declarations:
struct RangeMacroProps;
class DecimalQuantity;
class UFormattedNumberRangeData;
class NumberRangeFormatterImpl;
struct UFormattedNumberRangeImpl;
} // namespace impl
/**
* \cond
* Export an explicit template instantiation. See datefmt.h
* (When building DLLs for Windows this is required.)
*/
#if U_PLATFORM == U_PF_WINDOWS && !defined(U_IN_DOXYGEN) && !defined(U_STATIC_IMPLEMENTATION)
} // namespace icu::number
U_NAMESPACE_END
template struct U_I18N_API std::atomic< U_NAMESPACE_QUALIFIER number::impl::NumberRangeFormatterImpl*>;
U_NAMESPACE_BEGIN
namespace number { // icu::number
#endif
/** \endcond */
// Other helper classes would go here, but there are none.
namespace impl { // icu::number::impl
// Do not enclose entire MacroProps with #ifndef U_HIDE_INTERNAL_API, needed for a protected field
/** @internal */
struct U_I18N_API RangeMacroProps : public UMemory {
/** @internal */
UnlocalizedNumberFormatter formatter1; // = NumberFormatter::with();
/** @internal */
UnlocalizedNumberFormatter formatter2; // = NumberFormatter::with();
/** @internal */
bool singleFormatter = true;
/** @internal */
UNumberRangeCollapse collapse = UNUM_RANGE_COLLAPSE_AUTO;
/** @internal */
UNumberRangeIdentityFallback identityFallback = UNUM_IDENTITY_FALLBACK_APPROXIMATELY;
/** @internal */
Locale locale;
// NOTE: Uses default copy and move constructors.
/**
* Check all members for errors.
* @internal
*/
bool copyErrorTo(UErrorCode &status) const {
return formatter1.copyErrorTo(status) || formatter2.copyErrorTo(status);
}
};
} // namespace impl
/**
* An abstract base class for specifying settings related to number formatting. This class is implemented by
* {@link UnlocalizedNumberRangeFormatter} and {@link LocalizedNumberRangeFormatter}. This class is not intended for
* public subclassing.
*/
template<typename Derived>
class U_I18N_API NumberRangeFormatterSettings {
public:
/**
* Sets the NumberFormatter instance to use for the numbers in the range. The same formatter is applied to both
* sides of the range.
* <p>
* The NumberFormatter instances must not have a locale applied yet; the locale specified on the
* NumberRangeFormatter will be used.
*
* @param formatter
* The formatter to use for both numbers in the range.
* @return The fluent chain.
* @stable ICU 63
*/
Derived numberFormatterBoth(const UnlocalizedNumberFormatter &formatter) const &;
/**
* Overload of numberFormatterBoth() for use on an rvalue reference.
*
* @param formatter
* The formatter to use for both numbers in the range.
* @return The fluent chain.
* @see #numberFormatterBoth
* @stable ICU 63
*/
Derived numberFormatterBoth(const UnlocalizedNumberFormatter &formatter) &&;
/**
* Overload of numberFormatterBoth() for use on an rvalue reference.
*
* @param formatter
* The formatter to use for both numbers in the range.
* @return The fluent chain.
* @see #numberFormatterBoth
* @stable ICU 63
*/
Derived numberFormatterBoth(UnlocalizedNumberFormatter &&formatter) const &;
/**
* Overload of numberFormatterBoth() for use on an rvalue reference.
*
* @param formatter
* The formatter to use for both numbers in the range.
* @return The fluent chain.
* @see #numberFormatterBoth
* @stable ICU 63
*/
Derived numberFormatterBoth(UnlocalizedNumberFormatter &&formatter) &&;
/**
* Sets the NumberFormatter instance to use for the first number in the range.
* <p>
* The NumberFormatter instances must not have a locale applied yet; the locale specified on the
* NumberRangeFormatter will be used.
*
* @param formatterFirst
* The formatter to use for the first number in the range.
* @return The fluent chain.
* @stable ICU 63
*/
Derived numberFormatterFirst(const UnlocalizedNumberFormatter &formatterFirst) const &;
/**
* Overload of numberFormatterFirst() for use on an rvalue reference.
*
* @param formatterFirst
* The formatter to use for the first number in the range.
* @return The fluent chain.
* @see #numberFormatterFirst
* @stable ICU 63
*/
Derived numberFormatterFirst(const UnlocalizedNumberFormatter &formatterFirst) &&;
/**
* Overload of numberFormatterFirst() for use on an rvalue reference.
*
* @param formatterFirst
* The formatter to use for the first number in the range.
* @return The fluent chain.
* @see #numberFormatterFirst
* @stable ICU 63
*/
Derived numberFormatterFirst(UnlocalizedNumberFormatter &&formatterFirst) const &;
/**
* Overload of numberFormatterFirst() for use on an rvalue reference.
*
* @param formatterFirst
* The formatter to use for the first number in the range.
* @return The fluent chain.
* @see #numberFormatterFirst
* @stable ICU 63
*/
Derived numberFormatterFirst(UnlocalizedNumberFormatter &&formatterFirst) &&;
/**
* Sets the NumberFormatter instance to use for the second number in the range.
* <p>
* The NumberFormatter instances must not have a locale applied yet; the locale specified on the
* NumberRangeFormatter will be used.
*
* @param formatterSecond
* The formatter to use for the second number in the range.
* @return The fluent chain.
* @stable ICU 63
*/
Derived numberFormatterSecond(const UnlocalizedNumberFormatter &formatterSecond) const &;
/**
* Overload of numberFormatterSecond() for use on an rvalue reference.
*
* @param formatterSecond
* The formatter to use for the second number in the range.
* @return The fluent chain.
* @see #numberFormatterSecond
* @stable ICU 63
*/
Derived numberFormatterSecond(const UnlocalizedNumberFormatter &formatterSecond) &&;
/**
* Overload of numberFormatterSecond() for use on an rvalue reference.
*
* @param formatterSecond
* The formatter to use for the second number in the range.
* @return The fluent chain.
* @see #numberFormatterSecond
* @stable ICU 63
*/
Derived numberFormatterSecond(UnlocalizedNumberFormatter &&formatterSecond) const &;
/**
* Overload of numberFormatterSecond() for use on an rvalue reference.
*
* @param formatterSecond
* The formatter to use for the second number in the range.
* @return The fluent chain.
* @see #numberFormatterSecond
* @stable ICU 63
*/
Derived numberFormatterSecond(UnlocalizedNumberFormatter &&formatterSecond) &&;
/**
* Sets the aggressiveness of "collapsing" fields across the range separator. Possible values:
* <p>
* <ul>
* <li>ALL: "3-5K miles"</li>
* <li>UNIT: "3K - 5K miles"</li>
* <li>NONE: "3K miles - 5K miles"</li>
* <li>AUTO: usually UNIT or NONE, depending on the locale and formatter settings</li>
* </ul>
* <p>
* The default value is AUTO.
*
* @param collapse
* The collapsing strategy to use for this range.
* @return The fluent chain.
* @stable ICU 63
*/
Derived collapse(UNumberRangeCollapse collapse) const &;
/**
* Overload of collapse() for use on an rvalue reference.
*
* @param collapse
* The collapsing strategy to use for this range.
* @return The fluent chain.
* @see #collapse
* @stable ICU 63
*/
Derived collapse(UNumberRangeCollapse collapse) &&;
/**
* Sets the behavior when the two sides of the range are the same. This could happen if the same two numbers are
* passed to the formatFormattableRange function, or if different numbers are passed to the function but they
* become the same after rounding rules are applied. Possible values:
* <p>
* <ul>
* <li>SINGLE_VALUE: "5 miles"</li>
* <li>APPROXIMATELY_OR_SINGLE_VALUE: "~5 miles" or "5 miles", depending on whether the number was the same before
* rounding was applied</li>
* <li>APPROXIMATELY: "~5 miles"</li>
* <li>RANGE: "5-5 miles" (with collapse=UNIT)</li>
* </ul>
* <p>
* The default value is APPROXIMATELY.
*
* @param identityFallback
* The strategy to use when formatting two numbers that end up being the same.
* @return The fluent chain.
* @stable ICU 63
*/
Derived identityFallback(UNumberRangeIdentityFallback identityFallback) const &;
/**
* Overload of identityFallback() for use on an rvalue reference.
*
* @param identityFallback
* The strategy to use when formatting two numbers that end up being the same.
* @return The fluent chain.
* @see #identityFallback
* @stable ICU 63
*/
Derived identityFallback(UNumberRangeIdentityFallback identityFallback) &&;
/**
* Returns the current (Un)LocalizedNumberRangeFormatter as a LocalPointer
* wrapping a heap-allocated copy of the current object.
*
* This is equivalent to new-ing the move constructor with a value object
* as the argument.
*
* @return A wrapped (Un)LocalizedNumberRangeFormatter pointer, or a wrapped
* nullptr on failure.
* @stable ICU 64
*/
LocalPointer<Derived> clone() const &;
/**
* Overload of clone for use on an rvalue reference.
*
* @return A wrapped (Un)LocalizedNumberRangeFormatter pointer, or a wrapped
* nullptr on failure.
* @stable ICU 64
*/
LocalPointer<Derived> clone() &&;
/**
* Sets the UErrorCode if an error occurred in the fluent chain.
* Preserves older error codes in the outErrorCode.
* @return true if U_FAILURE(outErrorCode)
* @stable ICU 63
*/
UBool copyErrorTo(UErrorCode &outErrorCode) const {
if (U_FAILURE(outErrorCode)) {
// Do not overwrite the older error code
return true;
}
fMacros.copyErrorTo(outErrorCode);
return U_FAILURE(outErrorCode);
}
// NOTE: Uses default copy and move constructors.
private:
impl::RangeMacroProps fMacros;
// Don't construct me directly! Use (Un)LocalizedNumberFormatter.
NumberRangeFormatterSettings() = default;
friend class LocalizedNumberRangeFormatter;
friend class UnlocalizedNumberRangeFormatter;
};
// Explicit instantiations in source/i18n/numrange_fluent.cpp.
// (MSVC treats imports/exports of explicit instantiations differently.)
#ifndef _MSC_VER
extern template class NumberRangeFormatterSettings<UnlocalizedNumberRangeFormatter>;
extern template class NumberRangeFormatterSettings<LocalizedNumberRangeFormatter>;
#endif
/**
* A NumberRangeFormatter that does not yet have a locale. In order to format, a locale must be specified.
*
* Instances of this class are immutable and thread-safe.
*
* @see NumberRangeFormatter
* @stable ICU 63
*/
class U_I18N_API UnlocalizedNumberRangeFormatter
: public NumberRangeFormatterSettings<UnlocalizedNumberRangeFormatter>, public UMemory {
public:
/**
* Associate the given locale with the number range formatter. The locale is used for picking the
* appropriate symbols, formats, and other data for number display.
*
* @param locale
* The locale to use when loading data for number formatting.
* @return The fluent chain.
* @stable ICU 63
*/
LocalizedNumberRangeFormatter locale(const icu::Locale &locale) const &;
/**
* Overload of locale() for use on an rvalue reference.
*
* @param locale
* The locale to use when loading data for number formatting.
* @return The fluent chain.
* @see #locale
* @stable ICU 63
*/
LocalizedNumberRangeFormatter locale(const icu::Locale &locale) &&;
/**
* Default constructor: puts the formatter into a valid but undefined state.
*
* @stable ICU 63
*/
UnlocalizedNumberRangeFormatter() = default;
/**
* Returns a copy of this UnlocalizedNumberRangeFormatter.
* @stable ICU 63
*/
UnlocalizedNumberRangeFormatter(const UnlocalizedNumberRangeFormatter &other);
/**
* Move constructor:
* The source UnlocalizedNumberRangeFormatter will be left in a valid but undefined state.
* @stable ICU 63
*/
UnlocalizedNumberRangeFormatter(UnlocalizedNumberRangeFormatter&& src) noexcept;
/**
* Copy assignment operator.
* @stable ICU 63
*/
UnlocalizedNumberRangeFormatter& operator=(const UnlocalizedNumberRangeFormatter& other);
/**
* Move assignment operator:
* The source UnlocalizedNumberRangeFormatter will be left in a valid but undefined state.
* @stable ICU 63
*/
UnlocalizedNumberRangeFormatter& operator=(UnlocalizedNumberRangeFormatter&& src) noexcept;
private:
explicit UnlocalizedNumberRangeFormatter(
const NumberRangeFormatterSettings<UnlocalizedNumberRangeFormatter>& other);
explicit UnlocalizedNumberRangeFormatter(
NumberRangeFormatterSettings<UnlocalizedNumberRangeFormatter>&& src) noexcept;
explicit UnlocalizedNumberRangeFormatter(const impl::RangeMacroProps &macros);
explicit UnlocalizedNumberRangeFormatter(impl::RangeMacroProps &&macros);
// To give the fluent setters access to this class's constructor:
friend class NumberRangeFormatterSettings<UnlocalizedNumberRangeFormatter>;
// To give NumberRangeFormatter::with() access to this class's constructor:
friend class NumberRangeFormatter;
// To give LNRF::withoutLocale() access to this class's constructor:
friend class LocalizedNumberRangeFormatter;
};
/**
* A NumberRangeFormatter that has a locale associated with it; this means .formatRange() methods are available.
*
* Instances of this class are immutable and thread-safe.
*
* @see NumberFormatter
* @stable ICU 63
*/
class U_I18N_API LocalizedNumberRangeFormatter
: public NumberRangeFormatterSettings<LocalizedNumberRangeFormatter>, public UMemory {
public:
/**
* Format the given Formattables to a string using the settings specified in the NumberRangeFormatter fluent setting
* chain.
*
* @param first
* The first number in the range, usually to the left in LTR locales.
* @param second
* The second number in the range, usually to the right in LTR locales.
* @param status
* Set if an error occurs while formatting.
* @return A FormattedNumberRange object; call .toString() to get the string.
* @stable ICU 63
*/
FormattedNumberRange formatFormattableRange(
const Formattable& first, const Formattable& second, UErrorCode& status) const;
/**
* Disassociate the locale from this formatter.
*
* @return The fluent chain.
* @stable ICU 75
*/
UnlocalizedNumberRangeFormatter withoutLocale() const &;
/**
* Overload of withoutLocale() for use on an rvalue reference.
*
* @return The fluent chain.
* @see #withoutLocale
* @stable ICU 75
*/
UnlocalizedNumberRangeFormatter withoutLocale() &&;
/**
* Default constructor: puts the formatter into a valid but undefined state.
*
* @stable ICU 63
*/
LocalizedNumberRangeFormatter() = default;
/**
* Returns a copy of this LocalizedNumberRangeFormatter.
* @stable ICU 63
*/
LocalizedNumberRangeFormatter(const LocalizedNumberRangeFormatter &other);
/**
* Move constructor:
* The source LocalizedNumberRangeFormatter will be left in a valid but undefined state.
* @stable ICU 63
*/
LocalizedNumberRangeFormatter(LocalizedNumberRangeFormatter&& src) noexcept;
/**
* Copy assignment operator.
* @stable ICU 63
*/
LocalizedNumberRangeFormatter& operator=(const LocalizedNumberRangeFormatter& other);
/**
* Move assignment operator:
* The source LocalizedNumberRangeFormatter will be left in a valid but undefined state.
* @stable ICU 63
*/
LocalizedNumberRangeFormatter& operator=(LocalizedNumberRangeFormatter&& src) noexcept;
#ifndef U_HIDE_INTERNAL_API
/**
* @param results
* The results object. This method will mutate it to save the results.
* @param equalBeforeRounding
* Whether the number was equal before copying it into a DecimalQuantity.
* Used for determining the identity fallback behavior.
* @param status
* Set if an error occurs while formatting.
* @internal
*/
void formatImpl(impl::UFormattedNumberRangeData& results, bool equalBeforeRounding,
UErrorCode& status) const;
#endif /* U_HIDE_INTERNAL_API */
/**
* Destruct this LocalizedNumberRangeFormatter, cleaning up any memory it might own.
* @stable ICU 63
*/
~LocalizedNumberRangeFormatter();
private:
std::atomic<impl::NumberRangeFormatterImpl*> fAtomicFormatter = {};
const impl::NumberRangeFormatterImpl* getFormatter(UErrorCode& stauts) const;
explicit LocalizedNumberRangeFormatter(
const NumberRangeFormatterSettings<LocalizedNumberRangeFormatter>& other);
explicit LocalizedNumberRangeFormatter(
NumberRangeFormatterSettings<LocalizedNumberRangeFormatter>&& src) noexcept;
LocalizedNumberRangeFormatter(const impl::RangeMacroProps &macros, const Locale &locale);
LocalizedNumberRangeFormatter(impl::RangeMacroProps &&macros, const Locale &locale);
// To give the fluent setters access to this class's constructor:
friend class NumberRangeFormatterSettings<UnlocalizedNumberRangeFormatter>;
friend class NumberRangeFormatterSettings<LocalizedNumberRangeFormatter>;
// To give UnlocalizedNumberRangeFormatter::locale() access to this class's constructor:
friend class UnlocalizedNumberRangeFormatter;
};
/**
* The result of a number range formatting operation. This class allows the result to be exported in several data types,
* including a UnicodeString and a FieldPositionIterator.
*
* Instances of this class are immutable and thread-safe.
*
* @stable ICU 63
*/
class U_I18N_API FormattedNumberRange : public UMemory, public FormattedValue {
public:
// Copybrief: this method is older than the parent method
/**
* @copybrief FormattedValue::toString()
*
* For more information, see FormattedValue::toString()
*
* @stable ICU 63
*/
UnicodeString toString(UErrorCode& status) const override;
// Copydoc: this method is new in ICU 64
/** @copydoc FormattedValue::toTempString() */
UnicodeString toTempString(UErrorCode& status) const override;
// Copybrief: this method is older than the parent method
/**
* @copybrief FormattedValue::appendTo()
*
* For more information, see FormattedValue::appendTo()
*
* @stable ICU 63
*/
Appendable &appendTo(Appendable &appendable, UErrorCode& status) const override;
// Copydoc: this method is new in ICU 64
/** @copydoc FormattedValue::nextPosition() */
UBool nextPosition(ConstrainedFieldPosition& cfpos, UErrorCode& status) const override;
/**
* Extracts the formatted range as a pair of decimal numbers. This endpoint
* is useful for obtaining the exact number being printed after scaling
* and rounding have been applied by the number range formatting pipeline.
*
* The syntax of the unformatted numbers is a "numeric string"
* as defined in the Decimal Arithmetic Specification, available at
* http://speleotrove.com/decimal
*
* Example C++17 call site:
*
* auto [ first, second ] = range.getDecimalNumbers<std::string>(status);
*
* @tparam StringClass A string class compatible with StringByteSink;
* for example, std::string.
* @param status Set if an error occurs.
* @return A pair of StringClasses containing the numeric strings.
* @stable ICU 68
*/
template<typename StringClass>
inline std::pair<StringClass, StringClass> getDecimalNumbers(UErrorCode& status) const;
/**
* Returns whether the pair of numbers was successfully formatted as a range or whether an identity fallback was
* used. For example, if the first and second number were the same either before or after rounding occurred, an
* identity fallback was used.
*
* @return An indication the resulting identity situation in the formatted number range.
* @stable ICU 63
* @see UNumberRangeIdentityFallback
*/
UNumberRangeIdentityResult getIdentityResult(UErrorCode& status) const;
/**
* Default constructor; makes an empty FormattedNumberRange.
* @stable ICU 70
*/
FormattedNumberRange()
: fData(nullptr), fErrorCode(U_INVALID_STATE_ERROR) {}
/**
* Copying not supported; use move constructor instead.
*/
FormattedNumberRange(const FormattedNumberRange&) = delete;
/**
* Copying not supported; use move assignment instead.
*/
FormattedNumberRange& operator=(const FormattedNumberRange&) = delete;
/**
* Move constructor:
* Leaves the source FormattedNumberRange in an undefined state.
* @stable ICU 63
*/
FormattedNumberRange(FormattedNumberRange&& src) noexcept;
/**
* Move assignment:
* Leaves the source FormattedNumberRange in an undefined state.
* @stable ICU 63
*/
FormattedNumberRange& operator=(FormattedNumberRange&& src) noexcept;
/**
* Destruct an instance of FormattedNumberRange, cleaning up any memory it might own.
* @stable ICU 63
*/
~FormattedNumberRange();
private:
// Can't use LocalPointer because UFormattedNumberRangeData is forward-declared
const impl::UFormattedNumberRangeData *fData;
// Error code for the terminal methods
UErrorCode fErrorCode;
/**
* Internal constructor from data type. Adopts the data pointer.
*/
explicit FormattedNumberRange(impl::UFormattedNumberRangeData *results)
: fData(results), fErrorCode(U_ZERO_ERROR) {}
explicit FormattedNumberRange(UErrorCode errorCode)
: fData(nullptr), fErrorCode(errorCode) {}
void getDecimalNumbers(ByteSink& sink1, ByteSink& sink2, UErrorCode& status) const;
const impl::UFormattedNumberRangeData* getData(UErrorCode& status) const;
// To allow PluralRules to access the underlying data
friend class ::icu::PluralRules;
// To give LocalizedNumberRangeFormatter format methods access to this class's constructor:
friend class LocalizedNumberRangeFormatter;
// To give C API access to internals
friend struct impl::UFormattedNumberRangeImpl;
};
// inline impl of @stable ICU 68 method
template<typename StringClass>
std::pair<StringClass, StringClass> FormattedNumberRange::getDecimalNumbers(UErrorCode& status) const {
StringClass str1;
StringClass str2;
StringByteSink<StringClass> sink1(&str1);
StringByteSink<StringClass> sink2(&str2);
getDecimalNumbers(sink1, sink2, status);
return std::make_pair(str1, str2);
}
/**
* See the main description in numberrangeformatter.h for documentation and examples.
*
* @stable ICU 63
*/
class U_I18N_API NumberRangeFormatter final {
public:
/**
* Call this method at the beginning of a NumberRangeFormatter fluent chain in which the locale is not currently
* known at the call site.
*
* @return An {@link UnlocalizedNumberRangeFormatter}, to be used for chaining.
* @stable ICU 63
*/
static UnlocalizedNumberRangeFormatter with();
/**
* Call this method at the beginning of a NumberRangeFormatter fluent chain in which the locale is known at the call
* site.
*
* @param locale
* The locale from which to load formats and symbols for number range formatting.
* @return A {@link LocalizedNumberRangeFormatter}, to be used for chaining.
* @stable ICU 63
*/
static LocalizedNumberRangeFormatter withLocale(const Locale &locale);
/**
* Use factory methods instead of the constructor to create a NumberFormatter.
*/
NumberRangeFormatter() = delete;
};
} // namespace number
U_NAMESPACE_END
#endif /* #if !UCONFIG_NO_FORMATTING */
#endif /* U_SHOW_CPLUSPLUS_API */
#endif // __NUMBERRANGEFORMATTER_H__

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,220 @@
// © 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
/*
*******************************************************************************
* Copyright (C) 2010-2014, International Business Machines Corporation and
* others. All Rights Reserved.
*******************************************************************************
*
*
* File NUMSYS.H
*
* Modification History:*
* Date Name Description
*
********************************************************************************
*/
#ifndef NUMSYS
#define NUMSYS
#include "unicode/utypes.h"
#if U_SHOW_CPLUSPLUS_API
/**
* \file
* \brief C++ API: NumberingSystem object
*/
#if !UCONFIG_NO_FORMATTING
#include "unicode/format.h"
#include "unicode/uobject.h"
U_NAMESPACE_BEGIN
// can't be #ifndef U_HIDE_INTERNAL_API; needed for char[] field size
/**
* Size of a numbering system name.
* @internal
*/
constexpr const size_t kInternalNumSysNameCapacity = 8;
/**
* Defines numbering systems. A numbering system describes the scheme by which
* numbers are to be presented to the end user. In its simplest form, a numbering
* system describes the set of digit characters that are to be used to display
* numbers, such as Western digits, Thai digits, Arabic-Indic digits, etc., in a
* positional numbering system with a specified radix (typically 10).
* More complicated numbering systems are algorithmic in nature, and require use
* of an RBNF formatter ( rule based number formatter ), in order to calculate
* the characters to be displayed for a given number. Examples of algorithmic
* numbering systems include Roman numerals, Chinese numerals, and Hebrew numerals.
* Formatting rules for many commonly used numbering systems are included in
* the ICU package, based on the numbering system rules defined in CLDR.
* Alternate numbering systems can be specified to a locale by using the
* numbers locale keyword.
*/
class U_I18N_API NumberingSystem : public UObject {
public:
/**
* Default Constructor.
*
* @stable ICU 4.2
*/
NumberingSystem();
/**
* Copy constructor.
* @stable ICU 4.2
*/
NumberingSystem(const NumberingSystem& other);
/**
* Copy assignment.
* @stable ICU 4.2
*/
NumberingSystem& operator=(const NumberingSystem& other) = default;
/**
* Destructor.
* @stable ICU 4.2
*/
virtual ~NumberingSystem();
/**
* Create the default numbering system associated with the specified locale.
* @param inLocale The given locale.
* @param status ICU status
* @stable ICU 4.2
*/
static NumberingSystem* U_EXPORT2 createInstance(const Locale & inLocale, UErrorCode& status);
/**
* Create the default numbering system associated with the default locale.
* @stable ICU 4.2
*/
static NumberingSystem* U_EXPORT2 createInstance(UErrorCode& status);
/**
* Create a numbering system using the specified radix, type, and description.
* @param radix The radix (base) for this numbering system.
* @param isAlgorithmic true if the numbering system is algorithmic rather than numeric.
* @param description The string representing the set of digits used in a numeric system, or the name of the RBNF
* ruleset to be used in an algorithmic system.
* @param status ICU status
* @stable ICU 4.2
*/
static NumberingSystem* U_EXPORT2 createInstance(int32_t radix, UBool isAlgorithmic, const UnicodeString& description, UErrorCode& status );
/**
* Return a StringEnumeration over all the names of numbering systems known to ICU.
* The numbering system names will be in alphabetical (invariant) order.
*
* The returned StringEnumeration is owned by the caller, who must delete it when
* finished with it.
*
* @stable ICU 4.2
*/
static StringEnumeration * U_EXPORT2 getAvailableNames(UErrorCode& status);
/**
* Create a numbering system from one of the predefined numbering systems specified
* by CLDR and known to ICU, such as "latn", "arabext", or "hanidec"; the full list
* is returned by unumsys_openAvailableNames. Note that some of the names listed at
* http://unicode.org/repos/cldr/tags/latest/common/bcp47/number.xml - e.g.
* default, native, traditional, finance - do not identify specific numbering systems,
* but rather key values that may only be used as part of a locale, which in turn
* defines how they are mapped to a specific numbering system such as "latn" or "hant".
*
* @param name The name of the numbering system.
* @param status ICU status; set to U_UNSUPPORTED_ERROR if numbering system not found.
* @return The NumberingSystem instance, or nullptr if not found.
* @stable ICU 4.2
*/
static NumberingSystem* U_EXPORT2 createInstanceByName(const char* name, UErrorCode& status);
/**
* Returns the radix of this numbering system. Simple positional numbering systems
* typically have radix 10, but might have a radix of e.g. 16 for hexadecimal. The
* radix is less well-defined for non-positional algorithmic systems.
* @stable ICU 4.2
*/
int32_t getRadix() const;
/**
* Returns the name of this numbering system if it was created using one of the predefined names
* known to ICU. Otherwise, returns nullptr.
* The predefined names are identical to the numbering system names as defined by
* the BCP47 definition in Unicode CLDR.
* See also, http://www.unicode.org/repos/cldr/tags/latest/common/bcp47/number.xml
* @stable ICU 4.6
*/
const char * getName() const;
/**
* Returns the description string of this numbering system. For simple
* positional systems this is the ordered string of digits (with length matching
* the radix), e.g. "\u3007\u4E00\u4E8C\u4E09\u56DB\u4E94\u516D\u4E03\u516B\u4E5D"
* for "hanidec"; it would be "0123456789ABCDEF" for hexadecimal. For
* algorithmic systems this is the name of the RBNF ruleset used for formatting,
* e.g. "zh/SpelloutRules/%spellout-cardinal" for "hans" or "%greek-upper" for
* "grek".
* @stable ICU 4.2
*/
virtual UnicodeString getDescription() const;
/**
* Returns true if the given numbering system is algorithmic
*
* @return true if the numbering system is algorithmic.
* Otherwise, return false.
* @stable ICU 4.2
*/
UBool isAlgorithmic() const;
/**
* ICU "poor man's RTTI", returns a UClassID for this class.
*
* @stable ICU 4.2
*
*/
static UClassID U_EXPORT2 getStaticClassID();
/**
* ICU "poor man's RTTI", returns a UClassID for the actual class.
*
* @stable ICU 4.2
*/
virtual UClassID getDynamicClassID() const override;
private:
UnicodeString desc;
int32_t radix;
UBool algorithmic;
char name[kInternalNumSysNameCapacity+1];
void setRadix(int32_t radix);
void setAlgorithmic(UBool algorithmic);
void setDesc(const UnicodeString &desc);
void setName(const char* name);
};
U_NAMESPACE_END
#endif /* #if !UCONFIG_NO_FORMATTING */
#endif /* U_SHOW_CPLUSPLUS_API */
#endif // _NUMSYS
//eof

View File

@ -0,0 +1,601 @@
// © 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
/*
*******************************************************************************
* Copyright (C) 2007-2014, International Business Machines Corporation and
* others. All Rights Reserved.
*******************************************************************************
*
* File PLURFMT.H
********************************************************************************
*/
#ifndef PLURFMT
#define PLURFMT
#include "unicode/utypes.h"
#if U_SHOW_CPLUSPLUS_API
/**
* \file
* \brief C++ API: PluralFormat object
*/
#if !UCONFIG_NO_FORMATTING
#include "unicode/messagepattern.h"
#include "unicode/numfmt.h"
#include "unicode/plurrule.h"
U_NAMESPACE_BEGIN
class Hashtable;
class NFRule;
/**
* <p>
* <code>PluralFormat</code> supports the creation of internationalized
* messages with plural inflection. It is based on <i>plural
* selection</i>, i.e. the caller specifies messages for each
* plural case that can appear in the user's language and the
* <code>PluralFormat</code> selects the appropriate message based on
* the number.
* </p>
* <h4>The Problem of Plural Forms in Internationalized Messages</h4>
* <p>
* Different languages have different ways to inflect
* plurals. Creating internationalized messages that include plural
* forms is only feasible when the framework is able to handle plural
* forms of <i>all</i> languages correctly. <code>ChoiceFormat</code>
* doesn't handle this well, because it attaches a number interval to
* each message and selects the message whose interval contains a
* given number. This can only handle a finite number of
* intervals. But in some languages, like Polish, one plural case
* applies to infinitely many intervals (e.g., the plural case applies to
* numbers ending with 2, 3, or 4 except those ending with 12, 13, or
* 14). Thus <code>ChoiceFormat</code> is not adequate.
* </p><p>
* <code>PluralFormat</code> deals with this by breaking the problem
* into two parts:
* <ul>
* <li>It uses <code>PluralRules</code> that can define more complex
* conditions for a plural case than just a single interval. These plural
* rules define both what plural cases exist in a language, and to
* which numbers these cases apply.
* <li>It provides predefined plural rules for many languages. Thus, the programmer
* need not worry about the plural cases of a language and
* does not have to define the plural cases; they can simply
* use the predefined keywords. The whole plural formatting of messages can
* be done using localized patterns from resource bundles. For predefined plural
* rules, see the CLDR <i>Language Plural Rules</i> page at
* https://unicode-org.github.io/cldr-staging/charts/latest/supplemental/language_plural_rules.html
* </ul>
* </p>
* <h4>Usage of <code>PluralFormat</code></h4>
* <p>Note: Typically, plural formatting is done via <code>MessageFormat</code>
* with a <code>plural</code> argument type,
* rather than using a stand-alone <code>PluralFormat</code>.
* </p><p>
* This discussion assumes that you use <code>PluralFormat</code> with
* a predefined set of plural rules. You can create one using one of
* the constructors that takes a <code>locale</code> object. To
* specify the message pattern, you can either pass it to the
* constructor or set it explicitly using the
* <code>applyPattern()</code> method. The <code>format()</code>
* method takes a number object and selects the message of the
* matching plural case. This message will be returned.
* </p>
* <h5>Patterns and Their Interpretation</h5>
* <p>
* The pattern text defines the message output for each plural case of the
* specified locale. Syntax:
* <pre>
* pluralStyle = [offsetValue] (selector '{' message '}')+
* offsetValue = "offset:" number
* selector = explicitValue | keyword
* explicitValue = '=' number // adjacent, no white space in between
* keyword = [^[[:Pattern_Syntax:][:Pattern_White_Space:]]]+
* message: see {@link MessageFormat}
* </pre>
* Pattern_White_Space between syntax elements is ignored, except
* between the {curly braces} and their sub-message,
* and between the '=' and the number of an explicitValue.
*
* </p><p>
* There are 6 predefined casekeyword in CLDR/ICU - 'zero', 'one', 'two', 'few', 'many' and
* 'other'. You always have to define a message text for the default plural case
* <code>other</code> which is contained in every rule set.
* If you do not specify a message text for a particular plural case, the
* message text of the plural case <code>other</code> gets assigned to this
* plural case.
* </p><p>
* When formatting, the input number is first matched against the explicitValue clauses.
* If there is no exact-number match, then a keyword is selected by calling
* the <code>PluralRules</code> with the input number <em>minus the offset</em>.
* (The offset defaults to 0 if it is omitted from the pattern string.)
* If there is no clause with that keyword, then the "other" clauses is returned.
* </p><p>
* An unquoted pound sign (<code>#</code>) in the selected sub-message
* itself (i.e., outside of arguments nested in the sub-message)
* is replaced by the input number minus the offset.
* The number-minus-offset value is formatted using a
* <code>NumberFormat</code> for the <code>PluralFormat</code>'s locale. If you
* need special number formatting, you have to use a <code>MessageFormat</code>
* and explicitly specify a <code>NumberFormat</code> argument.
* <strong>Note:</strong> That argument is formatting without subtracting the offset!
* If you need a custom format and have a non-zero offset, then you need to pass the
* number-minus-offset value as a separate parameter.
* </p>
* For a usage example, see the {@link MessageFormat} class documentation.
*
* <h4>Defining Custom Plural Rules</h4>
* <p>If you need to use <code>PluralFormat</code> with custom rules, you can
* create a <code>PluralRules</code> object and pass it to
* <code>PluralFormat</code>'s constructor. If you also specify a locale in this
* constructor, this locale will be used to format the number in the message
* texts.
* </p><p>
* For more information about <code>PluralRules</code>, see
* {@link PluralRules}.
* </p>
*
* ported from Java
* @stable ICU 4.0
*/
class U_I18N_API PluralFormat : public Format {
public:
/**
* Creates a new cardinal-number <code>PluralFormat</code> for the default locale.
* This locale will be used to get the set of plural rules and for standard
* number formatting.
* @param status output param set to success/failure code on exit, which
* must not indicate a failure before the function call.
* @stable ICU 4.0
*/
PluralFormat(UErrorCode& status);
/**
* Creates a new cardinal-number <code>PluralFormat</code> for a given locale.
* @param locale the <code>PluralFormat</code> will be configured with
* rules for this locale. This locale will also be used for
* standard number formatting.
* @param status output param set to success/failure code on exit, which
* must not indicate a failure before the function call.
* @stable ICU 4.0
*/
PluralFormat(const Locale& locale, UErrorCode& status);
/**
* Creates a new <code>PluralFormat</code> for a given set of rules.
* The standard number formatting will be done using the default locale.
* @param rules defines the behavior of the <code>PluralFormat</code>
* object.
* @param status output param set to success/failure code on exit, which
* must not indicate a failure before the function call.
* @stable ICU 4.0
*/
PluralFormat(const PluralRules& rules, UErrorCode& status);
/**
* Creates a new <code>PluralFormat</code> for a given set of rules.
* The standard number formatting will be done using the given locale.
* @param locale the default number formatting will be done using this
* locale.
* @param rules defines the behavior of the <code>PluralFormat</code>
* object.
* @param status output param set to success/failure code on exit, which
* must not indicate a failure before the function call.
* @stable ICU 4.0
*/
PluralFormat(const Locale& locale, const PluralRules& rules, UErrorCode& status);
/**
* Creates a new <code>PluralFormat</code> for the plural type.
* The standard number formatting will be done using the given locale.
* @param locale the default number formatting will be done using this
* locale.
* @param type The plural type (e.g., cardinal or ordinal).
* @param status output param set to success/failure code on exit, which
* must not indicate a failure before the function call.
* @stable ICU 50
*/
PluralFormat(const Locale& locale, UPluralType type, UErrorCode& status);
/**
* Creates a new cardinal-number <code>PluralFormat</code> for a given pattern string.
* The default locale will be used to get the set of plural rules and for
* standard number formatting.
* @param pattern the pattern for this <code>PluralFormat</code>.
* errors are returned to status if the pattern is invalid.
* @param status output param set to success/failure code on exit, which
* must not indicate a failure before the function call.
* @stable ICU 4.0
*/
PluralFormat(const UnicodeString& pattern, UErrorCode& status);
/**
* Creates a new cardinal-number <code>PluralFormat</code> for a given pattern string and
* locale.
* The locale will be used to get the set of plural rules and for
* standard number formatting.
* @param locale the <code>PluralFormat</code> will be configured with
* rules for this locale. This locale will also be used for
* standard number formatting.
* @param pattern the pattern for this <code>PluralFormat</code>.
* errors are returned to status if the pattern is invalid.
* @param status output param set to success/failure code on exit, which
* must not indicate a failure before the function call.
* @stable ICU 4.0
*/
PluralFormat(const Locale& locale, const UnicodeString& pattern, UErrorCode& status);
/**
* Creates a new <code>PluralFormat</code> for a given set of rules, a
* pattern and a locale.
* @param rules defines the behavior of the <code>PluralFormat</code>
* object.
* @param pattern the pattern for this <code>PluralFormat</code>.
* errors are returned to status if the pattern is invalid.
* @param status output param set to success/failure code on exit, which
* must not indicate a failure before the function call.
* @stable ICU 4.0
*/
PluralFormat(const PluralRules& rules,
const UnicodeString& pattern,
UErrorCode& status);
/**
* Creates a new <code>PluralFormat</code> for a given set of rules, a
* pattern and a locale.
* @param locale the <code>PluralFormat</code> will be configured with
* rules for this locale. This locale will also be used for
* standard number formatting.
* @param rules defines the behavior of the <code>PluralFormat</code>
* object.
* @param pattern the pattern for this <code>PluralFormat</code>.
* errors are returned to status if the pattern is invalid.
* @param status output param set to success/failure code on exit, which
* must not indicate a failure before the function call.
* @stable ICU 4.0
*/
PluralFormat(const Locale& locale,
const PluralRules& rules,
const UnicodeString& pattern,
UErrorCode& status);
/**
* Creates a new <code>PluralFormat</code> for a plural type, a
* pattern and a locale.
* @param locale the <code>PluralFormat</code> will be configured with
* rules for this locale. This locale will also be used for
* standard number formatting.
* @param type The plural type (e.g., cardinal or ordinal).
* @param pattern the pattern for this <code>PluralFormat</code>.
* errors are returned to status if the pattern is invalid.
* @param status output param set to success/failure code on exit, which
* must not indicate a failure before the function call.
* @stable ICU 50
*/
PluralFormat(const Locale& locale,
UPluralType type,
const UnicodeString& pattern,
UErrorCode& status);
/**
* copy constructor.
* @stable ICU 4.0
*/
PluralFormat(const PluralFormat& other);
/**
* Destructor.
* @stable ICU 4.0
*/
virtual ~PluralFormat();
/**
* Sets the pattern used by this plural format.
* The method parses the pattern and creates a map of format strings
* for the plural rules.
* Patterns and their interpretation are specified in the class description.
*
* @param pattern the pattern for this plural format
* errors are returned to status if the pattern is invalid.
* @param status output param set to success/failure code on exit, which
* must not indicate a failure before the function call.
* @stable ICU 4.0
*/
void applyPattern(const UnicodeString& pattern, UErrorCode& status);
using Format::format;
/**
* Formats a plural message for a given number.
*
* @param number a number for which the plural message should be formatted
* for. If no pattern has been applied to this
* <code>PluralFormat</code> object yet, the formatted number
* will be returned.
* @param status output param set to success/failure code on exit, which
* must not indicate a failure before the function call.
* @return the string containing the formatted plural message.
* @stable ICU 4.0
*/
UnicodeString format(int32_t number, UErrorCode& status) const;
/**
* Formats a plural message for a given number.
*
* @param number a number for which the plural message should be formatted
* for. If no pattern has been applied to this
* PluralFormat object yet, the formatted number
* will be returned.
* @param status output param set to success or failure code on exit, which
* must not indicate a failure before the function call.
* @return the string containing the formatted plural message.
* @stable ICU 4.0
*/
UnicodeString format(double number, UErrorCode& status) const;
/**
* Formats a plural message for a given number.
*
* @param number a number for which the plural message should be formatted
* for. If no pattern has been applied to this
* <code>PluralFormat</code> object yet, the formatted number
* will be returned.
* @param appendTo output parameter to receive result.
* result is appended to existing contents.
* @param pos On input: an alignment field, if desired.
* On output: the offsets of the alignment field.
* @param status output param set to success/failure code on exit, which
* must not indicate a failure before the function call.
* @return the string containing the formatted plural message.
* @stable ICU 4.0
*/
UnicodeString& format(int32_t number,
UnicodeString& appendTo,
FieldPosition& pos,
UErrorCode& status) const;
/**
* Formats a plural message for a given number.
*
* @param number a number for which the plural message should be formatted
* for. If no pattern has been applied to this
* PluralFormat object yet, the formatted number
* will be returned.
* @param appendTo output parameter to receive result.
* result is appended to existing contents.
* @param pos On input: an alignment field, if desired.
* On output: the offsets of the alignment field.
* @param status output param set to success/failure code on exit, which
* must not indicate a failure before the function call.
* @return the string containing the formatted plural message.
* @stable ICU 4.0
*/
UnicodeString& format(double number,
UnicodeString& appendTo,
FieldPosition& pos,
UErrorCode& status) const;
#ifndef U_HIDE_DEPRECATED_API
/**
* Sets the locale used by this <code>PluraFormat</code> object.
* Note: Calling this method resets this <code>PluraFormat</code> object,
* i.e., a pattern that was applied previously will be removed,
* and the NumberFormat is set to the default number format for
* the locale. The resulting format behaves the same as one
* constructed from {@link #PluralFormat(const Locale& locale, UPluralType type, UErrorCode& status)}
* with UPLURAL_TYPE_CARDINAL.
* @param locale the <code>locale</code> to use to configure the formatter.
* @param status output param set to success/failure code on exit, which
* must not indicate a failure before the function call.
* @deprecated ICU 50 This method clears the pattern and might create
* a different kind of PluralRules instance;
* use one of the constructors to create a new instance instead.
*/
void setLocale(const Locale& locale, UErrorCode& status);
#endif /* U_HIDE_DEPRECATED_API */
/**
* Sets the number format used by this formatter. You only need to
* call this if you want a different number format than the default
* formatter for the locale.
* @param format the number format to use.
* @param status output param set to success/failure code on exit, which
* must not indicate a failure before the function call.
* @stable ICU 4.0
*/
void setNumberFormat(const NumberFormat* format, UErrorCode& status);
/**
* Assignment operator
*
* @param other the PluralFormat object to copy from.
* @stable ICU 4.0
*/
PluralFormat& operator=(const PluralFormat& other);
/**
* Return true if another object is semantically equal to this one.
*
* @param other the PluralFormat object to be compared with.
* @return true if other is semantically equal to this.
* @stable ICU 4.0
*/
virtual bool operator==(const Format& other) const override;
/**
* Return true if another object is semantically unequal to this one.
*
* @param other the PluralFormat object to be compared with.
* @return true if other is semantically unequal to this.
* @stable ICU 4.0
*/
virtual bool operator!=(const Format& other) const;
/**
* Clones this Format object polymorphically. The caller owns the
* result and should delete it when done.
* @stable ICU 4.0
*/
virtual PluralFormat* clone() const override;
/**
* Formats a plural message for a number taken from a Formattable object.
*
* @param obj The object containing a number for which the
* plural message should be formatted.
* The object must be of a numeric type.
* @param appendTo output parameter to receive result.
* Result is appended to existing contents.
* @param pos On input: an alignment field, if desired.
* On output: the offsets of the alignment field.
* @param status output param filled with success/failure status.
* @return Reference to 'appendTo' parameter.
* @stable ICU 4.0
*/
UnicodeString& format(const Formattable& obj,
UnicodeString& appendTo,
FieldPosition& pos,
UErrorCode& status) const override;
/**
* Returns the pattern from applyPattern() or constructor().
*
* @param appendTo output parameter to receive result.
* Result is appended to existing contents.
* @return the UnicodeString with inserted pattern.
* @stable ICU 4.0
*/
UnicodeString& toPattern(UnicodeString& appendTo);
/**
* This method is not yet supported by <code>PluralFormat</code>.
* <P>
* Before calling, set parse_pos.index to the offset you want to start
* parsing at in the source. After calling, parse_pos.index is the end of
* the text you parsed. If error occurs, index is unchanged.
* <P>
* When parsing, leading whitespace is discarded (with a successful parse),
* while trailing whitespace is left as is.
* <P>
* See Format::parseObject() for more.
*
* @param source The string to be parsed into an object.
* @param result Formattable to be set to the parse result.
* If parse fails, return contents are undefined.
* @param parse_pos The position to start parsing at. Upon return
* this param is set to the position after the
* last character successfully parsed. If the
* source is not parsed successfully, this param
* will remain unchanged.
* @stable ICU 4.0
*/
virtual void parseObject(const UnicodeString& source,
Formattable& result,
ParsePosition& parse_pos) const override;
/**
* ICU "poor man's RTTI", returns a UClassID for this class.
*
* @stable ICU 4.0
*
*/
static UClassID U_EXPORT2 getStaticClassID();
/**
* ICU "poor man's RTTI", returns a UClassID for the actual class.
*
* @stable ICU 4.0
*/
virtual UClassID getDynamicClassID() const override;
private:
/**
* @internal (private)
*/
class U_I18N_API PluralSelector : public UMemory {
public:
virtual ~PluralSelector();
/**
* Given a number, returns the appropriate PluralFormat keyword.
*
* @param context worker object for the selector.
* @param number The number to be plural-formatted.
* @param ec Error code.
* @return The selected PluralFormat keyword.
* @internal (private)
*/
virtual UnicodeString select(void *context, double number, UErrorCode& ec) const = 0;
};
class U_I18N_API PluralSelectorAdapter : public PluralSelector {
public:
PluralSelectorAdapter() : pluralRules(nullptr) {
}
virtual ~PluralSelectorAdapter();
virtual UnicodeString select(void *context, double number, UErrorCode& /*ec*/) const override;
void reset();
PluralRules* pluralRules;
};
Locale locale;
MessagePattern msgPattern;
NumberFormat* numberFormat;
double offset;
PluralSelectorAdapter pluralRulesWrapper;
PluralFormat() = delete; // default constructor not implemented
void init(const PluralRules* rules, UPluralType type, UErrorCode& status);
/**
* Copies dynamically allocated values (pointer fields).
* Others are copied using their copy constructors and assignment operators.
*/
void copyObjects(const PluralFormat& other);
UnicodeString& format(const Formattable& numberObject, double number,
UnicodeString& appendTo,
FieldPosition& pos,
UErrorCode& status) const;
/**
* Finds the PluralFormat sub-message for the given number, or the "other" sub-message.
* @param pattern A MessagePattern.
* @param partIndex the index of the first PluralFormat argument style part.
* @param selector the PluralSelector for mapping the number (minus offset) to a keyword.
* @param context worker object for the selector.
* @param number a number to be matched to one of the PluralFormat argument's explicit values,
* or mapped via the PluralSelector.
* @param ec ICU error code.
* @return the sub-message start part index.
*/
static int32_t findSubMessage(
const MessagePattern& pattern, int32_t partIndex,
const PluralSelector& selector, void *context, double number, UErrorCode& ec);
void parseType(const UnicodeString& source, const NFRule *rbnfLenientScanner,
Formattable& result, FieldPosition& pos) const;
friend class MessageFormat;
friend class NFRule;
};
U_NAMESPACE_END
#endif /* #if !UCONFIG_NO_FORMATTING */
#endif /* U_SHOW_CPLUSPLUS_API */
#endif // _PLURFMT
//eof

View File

@ -0,0 +1,591 @@
// © 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
/*
*******************************************************************************
* Copyright (C) 2008-2015, International Business Machines Corporation and
* others. All Rights Reserved.
*******************************************************************************
*
*
* File PLURRULE.H
*
* Modification History:*
* Date Name Description
*
********************************************************************************
*/
#ifndef PLURRULE
#define PLURRULE
#include "unicode/utypes.h"
#if U_SHOW_CPLUSPLUS_API
/**
* \file
* \brief C++ API: PluralRules object
*/
#if !UCONFIG_NO_FORMATTING
#include "unicode/format.h"
#include "unicode/upluralrules.h"
#ifndef U_HIDE_INTERNAL_API
#include "unicode/numfmt.h"
#endif /* U_HIDE_INTERNAL_API */
/**
* Value returned by PluralRules::getUniqueKeywordValue() when there is no
* unique value to return.
* @stable ICU 4.8
*/
#define UPLRULES_NO_UNIQUE_VALUE ((double)-0.00123456777)
U_NAMESPACE_BEGIN
class Hashtable;
class IFixedDecimal;
class FixedDecimal;
class RuleChain;
class PluralRuleParser;
class PluralKeywordEnumeration;
class AndConstraint;
class SharedPluralRules;
class StandardPluralRanges;
namespace number {
class FormattedNumber;
class FormattedNumberRange;
namespace impl {
class UFormattedNumberRangeData;
class DecimalQuantity;
class DecNum;
}
}
#ifndef U_HIDE_INTERNAL_API
using icu::number::impl::DecimalQuantity;
#endif /* U_HIDE_INTERNAL_API */
/**
* Defines rules for mapping non-negative numeric values onto a small set of
* keywords. Rules are constructed from a text description, consisting
* of a series of keywords and conditions. The {@link #select} method
* examines each condition in order and returns the keyword for the
* first condition that matches the number. If none match,
* default rule(other) is returned.
*
* For more information, details, and tips for writing rules, see the
* LDML spec, Part 3.5 Language Plural Rules:
* https://www.unicode.org/reports/tr35/tr35-numbers.html#Language_Plural_Rules
*
* Examples:<pre>
* "one: n is 1; few: n in 2..4"</pre>
* This defines two rules, for 'one' and 'few'. The condition for
* 'one' is "n is 1" which means that the number must be equal to
* 1 for this condition to pass. The condition for 'few' is
* "n in 2..4" which means that the number must be between 2 and
* 4 inclusive for this condition to pass. All other numbers
* are assigned the keyword "other" by the default rule.
* </p><pre>
* "zero: n is 0; one: n is 1; zero: n mod 100 in 1..19"</pre>
* This illustrates that the same keyword can be defined multiple times.
* Each rule is examined in order, and the first keyword whose condition
* passes is the one returned. Also notes that a modulus is applied
* to n in the last rule. Thus its condition holds for 119, 219, 319...
* </p><pre>
* "one: n is 1; few: n mod 10 in 2..4 and n mod 100 not in 12..14"</pre>
* This illustrates conjunction and negation. The condition for 'few'
* has two parts, both of which must be met: "n mod 10 in 2..4" and
* "n mod 100 not in 12..14". The first part applies a modulus to n
* before the test as in the previous example. The second part applies
* a different modulus and also uses negation, thus it matches all
* numbers _not_ in 12, 13, 14, 112, 113, 114, 212, 213, 214...
* </p>
* <p>
* Syntax:<pre>
* \code
* rules = rule (';' rule)*
* rule = keyword ':' condition
* keyword = <identifier>
* condition = and_condition ('or' and_condition)*
* and_condition = relation ('and' relation)*
* relation = is_relation | in_relation | within_relation | 'n' <EOL>
* is_relation = expr 'is' ('not')? value
* in_relation = expr ('not')? 'in' range_list
* within_relation = expr ('not')? 'within' range
* expr = ('n' | 'i' | 'f' | 'v' | 'j') ('mod' value)?
* range_list = (range | value) (',' range_list)*
* value = digit+ ('.' digit+)?
* digit = 0|1|2|3|4|5|6|7|8|9
* range = value'..'value
* \endcode
* </pre></p>
* <p>
* <p>
* The i, f, and v values are defined as follows:
* </p>
* <ul>
* <li>i to be the integer digits.</li>
* <li>f to be the visible fractional digits, as an integer.</li>
* <li>v to be the number of visible fraction digits.</li>
* <li>j is defined to only match integers. That is j is 3 fails if v != 0 (eg for 3.1 or 3.0).</li>
* </ul>
* <p>
* Examples are in the following table:
* </p>
* <table border='1' style="border-collapse:collapse">
* <tr>
* <th>n</th>
* <th>i</th>
* <th>f</th>
* <th>v</th>
* </tr>
* <tr>
* <td>1.0</td>
* <td>1</td>
* <td align="right">0</td>
* <td>1</td>
* </tr>
* <tr>
* <td>1.00</td>
* <td>1</td>
* <td align="right">0</td>
* <td>2</td>
* </tr>
* <tr>
* <td>1.3</td>
* <td>1</td>
* <td align="right">3</td>
* <td>1</td>
* </tr>
* <tr>
* <td>1.03</td>
* <td>1</td>
* <td align="right">3</td>
* <td>2</td>
* </tr>
* <tr>
* <td>1.23</td>
* <td>1</td>
* <td align="right">23</td>
* <td>2</td>
* </tr>
* </table>
* <p>
* The difference between 'in' and 'within' is that 'in' only includes integers in the specified range, while 'within'
* includes all values. Using 'within' with a range_list consisting entirely of values is the same as using 'in' (it's
* not an error).
* </p>
* An "identifier" is a sequence of characters that do not have the
* Unicode Pattern_Syntax or Pattern_White_Space properties.
* <p>
* The difference between 'in' and 'within' is that 'in' only includes
* integers in the specified range, while 'within' includes all values.
* Using 'within' with a range_list consisting entirely of values is the
* same as using 'in' (it's not an error).
*</p>
* <p>
* Keywords
* could be defined by users or from ICU locale data. There are 6
* predefined values in ICU - 'zero', 'one', 'two', 'few', 'many' and
* 'other'. Callers need to check the value of keyword returned by
* {@link #select} method.
* </p>
*
* Examples:<pre>
* UnicodeString keyword = pl->select(number);
* if (keyword== UnicodeString("one") {
* ...
* }
* else if ( ... )
* </pre>
* <strong>Note:</strong><br>
* <p>
* ICU defines plural rules for many locales based on CLDR <i>Language Plural Rules</i>.
* For these predefined rules, see CLDR page at
* https://unicode-org.github.io/cldr-staging/charts/latest/supplemental/language_plural_rules.html
* </p>
*/
class U_I18N_API PluralRules : public UObject {
public:
/**
* Constructor.
* @param status Output param set to success/failure code on exit, which
* must not indicate a failure before the function call.
*
* @stable ICU 4.0
*/
PluralRules(UErrorCode& status);
/**
* Copy constructor.
* @stable ICU 4.0
*/
PluralRules(const PluralRules& other);
/**
* Destructor.
* @stable ICU 4.0
*/
virtual ~PluralRules();
/**
* Clone
* @stable ICU 4.0
*/
PluralRules* clone() const;
/**
* Assignment operator.
* @stable ICU 4.0
*/
PluralRules& operator=(const PluralRules&);
/**
* Creates a PluralRules from a description if it is parsable, otherwise
* returns nullptr.
*
* @param description rule description
* @param status Output param set to success/failure code on exit, which
* must not indicate a failure before the function call.
* @return new PluralRules pointer. nullptr if there is an error.
* @stable ICU 4.0
*/
static PluralRules* U_EXPORT2 createRules(const UnicodeString& description,
UErrorCode& status);
/**
* The default rules that accept any number.
*
* @param status Output param set to success/failure code on exit, which
* must not indicate a failure before the function call.
* @return new PluralRules pointer. nullptr if there is an error.
* @stable ICU 4.0
*/
static PluralRules* U_EXPORT2 createDefaultRules(UErrorCode& status);
/**
* Provides access to the predefined cardinal-number <code>PluralRules</code> for a given
* locale.
* Same as forLocale(locale, UPLURAL_TYPE_CARDINAL, status).
*
* @param locale The locale for which a <code>PluralRules</code> object is
* returned.
* @param status Output param set to success/failure code on exit, which
* must not indicate a failure before the function call.
* @return The predefined <code>PluralRules</code> object pointer for
* this locale. If there's no predefined rules for this locale,
* the rules for the closest parent in the locale hierarchy
* that has one will be returned. The final fallback always
* returns the default 'other' rules.
* @stable ICU 4.0
*/
static PluralRules* U_EXPORT2 forLocale(const Locale& locale, UErrorCode& status);
/**
* Provides access to the predefined <code>PluralRules</code> for a given
* locale and the plural type.
*
* @param locale The locale for which a <code>PluralRules</code> object is
* returned.
* @param type The plural type (e.g., cardinal or ordinal).
* @param status Output param set to success/failure code on exit, which
* must not indicate a failure before the function call.
* @return The predefined <code>PluralRules</code> object pointer for
* this locale. If there's no predefined rules for this locale,
* the rules for the closest parent in the locale hierarchy
* that has one will be returned. The final fallback always
* returns the default 'other' rules.
* @stable ICU 50
*/
static PluralRules* U_EXPORT2 forLocale(const Locale& locale, UPluralType type, UErrorCode& status);
#ifndef U_HIDE_INTERNAL_API
/**
* Return a StringEnumeration over the locales for which there is plurals data.
* @return a StringEnumeration over the locales available.
* @internal
*/
static StringEnumeration* U_EXPORT2 getAvailableLocales(UErrorCode &status);
/**
* For ICU use only.
* creates a SharedPluralRules object
* @internal
*/
static PluralRules* U_EXPORT2 internalForLocale(const Locale& locale, UPluralType type, UErrorCode& status);
/**
* For ICU use only.
* Returns handle to the shared, cached PluralRules instance.
* Caller must call removeRef() on returned value once it is done with
* the shared instance.
* @internal
*/
static const SharedPluralRules* U_EXPORT2 createSharedInstance(
const Locale& locale, UPluralType type, UErrorCode& status);
#endif /* U_HIDE_INTERNAL_API */
/**
* Given an integer, returns the keyword of the first rule
* that applies to the number. This function can be used with
* isKeyword* functions to determine the keyword for default plural rules.
*
* @param number The number for which the rule has to be determined.
* @return The keyword of the selected rule.
* @stable ICU 4.0
*/
UnicodeString select(int32_t number) const;
/**
* Given a floating-point number, returns the keyword of the first rule
* that applies to the number. This function can be used with
* isKeyword* functions to determine the keyword for default plural rules.
*
* @param number The number for which the rule has to be determined.
* @return The keyword of the selected rule.
* @stable ICU 4.0
*/
UnicodeString select(double number) const;
/**
* Given a formatted number, returns the keyword of the first rule
* that applies to the number. This function can be used with
* isKeyword* functions to determine the keyword for default plural rules.
*
* A FormattedNumber allows you to specify an exponent or trailing zeros,
* which can affect the plural category. To get a FormattedNumber, see
* NumberFormatter.
*
* @param number The number for which the rule has to be determined.
* @param status Set if an error occurs while selecting plural keyword.
* This could happen if the FormattedNumber is invalid.
* @return The keyword of the selected rule.
* @stable ICU 64
*/
UnicodeString select(const number::FormattedNumber& number, UErrorCode& status) const;
/**
* Given a formatted number range, returns the overall plural form of the
* range. For example, "3-5" returns "other" in English.
*
* To get a FormattedNumberRange, see NumberRangeFormatter.
*
* This method only works if PluralRules was created with a locale. If it was created
* from PluralRules::createRules(), this method sets status code U_UNSUPPORTED_ERROR.
*
* @param range The number range onto which the rules will be applied.
* @param status Set if an error occurs while selecting plural keyword.
* This could happen if the FormattedNumberRange is invalid,
* or if plural ranges data is unavailable.
* @return The keyword of the selected rule.
* @stable ICU 68
*/
UnicodeString select(const number::FormattedNumberRange& range, UErrorCode& status) const;
#ifndef U_HIDE_INTERNAL_API
/**
* @internal
*/
UnicodeString select(const IFixedDecimal &number) const;
/**
* @internal
*/
UnicodeString select(const number::impl::UFormattedNumberRangeData* urange, UErrorCode& status) const;
#endif /* U_HIDE_INTERNAL_API */
/**
* Returns a list of all rule keywords used in this <code>PluralRules</code>
* object. The rule 'other' is always present by default.
*
* @param status Output param set to success/failure code on exit, which
* must not indicate a failure before the function call.
* @return StringEnumeration with the keywords.
* The caller must delete the object.
* @stable ICU 4.0
*/
StringEnumeration* getKeywords(UErrorCode& status) const;
#ifndef U_HIDE_DEPRECATED_API
/**
* Deprecated Function, does not return useful results.
*
* Originally intended to return a unique value for this keyword if it exists,
* else the constant UPLRULES_NO_UNIQUE_VALUE.
*
* @param keyword The keyword.
* @return Stub deprecated function returns UPLRULES_NO_UNIQUE_VALUE always.
* @deprecated ICU 55
*/
double getUniqueKeywordValue(const UnicodeString& keyword);
/**
* Deprecated Function, does not produce useful results.
*
* Originally intended to return all the values for which select() would return the keyword.
* If the keyword is unknown, returns no values, but this is not an error. If
* the number of values is unlimited, returns no values and -1 as the
* count.
*
* The number of returned values is typically small.
*
* @param keyword The keyword.
* @param dest Array into which to put the returned values. May
* be nullptr if destCapacity is 0.
* @param destCapacity The capacity of the array, must be at least 0.
* @param status The error code. Deprecated function, always sets U_UNSUPPORTED_ERROR.
* @return The count of values available, or -1. This count
* can be larger than destCapacity, but no more than
* destCapacity values will be written.
* @deprecated ICU 55
*/
int32_t getAllKeywordValues(const UnicodeString &keyword,
double *dest, int32_t destCapacity,
UErrorCode& status);
#endif /* U_HIDE_DEPRECATED_API */
/**
* Returns sample values for which select() would return the keyword. If
* the keyword is unknown, returns no values, but this is not an error.
*
* The number of returned values is typically small.
*
* @param keyword The keyword.
* @param dest Array into which to put the returned values. May
* be nullptr if destCapacity is 0.
* @param destCapacity The capacity of the array, must be at least 0.
* @param status The error code.
* @return The count of values written.
* If more than destCapacity samples are available, then
* only destCapacity are written, and destCapacity is returned as the count,
* rather than setting a U_BUFFER_OVERFLOW_ERROR.
* (The actual number of keyword values could be unlimited.)
* @stable ICU 4.8
*/
int32_t getSamples(const UnicodeString &keyword,
double *dest, int32_t destCapacity,
UErrorCode& status);
#ifndef U_HIDE_INTERNAL_API
/**
* Internal-only function that returns DecimalQuantitys instead of doubles.
*
* Returns sample values for which select() would return the keyword. If
* the keyword is unknown, returns no values, but this is not an error.
*
* The number of returned values is typically small.
*
* @param keyword The keyword.
* @param dest Array into which to put the returned values. May
* be nullptr if destCapacity is 0.
* @param destCapacity The capacity of the array, must be at least 0.
* @param status The error code.
* @return The count of values written.
* If more than destCapacity samples are available, then
* only destCapacity are written, and destCapacity is returned as the count,
* rather than setting a U_BUFFER_OVERFLOW_ERROR.
* (The actual number of keyword values could be unlimited.)
* @internal
*/
int32_t getSamples(const UnicodeString &keyword,
DecimalQuantity *dest, int32_t destCapacity,
UErrorCode& status);
#endif /* U_HIDE_INTERNAL_API */
/**
* Returns true if the given keyword is defined in this
* <code>PluralRules</code> object.
*
* @param keyword the input keyword.
* @return true if the input keyword is defined.
* Otherwise, return false.
* @stable ICU 4.0
*/
UBool isKeyword(const UnicodeString& keyword) const;
/**
* Returns keyword for default plural form.
*
* @return keyword for default plural form.
* @stable ICU 4.0
*/
UnicodeString getKeywordOther() const;
#ifndef U_HIDE_INTERNAL_API
/**
*
* @internal
*/
UnicodeString getRules() const;
#endif /* U_HIDE_INTERNAL_API */
/**
* Compares the equality of two PluralRules objects.
*
* @param other The other PluralRules object to be compared with.
* @return true if the given PluralRules is the same as this
* PluralRules; false otherwise.
* @stable ICU 4.0
*/
virtual bool operator==(const PluralRules& other) const;
/**
* Compares the inequality of two PluralRules objects.
*
* @param other The PluralRules object to be compared with.
* @return true if the given PluralRules is not the same as this
* PluralRules; false otherwise.
* @stable ICU 4.0
*/
bool operator!=(const PluralRules& other) const {return !operator==(other);}
/**
* ICU "poor man's RTTI", returns a UClassID for this class.
*
* @stable ICU 4.0
*
*/
static UClassID U_EXPORT2 getStaticClassID();
/**
* ICU "poor man's RTTI", returns a UClassID for the actual class.
*
* @stable ICU 4.0
*/
virtual UClassID getDynamicClassID() const override;
private:
RuleChain *mRules;
StandardPluralRanges *mStandardPluralRanges;
PluralRules() = delete; // default constructor not implemented
UnicodeString getRuleFromResource(const Locale& locale, UPluralType type, UErrorCode& status);
RuleChain *rulesForKeyword(const UnicodeString &keyword) const;
PluralRules *clone(UErrorCode& status) const;
/**
* An internal status variable used to indicate that the object is in an 'invalid' state.
* Used by copy constructor, the assignment operator and the clone method.
*/
UErrorCode mInternalStatus;
friend class PluralRuleParser;
};
U_NAMESPACE_END
#endif /* #if !UCONFIG_NO_FORMATTING */
#endif /* U_SHOW_CPLUSPLUS_API */
#endif // _PLURRULE
//eof

1186
deps/icu-small/source/i18n/unicode/rbnf.h vendored Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,373 @@
// © 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
/*
*******************************************************************************
* Copyright (C) 2007-2013, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
*/
#ifndef RBTZ_H
#define RBTZ_H
#include "unicode/utypes.h"
#if U_SHOW_CPLUSPLUS_API
/**
* \file
* \brief C++ API: Rule based customizable time zone
*/
#if !UCONFIG_NO_FORMATTING
#include "unicode/basictz.h"
#include "unicode/unistr.h"
U_NAMESPACE_BEGIN
// forward declaration
class UVector;
struct Transition;
/**
* a BasicTimeZone subclass implemented in terms of InitialTimeZoneRule and TimeZoneRule instances
* @see BasicTimeZone
* @see InitialTimeZoneRule
* @see TimeZoneRule
*/
class U_I18N_API RuleBasedTimeZone : public BasicTimeZone {
public:
/**
* Constructs a <code>RuleBasedTimeZone</code> object with the ID and the
* <code>InitialTimeZoneRule</code>. The input <code>InitialTimeZoneRule</code>
* is adopted by this <code>RuleBasedTimeZone</code>, thus the caller must not
* delete it.
* @param id The time zone ID.
* @param initialRule The initial time zone rule.
* @stable ICU 3.8
*/
RuleBasedTimeZone(const UnicodeString& id, InitialTimeZoneRule* initialRule);
/**
* Copy constructor.
* @param source The RuleBasedTimeZone object to be copied.
* @stable ICU 3.8
*/
RuleBasedTimeZone(const RuleBasedTimeZone& source);
/**
* Destructor.
* @stable ICU 3.8
*/
virtual ~RuleBasedTimeZone();
/**
* Assignment operator.
* @param right The object to be copied.
* @stable ICU 3.8
*/
RuleBasedTimeZone& operator=(const RuleBasedTimeZone& right);
/**
* Return true if the given <code>TimeZone</code> objects are
* semantically equal. Objects of different subclasses are considered unequal.
* @param that The object to be compared with.
* @return true if the given <code>TimeZone</code> objects are
*semantically equal.
* @stable ICU 3.8
*/
virtual bool operator==(const TimeZone& that) const override;
/**
* Return true if the given <code>TimeZone</code> objects are
* semantically unequal. Objects of different subclasses are considered unequal.
* @param that The object to be compared with.
* @return true if the given <code>TimeZone</code> objects are
* semantically unequal.
* @stable ICU 3.8
*/
virtual bool operator!=(const TimeZone& that) const;
/**
* Adds the `TimeZoneRule` which represents time transitions.
* The `TimeZoneRule` must have start times, that is, the result
* of `isTransitionRule()` must be true. Otherwise, U_ILLEGAL_ARGUMENT_ERROR
* is set to the error code.
* The input `TimeZoneRule` is adopted by this `RuleBasedTimeZone`;
* the caller must not delete it. Should an error condition prevent
* the successful adoption of the rule, this function will delete it.
*
* After all rules are added, the caller must call `complete()` method to
* make this `RuleBasedTimeZone` ready to handle common time
* zone functions.
* @param rule The `TimeZoneRule`.
* @param status Output param to filled in with a success or an error.
* @stable ICU 3.8
*/
void addTransitionRule(TimeZoneRule* rule, UErrorCode& status);
/**
* Makes the <code>TimeZoneRule</code> ready to handle actual timezone
* calculation APIs. This method collects time zone rules specified
* by the caller via the constructor and addTransitionRule() and
* builds internal structure for making the object ready to support
* time zone APIs such as getOffset(), getNextTransition() and others.
* @param status Output param to filled in with a success or an error.
* @stable ICU 3.8
*/
void complete(UErrorCode& status);
/**
* Clones TimeZone objects polymorphically. Clients are responsible for deleting
* the TimeZone object cloned.
*
* @return A new copy of this TimeZone object.
* @stable ICU 3.8
*/
virtual RuleBasedTimeZone* clone() const override;
/**
* Returns the TimeZone's adjusted GMT offset (i.e., the number of milliseconds to add
* to GMT to get local time in this time zone, taking daylight savings time into
* account) as of a particular reference date. The reference date is used to determine
* whether daylight savings time is in effect and needs to be figured into the offset
* that is returned (in other words, what is the adjusted GMT offset in this time zone
* at this particular date and time?). For the time zones produced by createTimeZone(),
* the reference data is specified according to the Gregorian calendar, and the date
* and time fields are local standard time.
*
* <p>Note: Don't call this method. Instead, call the getOffset(UDate...) overload,
* which returns both the raw and the DST offset for a given time. This method
* is retained only for backward compatibility.
*
* @param era The reference date's era
* @param year The reference date's year
* @param month The reference date's month (0-based; 0 is January)
* @param day The reference date's day-in-month (1-based)
* @param dayOfWeek The reference date's day-of-week (1-based; 1 is Sunday)
* @param millis The reference date's milliseconds in day, local standard time
* @param status Output param to filled in with a success or an error.
* @return The offset in milliseconds to add to GMT to get local time.
* @stable ICU 3.8
*/
virtual int32_t getOffset(uint8_t era, int32_t year, int32_t month, int32_t day,
uint8_t dayOfWeek, int32_t millis, UErrorCode& status) const override;
/**
* Gets the time zone offset, for current date, modified in case of
* daylight savings. This is the offset to add *to* UTC to get local time.
*
* <p>Note: Don't call this method. Instead, call the getOffset(UDate...) overload,
* which returns both the raw and the DST offset for a given time. This method
* is retained only for backward compatibility.
*
* @param era The reference date's era
* @param year The reference date's year
* @param month The reference date's month (0-based; 0 is January)
* @param day The reference date's day-in-month (1-based)
* @param dayOfWeek The reference date's day-of-week (1-based; 1 is Sunday)
* @param millis The reference date's milliseconds in day, local standard time
* @param monthLength The length of the given month in days.
* @param status Output param to filled in with a success or an error.
* @return The offset in milliseconds to add to GMT to get local time.
* @stable ICU 3.8
*/
virtual int32_t getOffset(uint8_t era, int32_t year, int32_t month, int32_t day,
uint8_t dayOfWeek, int32_t millis,
int32_t monthLength, UErrorCode& status) const override;
/**
* Returns the time zone raw and GMT offset for the given moment
* in time. Upon return, local-millis = GMT-millis + rawOffset +
* dstOffset. All computations are performed in the proleptic
* Gregorian calendar. The default implementation in the TimeZone
* class delegates to the 8-argument getOffset().
*
* @param date moment in time for which to return offsets, in
* units of milliseconds from January 1, 1970 0:00 GMT, either GMT
* time or local wall time, depending on `local'.
* @param local if true, `date' is local wall time; otherwise it
* is in GMT time.
* @param rawOffset output parameter to receive the raw offset, that
* is, the offset not including DST adjustments
* @param dstOffset output parameter to receive the DST offset,
* that is, the offset to be added to `rawOffset' to obtain the
* total offset between local and GMT time. If DST is not in
* effect, this value is zero; otherwise it is a positive value,
* typically one hour.
* @param ec input-output error code
* @stable ICU 3.8
*/
virtual void getOffset(UDate date, UBool local, int32_t& rawOffset,
int32_t& dstOffset, UErrorCode& ec) const override;
/**
* Sets the TimeZone's raw GMT offset (i.e., the number of milliseconds to add
* to GMT to get local time, before taking daylight savings time into account).
*
* @param offsetMillis The new raw GMT offset for this time zone.
* @stable ICU 3.8
*/
virtual void setRawOffset(int32_t offsetMillis) override;
/**
* Returns the TimeZone's raw GMT offset (i.e., the number of milliseconds to add
* to GMT to get local time, before taking daylight savings time into account).
*
* @return The TimeZone's raw GMT offset.
* @stable ICU 3.8
*/
virtual int32_t getRawOffset() const override;
/**
* Queries if this time zone uses daylight savings time.
* @return true if this time zone uses daylight savings time,
* false, otherwise.
* @stable ICU 3.8
*/
virtual UBool useDaylightTime() const override;
#ifndef U_FORCE_HIDE_DEPRECATED_API
/**
* Queries if the given date is in daylight savings time in
* this time zone.
* This method is wasteful since it creates a new GregorianCalendar and
* deletes it each time it is called. This is a deprecated method
* and provided only for Java compatibility.
*
* @param date the given UDate.
* @param status Output param filled in with success/error code.
* @return true if the given date is in daylight savings time,
* false, otherwise.
* @deprecated ICU 2.4. Use Calendar::inDaylightTime() instead.
*/
virtual UBool inDaylightTime(UDate date, UErrorCode& status) const override;
#endif // U_FORCE_HIDE_DEPRECATED_API
/**
* Returns true if this zone has the same rule and offset as another zone.
* That is, if this zone differs only in ID, if at all.
* @param other the <code>TimeZone</code> object to be compared with
* @return true if the given zone is the same as this one,
* with the possible exception of the ID
* @stable ICU 3.8
*/
virtual UBool hasSameRules(const TimeZone& other) const override;
/**
* Gets the first time zone transition after the base time.
* @param base The base time.
* @param inclusive Whether the base time is inclusive or not.
* @param result Receives the first transition after the base time.
* @return true if the transition is found.
* @stable ICU 3.8
*/
virtual UBool getNextTransition(UDate base, UBool inclusive, TimeZoneTransition& result) const override;
/**
* Gets the most recent time zone transition before the base time.
* @param base The base time.
* @param inclusive Whether the base time is inclusive or not.
* @param result Receives the most recent transition before the base time.
* @return true if the transition is found.
* @stable ICU 3.8
*/
virtual UBool getPreviousTransition(UDate base, UBool inclusive, TimeZoneTransition& result) const override;
/**
* Returns the number of <code>TimeZoneRule</code>s which represents time transitions,
* for this time zone, that is, all <code>TimeZoneRule</code>s for this time zone except
* <code>InitialTimeZoneRule</code>. The return value range is 0 or any positive value.
* @param status Receives error status code.
* @return The number of <code>TimeZoneRule</code>s representing time transitions.
* @stable ICU 3.8
*/
virtual int32_t countTransitionRules(UErrorCode& status) const override;
/**
* Gets the <code>InitialTimeZoneRule</code> and the set of <code>TimeZoneRule</code>
* which represent time transitions for this time zone. On successful return,
* the argument initial points to non-nullptr <code>InitialTimeZoneRule</code> and
* the array trsrules is filled with 0 or multiple <code>TimeZoneRule</code>
* instances up to the size specified by trscount. The results are referencing the
* rule instance held by this time zone instance. Therefore, after this time zone
* is destructed, they are no longer available.
* @param initial Receives the initial timezone rule
* @param trsrules Receives the timezone transition rules
* @param trscount On input, specify the size of the array 'transitions' receiving
* the timezone transition rules. On output, actual number of
* rules filled in the array will be set.
* @param status Receives error status code.
* @stable ICU 3.8
*/
virtual void getTimeZoneRules(const InitialTimeZoneRule*& initial,
const TimeZoneRule* trsrules[], int32_t& trscount, UErrorCode& status) const override;
/**
* Get time zone offsets from local wall time.
* @stable ICU 69
*/
virtual void getOffsetFromLocal(
UDate date, UTimeZoneLocalOption nonExistingTimeOpt,
UTimeZoneLocalOption duplicatedTimeOpt,
int32_t& rawOffset, int32_t& dstOffset, UErrorCode& status) const override;
private:
void deleteRules();
void deleteTransitions();
UVector* copyRules(UVector* source);
TimeZoneRule* findRuleInFinal(UDate date, UBool local,
int32_t NonExistingTimeOpt, int32_t DuplicatedTimeOpt) const;
UBool findNext(UDate base, UBool inclusive, UDate& time, TimeZoneRule*& from, TimeZoneRule*& to) const;
UBool findPrev(UDate base, UBool inclusive, UDate& time, TimeZoneRule*& from, TimeZoneRule*& to) const;
int32_t getLocalDelta(int32_t rawBefore, int32_t dstBefore, int32_t rawAfter, int32_t dstAfter,
int32_t NonExistingTimeOpt, int32_t DuplicatedTimeOpt) const;
UDate getTransitionTime(Transition* transition, UBool local,
int32_t NonExistingTimeOpt, int32_t DuplicatedTimeOpt) const;
void getOffsetInternal(UDate date, UBool local, int32_t NonExistingTimeOpt, int32_t DuplicatedTimeOpt,
int32_t& rawOffset, int32_t& dstOffset, UErrorCode& ec) const;
void completeConst(UErrorCode &status) const;
InitialTimeZoneRule *fInitialRule;
UVector *fHistoricRules;
UVector *fFinalRules;
UVector *fHistoricTransitions;
UBool fUpToDate;
public:
/**
* Return the class ID for this class. This is useful only for comparing to
* a return value from getDynamicClassID(). For example:
* <pre>
* . Base* polymorphic_pointer = createPolymorphicObject();
* . if (polymorphic_pointer->getDynamicClassID() ==
* . erived::getStaticClassID()) ...
* </pre>
* @return The class ID for all objects of this class.
* @stable ICU 3.8
*/
static UClassID U_EXPORT2 getStaticClassID();
/**
* Returns a unique class ID POLYMORPHICALLY. Pure virtual override. This
* method is to implement a simple version of RTTI, since not all C++
* compilers support genuine RTTI. Polymorphic operator==() and clone()
* methods call this method.
*
* @return The class ID for this object. All objects of a
* given class have the same class ID. Objects of
* other classes have different class IDs.
* @stable ICU 3.8
*/
virtual UClassID getDynamicClassID() const override;
};
U_NAMESPACE_END
#endif /* #if !UCONFIG_NO_FORMATTING */
#endif /* U_SHOW_CPLUSPLUS_API */
#endif // RBTZ_H
//eof

1882
deps/icu-small/source/i18n/unicode/regex.h vendored Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,229 @@
// © 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
/*
*******************************************************************************
* Copyright (C) 2014-2016, International Business Machines Corporation and others.
* All Rights Reserved.
*******************************************************************************
*/
#ifndef REGION_H
#define REGION_H
/**
* \file
* \brief C++ API: Region classes (territory containment)
*/
#include "unicode/utypes.h"
#if U_SHOW_CPLUSPLUS_API
#if !UCONFIG_NO_FORMATTING
#include "unicode/uregion.h"
#include "unicode/uobject.h"
#include "unicode/uniset.h"
#include "unicode/unistr.h"
#include "unicode/strenum.h"
U_NAMESPACE_BEGIN
/**
* <code>Region</code> is the class representing a Unicode Region Code, also known as a
* Unicode Region Subtag, which is defined based upon the BCP 47 standard. We often think of
* "regions" as "countries" when defining the characteristics of a locale. Region codes There are different
* types of region codes that are important to distinguish.
* <p>
* Macroregion - A code for a "macro geographical (continental) region, geographical sub-region, or
* selected economic and other grouping" as defined in
* UN M.49 (http://unstats.un.org/unsd/methods/m49/m49regin.htm).
* These are typically 3-digit codes, but contain some 2-letter codes, such as the LDML code QO
* added for Outlying Oceania. Not all UNM.49 codes are defined in LDML, but most of them are.
* Macroregions are represented in ICU by one of three region types: WORLD ( region code 001 ),
* CONTINENTS ( regions contained directly by WORLD ), and SUBCONTINENTS ( things contained directly
* by a continent ).
* <p>
* TERRITORY - A Region that is not a Macroregion. These are typically codes for countries, but also
* include areas that are not separate countries, such as the code "AQ" for Antarctica or the code
* "HK" for Hong Kong (SAR China). Overseas dependencies of countries may or may not have separate
* codes. The codes are typically 2-letter codes aligned with the ISO 3166 standard, but BCP47 allows
* for the use of 3-digit codes in the future.
* <p>
* UNKNOWN - The code ZZ is defined by Unicode LDML for use to indicate that the Region is unknown,
* or that the value supplied as a region was invalid.
* <p>
* DEPRECATED - Region codes that have been defined in the past but are no longer in modern usage,
* usually due to a country splitting into multiple territories or changing its name.
* <p>
* GROUPING - A widely understood grouping of territories that has a well defined membership such
* that a region code has been assigned for it. Some of these are UNM.49 codes that do't fall into
* the world/continent/sub-continent hierarchy, while others are just well known groupings that have
* their own region code. Region "EU" (European Union) is one such region code that is a grouping.
* Groupings will never be returned by the getContainingRegion() API, since a different type of region
* ( WORLD, CONTINENT, or SUBCONTINENT ) will always be the containing region instead.
*
* The Region class is not intended for public subclassing.
*
* @author John Emmons
* @stable ICU 51
*/
class U_I18N_API Region : public UObject {
public:
/**
* Destructor.
* @stable ICU 51
*/
virtual ~Region();
/**
* Returns true if the two regions are equal.
* @stable ICU 51
*/
bool operator==(const Region &that) const;
/**
* Returns true if the two regions are NOT equal; that is, if operator ==() returns false.
* @stable ICU 51
*/
bool operator!=(const Region &that) const;
/**
* Returns a pointer to a Region using the given region code. The region code can be either 2-letter ISO code,
* 3-letter ISO code, UNM.49 numeric code, or other valid Unicode Region Code as defined by the LDML specification.
* The identifier will be canonicalized internally using the supplemental metadata as defined in the CLDR.
* If the region code is nullptr or not recognized, the appropriate error code will be set ( U_ILLEGAL_ARGUMENT_ERROR )
* @stable ICU 51
*/
static const Region* U_EXPORT2 getInstance(const char *region_code, UErrorCode &status);
/**
* Returns a pointer to a Region using the given numeric region code. If the numeric region code is not recognized,
* the appropriate error code will be set ( U_ILLEGAL_ARGUMENT_ERROR ).
* @stable ICU 51
*/
static const Region* U_EXPORT2 getInstance (int32_t code, UErrorCode &status);
/**
* Returns an enumeration over the IDs of all known regions that match the given type.
* @stable ICU 55
*/
static StringEnumeration* U_EXPORT2 getAvailable(URegionType type, UErrorCode &status);
/**
* Returns a pointer to the region that contains this region. Returns nullptr if this region is code "001" (World)
* or "ZZ" (Unknown region). For example, calling this method with region "IT" (Italy) returns the
* region "039" (Southern Europe).
* @stable ICU 51
*/
const Region* getContainingRegion() const;
/**
* Return a pointer to the region that geographically contains this region and matches the given type,
* moving multiple steps up the containment chain if necessary. Returns nullptr if no containing region can be found
* that matches the given type. Note: The URegionTypes = "URGN_GROUPING", "URGN_DEPRECATED", or "URGN_UNKNOWN"
* are not appropriate for use in this API. nullptr will be returned in this case. For example, calling this method
* with region "IT" (Italy) for type "URGN_CONTINENT" returns the region "150" ( Europe ).
* @stable ICU 51
*/
const Region* getContainingRegion(URegionType type) const;
/**
* Return an enumeration over the IDs of all the regions that are immediate children of this region in the
* region hierarchy. These returned regions could be either macro regions, territories, or a mixture of the two,
* depending on the containment data as defined in CLDR. This API may return nullptr if this region doesn't have
* any sub-regions. For example, calling this method with region "150" (Europe) returns an enumeration containing
* the various sub regions of Europe - "039" (Southern Europe) - "151" (Eastern Europe) - "154" (Northern Europe)
* and "155" (Western Europe).
* @stable ICU 55
*/
StringEnumeration* getContainedRegions(UErrorCode &status) const;
/**
* Returns an enumeration over the IDs of all the regions that are children of this region anywhere in the region
* hierarchy and match the given type. This API may return an empty enumeration if this region doesn't have any
* sub-regions that match the given type. For example, calling this method with region "150" (Europe) and type
* "URGN_TERRITORY" returns a set containing all the territories in Europe ( "FR" (France) - "IT" (Italy) - "DE" (Germany) etc. )
* @stable ICU 55
*/
StringEnumeration* getContainedRegions( URegionType type, UErrorCode &status ) const;
/**
* Returns true if this region contains the supplied other region anywhere in the region hierarchy.
* @stable ICU 51
*/
UBool contains(const Region &other) const;
/**
* For deprecated regions, return an enumeration over the IDs of the regions that are the preferred replacement
* regions for this region. Returns null for a non-deprecated region. For example, calling this method with region
* "SU" (Soviet Union) would return a list of the regions containing "RU" (Russia), "AM" (Armenia), "AZ" (Azerbaijan), etc...
* @stable ICU 55
*/
StringEnumeration* getPreferredValues(UErrorCode &status) const;
/**
* Return this region's canonical region code.
* @stable ICU 51
*/
const char* getRegionCode() const;
/**
* Return this region's numeric code.
* Returns a negative value if the given region does not have a numeric code assigned to it.
* @stable ICU 51
*/
int32_t getNumericCode() const;
/**
* Returns the region type of this region.
* @stable ICU 51
*/
URegionType getType() const;
#ifndef U_HIDE_INTERNAL_API
/**
* Cleans up statically allocated memory.
* @internal
*/
static void cleanupRegionData();
#endif /* U_HIDE_INTERNAL_API */
private:
char id[4];
UnicodeString idStr;
int32_t code;
URegionType fType;
Region *containingRegion;
UVector *containedRegions;
UVector *preferredValues;
/**
* Default Constructor. Internal - use factory methods only.
*/
Region();
/*
* Initializes the region data from the ICU resource bundles. The region data
* contains the basic relationships such as which regions are known, what the numeric
* codes are, any known aliases, and the territory containment data.
*
* If the region data has already loaded, then this method simply returns without doing
* anything meaningful.
*/
static void U_CALLCONV loadRegionData(UErrorCode &status);
};
U_NAMESPACE_END
#endif /* #if !UCONFIG_NO_FORMATTING */
#endif /* U_SHOW_CPLUSPLUS_API */
#endif // REGION_H
//eof

View File

@ -0,0 +1,758 @@
// © 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
/*
*****************************************************************************
* Copyright (C) 2014-2016, International Business Machines Corporation and
* others.
* All Rights Reserved.
*****************************************************************************
*
* File RELDATEFMT.H
*****************************************************************************
*/
#ifndef __RELDATEFMT_H
#define __RELDATEFMT_H
#include "unicode/utypes.h"
#if U_SHOW_CPLUSPLUS_API
#include "unicode/uobject.h"
#include "unicode/udisplaycontext.h"
#include "unicode/ureldatefmt.h"
#include "unicode/locid.h"
#include "unicode/formattedvalue.h"
/**
* \file
* \brief C++ API: Formats relative dates such as "1 day ago" or "tomorrow"
*/
#if !UCONFIG_NO_FORMATTING
/**
* Represents the unit for formatting a relative date. e.g "in 5 days"
* or "in 3 months"
* @stable ICU 53
*/
typedef enum UDateRelativeUnit {
/**
* Seconds
* @stable ICU 53
*/
UDAT_RELATIVE_SECONDS,
/**
* Minutes
* @stable ICU 53
*/
UDAT_RELATIVE_MINUTES,
/**
* Hours
* @stable ICU 53
*/
UDAT_RELATIVE_HOURS,
/**
* Days
* @stable ICU 53
*/
UDAT_RELATIVE_DAYS,
/**
* Weeks
* @stable ICU 53
*/
UDAT_RELATIVE_WEEKS,
/**
* Months
* @stable ICU 53
*/
UDAT_RELATIVE_MONTHS,
/**
* Years
* @stable ICU 53
*/
UDAT_RELATIVE_YEARS,
#ifndef U_HIDE_DEPRECATED_API
/**
* One more than the highest normal UDateRelativeUnit value.
* @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420.
*/
UDAT_RELATIVE_UNIT_COUNT
#endif // U_HIDE_DEPRECATED_API
} UDateRelativeUnit;
/**
* Represents an absolute unit.
* @stable ICU 53
*/
typedef enum UDateAbsoluteUnit {
// Days of week have to remain together and in order from Sunday to
// Saturday.
/**
* Sunday
* @stable ICU 53
*/
UDAT_ABSOLUTE_SUNDAY,
/**
* Monday
* @stable ICU 53
*/
UDAT_ABSOLUTE_MONDAY,
/**
* Tuesday
* @stable ICU 53
*/
UDAT_ABSOLUTE_TUESDAY,
/**
* Wednesday
* @stable ICU 53
*/
UDAT_ABSOLUTE_WEDNESDAY,
/**
* Thursday
* @stable ICU 53
*/
UDAT_ABSOLUTE_THURSDAY,
/**
* Friday
* @stable ICU 53
*/
UDAT_ABSOLUTE_FRIDAY,
/**
* Saturday
* @stable ICU 53
*/
UDAT_ABSOLUTE_SATURDAY,
/**
* Day
* @stable ICU 53
*/
UDAT_ABSOLUTE_DAY,
/**
* Week
* @stable ICU 53
*/
UDAT_ABSOLUTE_WEEK,
/**
* Month
* @stable ICU 53
*/
UDAT_ABSOLUTE_MONTH,
/**
* Year
* @stable ICU 53
*/
UDAT_ABSOLUTE_YEAR,
/**
* Now
* @stable ICU 53
*/
UDAT_ABSOLUTE_NOW,
/**
* Quarter
* @stable ICU 63
*/
UDAT_ABSOLUTE_QUARTER,
/**
* Hour
* @stable ICU 65
*/
UDAT_ABSOLUTE_HOUR,
/**
* Minute
* @stable ICU 65
*/
UDAT_ABSOLUTE_MINUTE,
#ifndef U_HIDE_DEPRECATED_API
/**
* One more than the highest normal UDateAbsoluteUnit value.
* @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420.
*/
UDAT_ABSOLUTE_UNIT_COUNT = UDAT_ABSOLUTE_NOW + 4
#endif // U_HIDE_DEPRECATED_API
} UDateAbsoluteUnit;
/**
* Represents a direction for an absolute unit e.g "Next Tuesday"
* or "Last Tuesday"
* @stable ICU 53
*/
typedef enum UDateDirection {
/**
* Two before. Not fully supported in every locale.
* @stable ICU 53
*/
UDAT_DIRECTION_LAST_2,
/**
* Last
* @stable ICU 53
*/
UDAT_DIRECTION_LAST,
/**
* This
* @stable ICU 53
*/
UDAT_DIRECTION_THIS,
/**
* Next
* @stable ICU 53
*/
UDAT_DIRECTION_NEXT,
/**
* Two after. Not fully supported in every locale.
* @stable ICU 53
*/
UDAT_DIRECTION_NEXT_2,
/**
* Plain, which means the absence of a qualifier.
* @stable ICU 53
*/
UDAT_DIRECTION_PLAIN,
#ifndef U_HIDE_DEPRECATED_API
/**
* One more than the highest normal UDateDirection value.
* @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420.
*/
UDAT_DIRECTION_COUNT
#endif // U_HIDE_DEPRECATED_API
} UDateDirection;
U_NAMESPACE_BEGIN
class BreakIterator;
class RelativeDateTimeCacheData;
class SharedNumberFormat;
class SharedPluralRules;
class SharedBreakIterator;
class NumberFormat;
class UnicodeString;
class FormattedRelativeDateTime;
class FormattedRelativeDateTimeData;
/**
* An immutable class containing the result of a relative datetime formatting operation.
*
* Instances of this class are immutable and thread-safe.
*
* Not intended for public subclassing.
*
* @stable ICU 64
*/
class U_I18N_API FormattedRelativeDateTime : public UMemory, public FormattedValue {
public:
/**
* Default constructor; makes an empty FormattedRelativeDateTime.
* @stable ICU 64
*/
FormattedRelativeDateTime() : fData(nullptr), fErrorCode(U_INVALID_STATE_ERROR) {}
/**
* Move constructor: Leaves the source FormattedRelativeDateTime in an undefined state.
* @stable ICU 64
*/
FormattedRelativeDateTime(FormattedRelativeDateTime&& src) noexcept;
/**
* Destruct an instance of FormattedRelativeDateTime.
* @stable ICU 64
*/
virtual ~FormattedRelativeDateTime() override;
/** Copying not supported; use move constructor instead. */
FormattedRelativeDateTime(const FormattedRelativeDateTime&) = delete;
/** Copying not supported; use move assignment instead. */
FormattedRelativeDateTime& operator=(const FormattedRelativeDateTime&) = delete;
/**
* Move assignment: Leaves the source FormattedRelativeDateTime in an undefined state.
* @stable ICU 64
*/
FormattedRelativeDateTime& operator=(FormattedRelativeDateTime&& src) noexcept;
/** @copydoc FormattedValue::toString() */
UnicodeString toString(UErrorCode& status) const override;
/** @copydoc FormattedValue::toTempString() */
UnicodeString toTempString(UErrorCode& status) const override;
/** @copydoc FormattedValue::appendTo() */
Appendable &appendTo(Appendable& appendable, UErrorCode& status) const override;
/** @copydoc FormattedValue::nextPosition() */
UBool nextPosition(ConstrainedFieldPosition& cfpos, UErrorCode& status) const override;
private:
FormattedRelativeDateTimeData *fData;
UErrorCode fErrorCode;
explicit FormattedRelativeDateTime(FormattedRelativeDateTimeData *results)
: fData(results), fErrorCode(U_ZERO_ERROR) {}
explicit FormattedRelativeDateTime(UErrorCode errorCode)
: fData(nullptr), fErrorCode(errorCode) {}
friend class RelativeDateTimeFormatter;
};
/**
* Formats simple relative dates. There are two types of relative dates that
* it handles:
* <ul>
* <li>relative dates with a quantity e.g "in 5 days"</li>
* <li>relative dates without a quantity e.g "next Tuesday"</li>
* </ul>
* <p>
* This API is very basic and is intended to be a building block for more
* fancy APIs. The caller tells it exactly what to display in a locale
* independent way. While this class automatically provides the correct plural
* forms, the grammatical form is otherwise as neutral as possible. It is the
* caller's responsibility to handle cut-off logic such as deciding between
* displaying "in 7 days" or "in 1 week." This API supports relative dates
* involving one single unit. This API does not support relative dates
* involving compound units,
* e.g "in 5 days and 4 hours" nor does it support parsing.
* <p>
* This class is mostly thread safe and immutable with the following caveats:
* 1. The assignment operator violates Immutability. It must not be used
* concurrently with other operations.
* 2. Caller must not hold onto adopted pointers.
* <p>
* This class is not intended for public subclassing.
* <p>
* Here are some examples of use:
* <blockquote>
* <pre>
* UErrorCode status = U_ZERO_ERROR;
* UnicodeString appendTo;
* RelativeDateTimeFormatter fmt(status);
* // Appends "in 1 day"
* fmt.format(
* 1, UDAT_DIRECTION_NEXT, UDAT_RELATIVE_DAYS, appendTo, status);
* // Appends "in 3 days"
* fmt.format(
* 3, UDAT_DIRECTION_NEXT, UDAT_RELATIVE_DAYS, appendTo, status);
* // Appends "3.2 years ago"
* fmt.format(
* 3.2, UDAT_DIRECTION_LAST, UDAT_RELATIVE_YEARS, appendTo, status);
* // Appends "last Sunday"
* fmt.format(UDAT_DIRECTION_LAST, UDAT_ABSOLUTE_SUNDAY, appendTo, status);
* // Appends "this Sunday"
* fmt.format(UDAT_DIRECTION_THIS, UDAT_ABSOLUTE_SUNDAY, appendTo, status);
* // Appends "next Sunday"
* fmt.format(UDAT_DIRECTION_NEXT, UDAT_ABSOLUTE_SUNDAY, appendTo, status);
* // Appends "Sunday"
* fmt.format(UDAT_DIRECTION_PLAIN, UDAT_ABSOLUTE_SUNDAY, appendTo, status);
*
* // Appends "yesterday"
* fmt.format(UDAT_DIRECTION_LAST, UDAT_ABSOLUTE_DAY, appendTo, status);
* // Appends "today"
* fmt.format(UDAT_DIRECTION_THIS, UDAT_ABSOLUTE_DAY, appendTo, status);
* // Appends "tomorrow"
* fmt.format(UDAT_DIRECTION_NEXT, UDAT_ABSOLUTE_DAY, appendTo, status);
* // Appends "now"
* fmt.format(UDAT_DIRECTION_PLAIN, UDAT_ABSOLUTE_NOW, appendTo, status);
*
* </pre>
* </blockquote>
* <p>
* The UDateRelativeDateTimeFormatterStyle parameter allows selection of
* different length styles: LONG ("3 seconds ago"), SHORT ("3 sec. ago"),
* NARROW ("3s ago"). In the future, we may add more forms, such as
* relative day periods ("yesterday afternoon"), etc.
*
* The RelativeDateTimeFormatter class is not intended for public subclassing.
*
* @stable ICU 53
*/
class U_I18N_API RelativeDateTimeFormatter : public UObject {
public:
/**
* Create RelativeDateTimeFormatter with default locale.
* @stable ICU 53
*/
RelativeDateTimeFormatter(UErrorCode& status);
/**
* Create RelativeDateTimeFormatter with given locale.
* @stable ICU 53
*/
RelativeDateTimeFormatter(const Locale& locale, UErrorCode& status);
/**
* Create RelativeDateTimeFormatter with given locale and NumberFormat.
*
* @param locale the locale
* @param nfToAdopt Constructed object takes ownership of this pointer.
* It is an error for caller to delete this pointer or change its
* contents after calling this constructor.
* @param status Any error is returned here.
* @stable ICU 53
*/
RelativeDateTimeFormatter(
const Locale& locale, NumberFormat *nfToAdopt, UErrorCode& status);
/**
* Create RelativeDateTimeFormatter with given locale, NumberFormat,
* and capitalization context.
*
* @param locale the locale
* @param nfToAdopt Constructed object takes ownership of this pointer.
* It is an error for caller to delete this pointer or change its
* contents after calling this constructor. Caller may pass nullptr for
* this argument if they want default number format behavior.
* @param style the format style. The UDAT_RELATIVE bit field has no effect.
* @param capitalizationContext A value from UDisplayContext that pertains to
* capitalization.
* @param status Any error is returned here.
* @stable ICU 54
*/
RelativeDateTimeFormatter(
const Locale& locale,
NumberFormat *nfToAdopt,
UDateRelativeDateTimeFormatterStyle style,
UDisplayContext capitalizationContext,
UErrorCode& status);
/**
* Copy constructor.
* @stable ICU 53
*/
RelativeDateTimeFormatter(const RelativeDateTimeFormatter& other);
/**
* Assignment operator.
* @stable ICU 53
*/
RelativeDateTimeFormatter& operator=(
const RelativeDateTimeFormatter& other);
/**
* Destructor.
* @stable ICU 53
*/
virtual ~RelativeDateTimeFormatter();
/**
* Formats a relative date with a quantity such as "in 5 days" or
* "3 months ago"
*
* This method returns a String. To get more information about the
* formatting result, use formatToValue().
*
* @param quantity The numerical amount e.g 5. This value is formatted
* according to this object's NumberFormat object.
* @param direction NEXT means a future relative date; LAST means a past
* relative date. If direction is anything else, this method sets
* status to U_ILLEGAL_ARGUMENT_ERROR.
* @param unit the unit e.g day? month? year?
* @param appendTo The string to which the formatted result will be
* appended
* @param status ICU error code returned here.
* @return appendTo
* @stable ICU 53
*/
UnicodeString& format(
double quantity,
UDateDirection direction,
UDateRelativeUnit unit,
UnicodeString& appendTo,
UErrorCode& status) const;
/**
* Formats a relative date with a quantity such as "in 5 days" or
* "3 months ago"
*
* This method returns a FormattedRelativeDateTime, which exposes more
* information than the String returned by format().
*
* @param quantity The numerical amount e.g 5. This value is formatted
* according to this object's NumberFormat object.
* @param direction NEXT means a future relative date; LAST means a past
* relative date. If direction is anything else, this method sets
* status to U_ILLEGAL_ARGUMENT_ERROR.
* @param unit the unit e.g day? month? year?
* @param status ICU error code returned here.
* @return The formatted relative datetime
* @stable ICU 64
*/
FormattedRelativeDateTime formatToValue(
double quantity,
UDateDirection direction,
UDateRelativeUnit unit,
UErrorCode& status) const;
/**
* Formats a relative date without a quantity.
*
* This method returns a String. To get more information about the
* formatting result, use formatToValue().
*
* @param direction NEXT, LAST, THIS, etc.
* @param unit e.g SATURDAY, DAY, MONTH
* @param appendTo The string to which the formatted result will be
* appended. If the value of direction is documented as not being fully
* supported in all locales then this method leaves appendTo unchanged if
* no format string is available.
* @param status ICU error code returned here.
* @return appendTo
* @stable ICU 53
*/
UnicodeString& format(
UDateDirection direction,
UDateAbsoluteUnit unit,
UnicodeString& appendTo,
UErrorCode& status) const;
/**
* Formats a relative date without a quantity.
*
* This method returns a FormattedRelativeDateTime, which exposes more
* information than the String returned by format().
*
* If the string is not available in the requested locale, the return
* value will be empty (calling toString will give an empty string).
*
* @param direction NEXT, LAST, THIS, etc.
* @param unit e.g SATURDAY, DAY, MONTH
* @param status ICU error code returned here.
* @return The formatted relative datetime
* @stable ICU 64
*/
FormattedRelativeDateTime formatToValue(
UDateDirection direction,
UDateAbsoluteUnit unit,
UErrorCode& status) const;
/**
* Format a combination of URelativeDateTimeUnit and numeric offset
* using a numeric style, e.g. "1 week ago", "in 1 week",
* "5 weeks ago", "in 5 weeks".
*
* This method returns a String. To get more information about the
* formatting result, use formatNumericToValue().
*
* @param offset The signed offset for the specified unit. This
* will be formatted according to this object's
* NumberFormat object.
* @param unit The unit to use when formatting the relative
* date, e.g. UDAT_REL_UNIT_WEEK,
* UDAT_REL_UNIT_FRIDAY.
* @param appendTo The string to which the formatted result will be
* appended.
* @param status ICU error code returned here.
* @return appendTo
* @stable ICU 57
*/
UnicodeString& formatNumeric(
double offset,
URelativeDateTimeUnit unit,
UnicodeString& appendTo,
UErrorCode& status) const;
/**
* Format a combination of URelativeDateTimeUnit and numeric offset
* using a numeric style, e.g. "1 week ago", "in 1 week",
* "5 weeks ago", "in 5 weeks".
*
* This method returns a FormattedRelativeDateTime, which exposes more
* information than the String returned by formatNumeric().
*
* @param offset The signed offset for the specified unit. This
* will be formatted according to this object's
* NumberFormat object.
* @param unit The unit to use when formatting the relative
* date, e.g. UDAT_REL_UNIT_WEEK,
* UDAT_REL_UNIT_FRIDAY.
* @param status ICU error code returned here.
* @return The formatted relative datetime
* @stable ICU 64
*/
FormattedRelativeDateTime formatNumericToValue(
double offset,
URelativeDateTimeUnit unit,
UErrorCode& status) const;
/**
* Format a combination of URelativeDateTimeUnit and numeric offset
* using a text style if possible, e.g. "last week", "this week",
* "next week", "yesterday", "tomorrow". Falls back to numeric
* style if no appropriate text term is available for the specified
* offset in the object's locale.
*
* This method returns a String. To get more information about the
* formatting result, use formatToValue().
*
* @param offset The signed offset for the specified unit.
* @param unit The unit to use when formatting the relative
* date, e.g. UDAT_REL_UNIT_WEEK,
* UDAT_REL_UNIT_FRIDAY.
* @param appendTo The string to which the formatted result will be
* appended.
* @param status ICU error code returned here.
* @return appendTo
* @stable ICU 57
*/
UnicodeString& format(
double offset,
URelativeDateTimeUnit unit,
UnicodeString& appendTo,
UErrorCode& status) const;
/**
* Format a combination of URelativeDateTimeUnit and numeric offset
* using a text style if possible, e.g. "last week", "this week",
* "next week", "yesterday", "tomorrow". Falls back to numeric
* style if no appropriate text term is available for the specified
* offset in the object's locale.
*
* This method returns a FormattedRelativeDateTime, which exposes more
* information than the String returned by format().
*
* @param offset The signed offset for the specified unit.
* @param unit The unit to use when formatting the relative
* date, e.g. UDAT_REL_UNIT_WEEK,
* UDAT_REL_UNIT_FRIDAY.
* @param status ICU error code returned here.
* @return The formatted relative datetime
* @stable ICU 64
*/
FormattedRelativeDateTime formatToValue(
double offset,
URelativeDateTimeUnit unit,
UErrorCode& status) const;
/**
* Combines a relative date string and a time string in this object's
* locale. This is done with the same date-time separator used for the
* default calendar in this locale.
*
* @param relativeDateString the relative date, e.g 'yesterday'
* @param timeString the time e.g '3:45'
* @param appendTo concatenated date and time appended here
* @param status ICU error code returned here.
* @return appendTo
* @stable ICU 53
*/
UnicodeString& combineDateAndTime(
const UnicodeString& relativeDateString,
const UnicodeString& timeString,
UnicodeString& appendTo,
UErrorCode& status) const;
/**
* Returns the NumberFormat this object is using.
*
* @stable ICU 53
*/
const NumberFormat& getNumberFormat() const;
/**
* Returns the capitalization context.
*
* @stable ICU 54
*/
UDisplayContext getCapitalizationContext() const;
/**
* Returns the format style.
*
* @stable ICU 54
*/
UDateRelativeDateTimeFormatterStyle getFormatStyle() const;
private:
const RelativeDateTimeCacheData* fCache;
const SharedNumberFormat *fNumberFormat;
const SharedPluralRules *fPluralRules;
UDateRelativeDateTimeFormatterStyle fStyle;
UDisplayContext fContext;
#if !UCONFIG_NO_BREAK_ITERATION
const SharedBreakIterator *fOptBreakIterator;
#else
std::nullptr_t fOptBreakIterator = nullptr;
#endif // !UCONFIG_NO_BREAK_ITERATION
Locale fLocale;
void init(
NumberFormat *nfToAdopt,
#if !UCONFIG_NO_BREAK_ITERATION
BreakIterator *brkIter,
#else
std::nullptr_t,
#endif // !UCONFIG_NO_BREAK_ITERATION
UErrorCode &status);
UnicodeString& adjustForContext(UnicodeString &) const;
UBool checkNoAdjustForContext(UErrorCode& status) const;
template<typename F, typename... Args>
UnicodeString& doFormat(
F callback,
UnicodeString& appendTo,
UErrorCode& status,
Args... args) const;
template<typename F, typename... Args>
FormattedRelativeDateTime doFormatToValue(
F callback,
UErrorCode& status,
Args... args) const;
void formatImpl(
double quantity,
UDateDirection direction,
UDateRelativeUnit unit,
FormattedRelativeDateTimeData& output,
UErrorCode& status) const;
void formatAbsoluteImpl(
UDateDirection direction,
UDateAbsoluteUnit unit,
FormattedRelativeDateTimeData& output,
UErrorCode& status) const;
void formatNumericImpl(
double offset,
URelativeDateTimeUnit unit,
FormattedRelativeDateTimeData& output,
UErrorCode& status) const;
void formatRelativeImpl(
double offset,
URelativeDateTimeUnit unit,
FormattedRelativeDateTimeData& output,
UErrorCode& status) const;
};
U_NAMESPACE_END
#endif /* !UCONFIG_NO_FORMATTING */
#endif /* U_SHOW_CPLUSPLUS_API */
#endif /* __RELDATEFMT_H */

View File

@ -0,0 +1,222 @@
// © 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
/*
**********************************************************************
* Copyright (c) 2014-2016, International Business Machines
* Corporation and others. All Rights Reserved.
**********************************************************************
*/
#ifndef SCINUMBERFORMATTER_H
#define SCINUMBERFORMATTER_H
#include "unicode/utypes.h"
#if U_SHOW_CPLUSPLUS_API
#if !UCONFIG_NO_FORMATTING
#include "unicode/unistr.h"
/**
* \file
* \brief C++ API: Formats in scientific notation.
*/
U_NAMESPACE_BEGIN
class FieldPositionIterator;
class DecimalFormatSymbols;
class DecimalFormat;
class Formattable;
/**
* A formatter that formats numbers in user-friendly scientific notation.
*
* Sample code:
* <pre>
* UErrorCode status = U_ZERO_ERROR;
* LocalPointer<ScientificNumberFormatter> fmt(
* ScientificNumberFormatter::createMarkupInstance(
* "en", "<sup>", "</sup>", status));
* if (U_FAILURE(status)) {
* return;
* }
* UnicodeString appendTo;
* // appendTo = "1.23456x10<sup>-78</sup>"
* fmt->format(1.23456e-78, appendTo, status);
* </pre>
*
* @stable ICU 55
*/
class U_I18N_API ScientificNumberFormatter : public UObject {
public:
/**
* Creates a ScientificNumberFormatter instance that uses
* superscript characters for exponents.
* @param fmtToAdopt The DecimalFormat which must be configured for
* scientific notation.
* @param status error returned here.
* @return The new ScientificNumberFormatter instance.
*
* @stable ICU 55
*/
static ScientificNumberFormatter *createSuperscriptInstance(
DecimalFormat *fmtToAdopt, UErrorCode &status);
/**
* Creates a ScientificNumberFormatter instance that uses
* superscript characters for exponents for this locale.
* @param locale The locale
* @param status error returned here.
* @return The ScientificNumberFormatter instance.
*
* @stable ICU 55
*/
static ScientificNumberFormatter *createSuperscriptInstance(
const Locale &locale, UErrorCode &status);
/**
* Creates a ScientificNumberFormatter instance that uses
* markup for exponents.
* @param fmtToAdopt The DecimalFormat which must be configured for
* scientific notation.
* @param beginMarkup the markup to start superscript.
* @param endMarkup the markup to end superscript.
* @param status error returned here.
* @return The new ScientificNumberFormatter instance.
*
* @stable ICU 55
*/
static ScientificNumberFormatter *createMarkupInstance(
DecimalFormat *fmtToAdopt,
const UnicodeString &beginMarkup,
const UnicodeString &endMarkup,
UErrorCode &status);
/**
* Creates a ScientificNumberFormatter instance that uses
* markup for exponents for this locale.
* @param locale The locale
* @param beginMarkup the markup to start superscript.
* @param endMarkup the markup to end superscript.
* @param status error returned here.
* @return The ScientificNumberFormatter instance.
*
* @stable ICU 55
*/
static ScientificNumberFormatter *createMarkupInstance(
const Locale &locale,
const UnicodeString &beginMarkup,
const UnicodeString &endMarkup,
UErrorCode &status);
/**
* Returns a copy of this object. Caller must free returned copy.
* @stable ICU 55
*/
ScientificNumberFormatter *clone() const {
return new ScientificNumberFormatter(*this);
}
/**
* Destructor.
* @stable ICU 55
*/
virtual ~ScientificNumberFormatter();
/**
* Formats a number into user friendly scientific notation.
*
* @param number the number to format.
* @param appendTo formatted string appended here.
* @param status any error returned here.
* @return appendTo
*
* @stable ICU 55
*/
UnicodeString &format(
const Formattable &number,
UnicodeString &appendTo,
UErrorCode &status) const;
private:
class U_I18N_API Style : public UObject {
public:
virtual Style *clone() const = 0;
protected:
virtual UnicodeString &format(
const UnicodeString &original,
FieldPositionIterator &fpi,
const UnicodeString &preExponent,
UnicodeString &appendTo,
UErrorCode &status) const = 0;
private:
friend class ScientificNumberFormatter;
};
class U_I18N_API SuperscriptStyle : public Style {
public:
virtual SuperscriptStyle *clone() const override;
protected:
virtual UnicodeString &format(
const UnicodeString &original,
FieldPositionIterator &fpi,
const UnicodeString &preExponent,
UnicodeString &appendTo,
UErrorCode &status) const override;
};
class U_I18N_API MarkupStyle : public Style {
public:
MarkupStyle(
const UnicodeString &beginMarkup,
const UnicodeString &endMarkup)
: Style(),
fBeginMarkup(beginMarkup),
fEndMarkup(endMarkup) { }
virtual MarkupStyle *clone() const override;
protected:
virtual UnicodeString &format(
const UnicodeString &original,
FieldPositionIterator &fpi,
const UnicodeString &preExponent,
UnicodeString &appendTo,
UErrorCode &status) const override;
private:
UnicodeString fBeginMarkup;
UnicodeString fEndMarkup;
};
ScientificNumberFormatter(
DecimalFormat *fmtToAdopt,
Style *styleToAdopt,
UErrorCode &status);
ScientificNumberFormatter(const ScientificNumberFormatter &other);
ScientificNumberFormatter &operator=(const ScientificNumberFormatter &) = delete;
static void getPreExponent(
const DecimalFormatSymbols &dfs, UnicodeString &preExponent);
static ScientificNumberFormatter *createInstance(
DecimalFormat *fmtToAdopt,
Style *styleToAdopt,
UErrorCode &status);
UnicodeString fPreExponent;
DecimalFormat *fDecimalFormat;
Style *fStyle;
};
U_NAMESPACE_END
#endif /* !UCONFIG_NO_FORMATTING */
#endif /* U_SHOW_CPLUSPLUS_API */
#endif

View File

@ -0,0 +1,580 @@
// © 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
/*
**********************************************************************
* Copyright (C) 2001-2011 IBM and others. All rights reserved.
**********************************************************************
* Date Name Description
* 03/22/2000 helena Creation.
**********************************************************************
*/
#ifndef SEARCH_H
#define SEARCH_H
#include "unicode/utypes.h"
#if U_SHOW_CPLUSPLUS_API
/**
* \file
* \brief C++ API: SearchIterator object.
*/
#if !UCONFIG_NO_COLLATION && !UCONFIG_NO_BREAK_ITERATION
#include "unicode/uobject.h"
#include "unicode/unistr.h"
#include "unicode/chariter.h"
#include "unicode/brkiter.h"
#include "unicode/usearch.h"
/**
* @stable ICU 2.0
*/
struct USearch;
/**
* @stable ICU 2.0
*/
typedef struct USearch USearch;
U_NAMESPACE_BEGIN
/**
*
* <tt>SearchIterator</tt> is an abstract base class that provides
* methods to search for a pattern within a text string. Instances of
* <tt>SearchIterator</tt> maintain a current position and scans over the
* target text, returning the indices the pattern is matched and the length
* of each match.
* <p>
* <tt>SearchIterator</tt> defines a protocol for text searching.
* Subclasses provide concrete implementations of various search algorithms.
* For example, <tt>StringSearch</tt> implements language-sensitive pattern
* matching based on the comparison rules defined in a
* <tt>RuleBasedCollator</tt> object.
* <p>
* Other options for searching includes using a BreakIterator to restrict
* the points at which matches are detected.
* <p>
* <tt>SearchIterator</tt> provides an API that is similar to that of
* other text iteration classes such as <tt>BreakIterator</tt>. Using
* this class, it is easy to scan through text looking for all occurrences of
* a given pattern. The following example uses a <tt>StringSearch</tt>
* object to find all instances of "fox" in the target string. Any other
* subclass of <tt>SearchIterator</tt> can be used in an identical
* manner.
* <pre><code>
* UnicodeString target("The quick brown fox jumped over the lazy fox");
* UnicodeString pattern("fox");
*
* SearchIterator *iter = new StringSearch(pattern, target);
* UErrorCode error = U_ZERO_ERROR;
* for (int pos = iter->first(error); pos != USEARCH_DONE;
* pos = iter->next(error)) {
* printf("Found match at %d pos, length is %d\n", pos, iter.getMatchedLength());
* }
* </code></pre>
*
* @see StringSearch
* @see RuleBasedCollator
*/
class U_I18N_API SearchIterator : public UObject {
public:
// public constructors and destructors -------------------------------
/**
* Copy constructor that creates a SearchIterator instance with the same
* behavior, and iterating over the same text.
* @param other the SearchIterator instance to be copied.
* @stable ICU 2.0
*/
SearchIterator(const SearchIterator &other);
/**
* Destructor. Cleans up the search iterator data struct.
* @stable ICU 2.0
*/
virtual ~SearchIterator();
// public get and set methods ----------------------------------------
/**
* Sets the index to point to the given position, and clears any state
* that's affected.
* <p>
* This method takes the argument index and sets the position in the text
* string accordingly without checking if the index is pointing to a
* valid starting point to begin searching.
* @param position within the text to be set. If position is less
* than or greater than the text range for searching,
* an U_INDEX_OUTOFBOUNDS_ERROR will be returned
* @param status for errors if it occurs
* @stable ICU 2.0
*/
virtual void setOffset(int32_t position, UErrorCode &status) = 0;
/**
* Return the current index in the text being searched.
* If the iteration has gone past the end of the text
* (or past the beginning for a backwards search), USEARCH_DONE
* is returned.
* @return current index in the text being searched.
* @stable ICU 2.0
*/
virtual int32_t getOffset() const = 0;
/**
* Sets the text searching attributes located in the enum
* USearchAttribute with values from the enum USearchAttributeValue.
* USEARCH_DEFAULT can be used for all attributes for resetting.
* @param attribute text attribute (enum USearchAttribute) to be set
* @param value text attribute value
* @param status for errors if it occurs
* @stable ICU 2.0
*/
void setAttribute(USearchAttribute attribute,
USearchAttributeValue value,
UErrorCode &status);
/**
* Gets the text searching attributes
* @param attribute text attribute (enum USearchAttribute) to be retrieve
* @return text attribute value
* @stable ICU 2.0
*/
USearchAttributeValue getAttribute(USearchAttribute attribute) const;
/**
* Returns the index to the match in the text string that was searched.
* This call returns a valid result only after a successful call to
* <tt>first</tt>, <tt>next</tt>, <tt>previous</tt>, or <tt>last</tt>.
* Just after construction, or after a searching method returns
* <tt>USEARCH_DONE</tt>, this method will return <tt>USEARCH_DONE</tt>.
* <p>
* Use getMatchedLength to get the matched string length.
* @return index of a substring within the text string that is being
* searched.
* @see #first
* @see #next
* @see #previous
* @see #last
* @stable ICU 2.0
*/
int32_t getMatchedStart() const;
/**
* Returns the length of text in the string which matches the search
* pattern. This call returns a valid result only after a successful call
* to <tt>first</tt>, <tt>next</tt>, <tt>previous</tt>, or <tt>last</tt>.
* Just after construction, or after a searching method returns
* <tt>USEARCH_DONE</tt>, this method will return 0.
* @return The length of the match in the target text, or 0 if there
* is no match currently.
* @see #first
* @see #next
* @see #previous
* @see #last
* @stable ICU 2.0
*/
int32_t getMatchedLength() const;
/**
* Returns the text that was matched by the most recent call to
* <tt>first</tt>, <tt>next</tt>, <tt>previous</tt>, or <tt>last</tt>.
* If the iterator is not pointing at a valid match (e.g. just after
* construction or after <tt>USEARCH_DONE</tt> has been returned,
* returns an empty string.
* @param result stores the matched string or an empty string if a match
* is not found.
* @see #first
* @see #next
* @see #previous
* @see #last
* @stable ICU 2.0
*/
void getMatchedText(UnicodeString &result) const;
/**
* Set the BreakIterator that will be used to restrict the points
* at which matches are detected. The user is responsible for deleting
* the breakiterator.
* @param breakiter A BreakIterator that will be used to restrict the
* points at which matches are detected. If a match is
* found, but the match's start or end index is not a
* boundary as determined by the <tt>BreakIterator</tt>,
* the match will be rejected and another will be searched
* for. If this parameter is <tt>nullptr</tt>, no break
* detection is attempted.
* @param status for errors if it occurs
* @see BreakIterator
* @stable ICU 2.0
*/
void setBreakIterator(BreakIterator *breakiter, UErrorCode &status);
/**
* Returns the BreakIterator that is used to restrict the points at
* which matches are detected. This will be the same object that was
* passed to the constructor or to <tt>setBreakIterator</tt>.
* Note that <tt>nullptr</tt> is a legal value; it means that break
* detection should not be attempted.
* @return BreakIterator used to restrict matchings.
* @see #setBreakIterator
* @stable ICU 2.0
*/
const BreakIterator* getBreakIterator() const;
/**
* Set the string text to be searched. Text iteration will hence begin at
* the start of the text string. This method is useful if you want to
* re-use an iterator to search for the same pattern within a different
* body of text. The user is responsible for deleting the text.
* @param text string to be searched.
* @param status for errors. If the text length is 0,
* an U_ILLEGAL_ARGUMENT_ERROR is returned.
* @stable ICU 2.0
*/
virtual void setText(const UnicodeString &text, UErrorCode &status);
/**
* Set the string text to be searched. Text iteration will hence begin at
* the start of the text string. This method is useful if you want to
* re-use an iterator to search for the same pattern within a different
* body of text.
* <p>
* Note: No parsing of the text within the <tt>CharacterIterator</tt>
* will be done during searching for this version. The block of text
* in <tt>CharacterIterator</tt> will be used as it is.
* The user is responsible for deleting the text.
* @param text string iterator to be searched.
* @param status for errors if any. If the text length is 0 then an
* U_ILLEGAL_ARGUMENT_ERROR is returned.
* @stable ICU 2.0
*/
virtual void setText(CharacterIterator &text, UErrorCode &status);
/**
* Return the string text to be searched.
* @return text string to be searched.
* @stable ICU 2.0
*/
const UnicodeString& getText() const;
// operator overloading ----------------------------------------------
/**
* Equality operator.
* @param that SearchIterator instance to be compared.
* @return true if both BreakIterators are of the same class, have the
* same behavior, terates over the same text and have the same
* attributes. false otherwise.
* @stable ICU 2.0
*/
virtual bool operator==(const SearchIterator &that) const;
/**
* Not-equal operator.
* @param that SearchIterator instance to be compared.
* @return false if operator== returns true, and vice versa.
* @stable ICU 2.0
*/
bool operator!=(const SearchIterator &that) const;
// public methods ----------------------------------------------------
/**
* Returns a copy of SearchIterator with the same behavior, and
* iterating over the same text, as this one. Note that all data will be
* replicated, except for the text string to be searched.
* @return cloned object
* @stable ICU 2.0
*/
virtual SearchIterator* safeClone() const = 0;
/**
* Returns the first index at which the string text matches the search
* pattern. The iterator is adjusted so that its current index (as
* returned by <tt>getOffset</tt>) is the match position if one
* was found.
* If a match is not found, <tt>USEARCH_DONE</tt> will be returned and
* the iterator will be adjusted to the index USEARCH_DONE
* @param status for errors if it occurs
* @return The character index of the first match, or
* <tt>USEARCH_DONE</tt> if there are no matches.
* @see #getOffset
* @stable ICU 2.0
*/
int32_t first(UErrorCode &status);
/**
* Returns the first index equal or greater than <tt>position</tt> at which the
* string text matches the search pattern. The iterator is adjusted so
* that its current index (as returned by <tt>getOffset</tt>) is the
* match position if one was found.
* If a match is not found, <tt>USEARCH_DONE</tt> will be returned and the
* iterator will be adjusted to the index <tt>USEARCH_DONE</tt>.
* @param position where search if to start from. If position is less
* than or greater than the text range for searching,
* an U_INDEX_OUTOFBOUNDS_ERROR will be returned
* @param status for errors if it occurs
* @return The character index of the first match following
* <tt>position</tt>, or <tt>USEARCH_DONE</tt> if there are no
* matches.
* @see #getOffset
* @stable ICU 2.0
*/
int32_t following(int32_t position, UErrorCode &status);
/**
* Returns the last index in the target text at which it matches the
* search pattern. The iterator is adjusted so that its current index
* (as returned by <tt>getOffset</tt>) is the match position if one was
* found.
* If a match is not found, <tt>USEARCH_DONE</tt> will be returned and
* the iterator will be adjusted to the index USEARCH_DONE.
* @param status for errors if it occurs
* @return The index of the first match, or <tt>USEARCH_DONE</tt> if
* there are no matches.
* @see #getOffset
* @stable ICU 2.0
*/
int32_t last(UErrorCode &status);
/**
* Returns the first index less than <tt>position</tt> at which the string
* text matches the search pattern. The iterator is adjusted so that its
* current index (as returned by <tt>getOffset</tt>) is the match
* position if one was found. If a match is not found,
* <tt>USEARCH_DONE</tt> will be returned and the iterator will be
* adjusted to the index USEARCH_DONE
* <p>
* When <tt>USEARCH_OVERLAP</tt> option is off, the last index of the
* result match is always less than <tt>position</tt>.
* When <tt>USERARCH_OVERLAP</tt> is on, the result match may span across
* <tt>position</tt>.
*
* @param position where search is to start from. If position is less
* than or greater than the text range for searching,
* an U_INDEX_OUTOFBOUNDS_ERROR will be returned
* @param status for errors if it occurs
* @return The character index of the first match preceding
* <tt>position</tt>, or <tt>USEARCH_DONE</tt> if there are
* no matches.
* @see #getOffset
* @stable ICU 2.0
*/
int32_t preceding(int32_t position, UErrorCode &status);
/**
* Returns the index of the next point at which the text matches the
* search pattern, starting from the current position
* The iterator is adjusted so that its current index (as returned by
* <tt>getOffset</tt>) is the match position if one was found.
* If a match is not found, <tt>USEARCH_DONE</tt> will be returned and
* the iterator will be adjusted to a position after the end of the text
* string.
* @param status for errors if it occurs
* @return The index of the next match after the current position,
* or <tt>USEARCH_DONE</tt> if there are no more matches.
* @see #getOffset
* @stable ICU 2.0
*/
int32_t next(UErrorCode &status);
/**
* Returns the index of the previous point at which the string text
* matches the search pattern, starting at the current position.
* The iterator is adjusted so that its current index (as returned by
* <tt>getOffset</tt>) is the match position if one was found.
* If a match is not found, <tt>USEARCH_DONE</tt> will be returned and
* the iterator will be adjusted to the index USEARCH_DONE
* @param status for errors if it occurs
* @return The index of the previous match before the current position,
* or <tt>USEARCH_DONE</tt> if there are no more matches.
* @see #getOffset
* @stable ICU 2.0
*/
int32_t previous(UErrorCode &status);
/**
* Resets the iteration.
* Search will begin at the start of the text string if a forward
* iteration is initiated before a backwards iteration. Otherwise if a
* backwards iteration is initiated before a forwards iteration, the
* search will begin at the end of the text string.
* @stable ICU 2.0
*/
virtual void reset();
protected:
// protected data members ---------------------------------------------
/**
* C search data struct
* @stable ICU 2.0
*/
USearch *m_search_;
/**
* Break iterator.
* Currently the C++ breakiterator does not have getRules etc to reproduce
* another in C. Hence we keep the original around and do the verification
* at the end of the match. The user is responsible for deleting this
* break iterator.
* @stable ICU 2.0
*/
BreakIterator *m_breakiterator_;
/**
* Unicode string version of the search text
* @stable ICU 2.0
*/
UnicodeString m_text_;
// protected constructors and destructors -----------------------------
/**
* Default constructor.
* Initializes data to the default values.
* @stable ICU 2.0
*/
SearchIterator();
/**
* Constructor for use by subclasses.
* @param text The target text to be searched.
* @param breakiter A {@link BreakIterator} that is used to restrict the
* points at which matches are detected. If
* <tt>handleNext</tt> or <tt>handlePrev</tt> finds a
* match, but the match's start or end index is not a
* boundary as determined by the <tt>BreakIterator</tt>,
* the match is rejected and <tt>handleNext</tt> or
* <tt>handlePrev</tt> is called again. If this parameter
* is <tt>nullptr</tt>, no break detection is attempted.
* @see #handleNext
* @see #handlePrev
* @stable ICU 2.0
*/
SearchIterator(const UnicodeString &text,
BreakIterator *breakiter = nullptr);
/**
* Constructor for use by subclasses.
* <p>
* Note: No parsing of the text within the <tt>CharacterIterator</tt>
* will be done during searching for this version. The block of text
* in <tt>CharacterIterator</tt> will be used as it is.
* @param text The target text to be searched.
* @param breakiter A {@link BreakIterator} that is used to restrict the
* points at which matches are detected. If
* <tt>handleNext</tt> or <tt>handlePrev</tt> finds a
* match, but the match's start or end index is not a
* boundary as determined by the <tt>BreakIterator</tt>,
* the match is rejected and <tt>handleNext</tt> or
* <tt>handlePrev</tt> is called again. If this parameter
* is <tt>nullptr</tt>, no break detection is attempted.
* @see #handleNext
* @see #handlePrev
* @stable ICU 2.0
*/
SearchIterator(CharacterIterator &text, BreakIterator *breakiter = nullptr);
// protected methods --------------------------------------------------
/**
* Assignment operator. Sets this iterator to have the same behavior,
* and iterate over the same text, as the one passed in.
* @param that instance to be copied.
* @stable ICU 2.0
*/
SearchIterator & operator=(const SearchIterator &that);
/**
* Abstract method which subclasses override to provide the mechanism
* for finding the next match in the target text. This allows different
* subclasses to provide different search algorithms.
* <p>
* If a match is found, the implementation should return the index at
* which the match starts and should call
* <tt>setMatchLength</tt> with the number of characters
* in the target text that make up the match. If no match is found, the
* method should return USEARCH_DONE.
* <p>
* @param position The index in the target text at which the search
* should start.
* @param status for error codes if it occurs.
* @return index at which the match starts, else if match is not found
* USEARCH_DONE is returned
* @see #setMatchLength
* @stable ICU 2.0
*/
virtual int32_t handleNext(int32_t position, UErrorCode &status)
= 0;
/**
* Abstract method which subclasses override to provide the mechanism for
* finding the previous match in the target text. This allows different
* subclasses to provide different search algorithms.
* <p>
* If a match is found, the implementation should return the index at
* which the match starts and should call
* <tt>setMatchLength</tt> with the number of characters
* in the target text that make up the match. If no match is found, the
* method should return USEARCH_DONE.
* <p>
* @param position The index in the target text at which the search
* should start.
* @param status for error codes if it occurs.
* @return index at which the match starts, else if match is not found
* USEARCH_DONE is returned
* @see #setMatchLength
* @stable ICU 2.0
*/
virtual int32_t handlePrev(int32_t position, UErrorCode &status)
= 0;
/**
* Sets the length of the currently matched string in the text string to
* be searched.
* Subclasses' <tt>handleNext</tt> and <tt>handlePrev</tt>
* methods should call this when they find a match in the target text.
* @param length length of the matched text.
* @see #handleNext
* @see #handlePrev
* @stable ICU 2.0
*/
virtual void setMatchLength(int32_t length);
/**
* Sets the offset of the currently matched string in the text string to
* be searched.
* Subclasses' <tt>handleNext</tt> and <tt>handlePrev</tt>
* methods should call this when they find a match in the target text.
* @param position start offset of the matched text.
* @see #handleNext
* @see #handlePrev
* @stable ICU 2.0
*/
virtual void setMatchStart(int32_t position);
/**
* sets match not found
* @stable ICU 2.0
*/
void setMatchNotFound();
};
inline bool SearchIterator::operator!=(const SearchIterator &that) const
{
return !operator==(that);
}
U_NAMESPACE_END
#endif /* #if !UCONFIG_NO_COLLATION */
#endif /* U_SHOW_CPLUSPLUS_API */
#endif

View File

@ -0,0 +1,374 @@
// © 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
/********************************************************************
* COPYRIGHT:
* Copyright (c) 1997-2011, International Business Machines Corporation and
* others. All Rights Reserved.
* Copyright (C) 2010 , Yahoo! Inc.
********************************************************************
*
* File SELFMT.H
*
* Modification History:
*
* Date Name Description
* 11/11/09 kirtig Finished first cut of implementation.
********************************************************************/
#ifndef SELFMT
#define SELFMT
#include "unicode/utypes.h"
#if U_SHOW_CPLUSPLUS_API
#include "unicode/messagepattern.h"
#include "unicode/numfmt.h"
/**
* \file
* \brief C++ API: SelectFormat object
*/
#if !UCONFIG_NO_FORMATTING
U_NAMESPACE_BEGIN
class MessageFormat;
/**
* <p><code>SelectFormat</code> supports the creation of internationalized
* messages by selecting phrases based on keywords. The pattern specifies
* how to map keywords to phrases and provides a default phrase. The
* object provided to the format method is a string that's matched
* against the keywords. If there is a match, the corresponding phrase
* is selected; otherwise, the default phrase is used.</p>
*
* <h4>Using <code>SelectFormat</code> for Gender Agreement</h4>
*
* <p>Note: Typically, select formatting is done via <code>MessageFormat</code>
* with a <code>select</code> argument type,
* rather than using a stand-alone <code>SelectFormat</code>.</p>
*
* <p>The main use case for the select format is gender based inflection.
* When names or nouns are inserted into sentences, their gender can affect pronouns,
* verb forms, articles, and adjectives. Special care needs to be
* taken for the case where the gender cannot be determined.
* The impact varies between languages:</p>
* \htmlonly
* <ul>
* <li>English has three genders, and unknown gender is handled as a special
* case. Names use the gender of the named person (if known), nouns referring
* to people use natural gender, and inanimate objects are usually neutral.
* The gender only affects pronouns: "he", "she", "it", "they".
*
* <li>German differs from English in that the gender of nouns is rather
* arbitrary, even for nouns referring to people ("M&#x00E4;dchen", girl, is neutral).
* The gender affects pronouns ("er", "sie", "es"), articles ("der", "die",
* "das"), and adjective forms ("guter Mann", "gute Frau", "gutes M&#x00E4;dchen").
*
* <li>French has only two genders; as in German the gender of nouns
* is rather arbitrary - for sun and moon, the genders
* are the opposite of those in German. The gender affects
* pronouns ("il", "elle"), articles ("le", "la"),
* adjective forms ("bon", "bonne"), and sometimes
* verb forms ("all&#x00E9;", "all&#x00E9;e").
*
* <li>Polish distinguishes five genders (or noun classes),
* human masculine, animate non-human masculine, inanimate masculine,
* feminine, and neuter.
* </ul>
* \endhtmlonly
* <p>Some other languages have noun classes that are not related to gender,
* but similar in grammatical use.
* Some African languages have around 20 noun classes.</p>
*
* <p><b>Note:</b>For the gender of a <i>person</i> in a given sentence,
* we usually need to distinguish only between female, male and other/unknown.</p>
*
* <p>To enable localizers to create sentence patterns that take their
* language's gender dependencies into consideration, software has to provide
* information about the gender associated with a noun or name to
* <code>MessageFormat</code>.
* Two main cases can be distinguished:</p>
*
* <ul>
* <li>For people, natural gender information should be maintained for each person.
* Keywords like "male", "female", "mixed" (for groups of people)
* and "unknown" could be used.
*
* <li>For nouns, grammatical gender information should be maintained for
* each noun and per language, e.g., in resource bundles.
* The keywords "masculine", "feminine", and "neuter" are commonly used,
* but some languages may require other keywords.
* </ul>
*
* <p>The resulting keyword is provided to <code>MessageFormat</code> as a
* parameter separate from the name or noun it's associated with. For example,
* to generate a message such as "Jean went to Paris", three separate arguments
* would be provided: The name of the person as argument 0, the gender of
* the person as argument 1, and the name of the city as argument 2.
* The sentence pattern for English, where the gender of the person has
* no impact on this simple sentence, would not refer to argument 1 at all:</p>
*
* <pre>{0} went to {2}.</pre>
*
* <p><b>Note:</b> The entire sentence should be included (and partially repeated)
* inside each phrase. Otherwise translators would have to be trained on how to
* move bits of the sentence in and out of the select argument of a message.
* (The examples below do not follow this recommendation!)</p>
*
* <p>The sentence pattern for French, where the gender of the person affects
* the form of the participle, uses a select format based on argument 1:</p>
*
* \htmlonly<pre>{0} est {1, select, female {all&#x00E9;e} other {all&#x00E9;}} &#x00E0; {2}.</pre>\endhtmlonly
*
* <p>Patterns can be nested, so that it's possible to handle interactions of
* number and gender where necessary. For example, if the above sentence should
* allow for the names of several people to be inserted, the following sentence
* pattern can be used (with argument 0 the list of people's names,
* argument 1 the number of people, argument 2 their combined gender, and
* argument 3 the city name):</p>
*
* \htmlonly
* <pre>{0} {1, plural,
* one {est {2, select, female {all&#x00E9;e} other {all&#x00E9;}}}
* other {sont {2, select, female {all&#x00E9;es} other {all&#x00E9;s}}}
* }&#x00E0; {3}.</pre>
* \endhtmlonly
*
* <h4>Patterns and Their Interpretation</h4>
*
* <p>The <code>SelectFormat</code> pattern string defines the phrase output
* for each user-defined keyword.
* The pattern is a sequence of (keyword, message) pairs.
* A keyword is a "pattern identifier": [^[[:Pattern_Syntax:][:Pattern_White_Space:]]]+</p>
*
* <p>Each message is a MessageFormat pattern string enclosed in {curly braces}.</p>
*
* <p>You always have to define a phrase for the default keyword
* <code>other</code>; this phrase is returned when the keyword
* provided to
* the <code>format</code> method matches no other keyword.
* If a pattern does not provide a phrase for <code>other</code>, the method
* it's provided to returns the error <code>U_DEFAULT_KEYWORD_MISSING</code>.
* <br>
* Pattern_White_Space between keywords and messages is ignored.
* Pattern_White_Space within a message is preserved and output.</p>
*
* <p><pre>Example:
* \htmlonly
*
* UErrorCode status = U_ZERO_ERROR;
* MessageFormat *msgFmt = new MessageFormat(UnicodeString("{0} est {1, select, female {all&#x00E9;e} other {all&#x00E9;}} &#x00E0; Paris."), Locale("fr"), status);
* if (U_FAILURE(status)) {
* return;
* }
* FieldPosition ignore(FieldPosition::DONT_CARE);
* UnicodeString result;
*
* char* str1= "Kirti,female";
* Formattable args1[] = {"Kirti","female"};
* msgFmt->format(args1, 2, result, ignore, status);
* cout << "Input is " << str1 << " and result is: " << result << endl;
* delete msgFmt;
*
* \endhtmlonly
* </pre>
* </p>
*
* Produces the output:<br>
* \htmlonly
* <code>Kirti est all&#x00E9;e &#x00E0; Paris.</code>
* \endhtmlonly
*
* @stable ICU 4.4
*/
class U_I18N_API SelectFormat : public Format {
public:
/**
* Creates a new <code>SelectFormat</code> for a given pattern string.
* @param pattern the pattern for this <code>SelectFormat</code>.
* errors are returned to status if the pattern is invalid.
* @param status output param set to success/failure code on exit, which
* must not indicate a failure before the function call.
* @stable ICU 4.4
*/
SelectFormat(const UnicodeString& pattern, UErrorCode& status);
/**
* copy constructor.
* @stable ICU 4.4
*/
SelectFormat(const SelectFormat& other);
/**
* Destructor.
* @stable ICU 4.4
*/
virtual ~SelectFormat();
/**
* Sets the pattern used by this select format.
* for the keyword rules.
* Patterns and their interpretation are specified in the class description.
*
* @param pattern the pattern for this select format
* errors are returned to status if the pattern is invalid.
* @param status output param set to success/failure code on exit, which
* must not indicate a failure before the function call.
* @stable ICU 4.4
*/
void applyPattern(const UnicodeString& pattern, UErrorCode& status);
using Format::format;
/**
* Selects the phrase for the given keyword
*
* @param keyword The keyword that is used to select an alternative.
* @param appendTo output parameter to receive result.
* result is appended to existing contents.
* @param pos On input: an alignment field, if desired.
* On output: the offsets of the alignment field.
* @param status output param set to success/failure code on exit, which
* must not indicate a failure before the function call.
* @return Reference to 'appendTo' parameter.
* @stable ICU 4.4
*/
UnicodeString& format(const UnicodeString& keyword,
UnicodeString& appendTo,
FieldPosition& pos,
UErrorCode& status) const;
/**
* Assignment operator
*
* @param other the SelectFormat object to copy from.
* @stable ICU 4.4
*/
SelectFormat& operator=(const SelectFormat& other);
/**
* Return true if another object is semantically equal to this one.
*
* @param other the SelectFormat object to be compared with.
* @return true if other is semantically equal to this.
* @stable ICU 4.4
*/
virtual bool operator==(const Format& other) const override;
/**
* Return true if another object is semantically unequal to this one.
*
* @param other the SelectFormat object to be compared with.
* @return true if other is semantically unequal to this.
* @stable ICU 4.4
*/
virtual bool operator!=(const Format& other) const;
/**
* Clones this Format object polymorphically. The caller owns the
* result and should delete it when done.
* @stable ICU 4.4
*/
virtual SelectFormat* clone() const override;
/**
* Format an object to produce a string.
* This method handles keyword strings.
* If the Formattable object is not a <code>UnicodeString</code>,
* then it returns a failing UErrorCode.
*
* @param obj A keyword string that is used to select an alternative.
* @param appendTo output parameter to receive result.
* Result is appended to existing contents.
* @param pos On input: an alignment field, if desired.
* On output: the offsets of the alignment field.
* @param status output param filled with success/failure status.
* @return Reference to 'appendTo' parameter.
* @stable ICU 4.4
*/
UnicodeString& format(const Formattable& obj,
UnicodeString& appendTo,
FieldPosition& pos,
UErrorCode& status) const override;
/**
* Returns the pattern from applyPattern() or constructor.
*
* @param appendTo output parameter to receive result.
* Result is appended to existing contents.
* @return the UnicodeString with inserted pattern.
* @stable ICU 4.4
*/
UnicodeString& toPattern(UnicodeString& appendTo);
/**
* This method is not yet supported by <code>SelectFormat</code>.
* <P>
* Before calling, set parse_pos.index to the offset you want to start
* parsing at in the source. After calling, parse_pos.index is the end of
* the text you parsed. If error occurs, index is unchanged.
* <P>
* When parsing, leading whitespace is discarded (with a successful parse),
* while trailing whitespace is left as is.
* <P>
* See Format::parseObject() for more.
*
* @param source The string to be parsed into an object.
* @param result Formattable to be set to the parse result.
* If parse fails, return contents are undefined.
* @param parse_pos The position to start parsing at. Upon return
* this param is set to the position after the
* last character successfully parsed. If the
* source is not parsed successfully, this param
* will remain unchanged.
* @stable ICU 4.4
*/
virtual void parseObject(const UnicodeString& source,
Formattable& result,
ParsePosition& parse_pos) const override;
/**
* ICU "poor man's RTTI", returns a UClassID for this class.
* @stable ICU 4.4
*/
static UClassID U_EXPORT2 getStaticClassID();
/**
* ICU "poor man's RTTI", returns a UClassID for the actual class.
* @stable ICU 4.4
*/
virtual UClassID getDynamicClassID() const override;
private:
friend class MessageFormat;
SelectFormat() = delete; // default constructor not implemented.
/**
* Finds the SelectFormat sub-message for the given keyword, or the "other" sub-message.
* @param pattern A MessagePattern.
* @param partIndex the index of the first SelectFormat argument style part.
* @param keyword a keyword to be matched to one of the SelectFormat argument's keywords.
* @param ec Error code.
* @return the sub-message start part index.
*/
static int32_t findSubMessage(const MessagePattern& pattern, int32_t partIndex,
const UnicodeString& keyword, UErrorCode& ec);
MessagePattern msgPattern;
};
U_NAMESPACE_END
#endif /* #if !UCONFIG_NO_FORMATTING */
#endif /* U_SHOW_CPLUSPLUS_API */
#endif // _SELFMT
//eof

View File

@ -0,0 +1,324 @@
// © 2022 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
#ifndef __SIMPLENUMBERFORMATTERH__
#define __SIMPLENUMBERFORMATTERH__
#include "unicode/utypes.h"
#if U_SHOW_CPLUSPLUS_API
#if !UCONFIG_NO_FORMATTING
#include "unicode/dcfmtsym.h"
#include "unicode/usimplenumberformatter.h"
#include "unicode/formattednumber.h"
/**
* \file
* \brief C++ API: Simple number formatting focused on low memory and code size.
*
* These functions render locale-aware number strings but without the bells and whistles found in
* other number formatting APIs such as those in numberformatter.h, like units and currencies.
*
* <pre>
* SimpleNumberFormatter snf = SimpleNumberFormatter::forLocale("de-CH", status);
* FormattedNumber result = snf.formatInt64(-1000007, status);
* assertEquals("", u"-1000007", result.toString(status));
* </pre>
*/
U_NAMESPACE_BEGIN
/* forward declaration */
class SimpleDateFormat;
namespace number { // icu::number
namespace impl {
class UFormattedNumberData;
struct SimpleMicroProps;
class AdoptingSignumModifierStore;
} // icu::number::impl
/**
* An input type for SimpleNumberFormatter.
*
* This class is mutable and not intended for public subclassing. This class is movable but not copyable.
*
* @stable ICU 73
*/
class U_I18N_API SimpleNumber : public UMemory {
public:
/**
* Creates a SimpleNumber for an integer.
*
* @stable ICU 73
*/
static SimpleNumber forInt64(int64_t value, UErrorCode& status);
/**
* Changes the value of the SimpleNumber by a power of 10.
*
* This function immediately mutates the inner value.
*
* @stable ICU 73
*/
void multiplyByPowerOfTen(int32_t power, UErrorCode& status);
/**
* Rounds the value currently stored in the SimpleNumber to the given power of 10,
* which can be before or after the decimal separator.
*
* This function does not change minimum integer digits.
*
* @stable ICU 73
*/
void roundTo(int32_t power, UNumberFormatRoundingMode roundingMode, UErrorCode& status);
/**
* Sets the number of integer digits to the given amount, truncating if necessary.
*
* @stable ICU 75
*/
void setMaximumIntegerDigits(uint32_t maximumIntegerDigits, UErrorCode& status);
/**
* Pads the beginning of the number with zeros up to the given minimum number of integer digits.
*
* @stable ICU 73
*/
void setMinimumIntegerDigits(uint32_t minimumIntegerDigits, UErrorCode& status);
/**
* Pads the end of the number with zeros up to the given minimum number of fraction digits.
*
* @stable ICU 73
*/
void setMinimumFractionDigits(uint32_t minimumFractionDigits, UErrorCode& status);
/**
* Sets the sign of the number: an explicit plus sign, explicit minus sign, or no sign.
*
* This setting is applied upon formatting the number.
*
* NOTE: This does not support accounting sign notation.
*
* @stable ICU 73
*/
void setSign(USimpleNumberSign sign, UErrorCode& status);
/**
* Creates a new, empty SimpleNumber that does not contain a value.
*
* NOTE: This number will fail to format; use forInt64() to create a SimpleNumber with a value.
*
* @stable ICU 73
*/
SimpleNumber() = default;
/**
* Destruct this SimpleNumber, cleaning up any memory it might own.
*
* @stable ICU 73
*/
~SimpleNumber() {
cleanup();
}
/**
* SimpleNumber move constructor.
*
* @stable ICU 73
*/
SimpleNumber(SimpleNumber&& other) noexcept {
fData = other.fData;
fSign = other.fSign;
other.fData = nullptr;
}
/**
* SimpleNumber move assignment.
*
* @stable ICU 73
*/
SimpleNumber& operator=(SimpleNumber&& other) noexcept {
cleanup();
fData = other.fData;
fSign = other.fSign;
other.fData = nullptr;
return *this;
}
private:
SimpleNumber(impl::UFormattedNumberData* data, UErrorCode& status);
SimpleNumber(const SimpleNumber&) = delete;
SimpleNumber& operator=(const SimpleNumber&) = delete;
void cleanup();
impl::UFormattedNumberData* fData = nullptr;
USimpleNumberSign fSign = UNUM_SIMPLE_NUMBER_NO_SIGN;
friend class SimpleNumberFormatter;
// Uses the private constructor to avoid a heap allocation
friend class icu::SimpleDateFormat;
};
/**
* A special NumberFormatter focused on smaller binary size and memory use.
*
* SimpleNumberFormatter is capable of basic number formatting, including grouping separators,
* sign display, and rounding. It is not capable of currencies, compact notation, or units.
*
* This class is immutable and not intended for public subclassing. This class is movable but not copyable.
*
* @stable ICU 73
*/
class U_I18N_API SimpleNumberFormatter : public UMemory {
public:
/**
* Creates a new SimpleNumberFormatter with all locale defaults.
*
* @stable ICU 73
*/
static SimpleNumberFormatter forLocale(
const icu::Locale &locale,
UErrorCode &status);
/**
* Creates a new SimpleNumberFormatter, overriding the grouping strategy.
*
* @stable ICU 73
*/
static SimpleNumberFormatter forLocaleAndGroupingStrategy(
const icu::Locale &locale,
UNumberGroupingStrategy groupingStrategy,
UErrorCode &status);
/**
* Creates a new SimpleNumberFormatter, overriding the grouping strategy and symbols.
*
* IMPORTANT: For efficiency, this function borrows the symbols. The symbols MUST remain valid
* for the lifetime of the SimpleNumberFormatter.
*
* @stable ICU 73
*/
static SimpleNumberFormatter forLocaleAndSymbolsAndGroupingStrategy(
const icu::Locale &locale,
const DecimalFormatSymbols &symbols,
UNumberGroupingStrategy groupingStrategy,
UErrorCode &status);
/**
* Formats a value using this SimpleNumberFormatter.
*
* The SimpleNumber argument is "consumed". A new SimpleNumber object should be created for
* every formatting operation.
*
* @stable ICU 73
*/
FormattedNumber format(SimpleNumber value, UErrorCode &status) const;
/**
* Formats an integer using this SimpleNumberFormatter.
*
* For more control over the formatting, use SimpleNumber.
*
* @stable ICU 73
*/
FormattedNumber formatInt64(int64_t value, UErrorCode &status) const {
return format(SimpleNumber::forInt64(value, status), status);
}
#ifndef U_HIDE_INTERNAL_API
/**
* Run the formatter with the internal types.
* @internal
*/
void formatImpl(impl::UFormattedNumberData* data, USimpleNumberSign sign, UErrorCode& status) const;
#endif // U_HIDE_INTERNAL_API
/**
* Destruct this SimpleNumberFormatter, cleaning up any memory it might own.
*
* @stable ICU 73
*/
~SimpleNumberFormatter() {
cleanup();
}
/**
* Creates a shell, initialized but non-functional SimpleNumberFormatter.
*
* @stable ICU 73
*/
SimpleNumberFormatter() = default;
/**
* SimpleNumberFormatter: Move constructor.
*
* @stable ICU 73
*/
SimpleNumberFormatter(SimpleNumberFormatter&& other) noexcept {
fGroupingStrategy = other.fGroupingStrategy;
fOwnedSymbols = other.fOwnedSymbols;
fMicros = other.fMicros;
fPatternModifier = other.fPatternModifier;
other.fOwnedSymbols = nullptr;
other.fMicros = nullptr;
other.fPatternModifier = nullptr;
}
/**
* SimpleNumberFormatter: Move assignment.
*
* @stable ICU 73
*/
SimpleNumberFormatter& operator=(SimpleNumberFormatter&& other) noexcept {
cleanup();
fGroupingStrategy = other.fGroupingStrategy;
fOwnedSymbols = other.fOwnedSymbols;
fMicros = other.fMicros;
fPatternModifier = other.fPatternModifier;
other.fOwnedSymbols = nullptr;
other.fMicros = nullptr;
other.fPatternModifier = nullptr;
return *this;
}
private:
void initialize(
const icu::Locale &locale,
const DecimalFormatSymbols &symbols,
UNumberGroupingStrategy groupingStrategy,
UErrorCode &status);
void cleanup();
SimpleNumberFormatter(const SimpleNumberFormatter&) = delete;
SimpleNumberFormatter& operator=(const SimpleNumberFormatter&) = delete;
UNumberGroupingStrategy fGroupingStrategy = UNUM_GROUPING_AUTO;
// Owned Pointers:
DecimalFormatSymbols* fOwnedSymbols = nullptr; // can be empty
impl::SimpleMicroProps* fMicros = nullptr;
impl::AdoptingSignumModifierStore* fPatternModifier = nullptr;
};
} // namespace number
U_NAMESPACE_END
#endif /* #if !UCONFIG_NO_FORMATTING */
#endif /* U_SHOW_CPLUSPLUS_API */
#endif // __SIMPLENUMBERFORMATTERH__

View File

@ -0,0 +1,940 @@
// © 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
/*
********************************************************************************
* Copyright (C) 1997-2013, International Business Machines *
* Corporation and others. All Rights Reserved. *
********************************************************************************
*
* File SIMPLETZ.H
*
* Modification History:
*
* Date Name Description
* 04/21/97 aliu Overhauled header.
* 08/10/98 stephen JDK 1.2 sync
* Added setStartRule() / setEndRule() overloads
* Added hasSameRules()
* 09/02/98 stephen Added getOffset(monthLen)
* Changed getOffset() to take UErrorCode
* 07/09/99 stephen Removed millisPerHour (unused, for HP compiler)
* 12/02/99 aliu Added TimeMode and constructor and setStart/EndRule
* methods that take TimeMode. Added to docs.
********************************************************************************
*/
#ifndef SIMPLETZ_H
#define SIMPLETZ_H
#include "unicode/utypes.h"
#if U_SHOW_CPLUSPLUS_API
/**
* \file
* \brief C++ API: SimpleTimeZone is a concrete subclass of TimeZone.
*/
#if !UCONFIG_NO_FORMATTING
#include "unicode/basictz.h"
U_NAMESPACE_BEGIN
// forward declaration
class InitialTimeZoneRule;
class TimeZoneTransition;
class AnnualTimeZoneRule;
/**
* <code>SimpleTimeZone</code> is a concrete subclass of <code>TimeZone</code>
* that represents a time zone for use with a Gregorian calendar. This
* class does not handle historical changes.
* <P>
* When specifying daylight-savings-time begin and end dates, use a negative value for
* <code>dayOfWeekInMonth</code> to indicate that <code>SimpleTimeZone</code> should
* count from the end of the month backwards. For example, if Daylight Savings
* Time starts or ends at the last Sunday a month, use <code>dayOfWeekInMonth = -1</code>
* along with <code>dayOfWeek = UCAL_SUNDAY</code> to specify the rule.
*
* @see Calendar
* @see GregorianCalendar
* @see TimeZone
* @author D. Goldsmith, Mark Davis, Chen-Lieh Huang, Alan Liu
*/
class U_I18N_API SimpleTimeZone: public BasicTimeZone {
public:
/**
* TimeMode is used, together with a millisecond offset after
* midnight, to specify a rule transition time. Most rules
* transition at a local wall time, that is, according to the
* current time in effect, either standard, or DST. However, some
* rules transition at local standard time, and some at a specific
* UTC time. Although it might seem that all times could be
* converted to wall time, thus eliminating the need for this
* parameter, this is not the case.
* @stable ICU 2.0
*/
enum TimeMode {
WALL_TIME = 0,
STANDARD_TIME,
UTC_TIME
};
/**
* Copy constructor
* @param source the object to be copied.
* @stable ICU 2.0
*/
SimpleTimeZone(const SimpleTimeZone& source);
/**
* Default assignment operator
* @param right the object to be copied.
* @stable ICU 2.0
*/
SimpleTimeZone& operator=(const SimpleTimeZone& right);
/**
* Destructor
* @stable ICU 2.0
*/
virtual ~SimpleTimeZone();
/**
* Returns true if the two TimeZone objects are equal; that is, they have
* the same ID, raw GMT offset, and DST rules.
*
* @param that The SimpleTimeZone object to be compared with.
* @return true if the given time zone is equal to this time zone; false
* otherwise.
* @stable ICU 2.0
*/
virtual bool operator==(const TimeZone& that) const override;
/**
* Constructs a SimpleTimeZone with the given raw GMT offset and time zone ID,
* and which doesn't observe daylight savings time. Normally you should use
* TimeZone::createInstance() to create a TimeZone instead of creating a
* SimpleTimeZone directly with this constructor.
*
* @param rawOffsetGMT The given base time zone offset to GMT.
* @param ID The timezone ID which is obtained from
* TimeZone.getAvailableIDs.
* @stable ICU 2.0
*/
SimpleTimeZone(int32_t rawOffsetGMT, const UnicodeString& ID);
/**
* Construct a SimpleTimeZone with the given raw GMT offset, time zone ID,
* and times to start and end daylight savings time. To create a TimeZone that
* doesn't observe daylight savings time, don't use this constructor; use
* SimpleTimeZone(rawOffset, ID) instead. Normally, you should use
* TimeZone.createInstance() to create a TimeZone instead of creating a
* SimpleTimeZone directly with this constructor.
* <P>
* Various types of daylight-savings time rules can be specified by using different
* values for startDay and startDayOfWeek and endDay and endDayOfWeek. For a
* complete explanation of how these parameters work, see the documentation for
* setStartRule().
*
* @param rawOffsetGMT The new SimpleTimeZone's raw GMT offset
* @param ID The new SimpleTimeZone's time zone ID.
* @param savingsStartMonth The daylight savings starting month. Month is
* 0-based. eg, 0 for January.
* @param savingsStartDayOfWeekInMonth The daylight savings starting
* day-of-week-in-month. See setStartRule() for a
* complete explanation.
* @param savingsStartDayOfWeek The daylight savings starting day-of-week.
* See setStartRule() for a complete explanation.
* @param savingsStartTime The daylight savings starting time, expressed as the
* number of milliseconds after midnight.
* @param savingsEndMonth The daylight savings ending month. Month is
* 0-based. eg, 0 for January.
* @param savingsEndDayOfWeekInMonth The daylight savings ending day-of-week-in-month.
* See setStartRule() for a complete explanation.
* @param savingsEndDayOfWeek The daylight savings ending day-of-week.
* See setStartRule() for a complete explanation.
* @param savingsEndTime The daylight savings ending time, expressed as the
* number of milliseconds after midnight.
* @param status An UErrorCode to receive the status.
* @stable ICU 2.0
*/
SimpleTimeZone(int32_t rawOffsetGMT, const UnicodeString& ID,
int8_t savingsStartMonth, int8_t savingsStartDayOfWeekInMonth,
int8_t savingsStartDayOfWeek, int32_t savingsStartTime,
int8_t savingsEndMonth, int8_t savingsEndDayOfWeekInMonth,
int8_t savingsEndDayOfWeek, int32_t savingsEndTime,
UErrorCode& status);
/**
* Construct a SimpleTimeZone with the given raw GMT offset, time zone ID,
* and times to start and end daylight savings time. To create a TimeZone that
* doesn't observe daylight savings time, don't use this constructor; use
* SimpleTimeZone(rawOffset, ID) instead. Normally, you should use
* TimeZone.createInstance() to create a TimeZone instead of creating a
* SimpleTimeZone directly with this constructor.
* <P>
* Various types of daylight-savings time rules can be specified by using different
* values for startDay and startDayOfWeek and endDay and endDayOfWeek. For a
* complete explanation of how these parameters work, see the documentation for
* setStartRule().
*
* @param rawOffsetGMT The new SimpleTimeZone's raw GMT offset
* @param ID The new SimpleTimeZone's time zone ID.
* @param savingsStartMonth The daylight savings starting month. Month is
* 0-based. eg, 0 for January.
* @param savingsStartDayOfWeekInMonth The daylight savings starting
* day-of-week-in-month. See setStartRule() for a
* complete explanation.
* @param savingsStartDayOfWeek The daylight savings starting day-of-week.
* See setStartRule() for a complete explanation.
* @param savingsStartTime The daylight savings starting time, expressed as the
* number of milliseconds after midnight.
* @param savingsEndMonth The daylight savings ending month. Month is
* 0-based. eg, 0 for January.
* @param savingsEndDayOfWeekInMonth The daylight savings ending day-of-week-in-month.
* See setStartRule() for a complete explanation.
* @param savingsEndDayOfWeek The daylight savings ending day-of-week.
* See setStartRule() for a complete explanation.
* @param savingsEndTime The daylight savings ending time, expressed as the
* number of milliseconds after midnight.
* @param savingsDST The number of milliseconds added to standard time
* to get DST time. Default is one hour.
* @param status An UErrorCode to receive the status.
* @stable ICU 2.0
*/
SimpleTimeZone(int32_t rawOffsetGMT, const UnicodeString& ID,
int8_t savingsStartMonth, int8_t savingsStartDayOfWeekInMonth,
int8_t savingsStartDayOfWeek, int32_t savingsStartTime,
int8_t savingsEndMonth, int8_t savingsEndDayOfWeekInMonth,
int8_t savingsEndDayOfWeek, int32_t savingsEndTime,
int32_t savingsDST, UErrorCode& status);
/**
* Construct a SimpleTimeZone with the given raw GMT offset, time zone ID,
* and times to start and end daylight savings time. To create a TimeZone that
* doesn't observe daylight savings time, don't use this constructor; use
* SimpleTimeZone(rawOffset, ID) instead. Normally, you should use
* TimeZone.createInstance() to create a TimeZone instead of creating a
* SimpleTimeZone directly with this constructor.
* <P>
* Various types of daylight-savings time rules can be specified by using different
* values for startDay and startDayOfWeek and endDay and endDayOfWeek. For a
* complete explanation of how these parameters work, see the documentation for
* setStartRule().
*
* @param rawOffsetGMT The new SimpleTimeZone's raw GMT offset
* @param ID The new SimpleTimeZone's time zone ID.
* @param savingsStartMonth The daylight savings starting month. Month is
* 0-based. eg, 0 for January.
* @param savingsStartDayOfWeekInMonth The daylight savings starting
* day-of-week-in-month. See setStartRule() for a
* complete explanation.
* @param savingsStartDayOfWeek The daylight savings starting day-of-week.
* See setStartRule() for a complete explanation.
* @param savingsStartTime The daylight savings starting time, expressed as the
* number of milliseconds after midnight.
* @param savingsStartTimeMode Whether the start time is local wall time, local
* standard time, or UTC time. Default is local wall time.
* @param savingsEndMonth The daylight savings ending month. Month is
* 0-based. eg, 0 for January.
* @param savingsEndDayOfWeekInMonth The daylight savings ending day-of-week-in-month.
* See setStartRule() for a complete explanation.
* @param savingsEndDayOfWeek The daylight savings ending day-of-week.
* See setStartRule() for a complete explanation.
* @param savingsEndTime The daylight savings ending time, expressed as the
* number of milliseconds after midnight.
* @param savingsEndTimeMode Whether the end time is local wall time, local
* standard time, or UTC time. Default is local wall time.
* @param savingsDST The number of milliseconds added to standard time
* to get DST time. Default is one hour.
* @param status An UErrorCode to receive the status.
* @stable ICU 2.0
*/
SimpleTimeZone(int32_t rawOffsetGMT, const UnicodeString& ID,
int8_t savingsStartMonth, int8_t savingsStartDayOfWeekInMonth,
int8_t savingsStartDayOfWeek, int32_t savingsStartTime,
TimeMode savingsStartTimeMode,
int8_t savingsEndMonth, int8_t savingsEndDayOfWeekInMonth,
int8_t savingsEndDayOfWeek, int32_t savingsEndTime, TimeMode savingsEndTimeMode,
int32_t savingsDST, UErrorCode& status);
/**
* Sets the daylight savings starting year, that is, the year this time zone began
* observing its specified daylight savings time rules. The time zone is considered
* not to observe daylight savings time prior to that year; SimpleTimeZone doesn't
* support historical daylight-savings-time rules.
* @param year the daylight savings starting year.
* @stable ICU 2.0
*/
void setStartYear(int32_t year);
/**
* Sets the daylight savings starting rule. For example, in the U.S., Daylight Savings
* Time starts at the second Sunday in March, at 2 AM in standard time.
* Therefore, you can set the start rule by calling:
* setStartRule(UCAL_MARCH, 2, UCAL_SUNDAY, 2*60*60*1000);
* The dayOfWeekInMonth and dayOfWeek parameters together specify how to calculate
* the exact starting date. Their exact meaning depend on their respective signs,
* allowing various types of rules to be constructed, as follows:
* <ul>
* <li>If both dayOfWeekInMonth and dayOfWeek are positive, they specify the
* day of week in the month (e.g., (2, WEDNESDAY) is the second Wednesday
* of the month).</li>
* <li>If dayOfWeek is positive and dayOfWeekInMonth is negative, they specify
* the day of week in the month counting backward from the end of the month.
* (e.g., (-1, MONDAY) is the last Monday in the month)</li>
* <li>If dayOfWeek is zero and dayOfWeekInMonth is positive, dayOfWeekInMonth
* specifies the day of the month, regardless of what day of the week it is.
* (e.g., (10, 0) is the tenth day of the month)</li>
* <li>If dayOfWeek is zero and dayOfWeekInMonth is negative, dayOfWeekInMonth
* specifies the day of the month counting backward from the end of the
* month, regardless of what day of the week it is (e.g., (-2, 0) is the
* next-to-last day of the month).</li>
* <li>If dayOfWeek is negative and dayOfWeekInMonth is positive, they specify the
* first specified day of the week on or after the specified day of the month.
* (e.g., (15, -SUNDAY) is the first Sunday after the 15th of the month
* [or the 15th itself if the 15th is a Sunday].)</li>
* <li>If dayOfWeek and DayOfWeekInMonth are both negative, they specify the
* last specified day of the week on or before the specified day of the month.
* (e.g., (-20, -TUESDAY) is the last Tuesday before the 20th of the month
* [or the 20th itself if the 20th is a Tuesday].)</li>
* </ul>
* @param month the daylight savings starting month. Month is 0-based.
* eg, 0 for January.
* @param dayOfWeekInMonth the daylight savings starting
* day-of-week-in-month. Please see the member description for an example.
* @param dayOfWeek the daylight savings starting day-of-week. Please see
* the member description for an example.
* @param time the daylight savings starting time. Please see the member
* description for an example.
* @param status An UErrorCode
* @stable ICU 2.0
*/
void setStartRule(int32_t month, int32_t dayOfWeekInMonth, int32_t dayOfWeek,
int32_t time, UErrorCode& status);
/**
* Sets the daylight savings starting rule. For example, in the U.S., Daylight Savings
* Time starts at the second Sunday in March, at 2 AM in standard time.
* Therefore, you can set the start rule by calling:
* setStartRule(UCAL_MARCH, 2, UCAL_SUNDAY, 2*60*60*1000);
* The dayOfWeekInMonth and dayOfWeek parameters together specify how to calculate
* the exact starting date. Their exact meaning depend on their respective signs,
* allowing various types of rules to be constructed, as follows:
* <ul>
* <li>If both dayOfWeekInMonth and dayOfWeek are positive, they specify the
* day of week in the month (e.g., (2, WEDNESDAY) is the second Wednesday
* of the month).</li>
* <li>If dayOfWeek is positive and dayOfWeekInMonth is negative, they specify
* the day of week in the month counting backward from the end of the month.
* (e.g., (-1, MONDAY) is the last Monday in the month)</li>
* <li>If dayOfWeek is zero and dayOfWeekInMonth is positive, dayOfWeekInMonth
* specifies the day of the month, regardless of what day of the week it is.
* (e.g., (10, 0) is the tenth day of the month)</li>
* <li>If dayOfWeek is zero and dayOfWeekInMonth is negative, dayOfWeekInMonth
* specifies the day of the month counting backward from the end of the
* month, regardless of what day of the week it is (e.g., (-2, 0) is the
* next-to-last day of the month).</li>
* <li>If dayOfWeek is negative and dayOfWeekInMonth is positive, they specify the
* first specified day of the week on or after the specified day of the month.
* (e.g., (15, -SUNDAY) is the first Sunday after the 15th of the month
* [or the 15th itself if the 15th is a Sunday].)</li>
* <li>If dayOfWeek and DayOfWeekInMonth are both negative, they specify the
* last specified day of the week on or before the specified day of the month.
* (e.g., (-20, -TUESDAY) is the last Tuesday before the 20th of the month
* [or the 20th itself if the 20th is a Tuesday].)</li>
* </ul>
* @param month the daylight savings starting month. Month is 0-based.
* eg, 0 for January.
* @param dayOfWeekInMonth the daylight savings starting
* day-of-week-in-month. Please see the member description for an example.
* @param dayOfWeek the daylight savings starting day-of-week. Please see
* the member description for an example.
* @param time the daylight savings starting time. Please see the member
* description for an example.
* @param mode whether the time is local wall time, local standard time,
* or UTC time. Default is local wall time.
* @param status An UErrorCode
* @stable ICU 2.0
*/
void setStartRule(int32_t month, int32_t dayOfWeekInMonth, int32_t dayOfWeek,
int32_t time, TimeMode mode, UErrorCode& status);
/**
* Sets the DST start rule to a fixed date within a month.
*
* @param month The month in which this rule occurs (0-based).
* @param dayOfMonth The date in that month (1-based).
* @param time The time of that day (number of millis after midnight)
* when DST takes effect in local wall time, which is
* standard time in this case.
* @param status An UErrorCode
* @stable ICU 2.0
*/
void setStartRule(int32_t month, int32_t dayOfMonth, int32_t time,
UErrorCode& status);
/**
* Sets the DST start rule to a fixed date within a month.
*
* @param month The month in which this rule occurs (0-based).
* @param dayOfMonth The date in that month (1-based).
* @param time The time of that day (number of millis after midnight)
* when DST takes effect in local wall time, which is
* standard time in this case.
* @param mode whether the time is local wall time, local standard time,
* or UTC time. Default is local wall time.
* @param status An UErrorCode
* @stable ICU 2.0
*/
void setStartRule(int32_t month, int32_t dayOfMonth, int32_t time,
TimeMode mode, UErrorCode& status);
/**
* Sets the DST start rule to a weekday before or after a give date within
* a month, e.g., the first Monday on or after the 8th.
*
* @param month The month in which this rule occurs (0-based).
* @param dayOfMonth A date within that month (1-based).
* @param dayOfWeek The day of the week on which this rule occurs.
* @param time The time of that day (number of millis after midnight)
* when DST takes effect in local wall time, which is
* standard time in this case.
* @param after If true, this rule selects the first dayOfWeek on
* or after dayOfMonth. If false, this rule selects
* the last dayOfWeek on or before dayOfMonth.
* @param status An UErrorCode
* @stable ICU 2.0
*/
void setStartRule(int32_t month, int32_t dayOfMonth, int32_t dayOfWeek,
int32_t time, UBool after, UErrorCode& status);
/**
* Sets the DST start rule to a weekday before or after a give date within
* a month, e.g., the first Monday on or after the 8th.
*
* @param month The month in which this rule occurs (0-based).
* @param dayOfMonth A date within that month (1-based).
* @param dayOfWeek The day of the week on which this rule occurs.
* @param time The time of that day (number of millis after midnight)
* when DST takes effect in local wall time, which is
* standard time in this case.
* @param mode whether the time is local wall time, local standard time,
* or UTC time. Default is local wall time.
* @param after If true, this rule selects the first dayOfWeek on
* or after dayOfMonth. If false, this rule selects
* the last dayOfWeek on or before dayOfMonth.
* @param status An UErrorCode
* @stable ICU 2.0
*/
void setStartRule(int32_t month, int32_t dayOfMonth, int32_t dayOfWeek,
int32_t time, TimeMode mode, UBool after, UErrorCode& status);
/**
* Sets the daylight savings ending rule. For example, if Daylight
* Savings Time ends at the last (-1) Sunday in October, at 2 AM in standard time.
* Therefore, you can set the end rule by calling:
* <pre>
* setEndRule(UCAL_OCTOBER, -1, UCAL_SUNDAY, 2*60*60*1000);
* </pre>
* Various other types of rules can be specified by manipulating the dayOfWeek
* and dayOfWeekInMonth parameters. For complete details, see the documentation
* for setStartRule().
*
* @param month the daylight savings ending month. Month is 0-based.
* eg, 0 for January.
* @param dayOfWeekInMonth the daylight savings ending
* day-of-week-in-month. See setStartRule() for a complete explanation.
* @param dayOfWeek the daylight savings ending day-of-week. See setStartRule()
* for a complete explanation.
* @param time the daylight savings ending time. Please see the member
* description for an example.
* @param status An UErrorCode
* @stable ICU 2.0
*/
void setEndRule(int32_t month, int32_t dayOfWeekInMonth, int32_t dayOfWeek,
int32_t time, UErrorCode& status);
/**
* Sets the daylight savings ending rule. For example, if Daylight
* Savings Time ends at the last (-1) Sunday in October, at 2 AM in standard time.
* Therefore, you can set the end rule by calling:
* <pre>
* setEndRule(UCAL_OCTOBER, -1, UCAL_SUNDAY, 2*60*60*1000);
* </pre>
* Various other types of rules can be specified by manipulating the dayOfWeek
* and dayOfWeekInMonth parameters. For complete details, see the documentation
* for setStartRule().
*
* @param month the daylight savings ending month. Month is 0-based.
* eg, 0 for January.
* @param dayOfWeekInMonth the daylight savings ending
* day-of-week-in-month. See setStartRule() for a complete explanation.
* @param dayOfWeek the daylight savings ending day-of-week. See setStartRule()
* for a complete explanation.
* @param time the daylight savings ending time. Please see the member
* description for an example.
* @param mode whether the time is local wall time, local standard time,
* or UTC time. Default is local wall time.
* @param status An UErrorCode
* @stable ICU 2.0
*/
void setEndRule(int32_t month, int32_t dayOfWeekInMonth, int32_t dayOfWeek,
int32_t time, TimeMode mode, UErrorCode& status);
/**
* Sets the DST end rule to a fixed date within a month.
*
* @param month The month in which this rule occurs (0-based).
* @param dayOfMonth The date in that month (1-based).
* @param time The time of that day (number of millis after midnight)
* when DST ends in local wall time, which is daylight
* time in this case.
* @param status An UErrorCode
* @stable ICU 2.0
*/
void setEndRule(int32_t month, int32_t dayOfMonth, int32_t time, UErrorCode& status);
/**
* Sets the DST end rule to a fixed date within a month.
*
* @param month The month in which this rule occurs (0-based).
* @param dayOfMonth The date in that month (1-based).
* @param time The time of that day (number of millis after midnight)
* when DST ends in local wall time, which is daylight
* time in this case.
* @param mode whether the time is local wall time, local standard time,
* or UTC time. Default is local wall time.
* @param status An UErrorCode
* @stable ICU 2.0
*/
void setEndRule(int32_t month, int32_t dayOfMonth, int32_t time,
TimeMode mode, UErrorCode& status);
/**
* Sets the DST end rule to a weekday before or after a give date within
* a month, e.g., the first Monday on or after the 8th.
*
* @param month The month in which this rule occurs (0-based).
* @param dayOfMonth A date within that month (1-based).
* @param dayOfWeek The day of the week on which this rule occurs.
* @param time The time of that day (number of millis after midnight)
* when DST ends in local wall time, which is daylight
* time in this case.
* @param after If true, this rule selects the first dayOfWeek on
* or after dayOfMonth. If false, this rule selects
* the last dayOfWeek on or before dayOfMonth.
* @param status An UErrorCode
* @stable ICU 2.0
*/
void setEndRule(int32_t month, int32_t dayOfMonth, int32_t dayOfWeek,
int32_t time, UBool after, UErrorCode& status);
/**
* Sets the DST end rule to a weekday before or after a give date within
* a month, e.g., the first Monday on or after the 8th.
*
* @param month The month in which this rule occurs (0-based).
* @param dayOfMonth A date within that month (1-based).
* @param dayOfWeek The day of the week on which this rule occurs.
* @param time The time of that day (number of millis after midnight)
* when DST ends in local wall time, which is daylight
* time in this case.
* @param mode whether the time is local wall time, local standard time,
* or UTC time. Default is local wall time.
* @param after If true, this rule selects the first dayOfWeek on
* or after dayOfMonth. If false, this rule selects
* the last dayOfWeek on or before dayOfMonth.
* @param status An UErrorCode
* @stable ICU 2.0
*/
void setEndRule(int32_t month, int32_t dayOfMonth, int32_t dayOfWeek,
int32_t time, TimeMode mode, UBool after, UErrorCode& status);
/**
* Returns the TimeZone's adjusted GMT offset (i.e., the number of milliseconds to add
* to GMT to get local time in this time zone, taking daylight savings time into
* account) as of a particular reference date. The reference date is used to determine
* whether daylight savings time is in effect and needs to be figured into the offset
* that is returned (in other words, what is the adjusted GMT offset in this time zone
* at this particular date and time?). For the time zones produced by createTimeZone(),
* the reference data is specified according to the Gregorian calendar, and the date
* and time fields are in GMT, NOT local time.
*
* @param era The reference date's era
* @param year The reference date's year
* @param month The reference date's month (0-based; 0 is January)
* @param day The reference date's day-in-month (1-based)
* @param dayOfWeek The reference date's day-of-week (1-based; 1 is Sunday)
* @param millis The reference date's milliseconds in day, UTT (NOT local time).
* @param status An UErrorCode to receive the status.
* @return The offset in milliseconds to add to GMT to get local time.
* @stable ICU 2.0
*/
virtual int32_t getOffset(uint8_t era, int32_t year, int32_t month, int32_t day,
uint8_t dayOfWeek, int32_t millis, UErrorCode& status) const override;
/**
* Gets the time zone offset, for current date, modified in case of
* daylight savings. This is the offset to add *to* UTC to get local time.
* @param era the era of the given date.
* @param year the year in the given date.
* @param month the month in the given date.
* Month is 0-based. e.g., 0 for January.
* @param day the day-in-month of the given date.
* @param dayOfWeek the day-of-week of the given date.
* @param milliseconds the millis in day in <em>standard</em> local time.
* @param monthLength the length of the given month in days.
* @param status An UErrorCode to receive the status.
* @return the offset to add *to* GMT to get local time.
* @stable ICU 2.0
*/
virtual int32_t getOffset(uint8_t era, int32_t year, int32_t month, int32_t day,
uint8_t dayOfWeek, int32_t milliseconds,
int32_t monthLength, UErrorCode& status) const override;
/**
* Gets the time zone offset, for current date, modified in case of
* daylight savings. This is the offset to add *to* UTC to get local time.
* @param era the era of the given date.
* @param year the year in the given date.
* @param month the month in the given date.
* Month is 0-based. e.g., 0 for January.
* @param day the day-in-month of the given date.
* @param dayOfWeek the day-of-week of the given date.
* @param milliseconds the millis in day in <em>standard</em> local time.
* @param monthLength the length of the given month in days.
* @param prevMonthLength length of the previous month in days.
* @param status An UErrorCode to receive the status.
* @return the offset to add *to* GMT to get local time.
* @stable ICU 2.0
*/
virtual int32_t getOffset(uint8_t era, int32_t year, int32_t month, int32_t day,
uint8_t dayOfWeek, int32_t milliseconds,
int32_t monthLength, int32_t prevMonthLength,
UErrorCode& status) const;
/**
* Redeclared TimeZone method. This implementation simply calls
* the base class method, which otherwise would be hidden.
* @stable ICU 2.8
*/
virtual void getOffset(UDate date, UBool local, int32_t& rawOffset,
int32_t& dstOffset, UErrorCode& ec) const override;
/**
* Get time zone offsets from local wall time.
* @stable ICU 69
*/
virtual void getOffsetFromLocal(
UDate date, UTimeZoneLocalOption nonExistingTimeOpt,
UTimeZoneLocalOption duplicatedTimeOpt,
int32_t& rawOffset, int32_t& dstOffset, UErrorCode& status) const override;
/**
* Returns the TimeZone's raw GMT offset (i.e., the number of milliseconds to add
* to GMT to get local time, before taking daylight savings time into account).
*
* @return The TimeZone's raw GMT offset.
* @stable ICU 2.0
*/
virtual int32_t getRawOffset() const override;
/**
* Sets the TimeZone's raw GMT offset (i.e., the number of milliseconds to add
* to GMT to get local time, before taking daylight savings time into account).
*
* @param offsetMillis The new raw GMT offset for this time zone.
* @stable ICU 2.0
*/
virtual void setRawOffset(int32_t offsetMillis) override;
/**
* Sets the amount of time in ms that the clock is advanced during DST.
* @param millisSavedDuringDST the number of milliseconds the time is
* advanced with respect to standard time when the daylight savings rules
* are in effect. Typically one hour (+3600000). The amount could be negative,
* but not 0.
* @param status An UErrorCode to receive the status.
* @stable ICU 2.0
*/
void setDSTSavings(int32_t millisSavedDuringDST, UErrorCode& status);
/**
* Returns the amount of time in ms that the clock is advanced during DST.
* @return the number of milliseconds the time is
* advanced with respect to standard time when the daylight savings rules
* are in effect. Typically one hour (+3600000). The amount could be negative,
* but not 0.
* @stable ICU 2.0
*/
virtual int32_t getDSTSavings() const override;
/**
* Queries if this TimeZone uses Daylight Savings Time.
*
* @return True if this TimeZone uses Daylight Savings Time; false otherwise.
* @stable ICU 2.0
*/
virtual UBool useDaylightTime() const override;
#ifndef U_FORCE_HIDE_DEPRECATED_API
/**
* Returns true if the given date is within the period when daylight savings time
* is in effect; false otherwise. If the TimeZone doesn't observe daylight savings
* time, this functions always returns false.
* This method is wasteful since it creates a new GregorianCalendar and
* deletes it each time it is called. This is a deprecated method
* and provided only for Java compatibility.
*
* @param date The date to test.
* @param status An UErrorCode to receive the status.
* @return true if the given date is in Daylight Savings Time;
* false otherwise.
* @deprecated ICU 2.4. Use Calendar::inDaylightTime() instead.
*/
virtual UBool inDaylightTime(UDate date, UErrorCode& status) const override;
#endif // U_FORCE_HIDE_DEPRECATED_API
/**
* Return true if this zone has the same rules and offset as another zone.
* @param other the TimeZone object to be compared with
* @return true if the given zone has the same rules and offset as this one
* @stable ICU 2.0
*/
UBool hasSameRules(const TimeZone& other) const override;
/**
* Clones TimeZone objects polymorphically. Clients are responsible for deleting
* the TimeZone object cloned.
*
* @return A new copy of this TimeZone object.
* @stable ICU 2.0
*/
virtual SimpleTimeZone* clone() const override;
/**
* Gets the first time zone transition after the base time.
* @param base The base time.
* @param inclusive Whether the base time is inclusive or not.
* @param result Receives the first transition after the base time.
* @return true if the transition is found.
* @stable ICU 3.8
*/
virtual UBool getNextTransition(UDate base, UBool inclusive, TimeZoneTransition& result) const override;
/**
* Gets the most recent time zone transition before the base time.
* @param base The base time.
* @param inclusive Whether the base time is inclusive or not.
* @param result Receives the most recent transition before the base time.
* @return true if the transition is found.
* @stable ICU 3.8
*/
virtual UBool getPreviousTransition(UDate base, UBool inclusive, TimeZoneTransition& result) const override;
/**
* Returns the number of <code>TimeZoneRule</code>s which represents time transitions,
* for this time zone, that is, all <code>TimeZoneRule</code>s for this time zone except
* <code>InitialTimeZoneRule</code>. The return value range is 0 or any positive value.
* @param status Receives error status code.
* @return The number of <code>TimeZoneRule</code>s representing time transitions.
* @stable ICU 3.8
*/
virtual int32_t countTransitionRules(UErrorCode& status) const override;
/**
* Gets the <code>InitialTimeZoneRule</code> and the set of <code>TimeZoneRule</code>
* which represent time transitions for this time zone. On successful return,
* the argument initial points to non-nullptr <code>InitialTimeZoneRule</code> and
* the array trsrules is filled with 0 or multiple <code>TimeZoneRule</code>
* instances up to the size specified by trscount. The results are referencing the
* rule instance held by this time zone instance. Therefore, after this time zone
* is destructed, they are no longer available.
* @param initial Receives the initial timezone rule
* @param trsrules Receives the timezone transition rules
* @param trscount On input, specify the size of the array 'transitions' receiving
* the timezone transition rules. On output, actual number of
* rules filled in the array will be set.
* @param status Receives error status code.
* @stable ICU 3.8
*/
virtual void getTimeZoneRules(const InitialTimeZoneRule*& initial,
const TimeZoneRule* trsrules[], int32_t& trscount, UErrorCode& status) const override;
public:
/**
* Override TimeZone Returns a unique class ID POLYMORPHICALLY. Pure virtual
* override. This method is to implement a simple version of RTTI, since not all C++
* compilers support genuine RTTI. Polymorphic operator==() and clone() methods call
* this method.
*
* @return The class ID for this object. All objects of a given class have the
* same class ID. Objects of other classes have different class IDs.
* @stable ICU 2.0
*/
virtual UClassID getDynamicClassID() const override;
/**
* Return the class ID for this class. This is useful only for comparing to a return
* value from getDynamicClassID(). For example:
* <pre>
* . Base* polymorphic_pointer = createPolymorphicObject();
* . if (polymorphic_pointer->getDynamicClassID() ==
* . Derived::getStaticClassID()) ...
* </pre>
* @return The class ID for all objects of this class.
* @stable ICU 2.0
*/
static UClassID U_EXPORT2 getStaticClassID();
private:
/**
* Constants specifying values of startMode and endMode.
*/
enum EMode
{
DOM_MODE = 1,
DOW_IN_MONTH_MODE,
DOW_GE_DOM_MODE,
DOW_LE_DOM_MODE
};
SimpleTimeZone() = delete; // default constructor not implemented
/**
* Internal construction method.
* @param rawOffsetGMT The new SimpleTimeZone's raw GMT offset
* @param startMonth the month DST starts
* @param startDay the day DST starts
* @param startDayOfWeek the DOW DST starts
* @param startTime the time DST starts
* @param startTimeMode Whether the start time is local wall time, local
* standard time, or UTC time. Default is local wall time.
* @param endMonth the month DST ends
* @param endDay the day DST ends
* @param endDayOfWeek the DOW DST ends
* @param endTime the time DST ends
* @param endTimeMode Whether the end time is local wall time, local
* standard time, or UTC time. Default is local wall time.
* @param dstSavings The number of milliseconds added to standard time
* to get DST time. Default is one hour.
* @param status An UErrorCode to receive the status.
*/
void construct(int32_t rawOffsetGMT,
int8_t startMonth, int8_t startDay, int8_t startDayOfWeek,
int32_t startTime, TimeMode startTimeMode,
int8_t endMonth, int8_t endDay, int8_t endDayOfWeek,
int32_t endTime, TimeMode endTimeMode,
int32_t dstSavings, UErrorCode& status);
/**
* Compare a given date in the year to a rule. Return 1, 0, or -1, depending
* on whether the date is after, equal to, or before the rule date. The
* millis are compared directly against the ruleMillis, so any
* standard-daylight adjustments must be handled by the caller.
*
* @return 1 if the date is after the rule date, -1 if the date is before
* the rule date, or 0 if the date is equal to the rule date.
*/
static int32_t compareToRule(int8_t month, int8_t monthLen, int8_t prevMonthLen,
int8_t dayOfMonth,
int8_t dayOfWeek, int32_t millis, int32_t millisDelta,
EMode ruleMode, int8_t ruleMonth, int8_t ruleDayOfWeek,
int8_t ruleDay, int32_t ruleMillis);
/**
* Given a set of encoded rules in startDay and startDayOfMonth, decode
* them and set the startMode appropriately. Do the same for endDay and
* endDayOfMonth.
* <P>
* Upon entry, the day of week variables may be zero or
* negative, in order to indicate special modes. The day of month
* variables may also be negative.
* <P>
* Upon exit, the mode variables will be
* set, and the day of week and day of month variables will be positive.
* <P>
* This method also recognizes a startDay or endDay of zero as indicating
* no DST.
*/
void decodeRules(UErrorCode& status);
void decodeStartRule(UErrorCode& status);
void decodeEndRule(UErrorCode& status);
int8_t startMonth, startDay, startDayOfWeek; // the month, day, DOW, and time DST starts
int32_t startTime;
TimeMode startTimeMode, endTimeMode; // Mode for startTime, endTime; see TimeMode
int8_t endMonth, endDay, endDayOfWeek; // the month, day, DOW, and time DST ends
int32_t endTime;
int32_t startYear; // the year these DST rules took effect
int32_t rawOffset; // the TimeZone's raw GMT offset
UBool useDaylight; // flag indicating whether this TimeZone uses DST
static const int8_t STATICMONTHLENGTH[12]; // lengths of the months
EMode startMode, endMode; // flags indicating what kind of rules the DST rules are
/**
* A positive value indicating the amount of time saved during DST in ms.
* Typically one hour; sometimes 30 minutes.
*/
int32_t dstSavings;
/* Private for BasicTimeZone implementation */
void checkTransitionRules(UErrorCode& status) const;
void initTransitionRules(UErrorCode& status);
void clearTransitionRules();
void deleteTransitionRules();
UBool transitionRulesInitialized;
InitialTimeZoneRule* initialRule;
TimeZoneTransition* firstTransition;
AnnualTimeZoneRule* stdRule;
AnnualTimeZoneRule* dstRule;
};
inline void SimpleTimeZone::setStartRule(int32_t month, int32_t dayOfWeekInMonth,
int32_t dayOfWeek,
int32_t time, UErrorCode& status) {
setStartRule(month, dayOfWeekInMonth, dayOfWeek, time, WALL_TIME, status);
}
inline void SimpleTimeZone::setStartRule(int32_t month, int32_t dayOfMonth,
int32_t time,
UErrorCode& status) {
setStartRule(month, dayOfMonth, time, WALL_TIME, status);
}
inline void SimpleTimeZone::setStartRule(int32_t month, int32_t dayOfMonth,
int32_t dayOfWeek,
int32_t time, UBool after, UErrorCode& status) {
setStartRule(month, dayOfMonth, dayOfWeek, time, WALL_TIME, after, status);
}
inline void SimpleTimeZone::setEndRule(int32_t month, int32_t dayOfWeekInMonth,
int32_t dayOfWeek,
int32_t time, UErrorCode& status) {
setEndRule(month, dayOfWeekInMonth, dayOfWeek, time, WALL_TIME, status);
}
inline void SimpleTimeZone::setEndRule(int32_t month, int32_t dayOfMonth,
int32_t time, UErrorCode& status) {
setEndRule(month, dayOfMonth, time, WALL_TIME, status);
}
inline void SimpleTimeZone::setEndRule(int32_t month, int32_t dayOfMonth, int32_t dayOfWeek,
int32_t time, UBool after, UErrorCode& status) {
setEndRule(month, dayOfMonth, dayOfWeek, time, WALL_TIME, after, status);
}
inline void
SimpleTimeZone::getOffset(UDate date, UBool local, int32_t& rawOffsetRef,
int32_t& dstOffsetRef, UErrorCode& ec) const {
TimeZone::getOffset(date, local, rawOffsetRef, dstOffsetRef, ec);
}
U_NAMESPACE_END
#endif /* #if !UCONFIG_NO_FORMATTING */
#endif /* U_SHOW_CPLUSPLUS_API */
#endif // _SIMPLETZ

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,344 @@
// © 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
/*
*****************************************************************************
* Copyright (C) 1996-2014, International Business Machines Corporation and others.
* All Rights Reserved.
*****************************************************************************
*
* File sortkey.h
*
* Created by: Helena Shih
*
* Modification History:
*
* Date Name Description
*
* 6/20/97 helena Java class name change.
* 8/18/97 helena Added internal API documentation.
* 6/26/98 erm Changed to use byte arrays and memcmp.
*****************************************************************************
*/
#ifndef SORTKEY_H
#define SORTKEY_H
#include "unicode/utypes.h"
#if U_SHOW_CPLUSPLUS_API
/**
* \file
* \brief C++ API: Keys for comparing strings multiple times.
*/
#if !UCONFIG_NO_COLLATION
#include "unicode/uobject.h"
#include "unicode/unistr.h"
#include "unicode/coll.h"
U_NAMESPACE_BEGIN
/* forward declaration */
class RuleBasedCollator;
class CollationKeyByteSink;
/**
*
* Collation keys are generated by the Collator class. Use the CollationKey objects
* instead of Collator to compare strings multiple times. A CollationKey
* preprocesses the comparison information from the Collator object to
* make the comparison faster. If you are not going to comparing strings
* multiple times, then using the Collator object is generally faster,
* since it only processes as much of the string as needed to make a
* comparison.
* <p> For example (with strength == tertiary)
* <p>When comparing "Abernathy" to "Baggins-Smythworthy", Collator
* only needs to process a couple of characters, while a comparison
* with CollationKeys will process all of the characters. On the other hand,
* if you are doing a sort of a number of fields, it is much faster to use
* CollationKeys, since you will be comparing strings multiple times.
* <p>Typical use of CollationKeys are in databases, where you store a CollationKey
* in a hidden field, and use it for sorting or indexing.
*
* <p>Example of use:
* <pre>
* \code
* UErrorCode success = U_ZERO_ERROR;
* Collator* myCollator = Collator::createInstance(success);
* CollationKey* keys = new CollationKey [3];
* myCollator->getCollationKey("Tom", keys[0], success );
* myCollator->getCollationKey("Dick", keys[1], success );
* myCollator->getCollationKey("Harry", keys[2], success );
*
* // Inside body of sort routine, compare keys this way:
* CollationKey tmp;
* if(keys[0].compareTo( keys[1] ) > 0 ) {
* tmp = keys[0]; keys[0] = keys[1]; keys[1] = tmp;
* }
* //...
* \endcode
* </pre>
* <p>Because Collator::compare()'s algorithm is complex, it is faster to sort
* long lists of words by retrieving collation keys with Collator::getCollationKey().
* You can then cache the collation keys and compare them using CollationKey::compareTo().
* <p>
* <strong>Note:</strong> <code>Collator</code>s with different Locale,
* CollationStrength and DecompositionMode settings will return different
* CollationKeys for the same set of strings. Locales have specific
* collation rules, and the way in which secondary and tertiary differences
* are taken into account, for example, will result in different CollationKeys
* for same strings.
* <p>
* @see Collator
* @see RuleBasedCollator
* @version 1.3 12/18/96
* @author Helena Shih
* @stable ICU 2.0
*/
class U_I18N_API CollationKey : public UObject {
public:
/**
* This creates an empty collation key based on the null string. An empty
* collation key contains no sorting information. When comparing two empty
* collation keys, the result is Collator::EQUAL. Comparing empty collation key
* with non-empty collation key is always Collator::LESS.
* @stable ICU 2.0
*/
CollationKey();
/**
* Creates a collation key based on the collation key values.
* @param values the collation key values
* @param count number of collation key values, including trailing nulls.
* @stable ICU 2.0
*/
CollationKey(const uint8_t* values,
int32_t count);
/**
* Copy constructor.
* @param other the object to be copied.
* @stable ICU 2.0
*/
CollationKey(const CollationKey& other);
/**
* Sort key destructor.
* @stable ICU 2.0
*/
virtual ~CollationKey();
/**
* Assignment operator
* @param other the object to be copied.
* @stable ICU 2.0
*/
const CollationKey& operator=(const CollationKey& other);
/**
* Compare if two collation keys are the same.
* @param source the collation key to compare to.
* @return Returns true if two collation keys are equal, false otherwise.
* @stable ICU 2.0
*/
bool operator==(const CollationKey& source) const;
/**
* Compare if two collation keys are not the same.
* @param source the collation key to compare to.
* @return Returns true if two collation keys are different, false otherwise.
* @stable ICU 2.0
*/
bool operator!=(const CollationKey& source) const;
/**
* Test to see if the key is in an invalid state. The key will be in an
* invalid state if it couldn't allocate memory for some operation.
* @return Returns true if the key is in an invalid, false otherwise.
* @stable ICU 2.0
*/
UBool isBogus() const;
/**
* Returns a pointer to the collation key values. The storage is owned
* by the collation key and the pointer will become invalid if the key
* is deleted.
* @param count the output parameter of number of collation key values,
* including any trailing nulls.
* @return a pointer to the collation key values.
* @stable ICU 2.0
*/
const uint8_t* getByteArray(int32_t& count) const;
#ifdef U_USE_COLLATION_KEY_DEPRECATES
/**
* Extracts the collation key values into a new array. The caller owns
* this storage and should free it.
* @param count the output parameter of number of collation key values,
* including any trailing nulls.
* @obsolete ICU 2.6. Use getByteArray instead since this API will be removed in that release.
*/
uint8_t* toByteArray(int32_t& count) const;
#endif
#ifndef U_HIDE_DEPRECATED_API
/**
* Convenience method which does a string(bit-wise) comparison of the
* two collation keys.
* @param target target collation key to be compared with
* @return Returns Collator::LESS if sourceKey &lt; targetKey,
* Collator::GREATER if sourceKey > targetKey and Collator::EQUAL
* otherwise.
* @deprecated ICU 2.6 use the overload with error code
*/
Collator::EComparisonResult compareTo(const CollationKey& target) const;
#endif /* U_HIDE_DEPRECATED_API */
/**
* Convenience method which does a string(bit-wise) comparison of the
* two collation keys.
* @param target target collation key to be compared with
* @param status error code
* @return Returns UCOL_LESS if sourceKey &lt; targetKey,
* UCOL_GREATER if sourceKey > targetKey and UCOL_EQUAL
* otherwise.
* @stable ICU 2.6
*/
UCollationResult compareTo(const CollationKey& target, UErrorCode &status) const;
/**
* Creates an integer that is unique to the collation key. NOTE: this
* is not the same as String.hashCode.
* <p>Example of use:
* <pre>
* . UErrorCode status = U_ZERO_ERROR;
* . Collator *myCollation = Collator::createInstance(Locale::US, status);
* . if (U_FAILURE(status)) return;
* . CollationKey key1, key2;
* . UErrorCode status1 = U_ZERO_ERROR, status2 = U_ZERO_ERROR;
* . myCollation->getCollationKey("abc", key1, status1);
* . if (U_FAILURE(status1)) { delete myCollation; return; }
* . myCollation->getCollationKey("ABC", key2, status2);
* . if (U_FAILURE(status2)) { delete myCollation; return; }
* . // key1.hashCode() != key2.hashCode()
* </pre>
* @return the hash value based on the string's collation order.
* @see UnicodeString#hashCode
* @stable ICU 2.0
*/
int32_t hashCode() const;
/**
* ICU "poor man's RTTI", returns a UClassID for the actual class.
* @stable ICU 2.2
*/
virtual UClassID getDynamicClassID() const override;
/**
* ICU "poor man's RTTI", returns a UClassID for this class.
* @stable ICU 2.2
*/
static UClassID U_EXPORT2 getStaticClassID();
private:
/**
* Replaces the current bytes buffer with a new one of newCapacity
* and copies length bytes from the old buffer to the new one.
* @return the new buffer, or nullptr if the allocation failed
*/
uint8_t *reallocate(int32_t newCapacity, int32_t length);
/**
* Set a new length for a new sort key in the existing fBytes.
*/
void setLength(int32_t newLength);
uint8_t *getBytes() {
return (fFlagAndLength >= 0) ? fUnion.fStackBuffer : fUnion.fFields.fBytes;
}
const uint8_t *getBytes() const {
return (fFlagAndLength >= 0) ? fUnion.fStackBuffer : fUnion.fFields.fBytes;
}
int32_t getCapacity() const {
return fFlagAndLength >= 0 ? static_cast<int32_t>(sizeof(fUnion)) : fUnion.fFields.fCapacity;
}
int32_t getLength() const { return fFlagAndLength & 0x7fffffff; }
/**
* Set the CollationKey to a "bogus" or invalid state
* @return this CollationKey
*/
CollationKey& setToBogus();
/**
* Resets this CollationKey to an empty state
* @return this CollationKey
*/
CollationKey& reset();
/**
* Allow private access to RuleBasedCollator
*/
friend class RuleBasedCollator;
friend class CollationKeyByteSink;
// Class fields. sizeof(CollationKey) is intended to be 48 bytes
// on a machine with 64-bit pointers.
// We use a union to maximize the size of the internal buffer,
// similar to UnicodeString but not as tight and complex.
// (implicit) *vtable;
/**
* Sort key length and flag.
* Bit 31 is set if the buffer is heap-allocated.
* Bits 30..0 contain the sort key length.
*/
int32_t fFlagAndLength;
/**
* Unique hash value of this CollationKey.
* Special value 2 if the key is bogus.
*/
mutable int32_t fHashCode;
/**
* fUnion provides 32 bytes for the internal buffer or for
* pointer+capacity.
*/
union StackBufferOrFields {
/** fStackBuffer is used iff fFlagAndLength>=0, else fFields is used */
uint8_t fStackBuffer[32];
struct {
uint8_t *fBytes;
int32_t fCapacity;
} fFields;
} fUnion;
};
inline bool
CollationKey::operator!=(const CollationKey& other) const
{
return !(*this == other);
}
inline UBool
CollationKey::isBogus() const
{
return fHashCode == 2; // kBogusHashCode
}
inline const uint8_t*
CollationKey::getByteArray(int32_t &count) const
{
count = getLength();
return getBytes();
}
U_NAMESPACE_END
#endif /* #if !UCONFIG_NO_COLLATION */
#endif /* U_SHOW_CPLUSPLUS_API */
#endif

View File

@ -0,0 +1,509 @@
// © 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
/*
**********************************************************************
* Copyright (C) 2001-2014 IBM and others. All rights reserved.
**********************************************************************
* Date Name Description
* 03/22/2000 helena Creation.
**********************************************************************
*/
#ifndef STSEARCH_H
#define STSEARCH_H
#include "unicode/utypes.h"
#if U_SHOW_CPLUSPLUS_API
/**
* \file
* \brief C++ API: Service for searching text based on RuleBasedCollator.
*/
#if !UCONFIG_NO_COLLATION && !UCONFIG_NO_BREAK_ITERATION
#include "unicode/tblcoll.h"
#include "unicode/coleitr.h"
#include "unicode/search.h"
U_NAMESPACE_BEGIN
/**
*
* <tt>StringSearch</tt> is a <tt>SearchIterator</tt> that provides
* language-sensitive text searching based on the comparison rules defined
* in a {@link RuleBasedCollator} object.
* StringSearch ensures that language eccentricity can be
* handled, e.g. for the German collator, characters &szlig; and SS will be matched
* if case is chosen to be ignored.
* See the <a href="https://htmlpreview.github.io/?https://github.com/unicode-org/icu-docs/blob/main/design/collation/ICU_collation_design.htm">
* "ICU Collation Design Document"</a> for more information.
* <p>
* There are 2 match options for selection:<br>
* Let S' be the sub-string of a text string S between the offsets start and
* end [start, end].
* <br>
* A pattern string P matches a text string S at the offsets [start, end]
* if
* <pre>
* option 1. Some canonical equivalent of P matches some canonical equivalent
* of S'
* option 2. P matches S' and if P starts or ends with a combining mark,
* there exists no non-ignorable combining mark before or after S?
* in S respectively.
* </pre>
* Option 2. will be the default.
* <p>
* This search has APIs similar to that of other text iteration mechanisms
* such as the break iterators in <tt>BreakIterator</tt>. Using these
* APIs, it is easy to scan through text looking for all occurrences of
* a given pattern. This search iterator allows changing of direction by
* calling a <tt>reset</tt> followed by a <tt>next</tt> or <tt>previous</tt>.
* Though a direction change can occur without calling <tt>reset</tt> first,
* this operation comes with some speed penalty.
* Match results in the forward direction will match the result matches in
* the backwards direction in the reverse order
* <p>
* <tt>SearchIterator</tt> provides APIs to specify the starting position
* within the text string to be searched, e.g. <tt>setOffset</tt>,
* <tt>preceding</tt> and <tt>following</tt>. Since the
* starting position will be set as it is specified, please take note that
* there are some danger points which the search may render incorrect
* results:
* <ul>
* <li> The midst of a substring that requires normalization.
* <li> If the following match is to be found, the position should not be the
* second character which requires to be swapped with the preceding
* character. Vice versa, if the preceding match is to be found,
* position to search from should not be the first character which
* requires to be swapped with the next character. E.g certain Thai and
* Lao characters require swapping.
* <li> If a following pattern match is to be found, any position within a
* contracting sequence except the first will fail. Vice versa if a
* preceding pattern match is to be found, a invalid starting point
* would be any character within a contracting sequence except the last.
* </ul>
* <p>
* A <tt>BreakIterator</tt> can be used if only matches at logical breaks are desired.
* Using a <tt>BreakIterator</tt> will only give you results that exactly matches the
* boundaries given by the breakiterator. For instance the pattern "e" will
* not be found in the string "\u00e9" if a character break iterator is used.
* <p>
* Options are provided to handle overlapping matches.
* E.g. In English, overlapping matches produces the result 0 and 2
* for the pattern "abab" in the text "ababab", where else mutually
* exclusive matches only produce the result of 0.
* <p>
* Though collator attributes will be taken into consideration while
* performing matches, there are no APIs here for setting and getting the
* attributes. These attributes can be set by getting the collator
* from <tt>getCollator</tt> and using the APIs in <tt>coll.h</tt>.
* Lastly to update <tt>StringSearch</tt> to the new collator attributes,
* <tt>reset</tt> has to be called.
* <p>
* Restriction: <br>
* Currently there are no composite characters that consists of a
* character with combining class > 0 before a character with combining
* class == 0. However, if such a character exists in the future,
* <tt>StringSearch</tt> does not guarantee the results for option 1.
* <p>
* Consult the <tt>SearchIterator</tt> documentation for information on
* and examples of how to use instances of this class to implement text
* searching.
* <pre><code>
* UnicodeString target("The quick brown fox jumps over the lazy dog.");
* UnicodeString pattern("fox");
*
* UErrorCode error = U_ZERO_ERROR;
* StringSearch iter(pattern, target, Locale::getUS(), nullptr, status);
* for (int pos = iter.first(error);
* pos != USEARCH_DONE;
* pos = iter.next(error))
* {
* printf("Found match at %d pos, length is %d\n", pos, iter.getMatchedLength());
* }
* </code></pre>
* <p>
* Note, <tt>StringSearch</tt> is not to be subclassed.
* </p>
* @see SearchIterator
* @see RuleBasedCollator
* @since ICU 2.0
*/
class U_I18N_API StringSearch final : public SearchIterator
{
public:
// public constructors and destructors --------------------------------
/**
* Creating a <tt>StringSearch</tt> instance using the argument locale
* language rule set. A collator will be created in the process, which
* will be owned by this instance and will be deleted during
* destruction
* @param pattern The text for which this object will search.
* @param text The text in which to search for the pattern.
* @param locale A locale which defines the language-sensitive
* comparison rules used to determine whether text in the
* pattern and target matches.
* @param breakiter A <tt>BreakIterator</tt> object used to constrain
* the matches that are found. Matches whose start and end
* indices in the target text are not boundaries as
* determined by the <tt>BreakIterator</tt> are
* ignored. If this behavior is not desired,
* <tt>nullptr</tt> can be passed in instead.
* @param status for errors if any. If pattern or text is nullptr, or if
* either the length of pattern or text is 0 then an
* U_ILLEGAL_ARGUMENT_ERROR is returned.
* @stable ICU 2.0
*/
StringSearch(const UnicodeString &pattern, const UnicodeString &text,
const Locale &locale,
BreakIterator *breakiter,
UErrorCode &status);
/**
* Creating a <tt>StringSearch</tt> instance using the argument collator
* language rule set. Note, user retains the ownership of this collator,
* it does not get destroyed during this instance's destruction.
* @param pattern The text for which this object will search.
* @param text The text in which to search for the pattern.
* @param coll A <tt>RuleBasedCollator</tt> object which defines
* the language-sensitive comparison rules used to
* determine whether text in the pattern and target
* matches. User is responsible for the clearing of this
* object.
* @param breakiter A <tt>BreakIterator</tt> object used to constrain
* the matches that are found. Matches whose start and end
* indices in the target text are not boundaries as
* determined by the <tt>BreakIterator</tt> are
* ignored. If this behavior is not desired,
* <tt>nullptr</tt> can be passed in instead.
* @param status for errors if any. If either the length of pattern or
* text is 0 then an U_ILLEGAL_ARGUMENT_ERROR is returned.
* @stable ICU 2.0
*/
StringSearch(const UnicodeString &pattern,
const UnicodeString &text,
RuleBasedCollator *coll,
BreakIterator *breakiter,
UErrorCode &status);
/**
* Creating a <tt>StringSearch</tt> instance using the argument locale
* language rule set. A collator will be created in the process, which
* will be owned by this instance and will be deleted during
* destruction
* <p>
* Note: No parsing of the text within the <tt>CharacterIterator</tt>
* will be done during searching for this version. The block of text
* in <tt>CharacterIterator</tt> will be used as it is.
* @param pattern The text for which this object will search.
* @param text The text iterator in which to search for the pattern.
* @param locale A locale which defines the language-sensitive
* comparison rules used to determine whether text in the
* pattern and target matches. User is responsible for
* the clearing of this object.
* @param breakiter A <tt>BreakIterator</tt> object used to constrain
* the matches that are found. Matches whose start and end
* indices in the target text are not boundaries as
* determined by the <tt>BreakIterator</tt> are
* ignored. If this behavior is not desired,
* <tt>nullptr</tt> can be passed in instead.
* @param status for errors if any. If either the length of pattern or
* text is 0 then an U_ILLEGAL_ARGUMENT_ERROR is returned.
* @stable ICU 2.0
*/
StringSearch(const UnicodeString &pattern, CharacterIterator &text,
const Locale &locale,
BreakIterator *breakiter,
UErrorCode &status);
/**
* Creating a <tt>StringSearch</tt> instance using the argument collator
* language rule set. Note, user retains the ownership of this collator,
* it does not get destroyed during this instance's destruction.
* <p>
* Note: No parsing of the text within the <tt>CharacterIterator</tt>
* will be done during searching for this version. The block of text
* in <tt>CharacterIterator</tt> will be used as it is.
* @param pattern The text for which this object will search.
* @param text The text in which to search for the pattern.
* @param coll A <tt>RuleBasedCollator</tt> object which defines
* the language-sensitive comparison rules used to
* determine whether text in the pattern and target
* matches. User is responsible for the clearing of this
* object.
* @param breakiter A <tt>BreakIterator</tt> object used to constrain
* the matches that are found. Matches whose start and end
* indices in the target text are not boundaries as
* determined by the <tt>BreakIterator</tt> are
* ignored. If this behavior is not desired,
* <tt>nullptr</tt> can be passed in instead.
* @param status for errors if any. If either the length of pattern or
* text is 0 then an U_ILLEGAL_ARGUMENT_ERROR is returned.
* @stable ICU 2.0
*/
StringSearch(const UnicodeString &pattern, CharacterIterator &text,
RuleBasedCollator *coll,
BreakIterator *breakiter,
UErrorCode &status);
/**
* Copy constructor that creates a StringSearch instance with the same
* behavior, and iterating over the same text.
* @param that StringSearch instance to be copied.
* @stable ICU 2.0
*/
StringSearch(const StringSearch &that);
/**
* Destructor. Cleans up the search iterator data struct.
* If a collator is created in the constructor, it will be destroyed here.
* @stable ICU 2.0
*/
virtual ~StringSearch();
/**
* Clone this object.
* Clones can be used concurrently in multiple threads.
* If an error occurs, then nullptr is returned.
* The caller must delete the clone.
*
* @return a clone of this object
*
* @see getDynamicClassID
* @stable ICU 2.8
*/
StringSearch *clone() const;
// operator overloading ---------------------------------------------
/**
* Assignment operator. Sets this iterator to have the same behavior,
* and iterate over the same text, as the one passed in.
* @param that instance to be copied.
* @stable ICU 2.0
*/
StringSearch & operator=(const StringSearch &that);
/**
* Equality operator.
* @param that instance to be compared.
* @return true if both instances have the same attributes,
* breakiterators, collators and iterate over the same text
* while looking for the same pattern.
* @stable ICU 2.0
*/
virtual bool operator==(const SearchIterator &that) const override;
// public get and set methods ----------------------------------------
/**
* Sets the index to point to the given position, and clears any state
* that's affected.
* <p>
* This method takes the argument index and sets the position in the text
* string accordingly without checking if the index is pointing to a
* valid starting point to begin searching.
* @param position within the text to be set. If position is less
* than or greater than the text range for searching,
* an U_INDEX_OUTOFBOUNDS_ERROR will be returned
* @param status for errors if it occurs
* @stable ICU 2.0
*/
virtual void setOffset(int32_t position, UErrorCode &status) override;
/**
* Return the current index in the text being searched.
* If the iteration has gone past the end of the text
* (or past the beginning for a backwards search), USEARCH_DONE
* is returned.
* @return current index in the text being searched.
* @stable ICU 2.0
*/
virtual int32_t getOffset() const override;
/**
* Set the target text to be searched.
* Text iteration will hence begin at the start of the text string.
* This method is
* useful if you want to re-use an iterator to search for the same
* pattern within a different body of text.
* @param text text string to be searched
* @param status for errors if any. If the text length is 0 then an
* U_ILLEGAL_ARGUMENT_ERROR is returned.
* @stable ICU 2.0
*/
virtual void setText(const UnicodeString &text, UErrorCode &status) override;
/**
* Set the target text to be searched.
* Text iteration will hence begin at the start of the text string.
* This method is
* useful if you want to re-use an iterator to search for the same
* pattern within a different body of text.
* Note: No parsing of the text within the <tt>CharacterIterator</tt>
* will be done during searching for this version. The block of text
* in <tt>CharacterIterator</tt> will be used as it is.
* @param text text string to be searched
* @param status for errors if any. If the text length is 0 then an
* U_ILLEGAL_ARGUMENT_ERROR is returned.
* @stable ICU 2.0
*/
virtual void setText(CharacterIterator &text, UErrorCode &status) override;
/**
* Gets the collator used for the language rules.
* <p>
* Caller may modify but <b>must not</b> delete the <tt>RuleBasedCollator</tt>!
* Modifications to this collator will affect the original collator passed in to
* the <tt>StringSearch></tt> constructor or to setCollator, if any.
* @return collator used for string search
* @stable ICU 2.0
*/
RuleBasedCollator * getCollator() const;
/**
* Sets the collator used for the language rules. User retains the
* ownership of this collator, thus the responsibility of deletion lies
* with the user. The iterator's position will not be changed by this method.
* @param coll collator
* @param status for errors if any
* @stable ICU 2.0
*/
void setCollator(RuleBasedCollator *coll, UErrorCode &status);
/**
* Sets the pattern used for matching.
* The iterator's position will not be changed by this method.
* @param pattern search pattern to be found
* @param status for errors if any. If the pattern length is 0 then an
* U_ILLEGAL_ARGUMENT_ERROR is returned.
* @stable ICU 2.0
*/
void setPattern(const UnicodeString &pattern, UErrorCode &status);
/**
* Gets the search pattern.
* @return pattern used for matching
* @stable ICU 2.0
*/
const UnicodeString & getPattern() const;
// public methods ----------------------------------------------------
/**
* Reset the iteration.
* Search will begin at the start of the text string if a forward
* iteration is initiated before a backwards iteration. Otherwise if
* a backwards iteration is initiated before a forwards iteration, the
* search will begin at the end of the text string.
* @stable ICU 2.0
*/
virtual void reset() override;
/**
* Returns a copy of StringSearch with the same behavior, and
* iterating over the same text, as this one. Note that all data will be
* replicated, except for the user-specified collator and the
* breakiterator.
* @return cloned object
* @stable ICU 2.0
*/
virtual StringSearch * safeClone() const override;
/**
* ICU "poor man's RTTI", returns a UClassID for the actual class.
*
* @stable ICU 2.2
*/
virtual UClassID getDynamicClassID() const override;
/**
* ICU "poor man's RTTI", returns a UClassID for this class.
*
* @stable ICU 2.2
*/
static UClassID U_EXPORT2 getStaticClassID();
protected:
// protected method -------------------------------------------------
/**
* Search forward for matching text, starting at a given location.
* Clients should not call this method directly; instead they should
* call {@link SearchIterator#next }.
* <p>
* If a match is found, this method returns the index at which the match
* starts and calls {@link SearchIterator#setMatchLength } with the number
* of characters in the target text that make up the match. If no match
* is found, the method returns <tt>USEARCH_DONE</tt>.
* <p>
* The <tt>StringSearch</tt> is adjusted so that its current index
* (as returned by {@link #getOffset }) is the match position if one was
* found.
* If a match is not found, <tt>USEARCH_DONE</tt> will be returned and
* the <tt>StringSearch</tt> will be adjusted to the index USEARCH_DONE.
* @param position The index in the target text at which the search
* starts
* @param status for errors if any occurs
* @return The index at which the matched text in the target starts, or
* USEARCH_DONE if no match was found.
* @stable ICU 2.0
*/
virtual int32_t handleNext(int32_t position, UErrorCode &status) override;
/**
* Search backward for matching text, starting at a given location.
* Clients should not call this method directly; instead they should call
* <tt>SearchIterator.previous()</tt>, which this method overrides.
* <p>
* If a match is found, this method returns the index at which the match
* starts and calls {@link SearchIterator#setMatchLength } with the number
* of characters in the target text that make up the match. If no match
* is found, the method returns <tt>USEARCH_DONE</tt>.
* <p>
* The <tt>StringSearch</tt> is adjusted so that its current index
* (as returned by {@link #getOffset }) is the match position if one was
* found.
* If a match is not found, <tt>USEARCH_DONE</tt> will be returned and
* the <tt>StringSearch</tt> will be adjusted to the index USEARCH_DONE.
* @param position The index in the target text at which the search
* starts.
* @param status for errors if any occurs
* @return The index at which the matched text in the target starts, or
* USEARCH_DONE if no match was found.
* @stable ICU 2.0
*/
virtual int32_t handlePrev(int32_t position, UErrorCode &status) override;
private :
StringSearch() = delete; // default constructor not implemented
// private data members ----------------------------------------------
/**
* Pattern text
* @stable ICU 2.0
*/
UnicodeString m_pattern_;
/**
* String search struct data
* @stable ICU 2.0
*/
UStringSearch *m_strsrch_;
};
U_NAMESPACE_END
#endif /* #if !UCONFIG_NO_COLLATION */
#endif /* U_SHOW_CPLUSPLUS_API */
#endif

View File

@ -0,0 +1,886 @@
// © 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
/*
******************************************************************************
* Copyright (C) 1996-2016, International Business Machines Corporation and
* others. All Rights Reserved.
******************************************************************************
*/
/**
* \file
* \brief C++ API: The RuleBasedCollator class implements the Collator abstract base class.
*/
/**
* File tblcoll.h
*
* Created by: Helena Shih
*
* Modification History:
*
* Date Name Description
* 2/5/97 aliu Added streamIn and streamOut methods. Added
* constructor which reads RuleBasedCollator object from
* a binary file. Added writeToFile method which streams
* RuleBasedCollator out to a binary file. The streamIn
* and streamOut methods use istream and ostream objects
* in binary mode.
* 2/12/97 aliu Modified to use TableCollationData sub-object to
* hold invariant data.
* 2/13/97 aliu Moved several methods into this class from Collation.
* Added a private RuleBasedCollator(Locale&) constructor,
* to be used by Collator::createDefault(). General
* clean up.
* 2/20/97 helena Added clone, operator==, operator!=, operator=, and copy
* constructor and getDynamicClassID.
* 3/5/97 aliu Modified constructFromFile() to add parameter
* specifying whether or not binary loading is to be
* attempted. This is required for dynamic rule loading.
* 05/07/97 helena Added memory allocation error detection.
* 6/17/97 helena Added IDENTICAL strength for compare, changed getRules to
* use MergeCollation::getPattern.
* 6/20/97 helena Java class name change.
* 8/18/97 helena Added internal API documentation.
* 09/03/97 helena Added createCollationKeyValues().
* 02/10/98 damiba Added compare with "length" parameter
* 08/05/98 erm Synched with 1.2 version of RuleBasedCollator.java
* 04/23/99 stephen Removed EDecompositionMode, merged with
* Normalizer::EMode
* 06/14/99 stephen Removed kResourceBundleSuffix
* 11/02/99 helena Collator performance enhancements. Eliminates the
* UnicodeString construction and special case for NO_OP.
* 11/23/99 srl More performance enhancements. Updates to NormalizerIterator
* internal state management.
* 12/15/99 aliu Update to support Thai collation. Move NormalizerIterator
* to implementation file.
* 01/29/01 synwee Modified into a C++ wrapper which calls C API
* (ucol.h)
* 2012-2014 markus Rewritten in C++ again.
*/
#ifndef TBLCOLL_H
#define TBLCOLL_H
#include "unicode/utypes.h"
#if U_SHOW_CPLUSPLUS_API
#if !UCONFIG_NO_COLLATION
#include "unicode/coll.h"
#include "unicode/locid.h"
#include "unicode/uiter.h"
#include "unicode/ucol.h"
U_NAMESPACE_BEGIN
struct CollationCacheEntry;
struct CollationData;
struct CollationSettings;
struct CollationTailoring;
/**
* @stable ICU 2.0
*/
class StringSearch;
/**
* @stable ICU 2.0
*/
class CollationElementIterator;
class CollationKey;
class SortKeyByteSink;
class UnicodeSet;
class UnicodeString;
class UVector64;
/**
* The RuleBasedCollator class provides the implementation of
* Collator, using data-driven tables. The user can create a customized
* table-based collation.
* <p>
* For more information about the collation service see
* <a href="https://unicode-org.github.io/icu/userguide/collation">the User Guide</a>.
* <p>
* Collation service provides correct sorting orders for most locales supported in ICU.
* If specific data for a locale is not available, the orders eventually falls back
* to the <a href="http://www.unicode.org/reports/tr35/tr35-collation.html#Root_Collation">CLDR root sort order</a>.
* <p>
* Sort ordering may be customized by providing your own set of rules. For more on
* this subject see the <a href="https://unicode-org.github.io/icu/userguide/collation/customization">
* Collation Customization</a> section of the User Guide.
* <p>
* Note, RuleBasedCollator is not to be subclassed.
* @see Collator
*/
class U_I18N_API RuleBasedCollator final : public Collator {
public:
/**
* RuleBasedCollator constructor. This takes the table rules and builds a
* collation table out of them. Please see RuleBasedCollator class
* description for more details on the collation rule syntax.
* @param rules the collation rules to build the collation table from.
* @param status reporting a success or an error.
* @stable ICU 2.0
*/
RuleBasedCollator(const UnicodeString& rules, UErrorCode& status);
/**
* RuleBasedCollator constructor. This takes the table rules and builds a
* collation table out of them. Please see RuleBasedCollator class
* description for more details on the collation rule syntax.
* @param rules the collation rules to build the collation table from.
* @param collationStrength strength for comparison
* @param status reporting a success or an error.
* @stable ICU 2.0
*/
RuleBasedCollator(const UnicodeString& rules,
ECollationStrength collationStrength,
UErrorCode& status);
/**
* RuleBasedCollator constructor. This takes the table rules and builds a
* collation table out of them. Please see RuleBasedCollator class
* description for more details on the collation rule syntax.
* @param rules the collation rules to build the collation table from.
* @param decompositionMode the normalisation mode
* @param status reporting a success or an error.
* @stable ICU 2.0
*/
RuleBasedCollator(const UnicodeString& rules,
UColAttributeValue decompositionMode,
UErrorCode& status);
/**
* RuleBasedCollator constructor. This takes the table rules and builds a
* collation table out of them. Please see RuleBasedCollator class
* description for more details on the collation rule syntax.
* @param rules the collation rules to build the collation table from.
* @param collationStrength strength for comparison
* @param decompositionMode the normalisation mode
* @param status reporting a success or an error.
* @stable ICU 2.0
*/
RuleBasedCollator(const UnicodeString& rules,
ECollationStrength collationStrength,
UColAttributeValue decompositionMode,
UErrorCode& status);
#ifndef U_HIDE_INTERNAL_API
/**
* TODO: document & propose as public API
* @internal
*/
RuleBasedCollator(const UnicodeString &rules,
UParseError &parseError, UnicodeString &reason,
UErrorCode &errorCode);
#endif /* U_HIDE_INTERNAL_API */
/**
* Copy constructor.
* @param other the RuleBasedCollator object to be copied
* @stable ICU 2.0
*/
RuleBasedCollator(const RuleBasedCollator& other);
/** Opens a collator from a collator binary image created using
* cloneBinary. Binary image used in instantiation of the
* collator remains owned by the user and should stay around for
* the lifetime of the collator. The API also takes a base collator
* which must be the root collator.
* @param bin binary image owned by the user and required through the
* lifetime of the collator
* @param length size of the image. If negative, the API will try to
* figure out the length of the image
* @param base Base collator, for lookup of untailored characters.
* Must be the root collator, must not be nullptr.
* The base is required to be present through the lifetime of the collator.
* @param status for catching errors
* @return newly created collator
* @see cloneBinary
* @stable ICU 3.4
*/
RuleBasedCollator(const uint8_t *bin, int32_t length,
const RuleBasedCollator *base,
UErrorCode &status);
/**
* Destructor.
* @stable ICU 2.0
*/
virtual ~RuleBasedCollator();
/**
* Assignment operator.
* @param other other RuleBasedCollator object to copy from.
* @stable ICU 2.0
*/
RuleBasedCollator& operator=(const RuleBasedCollator& other);
/**
* Returns true if argument is the same as this object.
* @param other Collator object to be compared.
* @return true if arguments is the same as this object.
* @stable ICU 2.0
*/
virtual bool operator==(const Collator& other) const override;
/**
* Makes a copy of this object.
* @return a copy of this object, owned by the caller
* @stable ICU 2.0
*/
virtual RuleBasedCollator* clone() const override;
/**
* Creates a collation element iterator for the source string. The caller of
* this method is responsible for the memory management of the return
* pointer.
* @param source the string over which the CollationElementIterator will
* iterate.
* @return the collation element iterator of the source string using this as
* the based Collator.
* @stable ICU 2.2
*/
virtual CollationElementIterator* createCollationElementIterator(
const UnicodeString& source) const;
/**
* Creates a collation element iterator for the source. The caller of this
* method is responsible for the memory management of the returned pointer.
* @param source the CharacterIterator which produces the characters over
* which the CollationElementItgerator will iterate.
* @return the collation element iterator of the source using this as the
* based Collator.
* @stable ICU 2.2
*/
virtual CollationElementIterator* createCollationElementIterator(
const CharacterIterator& source) const;
// Make deprecated versions of Collator::compare() visible.
using Collator::compare;
/**
* The comparison function compares the character data stored in two
* different strings. Returns information about whether a string is less
* than, greater than or equal to another string.
* @param source the source string to be compared with.
* @param target the string that is to be compared with the source string.
* @param status possible error code
* @return Returns an enum value. UCOL_GREATER if source is greater
* than target; UCOL_EQUAL if source is equal to target; UCOL_LESS if source is less
* than target
* @stable ICU 2.6
**/
virtual UCollationResult compare(const UnicodeString& source,
const UnicodeString& target,
UErrorCode &status) const override;
/**
* Does the same thing as compare but limits the comparison to a specified
* length
* @param source the source string to be compared with.
* @param target the string that is to be compared with the source string.
* @param length the length the comparison is limited to
* @param status possible error code
* @return Returns an enum value. UCOL_GREATER if source (up to the specified
* length) is greater than target; UCOL_EQUAL if source (up to specified
* length) is equal to target; UCOL_LESS if source (up to the specified
* length) is less than target.
* @stable ICU 2.6
*/
virtual UCollationResult compare(const UnicodeString& source,
const UnicodeString& target,
int32_t length,
UErrorCode &status) const override;
/**
* The comparison function compares the character data stored in two
* different string arrays. Returns information about whether a string array
* is less than, greater than or equal to another string array.
* @param source the source string array to be compared with.
* @param sourceLength the length of the source string array. If this value
* is equal to -1, the string array is null-terminated.
* @param target the string that is to be compared with the source string.
* @param targetLength the length of the target string array. If this value
* is equal to -1, the string array is null-terminated.
* @param status possible error code
* @return Returns an enum value. UCOL_GREATER if source is greater
* than target; UCOL_EQUAL if source is equal to target; UCOL_LESS if source is less
* than target
* @stable ICU 2.6
*/
virtual UCollationResult compare(const char16_t* source, int32_t sourceLength,
const char16_t* target, int32_t targetLength,
UErrorCode &status) const override;
/**
* Compares two strings using the Collator.
* Returns whether the first one compares less than/equal to/greater than
* the second one.
* This version takes UCharIterator input.
* @param sIter the first ("source") string iterator
* @param tIter the second ("target") string iterator
* @param status ICU status
* @return UCOL_LESS, UCOL_EQUAL or UCOL_GREATER
* @stable ICU 4.2
*/
virtual UCollationResult compare(UCharIterator &sIter,
UCharIterator &tIter,
UErrorCode &status) const override;
/**
* Compares two UTF-8 strings using the Collator.
* Returns whether the first one compares less than/equal to/greater than
* the second one.
* This version takes UTF-8 input.
* Note that a StringPiece can be implicitly constructed
* from a std::string or a NUL-terminated const char * string.
* @param source the first UTF-8 string
* @param target the second UTF-8 string
* @param status ICU status
* @return UCOL_LESS, UCOL_EQUAL or UCOL_GREATER
* @stable ICU 51
*/
virtual UCollationResult compareUTF8(const StringPiece &source,
const StringPiece &target,
UErrorCode &status) const override;
/**
* Transforms the string into a series of characters
* that can be compared with CollationKey.compare().
*
* Note that sort keys are often less efficient than simply doing comparison.
* For more details, see the ICU User Guide.
*
* @param source the source string.
* @param key the transformed key of the source string.
* @param status the error code status.
* @return the transformed key.
* @see CollationKey
* @stable ICU 2.0
*/
virtual CollationKey& getCollationKey(const UnicodeString& source,
CollationKey& key,
UErrorCode& status) const override;
/**
* Transforms a specified region of the string into a series of characters
* that can be compared with CollationKey.compare.
*
* Note that sort keys are often less efficient than simply doing comparison.
* For more details, see the ICU User Guide.
*
* @param source the source string.
* @param sourceLength the length of the source string.
* @param key the transformed key of the source string.
* @param status the error code status.
* @return the transformed key.
* @see CollationKey
* @stable ICU 2.0
*/
virtual CollationKey& getCollationKey(const char16_t *source,
int32_t sourceLength,
CollationKey& key,
UErrorCode& status) const override;
/**
* Generates the hash code for the rule-based collation object.
* @return the hash code.
* @stable ICU 2.0
*/
virtual int32_t hashCode() const override;
#ifndef U_FORCE_HIDE_DEPRECATED_API
/**
* Gets the locale of the Collator
* @param type can be either requested, valid or actual locale. For more
* information see the definition of ULocDataLocaleType in
* uloc.h
* @param status the error code status.
* @return locale where the collation data lives. If the collator
* was instantiated from rules, locale is empty.
* @deprecated ICU 2.8 likely to change in ICU 3.0, based on feedback
*/
virtual Locale getLocale(ULocDataLocaleType type, UErrorCode& status) const override;
#endif // U_FORCE_HIDE_DEPRECATED_API
/**
* Gets the tailoring rules for this collator.
* @return the collation tailoring from which this collator was created
* @stable ICU 2.0
*/
const UnicodeString& getRules() const;
/**
* Gets the version information for a Collator.
* @param info the version # information, the result will be filled in
* @stable ICU 2.0
*/
virtual void getVersion(UVersionInfo info) const override;
#ifndef U_HIDE_DEPRECATED_API
/**
* Returns the maximum length of any expansion sequences that end with the
* specified comparison order.
*
* This is specific to the kind of collation element values and sequences
* returned by the CollationElementIterator.
* Call CollationElementIterator::getMaxExpansion() instead.
*
* @param order a collation order returned by CollationElementIterator::previous
* or CollationElementIterator::next.
* @return maximum size of the expansion sequences ending with the collation
* element, or 1 if the collation element does not occur at the end of
* any expansion sequence
* @see CollationElementIterator#getMaxExpansion
* @deprecated ICU 51 Use CollationElementIterator::getMaxExpansion() instead.
*/
int32_t getMaxExpansion(int32_t order) const;
#endif /* U_HIDE_DEPRECATED_API */
/**
* Returns a unique class ID POLYMORPHICALLY. Pure virtual override. This
* method is to implement a simple version of RTTI, since not all C++
* compilers support genuine RTTI. Polymorphic operator==() and clone()
* methods call this method.
* @return The class ID for this object. All objects of a given class have
* the same class ID. Objects of other classes have different class
* IDs.
* @stable ICU 2.0
*/
virtual UClassID getDynamicClassID() const override;
/**
* Returns the class ID for this class. This is useful only for comparing to
* a return value from getDynamicClassID(). For example:
* <pre>
* Base* polymorphic_pointer = createPolymorphicObject();
* if (polymorphic_pointer->getDynamicClassID() ==
* Derived::getStaticClassID()) ...
* </pre>
* @return The class ID for all objects of this class.
* @stable ICU 2.0
*/
static UClassID U_EXPORT2 getStaticClassID();
#ifndef U_HIDE_DEPRECATED_API
/**
* Do not use this method: The caller and the ICU library might use different heaps.
* Use cloneBinary() instead which writes to caller-provided memory.
*
* Returns a binary format of this collator.
* @param length Returns the length of the data, in bytes
* @param status the error code status.
* @return memory, owned by the caller, of size 'length' bytes.
* @deprecated ICU 52. Use cloneBinary() instead.
*/
uint8_t *cloneRuleData(int32_t &length, UErrorCode &status) const;
#endif /* U_HIDE_DEPRECATED_API */
/** Creates a binary image of a collator. This binary image can be stored and
* later used to instantiate a collator using ucol_openBinary.
* This API supports preflighting.
* @param buffer a fill-in buffer to receive the binary image
* @param capacity capacity of the destination buffer
* @param status for catching errors
* @return size of the image
* @see ucol_openBinary
* @stable ICU 3.4
*/
int32_t cloneBinary(uint8_t *buffer, int32_t capacity, UErrorCode &status) const;
/**
* Returns current rules. Delta defines whether full rules are returned or
* just the tailoring.
*
* getRules(void) should normally be used instead.
* See https://unicode-org.github.io/icu/userguide/collation/customization#building-on-existing-locales
* @param delta one of UCOL_TAILORING_ONLY, UCOL_FULL_RULES.
* @param buffer UnicodeString to store the result rules
* @stable ICU 2.2
* @see UCOL_FULL_RULES
*/
void getRules(UColRuleOption delta, UnicodeString &buffer) const;
/**
* Universal attribute setter
* @param attr attribute type
* @param value attribute value
* @param status to indicate whether the operation went on smoothly or there were errors
* @stable ICU 2.2
*/
virtual void setAttribute(UColAttribute attr, UColAttributeValue value,
UErrorCode &status) override;
/**
* Universal attribute getter.
* @param attr attribute type
* @param status to indicate whether the operation went on smoothly or there were errors
* @return attribute value
* @stable ICU 2.2
*/
virtual UColAttributeValue getAttribute(UColAttribute attr,
UErrorCode &status) const override;
/**
* Sets the variable top to the top of the specified reordering group.
* The variable top determines the highest-sorting character
* which is affected by UCOL_ALTERNATE_HANDLING.
* If that attribute is set to UCOL_NON_IGNORABLE, then the variable top has no effect.
* @param group one of UCOL_REORDER_CODE_SPACE, UCOL_REORDER_CODE_PUNCTUATION,
* UCOL_REORDER_CODE_SYMBOL, UCOL_REORDER_CODE_CURRENCY;
* or UCOL_REORDER_CODE_DEFAULT to restore the default max variable group
* @param errorCode Standard ICU error code. Its input value must
* pass the U_SUCCESS() test, or else the function returns
* immediately. Check for U_FAILURE() on output or use with
* function chaining. (See User Guide for details.)
* @return *this
* @see getMaxVariable
* @stable ICU 53
*/
virtual Collator &setMaxVariable(UColReorderCode group, UErrorCode &errorCode) override;
/**
* Returns the maximum reordering group whose characters are affected by UCOL_ALTERNATE_HANDLING.
* @return the maximum variable reordering group.
* @see setMaxVariable
* @stable ICU 53
*/
virtual UColReorderCode getMaxVariable() const override;
#ifndef U_FORCE_HIDE_DEPRECATED_API
/**
* Sets the variable top to the primary weight of the specified string.
*
* Beginning with ICU 53, the variable top is pinned to
* the top of one of the supported reordering groups,
* and it must not be beyond the last of those groups.
* See setMaxVariable().
* @param varTop one or more (if contraction) char16_ts to which the variable top should be set
* @param len length of variable top string. If -1 it is considered to be zero terminated.
* @param status error code. If error code is set, the return value is undefined. Errors set by this function are: <br>
* U_CE_NOT_FOUND_ERROR if more than one character was passed and there is no such contraction<br>
* U_ILLEGAL_ARGUMENT_ERROR if the variable top is beyond
* the last reordering group supported by setMaxVariable()
* @return variable top primary weight
* @deprecated ICU 53 Call setMaxVariable() instead.
*/
virtual uint32_t setVariableTop(const char16_t *varTop, int32_t len, UErrorCode &status) override;
/**
* Sets the variable top to the primary weight of the specified string.
*
* Beginning with ICU 53, the variable top is pinned to
* the top of one of the supported reordering groups,
* and it must not be beyond the last of those groups.
* See setMaxVariable().
* @param varTop a UnicodeString size 1 or more (if contraction) of char16_ts to which the variable top should be set
* @param status error code. If error code is set, the return value is undefined. Errors set by this function are: <br>
* U_CE_NOT_FOUND_ERROR if more than one character was passed and there is no such contraction<br>
* U_ILLEGAL_ARGUMENT_ERROR if the variable top is beyond
* the last reordering group supported by setMaxVariable()
* @return variable top primary weight
* @deprecated ICU 53 Call setMaxVariable() instead.
*/
virtual uint32_t setVariableTop(const UnicodeString &varTop, UErrorCode &status) override;
/**
* Sets the variable top to the specified primary weight.
*
* Beginning with ICU 53, the variable top is pinned to
* the top of one of the supported reordering groups,
* and it must not be beyond the last of those groups.
* See setMaxVariable().
* @param varTop primary weight, as returned by setVariableTop or ucol_getVariableTop
* @param status error code
* @deprecated ICU 53 Call setMaxVariable() instead.
*/
virtual void setVariableTop(uint32_t varTop, UErrorCode &status) override;
#endif // U_FORCE_HIDE_DEPRECATED_API
/**
* Gets the variable top value of a Collator.
* @param status error code (not changed by function). If error code is set, the return value is undefined.
* @return the variable top primary weight
* @see getMaxVariable
* @stable ICU 2.0
*/
virtual uint32_t getVariableTop(UErrorCode &status) const override;
/**
* Get a UnicodeSet that contains all the characters and sequences tailored in
* this collator.
* @param status error code of the operation
* @return a pointer to a UnicodeSet object containing all the
* code points and sequences that may sort differently than
* in the root collator. The object must be disposed of by using delete
* @stable ICU 2.4
*/
virtual UnicodeSet *getTailoredSet(UErrorCode &status) const override;
/**
* Get the sort key as an array of bytes from a UnicodeString.
*
* Note that sort keys are often less efficient than simply doing comparison.
* For more details, see the ICU User Guide.
*
* @param source string to be processed.
* @param result buffer to store result in. If nullptr, number of bytes needed
* will be returned.
* @param resultLength length of the result buffer. If if not enough the
* buffer will be filled to capacity.
* @return Number of bytes needed for storing the sort key
* @stable ICU 2.0
*/
virtual int32_t getSortKey(const UnicodeString& source, uint8_t *result,
int32_t resultLength) const override;
/**
* Get the sort key as an array of bytes from a char16_t buffer.
*
* Note that sort keys are often less efficient than simply doing comparison.
* For more details, see the ICU User Guide.
*
* @param source string to be processed.
* @param sourceLength length of string to be processed. If -1, the string
* is 0 terminated and length will be decided by the function.
* @param result buffer to store result in. If nullptr, number of bytes needed
* will be returned.
* @param resultLength length of the result buffer. If if not enough the
* buffer will be filled to capacity.
* @return Number of bytes needed for storing the sort key
* @stable ICU 2.2
*/
virtual int32_t getSortKey(const char16_t *source, int32_t sourceLength,
uint8_t *result, int32_t resultLength) const override;
/**
* Retrieves the reordering codes for this collator.
* @param dest The array to fill with the script ordering.
* @param destCapacity The length of dest. If it is 0, then dest may be nullptr and the function
* will only return the length of the result without writing any codes (pre-flighting).
* @param status A reference to an error code value, which must not indicate
* a failure before the function call.
* @return The length of the script ordering array.
* @see ucol_setReorderCodes
* @see Collator#getEquivalentReorderCodes
* @see Collator#setReorderCodes
* @stable ICU 4.8
*/
virtual int32_t getReorderCodes(int32_t *dest,
int32_t destCapacity,
UErrorCode& status) const override;
/**
* Sets the ordering of scripts for this collator.
* @param reorderCodes An array of script codes in the new order. This can be nullptr if the
* length is also set to 0. An empty array will clear any reordering codes on the collator.
* @param reorderCodesLength The length of reorderCodes.
* @param status error code
* @see ucol_setReorderCodes
* @see Collator#getReorderCodes
* @see Collator#getEquivalentReorderCodes
* @stable ICU 4.8
*/
virtual void setReorderCodes(const int32_t* reorderCodes,
int32_t reorderCodesLength,
UErrorCode& status) override;
/**
* Implements ucol_strcollUTF8().
* @internal
*/
virtual UCollationResult internalCompareUTF8(
const char *left, int32_t leftLength,
const char *right, int32_t rightLength,
UErrorCode &errorCode) const override;
/** Get the short definition string for a collator. This internal API harvests the collator's
* locale and the attribute set and produces a string that can be used for opening
* a collator with the same attributes using the ucol_openFromShortString API.
* This string will be normalized.
* The structure and the syntax of the string is defined in the "Naming collators"
* section of the users guide:
* https://unicode-org.github.io/icu/userguide/collation/concepts#collator-naming-scheme
* This function supports preflighting.
*
* This is internal, and intended to be used with delegate converters.
*
* @param locale a locale that will appear as a collators locale in the resulting
* short string definition. If nullptr, the locale will be harvested
* from the collator.
* @param buffer space to hold the resulting string
* @param capacity capacity of the buffer
* @param status for returning errors. All the preflighting errors are featured
* @return length of the resulting string
* @see ucol_openFromShortString
* @see ucol_normalizeShortDefinitionString
* @see ucol_getShortDefinitionString
* @internal
*/
virtual int32_t internalGetShortDefinitionString(const char *locale,
char *buffer,
int32_t capacity,
UErrorCode &status) const override;
/**
* Implements ucol_nextSortKeyPart().
* @internal
*/
virtual int32_t internalNextSortKeyPart(
UCharIterator *iter, uint32_t state[2],
uint8_t *dest, int32_t count, UErrorCode &errorCode) const override;
// Do not enclose the default constructor with #ifndef U_HIDE_INTERNAL_API
/**
* Only for use in ucol_openRules().
* @internal
*/
RuleBasedCollator();
#ifndef U_HIDE_INTERNAL_API
/**
* Implements ucol_getLocaleByType().
* Needed because the lifetime of the locale ID string must match that of the collator.
* getLocale() returns a copy of a Locale, with minimal lifetime in a C wrapper.
* @internal
*/
const char *internalGetLocaleID(ULocDataLocaleType type, UErrorCode &errorCode) const;
/**
* Implements ucol_getContractionsAndExpansions().
* Gets this collator's sets of contraction strings and/or
* characters and strings that map to multiple collation elements (expansions).
* If addPrefixes is true, then contractions that are expressed as
* prefix/pre-context rules are included.
* @param contractions if not nullptr, the set to hold the contractions
* @param expansions if not nullptr, the set to hold the expansions
* @param addPrefixes include prefix contextual mappings
* @param errorCode in/out ICU error code
* @internal
*/
void internalGetContractionsAndExpansions(
UnicodeSet *contractions, UnicodeSet *expansions,
UBool addPrefixes, UErrorCode &errorCode) const;
/**
* Adds the contractions that start with character c to the set.
* Ignores prefixes. Used by AlphabeticIndex.
* @internal
*/
void internalAddContractions(UChar32 c, UnicodeSet &set, UErrorCode &errorCode) const;
/**
* Implements from-rule constructors, and ucol_openRules().
* @internal
*/
void internalBuildTailoring(
const UnicodeString &rules,
int32_t strength,
UColAttributeValue decompositionMode,
UParseError *outParseError, UnicodeString *outReason,
UErrorCode &errorCode);
/** @internal */
static inline RuleBasedCollator *rbcFromUCollator(UCollator *uc) {
return dynamic_cast<RuleBasedCollator *>(fromUCollator(uc));
}
/** @internal */
static inline const RuleBasedCollator *rbcFromUCollator(const UCollator *uc) {
return dynamic_cast<const RuleBasedCollator *>(fromUCollator(uc));
}
/**
* Appends the CEs for the string to the vector.
* @internal for tests & tools
*/
void internalGetCEs(const UnicodeString &str, UVector64 &ces, UErrorCode &errorCode) const;
#endif // U_HIDE_INTERNAL_API
protected:
/**
* Used internally by registration to define the requested and valid locales.
* @param requestedLocale the requested locale
* @param validLocale the valid locale
* @param actualLocale the actual locale
* @internal
*/
virtual void setLocales(const Locale& requestedLocale, const Locale& validLocale, const Locale& actualLocale) override;
private:
friend class CollationElementIterator;
friend class Collator;
RuleBasedCollator(const CollationCacheEntry *entry);
/**
* Enumeration of attributes that are relevant for short definition strings
* (e.g., ucol_getShortDefinitionString()).
* Effectively extends UColAttribute.
*/
enum Attributes {
ATTR_VARIABLE_TOP = UCOL_ATTRIBUTE_COUNT,
ATTR_LIMIT
};
void adoptTailoring(CollationTailoring *t, UErrorCode &errorCode);
// Both lengths must be <0 or else both must be >=0.
UCollationResult doCompare(const char16_t *left, int32_t leftLength,
const char16_t *right, int32_t rightLength,
UErrorCode &errorCode) const;
UCollationResult doCompare(const uint8_t *left, int32_t leftLength,
const uint8_t *right, int32_t rightLength,
UErrorCode &errorCode) const;
void writeSortKey(const char16_t *s, int32_t length,
SortKeyByteSink &sink, UErrorCode &errorCode) const;
void writeIdenticalLevel(const char16_t *s, const char16_t *limit,
SortKeyByteSink &sink, UErrorCode &errorCode) const;
const CollationSettings &getDefaultSettings() const;
void setAttributeDefault(int32_t attribute) {
explicitlySetAttributes &= ~(static_cast<uint32_t>(1) << attribute);
}
void setAttributeExplicitly(int32_t attribute) {
explicitlySetAttributes |= static_cast<uint32_t>(1) << attribute;
}
UBool attributeHasBeenSetExplicitly(int32_t attribute) const {
// assert(0 <= attribute < ATTR_LIMIT);
return (explicitlySetAttributes & (static_cast<uint32_t>(1) << attribute)) != 0;
}
/**
* Tests whether a character is "unsafe" for use as a collation starting point.
*
* @param c code point or code unit
* @return true if c is unsafe
* @see CollationElementIterator#setOffset(int)
*/
UBool isUnsafe(UChar32 c) const;
static void U_CALLCONV computeMaxExpansions(const CollationTailoring *t, UErrorCode &errorCode);
UBool initMaxExpansions(UErrorCode &errorCode) const;
void setFastLatinOptions(CollationSettings &ownedSettings) const;
const CollationData *data;
const CollationSettings *settings; // reference-counted
const CollationTailoring *tailoring; // alias of cacheEntry->tailoring
const CollationCacheEntry *cacheEntry; // reference-counted
Locale validLocale;
uint32_t explicitlySetAttributes;
UBool actualLocaleIsSameAsValid;
};
U_NAMESPACE_END
#endif // !UCONFIG_NO_COLLATION
#endif /* U_SHOW_CPLUSPLUS_API */
#endif // TBLCOLL_H

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,142 @@
// © 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
/*
*******************************************************************************
* Copyright (C) 2009-2016, International Business Machines Corporation, *
* Google, and others. All Rights Reserved. *
*******************************************************************************
*/
#ifndef __TMUNIT_H__
#define __TMUNIT_H__
/**
* \file
* \brief C++ API: time unit object
*/
#include "unicode/utypes.h"
#if U_SHOW_CPLUSPLUS_API
#include "unicode/measunit.h"
#if !UCONFIG_NO_FORMATTING
U_NAMESPACE_BEGIN
/**
* Measurement unit for time units.
* @see TimeUnitAmount
* @see TimeUnit
* @stable ICU 4.2
*/
class U_I18N_API TimeUnit: public MeasureUnit {
public:
/**
* Constants for all the time units we supported.
* @stable ICU 4.2
*/
enum UTimeUnitFields {
UTIMEUNIT_YEAR,
UTIMEUNIT_MONTH,
UTIMEUNIT_DAY,
UTIMEUNIT_WEEK,
UTIMEUNIT_HOUR,
UTIMEUNIT_MINUTE,
UTIMEUNIT_SECOND,
#ifndef U_HIDE_DEPRECATED_API
/**
* One more than the highest normal UTimeUnitFields value.
* @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420.
*/
UTIMEUNIT_FIELD_COUNT
#endif // U_HIDE_DEPRECATED_API
};
/**
* Create Instance.
* @param timeUnitField time unit field based on which the instance
* is created.
* @param status input-output error code.
* If the timeUnitField is invalid,
* then this will be set to U_ILLEGAL_ARGUMENT_ERROR.
* @return a TimeUnit instance
* @stable ICU 4.2
*/
static TimeUnit* U_EXPORT2 createInstance(UTimeUnitFields timeUnitField,
UErrorCode& status);
/**
* Override clone.
* @stable ICU 4.2
*/
virtual TimeUnit* clone() const override;
/**
* Copy operator.
* @stable ICU 4.2
*/
TimeUnit(const TimeUnit& other);
/**
* Assignment operator.
* @stable ICU 4.2
*/
TimeUnit& operator=(const TimeUnit& other);
/**
* Returns a unique class ID for this object POLYMORPHICALLY.
* This method implements a simple form of RTTI used by ICU.
* @return The class ID for this object. All objects of a given
* class have the same class ID. Objects of other classes have
* different class IDs.
* @stable ICU 4.2
*/
virtual UClassID getDynamicClassID() const override;
/**
* Returns the class ID for this class. This is used to compare to
* the return value of getDynamicClassID().
* @return The class ID for all objects of this class.
* @stable ICU 4.2
*/
static UClassID U_EXPORT2 getStaticClassID();
/**
* Get time unit field.
* @return time unit field.
* @stable ICU 4.2
*/
UTimeUnitFields getTimeUnitField() const;
/**
* Destructor.
* @stable ICU 4.2
*/
virtual ~TimeUnit();
private:
UTimeUnitFields fTimeUnitField;
/**
* Constructor
* @internal (private)
*/
TimeUnit(UTimeUnitFields timeUnitField);
};
U_NAMESPACE_END
#endif /* #if !UCONFIG_NO_FORMATTING */
#endif /* U_SHOW_CPLUSPLUS_API */
#endif // __TMUNIT_H__
//eof
//

View File

@ -0,0 +1,174 @@
// © 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
/*
*******************************************************************************
* Copyright (C) 2009-2010, Google, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
*/
#ifndef __TMUTAMT_H__
#define __TMUTAMT_H__
/**
* \file
* \brief C++ API: time unit amount object.
*/
#include "unicode/utypes.h"
#if U_SHOW_CPLUSPLUS_API
#if !UCONFIG_NO_FORMATTING
#include "unicode/measure.h"
#include "unicode/tmunit.h"
U_NAMESPACE_BEGIN
/**
* Express a duration as a time unit and number. Patterned after Currency.
* @see TimeUnitAmount
* @see TimeUnitFormat
* @stable ICU 4.2
*/
class U_I18N_API TimeUnitAmount: public Measure {
public:
/**
* Construct TimeUnitAmount object with the given number and the
* given time unit.
* @param number a numeric object; number.isNumeric() must be true
* @param timeUnitField the time unit field of a time unit
* @param status the input-output error code.
* If the number is not numeric or the timeUnitField
* is not valid,
* then this will be set to a failing value:
* U_ILLEGAL_ARGUMENT_ERROR.
* @stable ICU 4.2
*/
TimeUnitAmount(const Formattable& number,
TimeUnit::UTimeUnitFields timeUnitField,
UErrorCode& status);
/**
* Construct TimeUnitAmount object with the given numeric amount and the
* given time unit.
* @param amount a numeric amount.
* @param timeUnitField the time unit field on which a time unit amount
* object will be created.
* @param status the input-output error code.
* If the timeUnitField is not valid,
* then this will be set to a failing value:
* U_ILLEGAL_ARGUMENT_ERROR.
* @stable ICU 4.2
*/
TimeUnitAmount(double amount, TimeUnit::UTimeUnitFields timeUnitField,
UErrorCode& status);
/**
* Copy constructor
* @stable ICU 4.2
*/
TimeUnitAmount(const TimeUnitAmount& other);
/**
* Assignment operator
* @stable ICU 4.2
*/
TimeUnitAmount& operator=(const TimeUnitAmount& other);
/**
* Clone.
* @return a polymorphic clone of this object. The result will have the same class as returned by getDynamicClassID().
* @stable ICU 4.2
*/
virtual TimeUnitAmount* clone() const override;
/**
* Destructor
* @stable ICU 4.2
*/
virtual ~TimeUnitAmount();
/**
* Equality operator.
* @param other the object to compare to.
* @return true if this object is equal to the given object.
* @stable ICU 4.2
*/
virtual bool operator==(const UObject& other) const;
/**
* Not-equality operator.
* @param other the object to compare to.
* @return true if this object is not equal to the given object.
* @stable ICU 4.2
*/
bool operator!=(const UObject& other) const;
/**
* Return the class ID for this class. This is useful only for comparing to
* a return value from getDynamicClassID(). For example:
* <pre>
* . Base* polymorphic_pointer = createPolymorphicObject();
* . if (polymorphic_pointer->getDynamicClassID() ==
* . erived::getStaticClassID()) ...
* </pre>
* @return The class ID for all objects of this class.
* @stable ICU 4.2
*/
static UClassID U_EXPORT2 getStaticClassID();
/**
* Returns a unique class ID POLYMORPHICALLY. Pure virtual override. This
* method is to implement a simple version of RTTI, since not all C++
* compilers support genuine RTTI. Polymorphic operator==() and clone()
* methods call this method.
*
* @return The class ID for this object. All objects of a
* given class have the same class ID. Objects of
* other classes have different class IDs.
* @stable ICU 4.2
*/
virtual UClassID getDynamicClassID() const override;
/**
* Get the time unit.
* @return time unit object.
* @stable ICU 4.2
*/
const TimeUnit& getTimeUnit() const;
/**
* Get the time unit field value.
* @return time unit field value.
* @stable ICU 4.2
*/
TimeUnit::UTimeUnitFields getTimeUnitField() const;
};
inline bool
TimeUnitAmount::operator!=(const UObject& other) const {
return !operator==(other);
}
U_NAMESPACE_END
#endif /* #if !UCONFIG_NO_FORMATTING */
#endif /* U_SHOW_CPLUSPLUS_API */
#endif // __TMUTAMT_H__
//eof
//

View File

@ -0,0 +1,238 @@
// © 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
/*
*******************************************************************************
* Copyright (C) 2008-2014, Google, International Business Machines Corporation
* and others. All Rights Reserved.
*******************************************************************************
*/
#ifndef __TMUTFMT_H__
#define __TMUTFMT_H__
#include "unicode/utypes.h"
/**
* \file
* \brief C++ API: Format and parse duration in single time unit
*/
#if U_SHOW_CPLUSPLUS_API
#if !UCONFIG_NO_FORMATTING
#include "unicode/unistr.h"
#include "unicode/tmunit.h"
#include "unicode/tmutamt.h"
#include "unicode/measfmt.h"
#include "unicode/numfmt.h"
#include "unicode/plurrule.h"
#ifndef U_HIDE_DEPRECATED_API
/**
* Constants for various styles.
* There are 2 styles: full name and abbreviated name.
* For example, for English, the full name for hour duration is "3 hours",
* and the abbreviated name is "3 hrs".
* @deprecated ICU 53 Use MeasureFormat and UMeasureFormatWidth instead.
*/
enum UTimeUnitFormatStyle {
/** @deprecated ICU 53 */
UTMUTFMT_FULL_STYLE,
/** @deprecated ICU 53 */
UTMUTFMT_ABBREVIATED_STYLE,
/** @deprecated ICU 53 */
UTMUTFMT_FORMAT_STYLE_COUNT
};
typedef enum UTimeUnitFormatStyle UTimeUnitFormatStyle; /**< @deprecated ICU 53 */
U_NAMESPACE_BEGIN
class Hashtable;
class UVector;
struct TimeUnitFormatReadSink;
/**
* Format or parse a TimeUnitAmount, using plural rules for the units where available.
*
* <P>
* Code Sample:
* <pre>
* // create time unit amount instance - a combination of Number and time unit
* UErrorCode status = U_ZERO_ERROR;
* TimeUnitAmount* source = new TimeUnitAmount(2, TimeUnit::UTIMEUNIT_YEAR, status);
* // create time unit format instance
* TimeUnitFormat* format = new TimeUnitFormat(Locale("en"), status);
* // format a time unit amount
* UnicodeString formatted;
* Formattable formattable;
* if (U_SUCCESS(status)) {
* formattable.adoptObject(source);
* formatted = ((Format*)format)->format(formattable, formatted, status);
* Formattable result;
* ((Format*)format)->parseObject(formatted, result, status);
* if (U_SUCCESS(status)) {
* assert (result == formattable);
* }
* }
* </pre>
*
* <P>
* @see TimeUnitAmount
* @see TimeUnitFormat
* @deprecated ICU 53 Use the MeasureFormat class instead.
*/
class U_I18N_API TimeUnitFormat: public MeasureFormat {
public:
/**
* Create TimeUnitFormat with default locale, and full name style.
* Use setLocale and/or setFormat to modify.
* @deprecated ICU 53
*/
TimeUnitFormat(UErrorCode& status);
/**
* Create TimeUnitFormat given locale, and full name style.
* @deprecated ICU 53
*/
TimeUnitFormat(const Locale& locale, UErrorCode& status);
/**
* Create TimeUnitFormat given locale and style.
* @deprecated ICU 53
*/
TimeUnitFormat(const Locale& locale, UTimeUnitFormatStyle style, UErrorCode& status);
/**
* Copy constructor.
* @deprecated ICU 53
*/
TimeUnitFormat(const TimeUnitFormat&);
/**
* deconstructor
* @deprecated ICU 53
*/
virtual ~TimeUnitFormat();
/**
* Clone this Format object polymorphically. The caller owns the result and
* should delete it when done.
* @return A copy of the object.
* @deprecated ICU 53
*/
virtual TimeUnitFormat* clone() const override;
/**
* Assignment operator
* @deprecated ICU 53
*/
TimeUnitFormat& operator=(const TimeUnitFormat& other);
/**
* Set the locale used for formatting or parsing.
* @param locale the locale to be set
* @param status output param set to success/failure code on exit
* @deprecated ICU 53
*/
void setLocale(const Locale& locale, UErrorCode& status);
/**
* Set the number format used for formatting or parsing.
* @param format the number formatter to be set
* @param status output param set to success/failure code on exit
* @deprecated ICU 53
*/
void setNumberFormat(const NumberFormat& format, UErrorCode& status);
/**
* Parse a TimeUnitAmount.
* @see Format#parseObject(const UnicodeString&, Formattable&, ParsePosition&) const;
* @deprecated ICU 53
*/
virtual void parseObject(const UnicodeString& source,
Formattable& result,
ParsePosition& pos) const override;
/**
* Return the class ID for this class. This is useful only for comparing to
* a return value from getDynamicClassID(). For example:
* <pre>
* . Base* polymorphic_pointer = createPolymorphicObject();
* . if (polymorphic_pointer->getDynamicClassID() ==
* . erived::getStaticClassID()) ...
* </pre>
* @return The class ID for all objects of this class.
* @deprecated ICU 53
*/
static UClassID U_EXPORT2 getStaticClassID();
/**
* Returns a unique class ID POLYMORPHICALLY. Pure virtual override. This
* method is to implement a simple version of RTTI, since not all C++
* compilers support genuine RTTI. Polymorphic operator==() and clone()
* methods call this method.
*
* @return The class ID for this object. All objects of a
* given class have the same class ID. Objects of
* other classes have different class IDs.
* @deprecated ICU 53
*/
virtual UClassID getDynamicClassID() const override;
private:
Hashtable* fTimeUnitToCountToPatterns[TimeUnit::UTIMEUNIT_FIELD_COUNT];
UTimeUnitFormatStyle fStyle;
void create(UTimeUnitFormatStyle style, UErrorCode& status);
// it might actually be simpler to make them Decimal Formats later.
// initialize all private data members
void setup(UErrorCode& status);
// initialize data member without fill in data for fTimeUnitToCountToPattern
void initDataMembers(UErrorCode& status);
// initialize fTimeUnitToCountToPatterns from current locale's resource.
void readFromCurrentLocale(UTimeUnitFormatStyle style, const char* key, const UVector& pluralCounts,
UErrorCode& status);
// check completeness of fTimeUnitToCountToPatterns against all time units,
// and all plural rules, fill in fallback as necessary.
void checkConsistency(UTimeUnitFormatStyle style, const char* key, UErrorCode& status);
// fill in fTimeUnitToCountToPatterns from locale fall-back chain
void searchInLocaleChain(UTimeUnitFormatStyle style, const char* key, const char* localeName,
TimeUnit::UTimeUnitFields field, const UnicodeString&,
const char*, Hashtable*, UErrorCode&);
// initialize hash table
Hashtable* initHash(UErrorCode& status);
// delete hash table
void deleteHash(Hashtable* htable);
// copy hash table
void copyHash(const Hashtable* source, Hashtable* target, UErrorCode& status);
// get time unit name, such as "year", from time unit field enum, such as
// UTIMEUNIT_YEAR.
static const char* getTimeUnitName(TimeUnit::UTimeUnitFields field, UErrorCode& status);
friend struct TimeUnitFormatReadSink;
};
U_NAMESPACE_END
#endif /* U_HIDE_DEPRECATED_API */
#endif /* #if !UCONFIG_NO_FORMATTING */
#endif /* U_SHOW_CPLUSPLUS_API */
#endif // __TMUTFMT_H__
//eof

File diff suppressed because it is too large Load Diff

1102
deps/icu-small/source/i18n/unicode/tzfmt.h vendored Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,419 @@
// © 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
/*
*******************************************************************************
* Copyright (C) 2011-2016, International Business Machines Corporation and
* others. All Rights Reserved.
*******************************************************************************
*/
#ifndef __TZNAMES_H
#define __TZNAMES_H
/**
* \file
* \brief C++ API: TimeZoneNames
*/
#include "unicode/utypes.h"
#if U_SHOW_CPLUSPLUS_API
#if !UCONFIG_NO_FORMATTING
#include "unicode/uloc.h"
#include "unicode/unistr.h"
U_CDECL_BEGIN
/**
* Constants for time zone display name types.
* @stable ICU 50
*/
typedef enum UTimeZoneNameType {
/**
* Unknown display name type.
* @stable ICU 50
*/
UTZNM_UNKNOWN = 0x00,
/**
* Long display name, such as "Eastern Time".
* @stable ICU 50
*/
UTZNM_LONG_GENERIC = 0x01,
/**
* Long display name for standard time, such as "Eastern Standard Time".
* @stable ICU 50
*/
UTZNM_LONG_STANDARD = 0x02,
/**
* Long display name for daylight saving time, such as "Eastern Daylight Time".
* @stable ICU 50
*/
UTZNM_LONG_DAYLIGHT = 0x04,
/**
* Short display name, such as "ET".
* @stable ICU 50
*/
UTZNM_SHORT_GENERIC = 0x08,
/**
* Short display name for standard time, such as "EST".
* @stable ICU 50
*/
UTZNM_SHORT_STANDARD = 0x10,
/**
* Short display name for daylight saving time, such as "EDT".
* @stable ICU 50
*/
UTZNM_SHORT_DAYLIGHT = 0x20,
/**
* Exemplar location name, such as "Los Angeles".
* @stable ICU 51
*/
UTZNM_EXEMPLAR_LOCATION = 0x40
} UTimeZoneNameType;
U_CDECL_END
U_NAMESPACE_BEGIN
class UVector;
struct MatchInfo;
/**
* <code>TimeZoneNames</code> is an abstract class representing the time zone display name data model defined
* by <a href="http://www.unicode.org/reports/tr35/">UTS#35 Unicode Locale Data Markup Language (LDML)</a>.
* The model defines meta zone, which is used for storing a set of display names. A meta zone can be shared
* by multiple time zones. Also a time zone may have multiple meta zone historic mappings.
* <p>
* For example, people in the United States refer the zone used by the east part of North America as "Eastern Time".
* The tz database contains multiple time zones "America/New_York", "America/Detroit", "America/Montreal" and some
* others that belong to "Eastern Time". However, assigning different display names to these time zones does not make
* much sense for most of people.
* <p>
* In <a href="http://cldr.unicode.org/">CLDR</a> (which uses LDML for representing locale data), the display name
* "Eastern Time" is stored as long generic display name of a meta zone identified by the ID "America_Eastern".
* Then, there is another table maintaining the historic mapping to meta zones for each time zone. The time zones in
* the above example ("America/New_York", "America/Detroit"...) are mapped to the meta zone "America_Eastern".
* <p>
* Sometimes, a time zone is mapped to a different time zone in the past. For example, "America/Indiana/Knox"
* had been moving "Eastern Time" and "Central Time" back and forth. Therefore, it is necessary that time zone
* to meta zones mapping data are stored by date range.
*
* <p><b>Note:</b>
* The methods in this class assume that time zone IDs are already canonicalized. For example, you may not get proper
* result returned by a method with time zone ID "America/Indiana/Indianapolis", because it's not a canonical time zone
* ID (the canonical time zone ID for the time zone is "America/Indianapolis". See
* {@link TimeZone#getCanonicalID(const UnicodeString& id, UnicodeString& canonicalID, UErrorCode& status)} about ICU
* canonical time zone IDs.
*
* <p>
* In CLDR, most of time zone display names except location names are provided through meta zones. But a time zone may
* have a specific name that is not shared with other time zones.
*
* For example, time zone "Europe/London" has English long name for standard time "Greenwich Mean Time", which is also
* shared with other time zones. However, the long name for daylight saving time is "British Summer Time", which is only
* used for "Europe/London".
*
* <p>
* {@link #getTimeZoneDisplayName} is designed for accessing a name only used by a single time zone.
* But is not necessarily mean that a subclass implementation use the same model with CLDR. A subclass implementation
* may provide time zone names only through {@link #getTimeZoneDisplayName}, or only through {@link #getMetaZoneDisplayName},
* or both.
*
* <p>
* The default <code>TimeZoneNames</code> implementation returned by {@link #createInstance}
* uses the locale data imported from CLDR. In CLDR, set of meta zone IDs and mappings between zone IDs and meta zone
* IDs are shared by all locales. Therefore, the behavior of {@link #getAvailableMetaZoneIDs},
* {@link #getMetaZoneID}, and {@link #getReferenceZoneID} won't be changed no matter
* what locale is used for getting an instance of <code>TimeZoneNames</code>.
*
* @stable ICU 50
*/
class U_I18N_API TimeZoneNames : public UObject {
public:
/**
* Destructor.
* @stable ICU 50
*/
virtual ~TimeZoneNames();
/**
* Return true if the given TimeZoneNames objects are semantically equal.
* @param other the object to be compared with.
* @return Return true if the given Format objects are semantically equal.
* @stable ICU 50
*/
virtual bool operator==(const TimeZoneNames& other) const = 0;
/**
* Return true if the given TimeZoneNames objects are not semantically
* equal.
* @param other the object to be compared with.
* @return Return true if the given Format objects are not semantically equal.
* @stable ICU 50
*/
bool operator!=(const TimeZoneNames& other) const { return !operator==(other); }
/**
* Clone this object polymorphically. The caller is responsible
* for deleting the result when done.
* @return A copy of the object
* @stable ICU 50
*/
virtual TimeZoneNames* clone() const = 0;
/**
* Returns an instance of <code>TimeZoneNames</code> for the specified locale.
*
* @param locale The locale.
* @param status Receives the status.
* @return An instance of <code>TimeZoneNames</code>
* @stable ICU 50
*/
static TimeZoneNames* U_EXPORT2 createInstance(const Locale& locale, UErrorCode& status);
/**
* Returns an instance of <code>TimeZoneNames</code> containing only short specific
* zone names (SHORT_STANDARD and SHORT_DAYLIGHT),
* compatible with the IANA tz database's zone abbreviations (not localized).
* <br>
* Note: The input locale is used for resolving ambiguous names (e.g. "IST" is parsed
* as Israel Standard Time for Israel, while it is parsed as India Standard Time for
* all other regions). The zone names returned by this instance are not localized.
* @stable ICU 54
*/
static TimeZoneNames* U_EXPORT2 createTZDBInstance(const Locale& locale, UErrorCode& status);
/**
* Returns an enumeration of all available meta zone IDs.
* @param status Receives the status.
* @return an enumeration object, owned by the caller.
* @stable ICU 50
*/
virtual StringEnumeration* getAvailableMetaZoneIDs(UErrorCode& status) const = 0;
/**
* Returns an enumeration of all available meta zone IDs used by the given time zone.
* @param tzID The canonical time zone ID.
* @param status Receives the status.
* @return an enumeration object, owned by the caller.
* @stable ICU 50
*/
virtual StringEnumeration* getAvailableMetaZoneIDs(const UnicodeString& tzID, UErrorCode& status) const = 0;
/**
* Returns the meta zone ID for the given canonical time zone ID at the given date.
* @param tzID The canonical time zone ID.
* @param date The date.
* @param mzID Receives the meta zone ID for the given time zone ID at the given date. If the time zone does not have a
* corresponding meta zone at the given date or the implementation does not support meta zones, "bogus" state
* is set.
* @return A reference to the result.
* @stable ICU 50
*/
virtual UnicodeString& getMetaZoneID(const UnicodeString& tzID, UDate date, UnicodeString& mzID) const = 0;
/**
* Returns the reference zone ID for the given meta zone ID for the region.
*
* Note: Each meta zone must have a reference zone associated with a special region "001" (world).
* Some meta zones may have region specific reference zone IDs other than the special region
* "001". When a meta zone does not have any region specific reference zone IDs, this method
* return the reference zone ID for the special region "001" (world).
*
* @param mzID The meta zone ID.
* @param region The region.
* @param tzID Receives the reference zone ID ("golden zone" in the LDML specification) for the given time zone ID for the
* region. If the meta zone is unknown or the implementation does not support meta zones, "bogus" state
* is set.
* @return A reference to the result.
* @stable ICU 50
*/
virtual UnicodeString& getReferenceZoneID(const UnicodeString& mzID, const char* region, UnicodeString& tzID) const = 0;
/**
* Returns the display name of the meta zone.
* @param mzID The meta zone ID.
* @param type The display name type. See {@link #UTimeZoneNameType}.
* @param name Receives the display name of the meta zone. When this object does not have a localized display name for the given
* meta zone with the specified type or the implementation does not provide any display names associated
* with meta zones, "bogus" state is set.
* @return A reference to the result.
* @stable ICU 50
*/
virtual UnicodeString& getMetaZoneDisplayName(const UnicodeString& mzID, UTimeZoneNameType type, UnicodeString& name) const = 0;
/**
* Returns the display name of the time zone. Unlike {@link #getDisplayName},
* this method does not get a name from a meta zone used by the time zone.
* @param tzID The canonical time zone ID.
* @param type The display name type. See {@link #UTimeZoneNameType}.
* @param name Receives the display name for the time zone. When this object does not have a localized display name for the given
* time zone with the specified type, "bogus" state is set.
* @return A reference to the result.
* @stable ICU 50
*/
virtual UnicodeString& getTimeZoneDisplayName(const UnicodeString& tzID, UTimeZoneNameType type, UnicodeString& name) const = 0;
/**
* Returns the exemplar location name for the given time zone. When this object does not have a localized location
* name, the default implementation may still returns a programmatically generated name with the logic described
* below.
* <ol>
* <li>Check if the ID contains "/". If not, return null.
* <li>Check if the ID does not start with "Etc/" or "SystemV/". If it does, return null.
* <li>Extract a substring after the last occurrence of "/".
* <li>Replace "_" with " ".
* </ol>
* For example, "New York" is returned for the time zone ID "America/New_York" when this object does not have the
* localized location name.
*
* @param tzID The canonical time zone ID
* @param name Receives the exemplar location name for the given time zone, or "bogus" state is set when a localized
* location name is not available and the fallback logic described above cannot extract location from the ID.
* @return A reference to the result.
* @stable ICU 50
*/
virtual UnicodeString& getExemplarLocationName(const UnicodeString& tzID, UnicodeString& name) const;
/**
* Returns the display name of the time zone at the given date.
* <p>
* <b>Note:</b> This method calls the subclass's {@link #getTimeZoneDisplayName} first. When the
* result is bogus, this method calls {@link #getMetaZoneID} to get the meta zone ID mapped from the
* time zone, then calls {@link #getMetaZoneDisplayName}.
*
* @param tzID The canonical time zone ID.
* @param type The display name type. See {@link #UTimeZoneNameType}.
* @param date The date.
* @param name Receives the display name for the time zone at the given date. When this object does not have a localized display
* name for the time zone with the specified type and date, "bogus" state is set.
* @return A reference to the result.
* @stable ICU 50
*/
virtual UnicodeString& getDisplayName(const UnicodeString& tzID, UTimeZoneNameType type, UDate date, UnicodeString& name) const;
/**
* @internal ICU internal only, for specific users only until proposed publicly.
*/
virtual void loadAllDisplayNames(UErrorCode& status);
/**
* @internal ICU internal only, for specific users only until proposed publicly.
*/
virtual void getDisplayNames(const UnicodeString& tzID, const UTimeZoneNameType types[], int32_t numTypes, UDate date, UnicodeString dest[], UErrorCode& status) const;
/**
* <code>MatchInfoCollection</code> represents a collection of time zone name matches used by
* {@link TimeZoneNames#find}.
* @internal
*/
class U_I18N_API MatchInfoCollection : public UMemory {
public:
/**
* Constructor.
* @internal
*/
MatchInfoCollection();
/**
* Destructor.
* @internal
*/
virtual ~MatchInfoCollection();
#ifndef U_HIDE_INTERNAL_API
/**
* Adds a zone match.
* @param nameType The name type.
* @param matchLength The match length.
* @param tzID The time zone ID.
* @param status Receives the status
* @internal
*/
void addZone(UTimeZoneNameType nameType, int32_t matchLength,
const UnicodeString& tzID, UErrorCode& status);
/**
* Adds a meata zone match.
* @param nameType The name type.
* @param matchLength The match length.
* @param mzID The metazone ID.
* @param status Receives the status
* @internal
*/
void addMetaZone(UTimeZoneNameType nameType, int32_t matchLength,
const UnicodeString& mzID, UErrorCode& status);
/**
* Returns the number of entries available in this object.
* @return The number of entries.
* @internal
*/
int32_t size() const;
/**
* Returns the time zone name type of a match at the specified index.
* @param idx The index
* @return The time zone name type. If the specified idx is out of range,
* it returns UTZNM_UNKNOWN.
* @see UTimeZoneNameType
* @internal
*/
UTimeZoneNameType getNameTypeAt(int32_t idx) const;
/**
* Returns the match length of a match at the specified index.
* @param idx The index
* @return The match length. If the specified idx is out of range,
* it returns 0.
* @internal
*/
int32_t getMatchLengthAt(int32_t idx) const;
/**
* Gets the zone ID of a match at the specified index.
* @param idx The index
* @param tzID Receives the zone ID.
* @return true if the zone ID was set to tzID.
* @internal
*/
UBool getTimeZoneIDAt(int32_t idx, UnicodeString& tzID) const;
/**
* Gets the metazone ID of a match at the specified index.
* @param idx The index
* @param mzID Receives the metazone ID
* @return true if the meta zone ID was set to mzID.
* @internal
*/
UBool getMetaZoneIDAt(int32_t idx, UnicodeString& mzID) const;
#endif /* U_HIDE_INTERNAL_API */
private:
UVector* fMatches; // vector of MatchEntry
UVector* matches(UErrorCode& status);
};
/**
* Finds time zone name prefix matches for the input text at the
* given offset and returns a collection of the matches.
* @param text The text.
* @param start The starting offset within the text.
* @param types The set of name types represented by bitwise flags of UTimeZoneNameType enums,
* or UTZNM_UNKNOWN for all name types.
* @param status Receives the status.
* @return A collection of matches (owned by the caller), or nullptr if no matches are found.
* @see UTimeZoneNameType
* @see MatchInfoCollection
* @internal
*/
virtual MatchInfoCollection* find(const UnicodeString& text, int32_t start, uint32_t types, UErrorCode& status) const = 0;
};
U_NAMESPACE_END
#endif
#endif /* U_SHOW_CPLUSPLUS_API */
#endif

View File

@ -0,0 +1,820 @@
// © 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
/*
*******************************************************************************
* Copyright (C) 2007-2008, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
*/
#ifndef TZRULE_H
#define TZRULE_H
/**
* \file
* \brief C++ API: Time zone rule classes
*/
#include "unicode/utypes.h"
#if U_SHOW_CPLUSPLUS_API
#if !UCONFIG_NO_FORMATTING
#include "unicode/uobject.h"
#include "unicode/unistr.h"
#include "unicode/dtrule.h"
U_NAMESPACE_BEGIN
/**
* <code>TimeZoneRule</code> is a class representing a rule for time zone.
* <code>TimeZoneRule</code> has a set of time zone attributes, such as zone name,
* raw offset (UTC offset for standard time) and daylight saving time offset.
*
* @stable ICU 3.8
*/
class U_I18N_API TimeZoneRule : public UObject {
public:
/**
* Destructor.
* @stable ICU 3.8
*/
virtual ~TimeZoneRule();
/**
* Clone this TimeZoneRule object polymorphically. The caller owns the result and
* should delete it when done.
* @return A copy of the object.
* @stable ICU 3.8
*/
virtual TimeZoneRule* clone() const = 0;
/**
* Return true if the given <code>TimeZoneRule</code> objects are semantically equal. Objects
* of different subclasses are considered unequal.
* @param that The object to be compared with.
* @return true if the given <code>TimeZoneRule</code> objects are semantically equal.
* @stable ICU 3.8
*/
virtual bool operator==(const TimeZoneRule& that) const;
/**
* Return true if the given <code>TimeZoneRule</code> objects are semantically unequal. Objects
* of different subclasses are considered unequal.
* @param that The object to be compared with.
* @return true if the given <code>TimeZoneRule</code> objects are semantically unequal.
* @stable ICU 3.8
*/
virtual bool operator!=(const TimeZoneRule& that) const;
/**
* Fills in "name" with the name of this time zone.
* @param name Receives the name of this time zone.
* @return A reference to "name"
* @stable ICU 3.8
*/
UnicodeString& getName(UnicodeString& name) const;
/**
* Gets the standard time offset.
* @return The standard time offset from UTC in milliseconds.
* @stable ICU 3.8
*/
int32_t getRawOffset() const;
/**
* Gets the amount of daylight saving delta time from the standard time.
* @return The amount of daylight saving offset used by this rule
* in milliseconds.
* @stable ICU 3.8
*/
int32_t getDSTSavings() const;
/**
* Returns if this rule represents the same rule and offsets as another.
* When two <code>TimeZoneRule</code> objects differ only its names, this method
* returns true.
* @param other The <code>TimeZoneRule</code> object to be compared with.
* @return true if the other <code>TimeZoneRule</code> is the same as this one.
* @stable ICU 3.8
*/
virtual UBool isEquivalentTo(const TimeZoneRule& other) const;
/**
* Gets the very first time when this rule takes effect.
* @param prevRawOffset The standard time offset from UTC before this rule
* takes effect in milliseconds.
* @param prevDSTSavings The amount of daylight saving offset from the
* standard time.
* @param result Receives the very first time when this rule takes effect.
* @return true if the start time is available. When false is returned, output parameter
* "result" is unchanged.
* @stable ICU 3.8
*/
virtual UBool getFirstStart(int32_t prevRawOffset, int32_t prevDSTSavings, UDate& result) const = 0;
/**
* Gets the final time when this rule takes effect.
* @param prevRawOffset The standard time offset from UTC before this rule
* takes effect in milliseconds.
* @param prevDSTSavings The amount of daylight saving offset from the
* standard time.
* @param result Receives the final time when this rule takes effect.
* @return true if the start time is available. When false is returned, output parameter
* "result" is unchanged.
* @stable ICU 3.8
*/
virtual UBool getFinalStart(int32_t prevRawOffset, int32_t prevDSTSavings, UDate& result) const = 0;
/**
* Gets the first time when this rule takes effect after the specified time.
* @param base The first start time after this base time will be returned.
* @param prevRawOffset The standard time offset from UTC before this rule
* takes effect in milliseconds.
* @param prevDSTSavings The amount of daylight saving offset from the
* standard time.
* @param inclusive Whether the base time is inclusive or not.
* @param result Receives The first time when this rule takes effect after
* the specified base time.
* @return true if the start time is available. When false is returned, output parameter
* "result" is unchanged.
* @stable ICU 3.8
*/
virtual UBool getNextStart(UDate base, int32_t prevRawOffset, int32_t prevDSTSavings,
UBool inclusive, UDate& result) const = 0;
/**
* Gets the most recent time when this rule takes effect before the specified time.
* @param base The most recent time before this base time will be returned.
* @param prevRawOffset The standard time offset from UTC before this rule
* takes effect in milliseconds.
* @param prevDSTSavings The amount of daylight saving offset from the
* standard time.
* @param inclusive Whether the base time is inclusive or not.
* @param result Receives The most recent time when this rule takes effect before
* the specified base time.
* @return true if the start time is available. When false is returned, output parameter
* "result" is unchanged.
* @stable ICU 3.8
*/
virtual UBool getPreviousStart(UDate base, int32_t prevRawOffset, int32_t prevDSTSavings,
UBool inclusive, UDate& result) const = 0;
protected:
/**
* Constructs a <code>TimeZoneRule</code> with the name, the GMT offset of its
* standard time and the amount of daylight saving offset adjustment.
* @param name The time zone name.
* @param rawOffset The UTC offset of its standard time in milliseconds.
* @param dstSavings The amount of daylight saving offset adjustment in milliseconds.
* If this ia a rule for standard time, the value of this argument is 0.
* @stable ICU 3.8
*/
TimeZoneRule(const UnicodeString& name, int32_t rawOffset, int32_t dstSavings);
/**
* Copy constructor.
* @param source The TimeZoneRule object to be copied.
* @stable ICU 3.8
*/
TimeZoneRule(const TimeZoneRule& source);
/**
* Assignment operator.
* @param right The object to be copied.
* @stable ICU 3.8
*/
TimeZoneRule& operator=(const TimeZoneRule& right);
private:
UnicodeString fName; // time name
int32_t fRawOffset; // UTC offset of the standard time in milliseconds
int32_t fDSTSavings; // DST saving amount in milliseconds
};
/**
* <code>InitialTimeZoneRule</code> represents a time zone rule
* representing a time zone effective from the beginning and
* has no actual start times.
* @stable ICU 3.8
*/
class U_I18N_API InitialTimeZoneRule : public TimeZoneRule {
public:
/**
* Constructs an <code>InitialTimeZoneRule</code> with the name, the GMT offset of its
* standard time and the amount of daylight saving offset adjustment.
* @param name The time zone name.
* @param rawOffset The UTC offset of its standard time in milliseconds.
* @param dstSavings The amount of daylight saving offset adjustment in milliseconds.
* If this ia a rule for standard time, the value of this argument is 0.
* @stable ICU 3.8
*/
InitialTimeZoneRule(const UnicodeString& name, int32_t rawOffset, int32_t dstSavings);
/**
* Copy constructor.
* @param source The InitialTimeZoneRule object to be copied.
* @stable ICU 3.8
*/
InitialTimeZoneRule(const InitialTimeZoneRule& source);
/**
* Destructor.
* @stable ICU 3.8
*/
virtual ~InitialTimeZoneRule();
/**
* Clone this InitialTimeZoneRule object polymorphically. The caller owns the result and
* should delete it when done.
* @return A copy of the object.
* @stable ICU 3.8
*/
virtual InitialTimeZoneRule* clone() const override;
/**
* Assignment operator.
* @param right The object to be copied.
* @stable ICU 3.8
*/
InitialTimeZoneRule& operator=(const InitialTimeZoneRule& right);
/**
* Return true if the given <code>TimeZoneRule</code> objects are semantically equal. Objects
* of different subclasses are considered unequal.
* @param that The object to be compared with.
* @return true if the given <code>TimeZoneRule</code> objects are semantically equal.
* @stable ICU 3.8
*/
virtual bool operator==(const TimeZoneRule& that) const override;
/**
* Return true if the given <code>TimeZoneRule</code> objects are semantically unequal. Objects
* of different subclasses are considered unequal.
* @param that The object to be compared with.
* @return true if the given <code>TimeZoneRule</code> objects are semantically unequal.
* @stable ICU 3.8
*/
virtual bool operator!=(const TimeZoneRule& that) const override;
/**
* Returns if this rule represents the same rule and offsets as another.
* When two <code>TimeZoneRule</code> objects differ only its names, this method
* returns true.
* @param that The <code>TimeZoneRule</code> object to be compared with.
* @return true if the other <code>TimeZoneRule</code> is equivalent to this one.
* @stable ICU 3.8
*/
virtual UBool isEquivalentTo(const TimeZoneRule& that) const override;
/**
* Gets the very first time when this rule takes effect.
* @param prevRawOffset The standard time offset from UTC before this rule
* takes effect in milliseconds.
* @param prevDSTSavings The amount of daylight saving offset from the
* standard time.
* @param result Receives the very first time when this rule takes effect.
* @return true if the start time is available. When false is returned, output parameter
* "result" is unchanged.
* @stable ICU 3.8
*/
virtual UBool getFirstStart(int32_t prevRawOffset, int32_t prevDSTSavings, UDate& result) const override;
/**
* Gets the final time when this rule takes effect.
* @param prevRawOffset The standard time offset from UTC before this rule
* takes effect in milliseconds.
* @param prevDSTSavings The amount of daylight saving offset from the
* standard time.
* @param result Receives the final time when this rule takes effect.
* @return true if the start time is available. When false is returned, output parameter
* "result" is unchanged.
* @stable ICU 3.8
*/
virtual UBool getFinalStart(int32_t prevRawOffset, int32_t prevDSTSavings, UDate& result) const override;
/**
* Gets the first time when this rule takes effect after the specified time.
* @param base The first start time after this base time will be returned.
* @param prevRawOffset The standard time offset from UTC before this rule
* takes effect in milliseconds.
* @param prevDSTSavings The amount of daylight saving offset from the
* standard time.
* @param inclusive Whether the base time is inclusive or not.
* @param result Receives The first time when this rule takes effect after
* the specified base time.
* @return true if the start time is available. When false is returned, output parameter
* "result" is unchanged.
* @stable ICU 3.8
*/
virtual UBool getNextStart(UDate base, int32_t prevRawOffset, int32_t prevDSTSavings,
UBool inclusive, UDate& result) const override;
/**
* Gets the most recent time when this rule takes effect before the specified time.
* @param base The most recent time before this base time will be returned.
* @param prevRawOffset The standard time offset from UTC before this rule
* takes effect in milliseconds.
* @param prevDSTSavings The amount of daylight saving offset from the
* standard time.
* @param inclusive Whether the base time is inclusive or not.
* @param result Receives The most recent time when this rule takes effect before
* the specified base time.
* @return true if the start time is available. When false is returned, output parameter
* "result" is unchanged.
* @stable ICU 3.8
*/
virtual UBool getPreviousStart(UDate base, int32_t prevRawOffset, int32_t prevDSTSavings,
UBool inclusive, UDate& result) const override;
public:
/**
* Return the class ID for this class. This is useful only for comparing to
* a return value from getDynamicClassID(). For example:
* <pre>
* . Base* polymorphic_pointer = createPolymorphicObject();
* . if (polymorphic_pointer->getDynamicClassID() ==
* . erived::getStaticClassID()) ...
* </pre>
* @return The class ID for all objects of this class.
* @stable ICU 3.8
*/
static UClassID U_EXPORT2 getStaticClassID();
/**
* Returns a unique class ID POLYMORPHICALLY. Pure virtual override. This
* method is to implement a simple version of RTTI, since not all C++
* compilers support genuine RTTI. Polymorphic operator==() and clone()
* methods call this method.
*
* @return The class ID for this object. All objects of a
* given class have the same class ID. Objects of
* other classes have different class IDs.
* @stable ICU 3.8
*/
virtual UClassID getDynamicClassID() const override;
};
/**
* <code>AnnualTimeZoneRule</code> is a class used for representing a time zone
* rule which takes effect annually. The calendar system used for the rule is
* is based on Gregorian calendar
*
* @stable ICU 3.8
*/
class U_I18N_API AnnualTimeZoneRule : public TimeZoneRule {
public:
/**
* The constant representing the maximum year used for designating
* a rule is permanent.
*/
static const int32_t MAX_YEAR;
/**
* Constructs a <code>AnnualTimeZoneRule</code> with the name, the GMT offset of its
* standard time, the amount of daylight saving offset adjustment, the annual start
* time rule and the start/until years. The input DateTimeRule is copied by this
* constructor, so the caller remains responsible for deleting the object.
* @param name The time zone name.
* @param rawOffset The GMT offset of its standard time in milliseconds.
* @param dstSavings The amount of daylight saving offset adjustment in
* milliseconds. If this ia a rule for standard time,
* the value of this argument is 0.
* @param dateTimeRule The start date/time rule repeated annually.
* @param startYear The first year when this rule takes effect.
* @param endYear The last year when this rule takes effect. If this
* rule is effective forever in future, specify MAX_YEAR.
* @stable ICU 3.8
*/
AnnualTimeZoneRule(const UnicodeString& name, int32_t rawOffset, int32_t dstSavings,
const DateTimeRule& dateTimeRule, int32_t startYear, int32_t endYear);
/**
* Constructs a <code>AnnualTimeZoneRule</code> with the name, the GMT offset of its
* standard time, the amount of daylight saving offset adjustment, the annual start
* time rule and the start/until years. The input DateTimeRule object is adopted
* by this object, therefore, the caller must not delete the object.
* @param name The time zone name.
* @param rawOffset The GMT offset of its standard time in milliseconds.
* @param dstSavings The amount of daylight saving offset adjustment in
* milliseconds. If this ia a rule for standard time,
* the value of this argument is 0.
* @param dateTimeRule The start date/time rule repeated annually.
* @param startYear The first year when this rule takes effect.
* @param endYear The last year when this rule takes effect. If this
* rule is effective forever in future, specify MAX_YEAR.
* @stable ICU 3.8
*/
AnnualTimeZoneRule(const UnicodeString& name, int32_t rawOffset, int32_t dstSavings,
DateTimeRule* dateTimeRule, int32_t startYear, int32_t endYear);
/**
* Copy constructor.
* @param source The AnnualTimeZoneRule object to be copied.
* @stable ICU 3.8
*/
AnnualTimeZoneRule(const AnnualTimeZoneRule& source);
/**
* Destructor.
* @stable ICU 3.8
*/
virtual ~AnnualTimeZoneRule();
/**
* Clone this AnnualTimeZoneRule object polymorphically. The caller owns the result and
* should delete it when done.
* @return A copy of the object.
* @stable ICU 3.8
*/
virtual AnnualTimeZoneRule* clone() const override;
/**
* Assignment operator.
* @param right The object to be copied.
* @stable ICU 3.8
*/
AnnualTimeZoneRule& operator=(const AnnualTimeZoneRule& right);
/**
* Return true if the given <code>TimeZoneRule</code> objects are semantically equal. Objects
* of different subclasses are considered unequal.
* @param that The object to be compared with.
* @return true if the given <code>TimeZoneRule</code> objects are semantically equal.
* @stable ICU 3.8
*/
virtual bool operator==(const TimeZoneRule& that) const override;
/**
* Return true if the given <code>TimeZoneRule</code> objects are semantically unequal. Objects
* of different subclasses are considered unequal.
* @param that The object to be compared with.
* @return true if the given <code>TimeZoneRule</code> objects are semantically unequal.
* @stable ICU 3.8
*/
virtual bool operator!=(const TimeZoneRule& that) const override;
/**
* Gets the start date/time rule used by this rule.
* @return The <code>AnnualDateTimeRule</code> which represents the start date/time
* rule used by this time zone rule.
* @stable ICU 3.8
*/
const DateTimeRule* getRule() const;
/**
* Gets the first year when this rule takes effect.
* @return The start year of this rule. The year is in Gregorian calendar
* with 0 == 1 BCE, -1 == 2 BCE, etc.
* @stable ICU 3.8
*/
int32_t getStartYear() const;
/**
* Gets the end year when this rule takes effect.
* @return The end year of this rule (inclusive). The year is in Gregorian calendar
* with 0 == 1 BCE, -1 == 2 BCE, etc.
* @stable ICU 3.8
*/
int32_t getEndYear() const;
/**
* Gets the time when this rule takes effect in the given year.
* @param year The Gregorian year, with 0 == 1 BCE, -1 == 2 BCE, etc.
* @param prevRawOffset The standard time offset from UTC before this rule
* takes effect in milliseconds.
* @param prevDSTSavings The amount of daylight saving offset from the
* standard time.
* @param result Receives the start time in the year.
* @return true if this rule takes effect in the year and the result is set to
* "result".
* @stable ICU 3.8
*/
UBool getStartInYear(int32_t year, int32_t prevRawOffset, int32_t prevDSTSavings, UDate& result) const;
/**
* Returns if this rule represents the same rule and offsets as another.
* When two <code>TimeZoneRule</code> objects differ only its names, this method
* returns true.
* @param that The <code>TimeZoneRule</code> object to be compared with.
* @return true if the other <code>TimeZoneRule</code> is equivalent to this one.
* @stable ICU 3.8
*/
virtual UBool isEquivalentTo(const TimeZoneRule& that) const override;
/**
* Gets the very first time when this rule takes effect.
* @param prevRawOffset The standard time offset from UTC before this rule
* takes effect in milliseconds.
* @param prevDSTSavings The amount of daylight saving offset from the
* standard time.
* @param result Receives the very first time when this rule takes effect.
* @return true if the start time is available. When false is returned, output parameter
* "result" is unchanged.
* @stable ICU 3.8
*/
virtual UBool getFirstStart(int32_t prevRawOffset, int32_t prevDSTSavings, UDate& result) const override;
/**
* Gets the final time when this rule takes effect.
* @param prevRawOffset The standard time offset from UTC before this rule
* takes effect in milliseconds.
* @param prevDSTSavings The amount of daylight saving offset from the
* standard time.
* @param result Receives the final time when this rule takes effect.
* @return true if the start time is available. When false is returned, output parameter
* "result" is unchanged.
* @stable ICU 3.8
*/
virtual UBool getFinalStart(int32_t prevRawOffset, int32_t prevDSTSavings, UDate& result) const override;
/**
* Gets the first time when this rule takes effect after the specified time.
* @param base The first start time after this base time will be returned.
* @param prevRawOffset The standard time offset from UTC before this rule
* takes effect in milliseconds.
* @param prevDSTSavings The amount of daylight saving offset from the
* standard time.
* @param inclusive Whether the base time is inclusive or not.
* @param result Receives The first time when this rule takes effect after
* the specified base time.
* @return true if the start time is available. When false is returned, output parameter
* "result" is unchanged.
* @stable ICU 3.8
*/
virtual UBool getNextStart(UDate base, int32_t prevRawOffset, int32_t prevDSTSavings,
UBool inclusive, UDate& result) const override;
/**
* Gets the most recent time when this rule takes effect before the specified time.
* @param base The most recent time before this base time will be returned.
* @param prevRawOffset The standard time offset from UTC before this rule
* takes effect in milliseconds.
* @param prevDSTSavings The amount of daylight saving offset from the
* standard time.
* @param inclusive Whether the base time is inclusive or not.
* @param result Receives The most recent time when this rule takes effect before
* the specified base time.
* @return true if the start time is available. When false is returned, output parameter
* "result" is unchanged.
* @stable ICU 3.8
*/
virtual UBool getPreviousStart(UDate base, int32_t prevRawOffset, int32_t prevDSTSavings,
UBool inclusive, UDate& result) const override;
private:
DateTimeRule* fDateTimeRule;
int32_t fStartYear;
int32_t fEndYear;
public:
/**
* Return the class ID for this class. This is useful only for comparing to
* a return value from getDynamicClassID(). For example:
* <pre>
* . Base* polymorphic_pointer = createPolymorphicObject();
* . if (polymorphic_pointer->getDynamicClassID() ==
* . erived::getStaticClassID()) ...
* </pre>
* @return The class ID for all objects of this class.
* @stable ICU 3.8
*/
static UClassID U_EXPORT2 getStaticClassID();
/**
* Returns a unique class ID POLYMORPHICALLY. Pure virtual override. This
* method is to implement a simple version of RTTI, since not all C++
* compilers support genuine RTTI. Polymorphic operator==() and clone()
* methods call this method.
*
* @return The class ID for this object. All objects of a
* given class have the same class ID. Objects of
* other classes have different class IDs.
* @stable ICU 3.8
*/
virtual UClassID getDynamicClassID() const override;
};
/**
* <code>TimeArrayTimeZoneRule</code> represents a time zone rule whose start times are
* defined by an array of milliseconds since the standard base time.
*
* @stable ICU 3.8
*/
class U_I18N_API TimeArrayTimeZoneRule : public TimeZoneRule {
public:
/**
* Constructs a <code>TimeArrayTimeZoneRule</code> with the name, the GMT offset of its
* standard time, the amount of daylight saving offset adjustment and
* the array of times when this rule takes effect.
* @param name The time zone name.
* @param rawOffset The UTC offset of its standard time in milliseconds.
* @param dstSavings The amount of daylight saving offset adjustment in
* milliseconds. If this ia a rule for standard time,
* the value of this argument is 0.
* @param startTimes The array start times in milliseconds since the base time
* (January 1, 1970, 00:00:00).
* @param numStartTimes The number of elements in the parameter "startTimes"
* @param timeRuleType The time type of the start times, which is one of
* <code>DataTimeRule::WALL_TIME</code>, <code>STANDARD_TIME</code>
* and <code>UTC_TIME</code>.
* @stable ICU 3.8
*/
TimeArrayTimeZoneRule(const UnicodeString& name, int32_t rawOffset, int32_t dstSavings,
const UDate* startTimes, int32_t numStartTimes, DateTimeRule::TimeRuleType timeRuleType);
/**
* Copy constructor.
* @param source The TimeArrayTimeZoneRule object to be copied.
* @stable ICU 3.8
*/
TimeArrayTimeZoneRule(const TimeArrayTimeZoneRule& source);
/**
* Destructor.
* @stable ICU 3.8
*/
virtual ~TimeArrayTimeZoneRule();
/**
* Clone this TimeArrayTimeZoneRule object polymorphically. The caller owns the result and
* should delete it when done.
* @return A copy of the object.
* @stable ICU 3.8
*/
virtual TimeArrayTimeZoneRule* clone() const override;
/**
* Assignment operator.
* @param right The object to be copied.
* @stable ICU 3.8
*/
TimeArrayTimeZoneRule& operator=(const TimeArrayTimeZoneRule& right);
/**
* Return true if the given <code>TimeZoneRule</code> objects are semantically equal. Objects
* of different subclasses are considered unequal.
* @param that The object to be compared with.
* @return true if the given <code>TimeZoneRule</code> objects are semantically equal.
* @stable ICU 3.8
*/
virtual bool operator==(const TimeZoneRule& that) const override;
/**
* Return true if the given <code>TimeZoneRule</code> objects are semantically unequal. Objects
* of different subclasses are considered unequal.
* @param that The object to be compared with.
* @return true if the given <code>TimeZoneRule</code> objects are semantically unequal.
* @stable ICU 3.8
*/
virtual bool operator!=(const TimeZoneRule& that) const override;
/**
* Gets the time type of the start times used by this rule. The return value
* is either <code>DateTimeRule::WALL_TIME</code> or <code>STANDARD_TIME</code>
* or <code>UTC_TIME</code>.
*
* @return The time type used of the start times used by this rule.
* @stable ICU 3.8
*/
DateTimeRule::TimeRuleType getTimeType() const;
/**
* Gets a start time at the index stored in this rule.
* @param index The index of start times
* @param result Receives the start time at the index
* @return true if the index is within the valid range and
* and the result is set. When false, the output
* parameger "result" is unchanged.
* @stable ICU 3.8
*/
UBool getStartTimeAt(int32_t index, UDate& result) const;
/**
* Returns the number of start times stored in this rule
* @return The number of start times.
* @stable ICU 3.8
*/
int32_t countStartTimes() const;
/**
* Returns if this rule represents the same rule and offsets as another.
* When two <code>TimeZoneRule</code> objects differ only its names, this method
* returns true.
* @param that The <code>TimeZoneRule</code> object to be compared with.
* @return true if the other <code>TimeZoneRule</code> is equivalent to this one.
* @stable ICU 3.8
*/
virtual UBool isEquivalentTo(const TimeZoneRule& that) const override;
/**
* Gets the very first time when this rule takes effect.
* @param prevRawOffset The standard time offset from UTC before this rule
* takes effect in milliseconds.
* @param prevDSTSavings The amount of daylight saving offset from the
* standard time.
* @param result Receives the very first time when this rule takes effect.
* @return true if the start time is available. When false is returned, output parameter
* "result" is unchanged.
* @stable ICU 3.8
*/
virtual UBool getFirstStart(int32_t prevRawOffset, int32_t prevDSTSavings, UDate& result) const override;
/**
* Gets the final time when this rule takes effect.
* @param prevRawOffset The standard time offset from UTC before this rule
* takes effect in milliseconds.
* @param prevDSTSavings The amount of daylight saving offset from the
* standard time.
* @param result Receives the final time when this rule takes effect.
* @return true if the start time is available. When false is returned, output parameter
* "result" is unchanged.
* @stable ICU 3.8
*/
virtual UBool getFinalStart(int32_t prevRawOffset, int32_t prevDSTSavings, UDate& result) const override;
/**
* Gets the first time when this rule takes effect after the specified time.
* @param base The first start time after this base time will be returned.
* @param prevRawOffset The standard time offset from UTC before this rule
* takes effect in milliseconds.
* @param prevDSTSavings The amount of daylight saving offset from the
* standard time.
* @param inclusive Whether the base time is inclusive or not.
* @param result Receives The first time when this rule takes effect after
* the specified base time.
* @return true if the start time is available. When false is returned, output parameter
* "result" is unchanged.
* @stable ICU 3.8
*/
virtual UBool getNextStart(UDate base, int32_t prevRawOffset, int32_t prevDSTSavings,
UBool inclusive, UDate& result) const override;
/**
* Gets the most recent time when this rule takes effect before the specified time.
* @param base The most recent time before this base time will be returned.
* @param prevRawOffset The standard time offset from UTC before this rule
* takes effect in milliseconds.
* @param prevDSTSavings The amount of daylight saving offset from the
* standard time.
* @param inclusive Whether the base time is inclusive or not.
* @param result Receives The most recent time when this rule takes effect before
* the specified base time.
* @return true if the start time is available. When false is returned, output parameter
* "result" is unchanged.
* @stable ICU 3.8
*/
virtual UBool getPreviousStart(UDate base, int32_t prevRawOffset, int32_t prevDSTSavings,
UBool inclusive, UDate& result) const override;
private:
enum { TIMEARRAY_STACK_BUFFER_SIZE = 32 };
UBool initStartTimes(const UDate source[], int32_t size, UErrorCode& ec);
UDate getUTC(UDate time, int32_t raw, int32_t dst) const;
DateTimeRule::TimeRuleType fTimeRuleType;
int32_t fNumStartTimes;
UDate* fStartTimes;
UDate fLocalStartTimes[TIMEARRAY_STACK_BUFFER_SIZE];
public:
/**
* Return the class ID for this class. This is useful only for comparing to
* a return value from getDynamicClassID(). For example:
* <pre>
* . Base* polymorphic_pointer = createPolymorphicObject();
* . if (polymorphic_pointer->getDynamicClassID() ==
* . erived::getStaticClassID()) ...
* </pre>
* @return The class ID for all objects of this class.
* @stable ICU 3.8
*/
static UClassID U_EXPORT2 getStaticClassID();
/**
* Returns a unique class ID POLYMORPHICALLY. Pure virtual override. This
* method is to implement a simple version of RTTI, since not all C++
* compilers support genuine RTTI. Polymorphic operator==() and clone()
* methods call this method.
*
* @return The class ID for this object. All objects of a
* given class have the same class ID. Objects of
* other classes have different class IDs.
* @stable ICU 3.8
*/
virtual UClassID getDynamicClassID() const override;
};
U_NAMESPACE_END
#endif /* #if !UCONFIG_NO_FORMATTING */
#endif /* U_SHOW_CPLUSPLUS_API */
#endif // TZRULE_H
//eof

View File

@ -0,0 +1,201 @@
// © 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
/*
*******************************************************************************
* Copyright (C) 2007-2008, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
*/
#ifndef TZTRANS_H
#define TZTRANS_H
/**
* \file
* \brief C++ API: Time zone transition
*/
#include "unicode/utypes.h"
#if U_SHOW_CPLUSPLUS_API
#if !UCONFIG_NO_FORMATTING
#include "unicode/uobject.h"
U_NAMESPACE_BEGIN
// Forward declaration
class TimeZoneRule;
/**
* <code>TimeZoneTransition</code> is a class representing a time zone transition.
* An instance has a time of transition and rules for both before and after the transition.
* @stable ICU 3.8
*/
class U_I18N_API TimeZoneTransition : public UObject {
public:
/**
* Constructs a <code>TimeZoneTransition</code> with the time and the rules before/after
* the transition.
*
* @param time The time of transition in milliseconds since the base time.
* @param from The time zone rule used before the transition.
* @param to The time zone rule used after the transition.
* @stable ICU 3.8
*/
TimeZoneTransition(UDate time, const TimeZoneRule& from, const TimeZoneRule& to);
/**
* Constructs an empty <code>TimeZoneTransition</code>
* @stable ICU 3.8
*/
TimeZoneTransition();
/**
* Copy constructor.
* @param source The TimeZoneTransition object to be copied.
* @stable ICU 3.8
*/
TimeZoneTransition(const TimeZoneTransition& source);
/**
* Destructor.
* @stable ICU 3.8
*/
~TimeZoneTransition();
/**
* Clone this TimeZoneTransition object polymorphically. The caller owns the result and
* should delete it when done.
* @return A copy of the object.
* @stable ICU 3.8
*/
TimeZoneTransition* clone() const;
/**
* Assignment operator.
* @param right The object to be copied.
* @stable ICU 3.8
*/
TimeZoneTransition& operator=(const TimeZoneTransition& right);
/**
* Return true if the given TimeZoneTransition objects are semantically equal. Objects
* of different subclasses are considered unequal.
* @param that The object to be compared with.
* @return true if the given TimeZoneTransition objects are semantically equal.
* @stable ICU 3.8
*/
bool operator==(const TimeZoneTransition& that) const;
/**
* Return true if the given TimeZoneTransition objects are semantically unequal. Objects
* of different subclasses are considered unequal.
* @param that The object to be compared with.
* @return true if the given TimeZoneTransition objects are semantically unequal.
* @stable ICU 3.8
*/
bool operator!=(const TimeZoneTransition& that) const;
/**
* Returns the time of transition in milliseconds.
* @return The time of the transition in milliseconds since the 1970 Jan 1 epoch time.
* @stable ICU 3.8
*/
UDate getTime() const;
/**
* Sets the time of transition in milliseconds.
* @param time The time of the transition in milliseconds since the 1970 Jan 1 epoch time.
* @stable ICU 3.8
*/
void setTime(UDate time);
/**
* Returns the rule used before the transition.
* @return The time zone rule used after the transition.
* @stable ICU 3.8
*/
const TimeZoneRule* getFrom() const;
/**
* Sets the rule used before the transition. The caller remains
* responsible for deleting the <code>TimeZoneRule</code> object.
* @param from The time zone rule used before the transition.
* @stable ICU 3.8
*/
void setFrom(const TimeZoneRule& from);
/**
* Adopts the rule used before the transition. The caller must
* not delete the <code>TimeZoneRule</code> object passed in.
* @param from The time zone rule used before the transition.
* @stable ICU 3.8
*/
void adoptFrom(TimeZoneRule* from);
/**
* Sets the rule used after the transition. The caller remains
* responsible for deleting the <code>TimeZoneRule</code> object.
* @param to The time zone rule used after the transition.
* @stable ICU 3.8
*/
void setTo(const TimeZoneRule& to);
/**
* Adopts the rule used after the transition. The caller must
* not delete the <code>TimeZoneRule</code> object passed in.
* @param to The time zone rule used after the transition.
* @stable ICU 3.8
*/
void adoptTo(TimeZoneRule* to);
/**
* Returns the rule used after the transition.
* @return The time zone rule used after the transition.
* @stable ICU 3.8
*/
const TimeZoneRule* getTo() const;
private:
UDate fTime;
TimeZoneRule* fFrom;
TimeZoneRule* fTo;
public:
/**
* Return the class ID for this class. This is useful only for comparing to
* a return value from getDynamicClassID(). For example:
* <pre>
* . Base* polymorphic_pointer = createPolymorphicObject();
* . if (polymorphic_pointer->getDynamicClassID() ==
* . erived::getStaticClassID()) ...
* </pre>
* @return The class ID for all objects of this class.
* @stable ICU 3.8
*/
static UClassID U_EXPORT2 getStaticClassID();
/**
* Returns a unique class ID POLYMORPHICALLY. Pure virtual override. This
* method is to implement a simple version of RTTI, since not all C++
* compilers support genuine RTTI. Polymorphic operator==() and clone()
* methods call this method.
*
* @return The class ID for this object. All objects of a
* given class have the same class ID. Objects of
* other classes have different class IDs.
* @stable ICU 3.8
*/
virtual UClassID getDynamicClassID() const override;
};
U_NAMESPACE_END
#endif /* #if !UCONFIG_NO_FORMATTING */
#endif /* U_SHOW_CPLUSPLUS_API */
#endif // TZTRANS_H
//eof

1770
deps/icu-small/source/i18n/unicode/ucal.h vendored Normal file

File diff suppressed because it is too large Load Diff

1672
deps/icu-small/source/i18n/unicode/ucol.h vendored Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,276 @@
// © 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
/*
*******************************************************************************
* Copyright (C) 2001-2014, International Business Machines
* Corporation and others. All Rights Reserved.
*******************************************************************************
*
* File ucoleitr.h
*
* Modification History:
*
* Date Name Description
* 02/15/2001 synwee Modified all methods to process its own function
* instead of calling the equivalent c++ api (coleitr.h)
*******************************************************************************/
#ifndef UCOLEITR_H
#define UCOLEITR_H
#include "unicode/utypes.h"
#if !UCONFIG_NO_COLLATION
/**
* This indicates an error has occurred during processing or if no more CEs is
* to be returned.
* @stable ICU 2.0
*/
#define UCOL_NULLORDER ((int32_t)0xFFFFFFFF)
#include "unicode/ucol.h"
/**
* The UCollationElements struct.
* For usage in C programs.
* @stable ICU 2.0
*/
typedef struct UCollationElements UCollationElements;
/**
* \file
* \brief C API: UCollationElements
*
* The UCollationElements API is used as an iterator to walk through each
* character of an international string. Use the iterator to return the
* ordering priority of the positioned character. The ordering priority of a
* character, which we refer to as a key, defines how a character is collated
* in the given collation object.
* For example, consider the following in Slovak and in traditional Spanish collation:
* <pre>
* . "ca" -> the first key is key('c') and second key is key('a').
* . "cha" -> the first key is key('ch') and second key is key('a').
* </pre>
* And in German phonebook collation,
* <pre>
* . "<ae ligature>b"-> the first key is key('a'), the second key is key('e'), and
* . the third key is key('b').
* </pre>
* <p>Example of the iterator usage: (without error checking)
* <pre>
* . void CollationElementIterator_Example()
* . {
* . UChar *s;
* . t_int32 order, primaryOrder;
* . UCollationElements *c;
* . UCollatorOld *coll;
* . UErrorCode success = U_ZERO_ERROR;
* . str=(UChar*)malloc(sizeof(UChar) * (strlen("This is a test")+1) );
* . u_uastrcpy(str, "This is a test");
* . coll = ucol_open(NULL, &success);
* . c = ucol_openElements(coll, str, u_strlen(str), &status);
* . order = ucol_next(c, &success);
* . ucol_reset(c);
* . order = ucol_prev(c, &success);
* . free(str);
* . ucol_close(coll);
* . ucol_closeElements(c);
* . }
* </pre>
* <p>
* ucol_next() returns the collation order of the next.
* ucol_prev() returns the collation order of the previous character.
* The Collation Element Iterator moves only in one direction between calls to
* ucol_reset. That is, ucol_next() and ucol_prev can not be inter-used.
* Whenever ucol_prev is to be called after ucol_next() or vice versa,
* ucol_reset has to be called first to reset the status, shifting pointers to
* either the end or the start of the string. Hence at the next call of
* ucol_prev or ucol_next, the first or last collation order will be returned.
* If a change of direction is done without a ucol_reset, the result is
* undefined.
* The result of a forward iterate (ucol_next) and reversed result of the
* backward iterate (ucol_prev) on the same string are equivalent, if
* collation orders with the value 0 are ignored.
* Character based on the comparison level of the collator. A collation order
* consists of primary order, secondary order and tertiary order. The data
* type of the collation order is <strong>int32_t</strong>.
*
* @see UCollator
*/
/**
* Open the collation elements for a string.
*
* The UCollationElements retains a pointer to the supplied text.
* The caller must not modify or delete the text while the UCollationElements
* object is used to iterate over this text.
*
* @param coll The collator containing the desired collation rules.
* @param text The text to iterate over.
* @param textLength The number of characters in text, or -1 if null-terminated
* @param status A pointer to a UErrorCode to receive any errors.
* @return a struct containing collation element information
* @stable ICU 2.0
*/
U_CAPI UCollationElements* U_EXPORT2
ucol_openElements(const UCollator *coll,
const UChar *text,
int32_t textLength,
UErrorCode *status);
/**
* get a hash code for a key... Not very useful!
* @param key the given key.
* @param length the size of the key array.
* @return the hash code.
* @stable ICU 2.0
*/
U_CAPI int32_t U_EXPORT2
ucol_keyHashCode(const uint8_t* key, int32_t length);
/**
* Close a UCollationElements.
* Once closed, a UCollationElements may no longer be used.
* @param elems The UCollationElements to close.
* @stable ICU 2.0
*/
U_CAPI void U_EXPORT2
ucol_closeElements(UCollationElements *elems);
/**
* Reset the collation elements to their initial state.
* This will move the 'cursor' to the beginning of the text.
* Property settings for collation will be reset to the current status.
* @param elems The UCollationElements to reset.
* @see ucol_next
* @see ucol_previous
* @stable ICU 2.0
*/
U_CAPI void U_EXPORT2
ucol_reset(UCollationElements *elems);
/**
* Get the ordering priority of the next collation element in the text.
* A single character may contain more than one collation element.
* @param elems The UCollationElements containing the text.
* @param status A pointer to a UErrorCode to receive any errors.
* @return The next collation elements ordering, otherwise returns UCOL_NULLORDER
* if an error has occurred or if the end of string has been reached
* @stable ICU 2.0
*/
U_CAPI int32_t U_EXPORT2
ucol_next(UCollationElements *elems, UErrorCode *status);
/**
* Get the ordering priority of the previous collation element in the text.
* A single character may contain more than one collation element.
* Note that internally a stack is used to store buffered collation elements.
* @param elems The UCollationElements containing the text.
* @param status A pointer to a UErrorCode to receive any errors. Notably
* a U_BUFFER_OVERFLOW_ERROR is returned if the internal stack
* buffer has been exhausted.
* @return The previous collation elements ordering, otherwise returns
* UCOL_NULLORDER if an error has occurred or if the start of string has
* been reached.
* @stable ICU 2.0
*/
U_CAPI int32_t U_EXPORT2
ucol_previous(UCollationElements *elems, UErrorCode *status);
/**
* Get the maximum length of any expansion sequences that end with the
* specified comparison order.
* This is useful for .... ?
* @param elems The UCollationElements containing the text.
* @param order A collation order returned by previous or next.
* @return maximum size of the expansion sequences ending with the collation
* element or 1 if collation element does not occur at the end of any
* expansion sequence
* @stable ICU 2.0
*/
U_CAPI int32_t U_EXPORT2
ucol_getMaxExpansion(const UCollationElements *elems, int32_t order);
/**
* Set the text containing the collation elements.
* Property settings for collation will remain the same.
* In order to reset the iterator to the current collation property settings,
* the API reset() has to be called.
*
* The UCollationElements retains a pointer to the supplied text.
* The caller must not modify or delete the text while the UCollationElements
* object is used to iterate over this text.
*
* @param elems The UCollationElements to set.
* @param text The source text containing the collation elements.
* @param textLength The length of text, or -1 if null-terminated.
* @param status A pointer to a UErrorCode to receive any errors.
* @see ucol_getText
* @stable ICU 2.0
*/
U_CAPI void U_EXPORT2
ucol_setText( UCollationElements *elems,
const UChar *text,
int32_t textLength,
UErrorCode *status);
/**
* Get the offset of the current source character.
* This is an offset into the text of the character containing the current
* collation elements.
* @param elems The UCollationElements to query.
* @return The offset of the current source character.
* @see ucol_setOffset
* @stable ICU 2.0
*/
U_CAPI int32_t U_EXPORT2
ucol_getOffset(const UCollationElements *elems);
/**
* Set the offset of the current source character.
* This is an offset into the text of the character to be processed.
* Property settings for collation will remain the same.
* In order to reset the iterator to the current collation property settings,
* the API reset() has to be called.
* @param elems The UCollationElements to set.
* @param offset The desired character offset.
* @param status A pointer to a UErrorCode to receive any errors.
* @see ucol_getOffset
* @stable ICU 2.0
*/
U_CAPI void U_EXPORT2
ucol_setOffset(UCollationElements *elems,
int32_t offset,
UErrorCode *status);
/**
* Get the primary order of a collation order.
* @param order the collation order
* @return the primary order of a collation order.
* @stable ICU 2.6
*/
U_CAPI int32_t U_EXPORT2
ucol_primaryOrder (int32_t order);
/**
* Get the secondary order of a collation order.
* @param order the collation order
* @return the secondary order of a collation order.
* @stable ICU 2.6
*/
U_CAPI int32_t U_EXPORT2
ucol_secondaryOrder (int32_t order);
/**
* Get the tertiary order of a collation order.
* @param order the collation order
* @return the tertiary order of a collation order.
* @stable ICU 2.6
*/
U_CAPI int32_t U_EXPORT2
ucol_tertiaryOrder (int32_t order);
#endif /* #if !UCONFIG_NO_COLLATION */
#endif

View File

@ -0,0 +1,422 @@
// © 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
/*
**********************************************************************
* Copyright (C) 2005-2013, International Business Machines
* Corporation and others. All Rights Reserved.
**********************************************************************
* file name: ucsdet.h
* encoding: UTF-8
* indentation:4
*
* created on: 2005Aug04
* created by: Andy Heninger
*
* ICU Character Set Detection, API for C
*
* Draft version 18 Oct 2005
*
*/
#ifndef __UCSDET_H
#define __UCSDET_H
#include "unicode/utypes.h"
#if !UCONFIG_NO_CONVERSION
#include "unicode/uenum.h"
#if U_SHOW_CPLUSPLUS_API
#include "unicode/localpointer.h"
#endif // U_SHOW_CPLUSPLUS_API
/**
* \file
* \brief C API: Charset Detection API
*
* This API provides a facility for detecting the
* charset or encoding of character data in an unknown text format.
* The input data can be from an array of bytes.
* <p>
* Character set detection is at best an imprecise operation. The detection
* process will attempt to identify the charset that best matches the characteristics
* of the byte data, but the process is partly statistical in nature, and
* the results can not be guaranteed to always be correct.
* <p>
* For best accuracy in charset detection, the input data should be primarily
* in a single language, and a minimum of a few hundred bytes worth of plain text
* in the language are needed. The detection process will attempt to
* ignore html or xml style markup that could otherwise obscure the content.
* <p>
* An alternative to the ICU Charset Detector is the
* Compact Encoding Detector, https://github.com/google/compact_enc_det.
* It often gives more accurate results, especially with short input samples.
*/
struct UCharsetDetector;
/**
* Structure representing a charset detector
* @stable ICU 3.6
*/
typedef struct UCharsetDetector UCharsetDetector;
struct UCharsetMatch;
/**
* Opaque structure representing a match that was identified
* from a charset detection operation.
* @stable ICU 3.6
*/
typedef struct UCharsetMatch UCharsetMatch;
/**
* Open a charset detector.
*
* @param status Any error conditions occurring during the open
* operation are reported back in this variable.
* @return the newly opened charset detector.
* @stable ICU 3.6
*/
U_CAPI UCharsetDetector * U_EXPORT2
ucsdet_open(UErrorCode *status);
/**
* Close a charset detector. All storage and any other resources
* owned by this charset detector will be released. Failure to
* close a charset detector when finished with it can result in
* memory leaks in the application.
*
* @param ucsd The charset detector to be closed.
* @stable ICU 3.6
*/
U_CAPI void U_EXPORT2
ucsdet_close(UCharsetDetector *ucsd);
#if U_SHOW_CPLUSPLUS_API
U_NAMESPACE_BEGIN
/**
* \class LocalUCharsetDetectorPointer
* "Smart pointer" class, closes a UCharsetDetector via ucsdet_close().
* For most methods see the LocalPointerBase base class.
*
* @see LocalPointerBase
* @see LocalPointer
* @stable ICU 4.4
*/
U_DEFINE_LOCAL_OPEN_POINTER(LocalUCharsetDetectorPointer, UCharsetDetector, ucsdet_close);
U_NAMESPACE_END
#endif
/**
* Set the input byte data whose charset is to detected.
*
* Ownership of the input text byte array remains with the caller.
* The input string must not be altered or deleted until the charset
* detector is either closed or reset to refer to different input text.
*
* @param ucsd the charset detector to be used.
* @param textIn the input text of unknown encoding. .
* @param len the length of the input text, or -1 if the text
* is NUL terminated.
* @param status any error conditions are reported back in this variable.
*
* @stable ICU 3.6
*/
U_CAPI void U_EXPORT2
ucsdet_setText(UCharsetDetector *ucsd, const char *textIn, int32_t len, UErrorCode *status);
/** Set the declared encoding for charset detection.
* The declared encoding of an input text is an encoding obtained
* by the user from an http header or xml declaration or similar source that
* can be provided as an additional hint to the charset detector.
*
* How and whether the declared encoding will be used during the
* detection process is TBD.
*
* @param ucsd the charset detector to be used.
* @param encoding an encoding for the current data obtained from
* a header or declaration or other source outside
* of the byte data itself.
* @param length the length of the encoding name, or -1 if the name string
* is NUL terminated.
* @param status any error conditions are reported back in this variable.
*
* @stable ICU 3.6
*/
U_CAPI void U_EXPORT2
ucsdet_setDeclaredEncoding(UCharsetDetector *ucsd, const char *encoding, int32_t length, UErrorCode *status);
/**
* Return the charset that best matches the supplied input data.
*
* Note though, that because the detection
* only looks at the start of the input data,
* there is a possibility that the returned charset will fail to handle
* the full set of input data.
* <p>
* The returned UCharsetMatch object is owned by the UCharsetDetector.
* It will remain valid until the detector input is reset, or until
* the detector is closed.
* <p>
* The function will fail if
* <ul>
* <li>no charset appears to match the data.</li>
* <li>no input text has been provided</li>
* </ul>
*
* @param ucsd the charset detector to be used.
* @param status any error conditions are reported back in this variable.
* @return a UCharsetMatch representing the best matching charset,
* or NULL if no charset matches the byte data.
*
* @stable ICU 3.6
*/
U_CAPI const UCharsetMatch * U_EXPORT2
ucsdet_detect(UCharsetDetector *ucsd, UErrorCode *status);
/**
* Find all charset matches that appear to be consistent with the input,
* returning an array of results. The results are ordered with the
* best quality match first.
*
* Because the detection only looks at a limited amount of the
* input byte data, some of the returned charsets may fail to handle
* the all of input data.
* <p>
* The returned UCharsetMatch objects are owned by the UCharsetDetector.
* They will remain valid until the detector is closed or modified
*
* <p>
* Return an error if
* <ul>
* <li>no charsets appear to match the input data.</li>
* <li>no input text has been provided</li>
* </ul>
*
* @param ucsd the charset detector to be used.
* @param matchesFound pointer to a variable that will be set to the
* number of charsets identified that are consistent with
* the input data. Output only.
* @param status any error conditions are reported back in this variable.
* @return A pointer to an array of pointers to UCharSetMatch objects.
* This array, and the UCharSetMatch instances to which it refers,
* are owned by the UCharsetDetector, and will remain valid until
* the detector is closed or modified.
* @stable ICU 3.6
*/
U_CAPI const UCharsetMatch ** U_EXPORT2
ucsdet_detectAll(UCharsetDetector *ucsd, int32_t *matchesFound, UErrorCode *status);
/**
* Get the name of the charset represented by a UCharsetMatch.
*
* The storage for the returned name string is owned by the
* UCharsetMatch, and will remain valid while the UCharsetMatch
* is valid.
*
* The name returned is suitable for use with the ICU conversion APIs.
*
* @param ucsm The charset match object.
* @param status Any error conditions are reported back in this variable.
* @return The name of the matching charset.
*
* @stable ICU 3.6
*/
U_CAPI const char * U_EXPORT2
ucsdet_getName(const UCharsetMatch *ucsm, UErrorCode *status);
/**
* Get a confidence number for the quality of the match of the byte
* data with the charset. Confidence numbers range from zero to 100,
* with 100 representing complete confidence and zero representing
* no confidence.
*
* The confidence values are somewhat arbitrary. They define an
* an ordering within the results for any single detection operation
* but are not generally comparable between the results for different input.
*
* A confidence value of ten does have a general meaning - it is used
* for charsets that can represent the input data, but for which there
* is no other indication that suggests that the charset is the correct one.
* Pure 7 bit ASCII data, for example, is compatible with a
* great many charsets, most of which will appear as possible matches
* with a confidence of 10.
*
* @param ucsm The charset match object.
* @param status Any error conditions are reported back in this variable.
* @return A confidence number for the charset match.
*
* @stable ICU 3.6
*/
U_CAPI int32_t U_EXPORT2
ucsdet_getConfidence(const UCharsetMatch *ucsm, UErrorCode *status);
/**
* Get the RFC 3066 code for the language of the input data.
*
* The Charset Detection service is intended primarily for detecting
* charsets, not language. For some, but not all, charsets, a language is
* identified as a byproduct of the detection process, and that is what
* is returned by this function.
*
* CAUTION:
* 1. Language information is not available for input data encoded in
* all charsets. In particular, no language is identified
* for UTF-8 input data.
*
* 2. Closely related languages may sometimes be confused.
*
* If more accurate language detection is required, a linguistic
* analysis package should be used.
*
* The storage for the returned name string is owned by the
* UCharsetMatch, and will remain valid while the UCharsetMatch
* is valid.
*
* @param ucsm The charset match object.
* @param status Any error conditions are reported back in this variable.
* @return The RFC 3066 code for the language of the input data, or
* an empty string if the language could not be determined.
*
* @stable ICU 3.6
*/
U_CAPI const char * U_EXPORT2
ucsdet_getLanguage(const UCharsetMatch *ucsm, UErrorCode *status);
/**
* Get the entire input text as a UChar string, placing it into
* a caller-supplied buffer. A terminating
* NUL character will be appended to the buffer if space is available.
*
* The number of UChars in the output string, not including the terminating
* NUL, is returned.
*
* If the supplied buffer is smaller than required to hold the output,
* the contents of the buffer are undefined. The full output string length
* (in UChars) is returned as always, and can be used to allocate a buffer
* of the correct size.
*
*
* @param ucsm The charset match object.
* @param buf A UChar buffer to be filled with the converted text data.
* @param cap The capacity of the buffer in UChars.
* @param status Any error conditions are reported back in this variable.
* @return The number of UChars in the output string.
*
* @stable ICU 3.6
*/
U_CAPI int32_t U_EXPORT2
ucsdet_getUChars(const UCharsetMatch *ucsm,
UChar *buf, int32_t cap, UErrorCode *status);
/**
* Get an iterator over the set of all detectable charsets -
* over the charsets that are known to the charset detection
* service.
*
* The returned UEnumeration provides access to the names of
* the charsets.
*
* <p>
* The state of the Charset detector that is passed in does not
* affect the result of this function, but requiring a valid, open
* charset detector as a parameter insures that the charset detection
* service has been safely initialized and that the required detection
* data is available.
*
* <p>
* <b>Note:</b> Multiple different charset encodings in a same family may use
* a single shared name in this implementation. For example, this method returns
* an array including "ISO-8859-1" (ISO Latin 1), but not including "windows-1252"
* (Windows Latin 1). However, actual detection result could be "windows-1252"
* when the input data matches Latin 1 code points with any points only available
* in "windows-1252".
*
* @param ucsd a Charset detector.
* @param status Any error conditions are reported back in this variable.
* @return an iterator providing access to the detectable charset names.
* @stable ICU 3.6
*/
U_CAPI UEnumeration * U_EXPORT2
ucsdet_getAllDetectableCharsets(const UCharsetDetector *ucsd, UErrorCode *status);
/**
* Test whether input filtering is enabled for this charset detector.
* Input filtering removes text that appears to be HTML or xml
* markup from the input before applying the code page detection
* heuristics.
*
* @param ucsd The charset detector to check.
* @return true if filtering is enabled.
* @stable ICU 3.6
*/
U_CAPI UBool U_EXPORT2
ucsdet_isInputFilterEnabled(const UCharsetDetector *ucsd);
/**
* Enable filtering of input text. If filtering is enabled,
* text within angle brackets ("<" and ">") will be removed
* before detection, which will remove most HTML or xml markup.
*
* @param ucsd the charset detector to be modified.
* @param filter <code>true</code> to enable input text filtering.
* @return The previous setting.
*
* @stable ICU 3.6
*/
U_CAPI UBool U_EXPORT2
ucsdet_enableInputFilter(UCharsetDetector *ucsd, UBool filter);
#ifndef U_HIDE_INTERNAL_API
/**
* Get an iterator over the set of detectable charsets -
* over the charsets that are enabled by the specified charset detector.
*
* The returned UEnumeration provides access to the names of
* the charsets.
*
* @param ucsd a Charset detector.
* @param status Any error conditions are reported back in this variable.
* @return an iterator providing access to the detectable charset names by
* the specified charset detector.
* @internal
*/
U_CAPI UEnumeration * U_EXPORT2
ucsdet_getDetectableCharsets(const UCharsetDetector *ucsd, UErrorCode *status);
/**
* Enable or disable individual charset encoding.
* A name of charset encoding must be included in the names returned by
* {@link #ucsdet_getAllDetectableCharsets()}.
*
* @param ucsd a Charset detector.
* @param encoding encoding the name of charset encoding.
* @param enabled <code>true</code> to enable, or <code>false</code> to disable the
* charset encoding.
* @param status receives the return status. When the name of charset encoding
* is not supported, U_ILLEGAL_ARGUMENT_ERROR is set.
* @internal
*/
U_CAPI void U_EXPORT2
ucsdet_setDetectableCharset(UCharsetDetector *ucsd, const char *encoding, UBool enabled, UErrorCode *status);
#endif /* U_HIDE_INTERNAL_API */
#endif
#endif /* __UCSDET_H */

1741
deps/icu-small/source/i18n/unicode/udat.h vendored Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,332 @@
// © 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
/*
*****************************************************************************************
* Copyright (C) 2010-2012,2015 International Business Machines
* Corporation and others. All Rights Reserved.
*****************************************************************************************
*/
#ifndef UDATEINTERVALFORMAT_H
#define UDATEINTERVALFORMAT_H
#include "unicode/utypes.h"
#if !UCONFIG_NO_FORMATTING
#include "unicode/ucal.h"
#include "unicode/umisc.h"
#include "unicode/uformattedvalue.h"
#include "unicode/udisplaycontext.h"
#if U_SHOW_CPLUSPLUS_API
#include "unicode/localpointer.h"
#endif // U_SHOW_CPLUSPLUS_API
/**
* \file
* \brief C API: Format a date interval.
*
* A UDateIntervalFormat is used to format the range between two UDate values
* in a locale-sensitive way, using a skeleton that specifies the precision and
* completeness of the information to show. If the range smaller than the resolution
* specified by the skeleton, a single date format will be produced. If the range
* is larger than the format specified by the skeleton, a locale-specific fallback
* will be used to format the items missing from the skeleton.
*
* For example, if the range is 2010-03-04 07:56 - 2010-03-04 19:56 (12 hours)
* - The skeleton jm will produce
* for en_US, "7:56 AM - 7:56 PM"
* for en_GB, "7:56 - 19:56"
* - The skeleton MMMd will produce
* for en_US, "Mar 4"
* for en_GB, "4 Mar"
* If the range is 2010-03-04 07:56 - 2010-03-08 16:11 (4 days, 8 hours, 15 minutes)
* - The skeleton jm will produce
* for en_US, "3/4/2010 7:56 AM - 3/8/2010 4:11 PM"
* for en_GB, "4/3/2010 7:56 - 8/3/2010 16:11"
* - The skeleton MMMd will produce
* for en_US, "Mar 4-8"
* for en_GB, "4-8 Mar"
*
* Note: the "-" characters in the above sample output will actually be
* Unicode 2013, EN_DASH, in all but the last example.
*
* Note, in ICU 4.4 the standard skeletons for which date interval format data
* is usually available are as follows; best results will be obtained by using
* skeletons from this set, or those formed by combining these standard skeletons
* (note that for these skeletons, the length of digit field such as d, y, or
* M vs MM is irrelevant (but for non-digit fields such as MMM vs MMMM it is
* relevant). Note that a skeleton involving h or H generally explicitly requests
* that time style (12- or 24-hour time respectively). For a skeleton that
* requests the locale's default time style (h or H), use 'j' instead of h or H.
* h, H, hm, Hm,
* hv, Hv, hmv, Hmv,
* d,
* M, MMM, MMMM,
* Md, MMMd,
* MEd, MMMEd,
* y,
* yM, yMMM, yMMMM,
* yMd, yMMMd,
* yMEd, yMMMEd
*
* Locales for which ICU 4.4 seems to have a reasonable amount of this data
* include:
* af, am, ar, be, bg, bn, ca, cs, da, de (_AT), el, en (_AU,_CA,_GB,_IE,_IN...),
* eo, es (_AR,_CL,_CO,...,_US) et, fa, fi, fo, fr (_BE,_CH,_CA), fur, gsw, he,
* hr, hu, hy, is, it (_CH), ja, kk, km, ko, lt, lv, mk, ml, mt, nb, nl )_BE),
* nn, pl, pt (_PT), rm, ro, ru (_UA), sk, sl, so, sq, sr, sr_Latn, sv, th, to,
* tr, uk, ur, vi, zh (_SG), zh_Hant (_HK,_MO)
*/
/**
* Opaque UDateIntervalFormat object for use in C programs.
* @stable ICU 4.8
*/
struct UDateIntervalFormat;
typedef struct UDateIntervalFormat UDateIntervalFormat; /**< C typedef for struct UDateIntervalFormat. @stable ICU 4.8 */
struct UFormattedDateInterval;
/**
* Opaque struct to contain the results of a UDateIntervalFormat operation.
* @stable ICU 64
*/
typedef struct UFormattedDateInterval UFormattedDateInterval;
/**
* Open a new UDateIntervalFormat object using the predefined rules for a
* given locale plus a specified skeleton.
* @param locale
* The locale for whose rules should be used; may be NULL for
* default locale.
* @param skeleton
* A pattern containing only the fields desired for the interval
* format, for example "Hm", "yMMMd", or "yMMMEdHm".
* @param skeletonLength
* The length of skeleton; may be -1 if the skeleton is zero-terminated.
* @param tzID
* A timezone ID specifying the timezone to use. If 0, use the default
* timezone.
* @param tzIDLength
* The length of tzID, or -1 if null-terminated. If 0, use the default
* timezone.
* @param status
* A pointer to a UErrorCode to receive any errors.
* @return
* A pointer to a UDateIntervalFormat object for the specified locale,
* or NULL if an error occurred.
* @stable ICU 4.8
*/
U_CAPI UDateIntervalFormat* U_EXPORT2
udtitvfmt_open(const char* locale,
const UChar* skeleton,
int32_t skeletonLength,
const UChar* tzID,
int32_t tzIDLength,
UErrorCode* status);
/**
* Close a UDateIntervalFormat object. Once closed it may no longer be used.
* @param formatter
* The UDateIntervalFormat object to close.
* @stable ICU 4.8
*/
U_CAPI void U_EXPORT2
udtitvfmt_close(UDateIntervalFormat *formatter);
/**
* Creates an object to hold the result of a UDateIntervalFormat
* operation. The object can be used repeatedly; it is cleared whenever
* passed to a format function.
*
* @param ec Set if an error occurs.
* @return A pointer needing ownership.
* @stable ICU 64
*/
U_CAPI UFormattedDateInterval* U_EXPORT2
udtitvfmt_openResult(UErrorCode* ec);
/**
* Returns a representation of a UFormattedDateInterval as a UFormattedValue,
* which can be subsequently passed to any API requiring that type.
*
* The returned object is owned by the UFormattedDateInterval and is valid
* only as long as the UFormattedDateInterval is present and unchanged in memory.
*
* You can think of this method as a cast between types.
*
* When calling ufmtval_nextPosition():
* The fields are returned from left to right. The special field category
* UFIELD_CATEGORY_DATE_INTERVAL_SPAN is used to indicate which datetime
* primitives came from which arguments: 0 means fromCalendar, and 1 means
* toCalendar. The span category will always occur before the
* corresponding fields in UFIELD_CATEGORY_DATE
* in the ufmtval_nextPosition() iterator.
*
* @param uresult The object containing the formatted string.
* @param ec Set if an error occurs.
* @return A UFormattedValue owned by the input object.
* @stable ICU 64
*/
U_CAPI const UFormattedValue* U_EXPORT2
udtitvfmt_resultAsValue(const UFormattedDateInterval* uresult, UErrorCode* ec);
/**
* Releases the UFormattedDateInterval created by udtitvfmt_openResult().
*
* @param uresult The object to release.
* @stable ICU 64
*/
U_CAPI void U_EXPORT2
udtitvfmt_closeResult(UFormattedDateInterval* uresult);
#if U_SHOW_CPLUSPLUS_API
U_NAMESPACE_BEGIN
/**
* \class LocalUDateIntervalFormatPointer
* "Smart pointer" class, closes a UDateIntervalFormat via udtitvfmt_close().
* For most methods see the LocalPointerBase base class.
*
* @see LocalPointerBase
* @see LocalPointer
* @stable ICU 4.8
*/
U_DEFINE_LOCAL_OPEN_POINTER(LocalUDateIntervalFormatPointer, UDateIntervalFormat, udtitvfmt_close);
/**
* \class LocalUFormattedDateIntervalPointer
* "Smart pointer" class, closes a UFormattedDateInterval via udtitvfmt_close().
* For most methods see the LocalPointerBase base class.
*
* @see LocalPointerBase
* @see LocalPointer
* @stable ICU 64
*/
U_DEFINE_LOCAL_OPEN_POINTER(LocalUFormattedDateIntervalPointer, UFormattedDateInterval, udtitvfmt_closeResult);
U_NAMESPACE_END
#endif
/**
* Formats a date/time range using the conventions established for the
* UDateIntervalFormat object.
* @param formatter
* The UDateIntervalFormat object specifying the format conventions.
* @param fromDate
* The starting point of the range.
* @param toDate
* The ending point of the range.
* @param result
* A pointer to a buffer to receive the formatted range.
* @param resultCapacity
* The maximum size of result.
* @param position
* A pointer to a UFieldPosition. On input, position->field is read.
* On output, position->beginIndex and position->endIndex indicate
* the beginning and ending indices of field number position->field,
* if such a field exists. This parameter may be NULL, in which case
* no field position data is returned.
* There may be multiple instances of a given field type in an
* interval format; in this case the position indices refer to the
* first instance.
* @param status
* A pointer to a UErrorCode to receive any errors.
* @return
* The total buffer size needed; if greater than resultLength, the
* output was truncated.
* @stable ICU 4.8
*/
U_CAPI int32_t U_EXPORT2
udtitvfmt_format(const UDateIntervalFormat* formatter,
UDate fromDate,
UDate toDate,
UChar* result,
int32_t resultCapacity,
UFieldPosition* position,
UErrorCode* status);
/**
* Formats a date/time range using the conventions established for the
* UDateIntervalFormat object.
* @param formatter
* The UDateIntervalFormat object specifying the format conventions.
* @param fromDate
* The starting point of the range.
* @param toDate
* The ending point of the range.
* @param result
* The UFormattedDateInterval to contain the result of the
* formatting operation.
* @param status
* A pointer to a UErrorCode to receive any errors.
* @stable ICU 67
*/
U_CAPI void U_EXPORT2
udtitvfmt_formatToResult(
const UDateIntervalFormat* formatter,
UDate fromDate,
UDate toDate,
UFormattedDateInterval* result,
UErrorCode* status);
/**
* Formats a date/time range using the conventions established for the
* UDateIntervalFormat object.
* @param formatter
* The UDateIntervalFormat object specifying the format conventions.
* @param fromCalendar
* The starting point of the range.
* @param toCalendar
* The ending point of the range.
* @param result
* The UFormattedDateInterval to contain the result of the
* formatting operation.
* @param status
* A pointer to a UErrorCode to receive any errors.
* @stable ICU 67
*/
U_CAPI void U_EXPORT2
udtitvfmt_formatCalendarToResult(
const UDateIntervalFormat* formatter,
UCalendar* fromCalendar,
UCalendar* toCalendar,
UFormattedDateInterval* result,
UErrorCode* status);
/**
* Set a particular UDisplayContext value in the formatter, such as
* UDISPCTX_CAPITALIZATION_FOR_STANDALONE. This causes the formatted
* result to be capitalized appropriately for the context in which
* it is intended to be used, considering both the locale and the
* type of field at the beginning of the formatted result.
* @param formatter The formatter for which to set a UDisplayContext value.
* @param value The UDisplayContext value to set.
* @param status A pointer to an UErrorCode to receive any errors
* @stable ICU 68
*/
U_CAPI void U_EXPORT2
udtitvfmt_setContext(UDateIntervalFormat* formatter, UDisplayContext value, UErrorCode* status);
/**
* Get the formatter's UDisplayContext value for the specified UDisplayContextType,
* such as UDISPCTX_TYPE_CAPITALIZATION.
* @param formatter The formatter to query.
* @param type The UDisplayContextType whose value to return
* @param status A pointer to an UErrorCode to receive any errors
* @return The UDisplayContextValue for the specified type.
* @stable ICU 68
*/
U_CAPI UDisplayContext U_EXPORT2
udtitvfmt_getContext(const UDateIntervalFormat* formatter, UDisplayContextType type, UErrorCode* status);
#endif /* #if !UCONFIG_NO_FORMATTING */
#endif

View File

@ -0,0 +1,751 @@
// © 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
/*
*******************************************************************************
*
* Copyright (C) 2007-2015, International Business Machines
* Corporation and others. All Rights Reserved.
*
*******************************************************************************
* file name: udatpg.h
* encoding: UTF-8
* tab size: 8 (not used)
* indentation:4
*
* created on: 2007jul30
* created by: Markus W. Scherer
*/
#ifndef __UDATPG_H__
#define __UDATPG_H__
#include "unicode/utypes.h"
#include "unicode/udat.h"
#include "unicode/uenum.h"
#if U_SHOW_CPLUSPLUS_API
#include "unicode/localpointer.h"
#endif // U_SHOW_CPLUSPLUS_API
/**
* \file
* \brief C API: Wrapper for icu::DateTimePatternGenerator (unicode/dtptngen.h).
*
* UDateTimePatternGenerator provides flexible generation of date format patterns,
* like "yy-MM-dd". The user can build up the generator by adding successive
* patterns. Once that is done, a query can be made using a "skeleton", which is
* a pattern which just includes the desired fields and lengths. The generator
* will return the "best fit" pattern corresponding to that skeleton.
* <p>The main method people will use is udatpg_getBestPattern, since normally
* UDateTimePatternGenerator is pre-built with data from a particular locale.
* However, generators can be built directly from other data as well.
* <p><i>Issue: may be useful to also have a function that returns the list of
* fields in a pattern, in order, since we have that internally.
* That would be useful for getting the UI order of field elements.</i>
*/
/**
* Opaque type for a date/time pattern generator object.
* @stable ICU 3.8
*/
typedef void *UDateTimePatternGenerator;
/**
* Field number constants for udatpg_getAppendItemFormats() and similar functions.
* These constants are separate from UDateFormatField despite semantic overlap
* because some fields are merged for the date/time pattern generator.
* @stable ICU 3.8
*/
typedef enum UDateTimePatternField {
/** @stable ICU 3.8 */
UDATPG_ERA_FIELD,
/** @stable ICU 3.8 */
UDATPG_YEAR_FIELD,
/** @stable ICU 3.8 */
UDATPG_QUARTER_FIELD,
/** @stable ICU 3.8 */
UDATPG_MONTH_FIELD,
/** @stable ICU 3.8 */
UDATPG_WEEK_OF_YEAR_FIELD,
/** @stable ICU 3.8 */
UDATPG_WEEK_OF_MONTH_FIELD,
/** @stable ICU 3.8 */
UDATPG_WEEKDAY_FIELD,
/** @stable ICU 3.8 */
UDATPG_DAY_OF_YEAR_FIELD,
/** @stable ICU 3.8 */
UDATPG_DAY_OF_WEEK_IN_MONTH_FIELD,
/** @stable ICU 3.8 */
UDATPG_DAY_FIELD,
/** @stable ICU 3.8 */
UDATPG_DAYPERIOD_FIELD,
/** @stable ICU 3.8 */
UDATPG_HOUR_FIELD,
/** @stable ICU 3.8 */
UDATPG_MINUTE_FIELD,
/** @stable ICU 3.8 */
UDATPG_SECOND_FIELD,
/** @stable ICU 3.8 */
UDATPG_FRACTIONAL_SECOND_FIELD,
/** @stable ICU 3.8 */
UDATPG_ZONE_FIELD,
/* Do not conditionalize the following with #ifndef U_HIDE_DEPRECATED_API,
* it is needed for layout of DateTimePatternGenerator object. */
#ifndef U_FORCE_HIDE_DEPRECATED_API
/**
* One more than the highest normal UDateTimePatternField value.
* @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420.
*/
UDATPG_FIELD_COUNT
#endif // U_FORCE_HIDE_DEPRECATED_API
} UDateTimePatternField;
/**
* Field display name width constants for udatpg_getFieldDisplayName().
* @stable ICU 61
*/
typedef enum UDateTimePGDisplayWidth {
/** @stable ICU 61 */
UDATPG_WIDE,
/** @stable ICU 61 */
UDATPG_ABBREVIATED,
/** @stable ICU 61 */
UDATPG_NARROW
} UDateTimePGDisplayWidth;
/**
* Masks to control forcing the length of specified fields in the returned
* pattern to match those in the skeleton (when this would not happen
* otherwise). These may be combined to force the length of multiple fields.
* Used with udatpg_getBestPatternWithOptions, udatpg_replaceFieldTypesWithOptions.
* @stable ICU 4.4
*/
typedef enum UDateTimePatternMatchOptions {
/** @stable ICU 4.4 */
UDATPG_MATCH_NO_OPTIONS = 0,
/** @stable ICU 4.4 */
UDATPG_MATCH_HOUR_FIELD_LENGTH = 1 << UDATPG_HOUR_FIELD,
#ifndef U_HIDE_INTERNAL_API
/** @internal ICU 4.4 */
UDATPG_MATCH_MINUTE_FIELD_LENGTH = 1 << UDATPG_MINUTE_FIELD,
/** @internal ICU 4.4 */
UDATPG_MATCH_SECOND_FIELD_LENGTH = 1 << UDATPG_SECOND_FIELD,
#endif /* U_HIDE_INTERNAL_API */
/** @stable ICU 4.4 */
UDATPG_MATCH_ALL_FIELDS_LENGTH = (1 << UDATPG_FIELD_COUNT) - 1
} UDateTimePatternMatchOptions;
/**
* Status return values from udatpg_addPattern().
* @stable ICU 3.8
*/
typedef enum UDateTimePatternConflict {
/** @stable ICU 3.8 */
UDATPG_NO_CONFLICT,
/** @stable ICU 3.8 */
UDATPG_BASE_CONFLICT,
/** @stable ICU 3.8 */
UDATPG_CONFLICT,
#ifndef U_HIDE_DEPRECATED_API
/**
* One more than the highest normal UDateTimePatternConflict value.
* @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420.
*/
UDATPG_CONFLICT_COUNT
#endif // U_HIDE_DEPRECATED_API
} UDateTimePatternConflict;
/**
* Open a generator according to a given locale.
* @param locale
* @param pErrorCode a pointer to the UErrorCode which must not indicate a
* failure before the function call.
* @return a pointer to UDateTimePatternGenerator.
* @stable ICU 3.8
*/
U_CAPI UDateTimePatternGenerator * U_EXPORT2
udatpg_open(const char *locale, UErrorCode *pErrorCode);
/**
* Open an empty generator, to be constructed with udatpg_addPattern(...) etc.
* @param pErrorCode a pointer to the UErrorCode which must not indicate a
* failure before the function call.
* @return a pointer to UDateTimePatternGenerator.
* @stable ICU 3.8
*/
U_CAPI UDateTimePatternGenerator * U_EXPORT2
udatpg_openEmpty(UErrorCode *pErrorCode);
/**
* Close a generator.
* @param dtpg a pointer to UDateTimePatternGenerator.
* @stable ICU 3.8
*/
U_CAPI void U_EXPORT2
udatpg_close(UDateTimePatternGenerator *dtpg);
#if U_SHOW_CPLUSPLUS_API
U_NAMESPACE_BEGIN
/**
* \class LocalUDateTimePatternGeneratorPointer
* "Smart pointer" class, closes a UDateTimePatternGenerator via udatpg_close().
* For most methods see the LocalPointerBase base class.
*
* @see LocalPointerBase
* @see LocalPointer
* @stable ICU 4.4
*/
U_DEFINE_LOCAL_OPEN_POINTER(LocalUDateTimePatternGeneratorPointer, UDateTimePatternGenerator, udatpg_close);
U_NAMESPACE_END
#endif
/**
* Create a copy pf a generator.
* @param dtpg a pointer to UDateTimePatternGenerator to be copied.
* @param pErrorCode a pointer to the UErrorCode which must not indicate a
* failure before the function call.
* @return a pointer to a new UDateTimePatternGenerator.
* @stable ICU 3.8
*/
U_CAPI UDateTimePatternGenerator * U_EXPORT2
udatpg_clone(const UDateTimePatternGenerator *dtpg, UErrorCode *pErrorCode);
/**
* Get the best pattern matching the input skeleton. It is guaranteed to
* have all of the fields in the skeleton.
*
* Note that this function uses a non-const UDateTimePatternGenerator:
* It uses a stateful pattern parser which is set up for each generator object,
* rather than creating one for each function call.
* Consecutive calls to this function do not affect each other,
* but this function cannot be used concurrently on a single generator object.
*
* @param dtpg a pointer to UDateTimePatternGenerator.
* @param skeleton
* The skeleton is a pattern containing only the variable fields.
* For example, "MMMdd" and "mmhh" are skeletons.
* @param length the length of skeleton
* @param bestPattern
* The best pattern found from the given skeleton.
* @param capacity the capacity of bestPattern.
* @param pErrorCode a pointer to the UErrorCode which must not indicate a
* failure before the function call.
* @return the length of bestPattern.
* @stable ICU 3.8
*/
U_CAPI int32_t U_EXPORT2
udatpg_getBestPattern(UDateTimePatternGenerator *dtpg,
const UChar *skeleton, int32_t length,
UChar *bestPattern, int32_t capacity,
UErrorCode *pErrorCode);
/**
* Get the best pattern matching the input skeleton. It is guaranteed to
* have all of the fields in the skeleton.
*
* Note that this function uses a non-const UDateTimePatternGenerator:
* It uses a stateful pattern parser which is set up for each generator object,
* rather than creating one for each function call.
* Consecutive calls to this function do not affect each other,
* but this function cannot be used concurrently on a single generator object.
*
* @param dtpg a pointer to UDateTimePatternGenerator.
* @param skeleton
* The skeleton is a pattern containing only the variable fields.
* For example, "MMMdd" and "mmhh" are skeletons.
* @param length the length of skeleton
* @param options
* Options for forcing the length of specified fields in the
* returned pattern to match those in the skeleton (when this
* would not happen otherwise). For default behavior, use
* UDATPG_MATCH_NO_OPTIONS.
* @param bestPattern
* The best pattern found from the given skeleton.
* @param capacity
* the capacity of bestPattern.
* @param pErrorCode
* a pointer to the UErrorCode which must not indicate a
* failure before the function call.
* @return the length of bestPattern.
* @stable ICU 4.4
*/
U_CAPI int32_t U_EXPORT2
udatpg_getBestPatternWithOptions(UDateTimePatternGenerator *dtpg,
const UChar *skeleton, int32_t length,
UDateTimePatternMatchOptions options,
UChar *bestPattern, int32_t capacity,
UErrorCode *pErrorCode);
/**
* Get a unique skeleton from a given pattern. For example,
* both "MMM-dd" and "dd/MMM" produce the skeleton "MMMdd".
*
* Note that this function uses a non-const UDateTimePatternGenerator:
* It uses a stateful pattern parser which is set up for each generator object,
* rather than creating one for each function call.
* Consecutive calls to this function do not affect each other,
* but this function cannot be used concurrently on a single generator object.
*
* @param unusedDtpg a pointer to UDateTimePatternGenerator.
* This parameter is no longer used. Callers may pass NULL.
* @param pattern input pattern, such as "dd/MMM".
* @param length the length of pattern.
* @param skeleton such as "MMMdd"
* @param capacity the capacity of skeleton.
* @param pErrorCode a pointer to the UErrorCode which must not indicate a
* failure before the function call.
* @return the length of skeleton.
* @stable ICU 3.8
*/
U_CAPI int32_t U_EXPORT2
udatpg_getSkeleton(UDateTimePatternGenerator *unusedDtpg,
const UChar *pattern, int32_t length,
UChar *skeleton, int32_t capacity,
UErrorCode *pErrorCode);
/**
* Get a unique base skeleton from a given pattern. This is the same
* as the skeleton, except that differences in length are minimized so
* as to only preserve the difference between string and numeric form. So
* for example, both "MMM-dd" and "d/MMM" produce the skeleton "MMMd"
* (notice the single d).
*
* Note that this function uses a non-const UDateTimePatternGenerator:
* It uses a stateful pattern parser which is set up for each generator object,
* rather than creating one for each function call.
* Consecutive calls to this function do not affect each other,
* but this function cannot be used concurrently on a single generator object.
*
* @param unusedDtpg a pointer to UDateTimePatternGenerator.
* This parameter is no longer used. Callers may pass NULL.
* @param pattern input pattern, such as "dd/MMM".
* @param length the length of pattern.
* @param baseSkeleton such as "Md"
* @param capacity the capacity of base skeleton.
* @param pErrorCode a pointer to the UErrorCode which must not indicate a
* failure before the function call.
* @return the length of baseSkeleton.
* @stable ICU 3.8
*/
U_CAPI int32_t U_EXPORT2
udatpg_getBaseSkeleton(UDateTimePatternGenerator *unusedDtpg,
const UChar *pattern, int32_t length,
UChar *baseSkeleton, int32_t capacity,
UErrorCode *pErrorCode);
/**
* Adds a pattern to the generator. If the pattern has the same skeleton as
* an existing pattern, and the override parameter is set, then the previous
* value is overridden. Otherwise, the previous value is retained. In either
* case, the conflicting status is set and previous vale is stored in
* conflicting pattern.
* <p>
* Note that single-field patterns (like "MMM") are automatically added, and
* don't need to be added explicitly!
*
* @param dtpg a pointer to UDateTimePatternGenerator.
* @param pattern input pattern, such as "dd/MMM"
* @param patternLength the length of pattern.
* @param override When existing values are to be overridden use true,
* otherwise use false.
* @param conflictingPattern Previous pattern with the same skeleton.
* @param capacity the capacity of conflictingPattern.
* @param pLength a pointer to the length of conflictingPattern.
* @param pErrorCode a pointer to the UErrorCode which must not indicate a
* failure before the function call.
* @return conflicting status. The value could be UDATPG_NO_CONFLICT,
* UDATPG_BASE_CONFLICT or UDATPG_CONFLICT.
* @stable ICU 3.8
*/
U_CAPI UDateTimePatternConflict U_EXPORT2
udatpg_addPattern(UDateTimePatternGenerator *dtpg,
const UChar *pattern, int32_t patternLength,
UBool override,
UChar *conflictingPattern, int32_t capacity, int32_t *pLength,
UErrorCode *pErrorCode);
/**
* An AppendItem format is a pattern used to append a field if there is no
* good match. For example, suppose that the input skeleton is "GyyyyMMMd",
* and there is no matching pattern internally, but there is a pattern
* matching "yyyyMMMd", say "d-MM-yyyy". Then that pattern is used, plus the
* G. The way these two are conjoined is by using the AppendItemFormat for G
* (era). So if that value is, say "{0}, {1}" then the final resulting
* pattern is "d-MM-yyyy, G".
* <p>
* There are actually three available variables: {0} is the pattern so far,
* {1} is the element we are adding, and {2} is the name of the element.
* <p>
* This reflects the way that the CLDR data is organized.
*
* @param dtpg a pointer to UDateTimePatternGenerator.
* @param field UDateTimePatternField, such as UDATPG_ERA_FIELD
* @param value pattern, such as "{0}, {1}"
* @param length the length of value.
* @stable ICU 3.8
*/
U_CAPI void U_EXPORT2
udatpg_setAppendItemFormat(UDateTimePatternGenerator *dtpg,
UDateTimePatternField field,
const UChar *value, int32_t length);
/**
* Getter corresponding to setAppendItemFormat. Values below 0 or at or
* above UDATPG_FIELD_COUNT are illegal arguments.
*
* @param dtpg A pointer to UDateTimePatternGenerator.
* @param field UDateTimePatternField, such as UDATPG_ERA_FIELD
* @param pLength A pointer that will receive the length of appendItemFormat.
* @return appendItemFormat for field.
* @stable ICU 3.8
*/
U_CAPI const UChar * U_EXPORT2
udatpg_getAppendItemFormat(const UDateTimePatternGenerator *dtpg,
UDateTimePatternField field,
int32_t *pLength);
/**
* Set the name of field, eg "era" in English for ERA. These are only
* used if the corresponding AppendItemFormat is used, and if it contains a
* {2} variable.
* <p>
* This reflects the way that the CLDR data is organized.
*
* @param dtpg a pointer to UDateTimePatternGenerator.
* @param field UDateTimePatternField
* @param value name for the field.
* @param length the length of value.
* @stable ICU 3.8
*/
U_CAPI void U_EXPORT2
udatpg_setAppendItemName(UDateTimePatternGenerator *dtpg,
UDateTimePatternField field,
const UChar *value, int32_t length);
/**
* Getter corresponding to setAppendItemNames. Values below 0 or at or above
* UDATPG_FIELD_COUNT are illegal arguments. Note: The more general function
* for getting date/time field display names is udatpg_getFieldDisplayName.
*
* @param dtpg a pointer to UDateTimePatternGenerator.
* @param field UDateTimePatternField, such as UDATPG_ERA_FIELD
* @param pLength A pointer that will receive the length of the name for field.
* @return name for field
* @see udatpg_getFieldDisplayName
* @stable ICU 3.8
*/
U_CAPI const UChar * U_EXPORT2
udatpg_getAppendItemName(const UDateTimePatternGenerator *dtpg,
UDateTimePatternField field,
int32_t *pLength);
/**
* The general interface to get a display name for a particular date/time field,
* in one of several possible display widths.
*
* @param dtpg
* A pointer to the UDateTimePatternGenerator object with the localized
* display names.
* @param field
* The desired UDateTimePatternField, such as UDATPG_ERA_FIELD.
* @param width
* The desired UDateTimePGDisplayWidth, such as UDATPG_ABBREVIATED.
* @param fieldName
* A pointer to a buffer to receive the NULL-terminated display name. If the name
* fits into fieldName but cannot be NULL-terminated (length == capacity) then
* the error code is set to U_STRING_NOT_TERMINATED_WARNING. If the name doesn't
* fit into fieldName then the error code is set to U_BUFFER_OVERFLOW_ERROR.
* @param capacity
* The size of fieldName (in UChars).
* @param pErrorCode
* A pointer to a UErrorCode to receive any errors
* @return
* The full length of the name; if greater than capacity, fieldName contains a
* truncated result.
* @stable ICU 61
*/
U_CAPI int32_t U_EXPORT2
udatpg_getFieldDisplayName(const UDateTimePatternGenerator *dtpg,
UDateTimePatternField field,
UDateTimePGDisplayWidth width,
UChar *fieldName, int32_t capacity,
UErrorCode *pErrorCode);
/**
* The DateTimeFormat is a message format pattern used to compose date and
* time patterns. The default pattern in the root locale is "{1} {0}", where
* {1} will be replaced by the date pattern and {0} will be replaced by the
* time pattern; however, other locales may specify patterns such as
* "{1}, {0}" or "{1} 'at' {0}", etc.
* <p>
* This is used when the input skeleton contains both date and time fields,
* but there is not a close match among the added patterns. For example,
* suppose that this object was created by adding "dd-MMM" and "hh:mm", and
* its DateTimeFormat is the default "{1} {0}". Then if the input skeleton
* is "MMMdhmm", there is not an exact match, so the input skeleton is
* broken up into two components "MMMd" and "hmm". There are close matches
* for those two skeletons, so the result is put together with this pattern,
* resulting in "d-MMM h:mm".
*
* There are four DateTimeFormats in a UDateTimePatternGenerator object,
* corresponding to date styles UDAT_FULL..UDAT_SHORT. This method sets
* all of them to the specified pattern. To set them individually, see
* udatpg_setDateTimeFormatForStyle.
*
* @param dtpg a pointer to UDateTimePatternGenerator.
* @param dtFormat
* message format pattern, here {1} will be replaced by the date
* pattern and {0} will be replaced by the time pattern.
* @param length the length of dtFormat.
* @stable ICU 3.8
*/
U_CAPI void U_EXPORT2
udatpg_setDateTimeFormat(const UDateTimePatternGenerator *dtpg,
const UChar *dtFormat, int32_t length);
/**
* Getter corresponding to setDateTimeFormat.
*
* There are four DateTimeFormats in a UDateTimePatternGenerator object,
* corresponding to date styles UDAT_FULL..UDAT_SHORT. This method gets
* the style for UDAT_MEDIUM (the default). To get them individually, see
* udatpg_getDateTimeFormatForStyle.
*
* @param dtpg a pointer to UDateTimePatternGenerator.
* @param pLength A pointer that will receive the length of the format
* @return dateTimeFormat.
* @stable ICU 3.8
*/
U_CAPI const UChar * U_EXPORT2
udatpg_getDateTimeFormat(const UDateTimePatternGenerator *dtpg,
int32_t *pLength);
#if !UCONFIG_NO_FORMATTING
/**
* dateTimeFormats are message patterns used to compose combinations of date
* and time patterns. There are four length styles, corresponding to the
* inferred style of the date pattern; these are UDateFormatStyle values:
* - UDAT_FULL (for date pattern with weekday and long month), else
* - UDAT_LONG (for a date pattern with long month), else
* - UDAT_MEDIUM (for a date pattern with abbreviated month), else
* - UDAT_SHORT (for any other date pattern).
* For details on dateTimeFormats, see
* https://www.unicode.org/reports/tr35/tr35-dates.html#dateTimeFormats.
* The default pattern in the root locale for all styles is "{1} {0}".
*
* @param udtpg
* a pointer to the UDateTimePatternGenerator
* @param style
* one of UDAT_FULL..UDAT_SHORT. Error if out of range.
* @param dateTimeFormat
* the new dateTimeFormat to set for the the specified style
* @param length
* the length of dateTimeFormat, or -1 if unknown and pattern
* is null-terminated
* @param pErrorCode
* a pointer to the UErrorCode (in/out parameter); if no failure
* status is already set, it will be set according to result of the
* function (e.g. U_ILLEGAL_ARGUMENT_ERROR for style out of range).
* @stable ICU 71
*/
U_CAPI void U_EXPORT2
udatpg_setDateTimeFormatForStyle(UDateTimePatternGenerator *udtpg,
UDateFormatStyle style,
const UChar *dateTimeFormat, int32_t length,
UErrorCode *pErrorCode);
/**
* Getter corresponding to udatpg_setDateTimeFormatForStyle.
*
* @param udtpg
* a pointer to the UDateTimePatternGenerator
* @param style
* one of UDAT_FULL..UDAT_SHORT. Error if out of range.
* @param pLength
* a pointer that will receive the length of the format. May be NULL
* if length is not desired.
* @param pErrorCode
* a pointer to the UErrorCode (in/out parameter); if no failure
* status is already set, it will be set according to result of the
* function (e.g. U_ILLEGAL_ARGUMENT_ERROR for style out of range).
* @return
* pointer to the current dateTimeFormat (0 terminated) for the specified
* style, or empty string in case of error. The pointer and its contents
* may no longer be valid if udatpg_setDateTimeFormat is called, or
* udatpg_setDateTimeFormatForStyle for the same style is called, or the
* UDateTimePatternGenerator object is closed.
* @stable ICU 71
*/
U_CAPI const UChar* U_EXPORT2
udatpg_getDateTimeFormatForStyle(const UDateTimePatternGenerator *udtpg,
UDateFormatStyle style, int32_t *pLength,
UErrorCode *pErrorCode);
#endif /* #if !UCONFIG_NO_FORMATTING */
/**
* The decimal value is used in formatting fractions of seconds. If the
* skeleton contains fractional seconds, then this is used with the
* fractional seconds. For example, suppose that the input pattern is
* "hhmmssSSSS", and the best matching pattern internally is "H:mm:ss", and
* the decimal string is ",". Then the resulting pattern is modified to be
* "H:mm:ss,SSSS"
*
* @param dtpg a pointer to UDateTimePatternGenerator.
* @param decimal
* @param length the length of decimal.
* @stable ICU 3.8
*/
U_CAPI void U_EXPORT2
udatpg_setDecimal(UDateTimePatternGenerator *dtpg,
const UChar *decimal, int32_t length);
/**
* Getter corresponding to setDecimal.
*
* @param dtpg a pointer to UDateTimePatternGenerator.
* @param pLength A pointer that will receive the length of the decimal string.
* @return corresponding to the decimal point.
* @stable ICU 3.8
*/
U_CAPI const UChar * U_EXPORT2
udatpg_getDecimal(const UDateTimePatternGenerator *dtpg,
int32_t *pLength);
/**
* Adjusts the field types (width and subtype) of a pattern to match what is
* in a skeleton. That is, if you supply a pattern like "d-M H:m", and a
* skeleton of "MMMMddhhmm", then the input pattern is adjusted to be
* "dd-MMMM hh:mm". This is used internally to get the best match for the
* input skeleton, but can also be used externally.
*
* Note that this function uses a non-const UDateTimePatternGenerator:
* It uses a stateful pattern parser which is set up for each generator object,
* rather than creating one for each function call.
* Consecutive calls to this function do not affect each other,
* but this function cannot be used concurrently on a single generator object.
*
* @param dtpg a pointer to UDateTimePatternGenerator.
* @param pattern Input pattern
* @param patternLength the length of input pattern.
* @param skeleton
* @param skeletonLength the length of input skeleton.
* @param dest pattern adjusted to match the skeleton fields widths and subtypes.
* @param destCapacity the capacity of dest.
* @param pErrorCode a pointer to the UErrorCode which must not indicate a
* failure before the function call.
* @return the length of dest.
* @stable ICU 3.8
*/
U_CAPI int32_t U_EXPORT2
udatpg_replaceFieldTypes(UDateTimePatternGenerator *dtpg,
const UChar *pattern, int32_t patternLength,
const UChar *skeleton, int32_t skeletonLength,
UChar *dest, int32_t destCapacity,
UErrorCode *pErrorCode);
/**
* Adjusts the field types (width and subtype) of a pattern to match what is
* in a skeleton. That is, if you supply a pattern like "d-M H:m", and a
* skeleton of "MMMMddhhmm", then the input pattern is adjusted to be
* "dd-MMMM hh:mm". This is used internally to get the best match for the
* input skeleton, but can also be used externally.
*
* Note that this function uses a non-const UDateTimePatternGenerator:
* It uses a stateful pattern parser which is set up for each generator object,
* rather than creating one for each function call.
* Consecutive calls to this function do not affect each other,
* but this function cannot be used concurrently on a single generator object.
*
* @param dtpg a pointer to UDateTimePatternGenerator.
* @param pattern Input pattern
* @param patternLength the length of input pattern.
* @param skeleton
* @param skeletonLength the length of input skeleton.
* @param options
* Options controlling whether the length of specified fields in the
* pattern are adjusted to match those in the skeleton (when this
* would not happen otherwise). For default behavior, use
* UDATPG_MATCH_NO_OPTIONS.
* @param dest pattern adjusted to match the skeleton fields widths and subtypes.
* @param destCapacity the capacity of dest.
* @param pErrorCode a pointer to the UErrorCode which must not indicate a
* failure before the function call.
* @return the length of dest.
* @stable ICU 4.4
*/
U_CAPI int32_t U_EXPORT2
udatpg_replaceFieldTypesWithOptions(UDateTimePatternGenerator *dtpg,
const UChar *pattern, int32_t patternLength,
const UChar *skeleton, int32_t skeletonLength,
UDateTimePatternMatchOptions options,
UChar *dest, int32_t destCapacity,
UErrorCode *pErrorCode);
/**
* Return a UEnumeration list of all the skeletons in canonical form.
* Call udatpg_getPatternForSkeleton() to get the corresponding pattern.
*
* @param dtpg a pointer to UDateTimePatternGenerator.
* @param pErrorCode a pointer to the UErrorCode which must not indicate a
* failure before the function call
* @return a UEnumeration list of all the skeletons
* The caller must close the object.
* @stable ICU 3.8
*/
U_CAPI UEnumeration * U_EXPORT2
udatpg_openSkeletons(const UDateTimePatternGenerator *dtpg, UErrorCode *pErrorCode);
/**
* Return a UEnumeration list of all the base skeletons in canonical form.
*
* @param dtpg a pointer to UDateTimePatternGenerator.
* @param pErrorCode a pointer to the UErrorCode which must not indicate a
* failure before the function call.
* @return a UEnumeration list of all the base skeletons
* The caller must close the object.
* @stable ICU 3.8
*/
U_CAPI UEnumeration * U_EXPORT2
udatpg_openBaseSkeletons(const UDateTimePatternGenerator *dtpg, UErrorCode *pErrorCode);
/**
* Get the pattern corresponding to a given skeleton.
*
* @param dtpg a pointer to UDateTimePatternGenerator.
* @param skeleton
* @param skeletonLength pointer to the length of skeleton.
* @param pLength pointer to the length of return pattern.
* @return pattern corresponding to a given skeleton.
* @stable ICU 3.8
*/
U_CAPI const UChar * U_EXPORT2
udatpg_getPatternForSkeleton(const UDateTimePatternGenerator *dtpg,
const UChar *skeleton, int32_t skeletonLength,
int32_t *pLength);
#if !UCONFIG_NO_FORMATTING
/**
* Return the default hour cycle for a locale. Uses the locale that the
* UDateTimePatternGenerator was initially created with.
*
* Cannot be used on an empty UDateTimePatternGenerator instance.
*
* @param dtpg a pointer to UDateTimePatternGenerator.
* @param pErrorCode a pointer to the UErrorCode which must not indicate a
* failure before the function call. Set to U_UNSUPPORTED_ERROR
* if used on an empty instance.
* @return the default hour cycle.
* @stable ICU 67
*/
U_CAPI UDateFormatHourCycle U_EXPORT2
udatpg_getDefaultHourCycle(const UDateTimePatternGenerator *dtpg, UErrorCode* pErrorCode);
#endif /* #if !UCONFIG_NO_FORMATTING */
#endif

View File

@ -0,0 +1,321 @@
// © 2022 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
#ifndef __UDISPLAYOPTIONS_H__
#define __UDISPLAYOPTIONS_H__
#include "unicode/utypes.h"
#if !UCONFIG_NO_FORMATTING
/**
* \file
* \brief C API: Display options (enum types, values, helper functions)
*
* These display options are designed to be used in class DisplayOptions
* as a more modern version of the UDisplayContext mechanism.
*/
#include "unicode/uversion.h"
/**
* Represents all the grammatical cases that are supported by CLDR.
*
* @stable ICU 72
*/
typedef enum UDisplayOptionsGrammaticalCase {
/**
* A possible setting for GrammaticalCase.
* The grammatical case context to be used is unknown (this is the default value).
* @stable ICU 72
*/
UDISPOPT_GRAMMATICAL_CASE_UNDEFINED = 0,
/** @stable ICU 72 */
UDISPOPT_GRAMMATICAL_CASE_ABLATIVE = 1,
/** @stable ICU 72 */
UDISPOPT_GRAMMATICAL_CASE_ACCUSATIVE = 2,
/** @stable ICU 72 */
UDISPOPT_GRAMMATICAL_CASE_COMITATIVE = 3,
/** @stable ICU 72 */
UDISPOPT_GRAMMATICAL_CASE_DATIVE = 4,
/** @stable ICU 72 */
UDISPOPT_GRAMMATICAL_CASE_ERGATIVE = 5,
/** @stable ICU 72 */
UDISPOPT_GRAMMATICAL_CASE_GENITIVE = 6,
/** @stable ICU 72 */
UDISPOPT_GRAMMATICAL_CASE_INSTRUMENTAL = 7,
/** @stable ICU 72 */
UDISPOPT_GRAMMATICAL_CASE_LOCATIVE = 8,
/** @stable ICU 72 */
UDISPOPT_GRAMMATICAL_CASE_LOCATIVE_COPULATIVE = 9,
/** @stable ICU 72 */
UDISPOPT_GRAMMATICAL_CASE_NOMINATIVE = 10,
/** @stable ICU 72 */
UDISPOPT_GRAMMATICAL_CASE_OBLIQUE = 11,
/** @stable ICU 72 */
UDISPOPT_GRAMMATICAL_CASE_PREPOSITIONAL = 12,
/** @stable ICU 72 */
UDISPOPT_GRAMMATICAL_CASE_SOCIATIVE = 13,
/** @stable ICU 72 */
UDISPOPT_GRAMMATICAL_CASE_VOCATIVE = 14,
} UDisplayOptionsGrammaticalCase;
/**
* @param grammaticalCase The grammatical case.
* @return the lowercase CLDR keyword string for the grammatical case.
*
* @stable ICU 72
*/
U_CAPI const char * U_EXPORT2
udispopt_getGrammaticalCaseIdentifier(UDisplayOptionsGrammaticalCase grammaticalCase);
/**
* @param identifier in lower case such as "dative" or "nominative"
* @return the plural category corresponding to the identifier, or `UDISPOPT_GRAMMATICAL_CASE_UNDEFINED`
*
* @stable ICU 72
*/
U_CAPI UDisplayOptionsGrammaticalCase U_EXPORT2
udispopt_fromGrammaticalCaseIdentifier(const char *identifier);
/**
* Standard CLDR plural form/category constants.
* See https://www.unicode.org/reports/tr35/tr35-numbers.html#Language_Plural_Rules
*
* @stable ICU 72
*/
typedef enum UDisplayOptionsPluralCategory {
/**
* A possible setting for PluralCategory.
* The plural category case context to be used is unknown (this is the default value).
*
* @stable ICU 72
*/
UDISPOPT_PLURAL_CATEGORY_UNDEFINED = 0,
/** @stable ICU 72 */
UDISPOPT_PLURAL_CATEGORY_ZERO = 1,
/** @stable ICU 72 */
UDISPOPT_PLURAL_CATEGORY_ONE = 2,
/** @stable ICU 72 */
UDISPOPT_PLURAL_CATEGORY_TWO = 3,
/** @stable ICU 72 */
UDISPOPT_PLURAL_CATEGORY_FEW = 4,
/** @stable ICU 72 */
UDISPOPT_PLURAL_CATEGORY_MANY = 5,
/** @stable ICU 72 */
UDISPOPT_PLURAL_CATEGORY_OTHER = 6,
} UDisplayOptionsPluralCategory;
/**
* @param pluralCategory The plural category.
* @return the lowercase CLDR identifier string for the plural category.
*
* @stable ICU 72
*/
U_CAPI const char * U_EXPORT2
udispopt_getPluralCategoryIdentifier(UDisplayOptionsPluralCategory pluralCategory);
/**
* @param identifier for example "few" or "other"
* @return the plural category corresponding to the identifier (plural keyword),
* or `UDISPOPT_PLURAL_CATEGORY_UNDEFINED`
*
* @stable ICU 72
*/
U_CAPI UDisplayOptionsPluralCategory U_EXPORT2
udispopt_fromPluralCategoryIdentifier(const char *identifier);
/**
* Represents all the grammatical noun classes that are supported by CLDR.
*
* @stable ICU 72.
*/
typedef enum UDisplayOptionsNounClass {
/**
* A possible setting for NounClass.
* The noun class case context to be used is unknown (this is the default value).
*
* @stable ICU 72
*/
UDISPOPT_NOUN_CLASS_UNDEFINED = 0,
/** @stable ICU 72 */
UDISPOPT_NOUN_CLASS_OTHER = 1,
/** @stable ICU 72 */
UDISPOPT_NOUN_CLASS_NEUTER = 2,
/** @stable ICU 72 */
UDISPOPT_NOUN_CLASS_FEMININE = 3,
/** @stable ICU 72 */
UDISPOPT_NOUN_CLASS_MASCULINE = 4,
/** @stable ICU 72 */
UDISPOPT_NOUN_CLASS_ANIMATE = 5,
/** @stable ICU 72 */
UDISPOPT_NOUN_CLASS_INANIMATE = 6,
/** @stable ICU 72 */
UDISPOPT_NOUN_CLASS_PERSONAL = 7,
/** @stable ICU 72 */
UDISPOPT_NOUN_CLASS_COMMON = 8,
} UDisplayOptionsNounClass;
/**
* @param nounClass The noun class.
* @return the lowercase CLDR keyword string for the noun class.
*
* @stable ICU 72
*/
U_CAPI const char * U_EXPORT2
udispopt_getNounClassIdentifier(UDisplayOptionsNounClass nounClass);
/**
* @param identifier in lower case such as "feminine" or "masculine"
* @return the plural category corresponding to the identifier, or `UDISPOPT_NOUN_CLASS_UNDEFINED`
*
* @stable ICU 72
*/
U_CAPI UDisplayOptionsNounClass U_EXPORT2
udispopt_fromNounClassIdentifier(const char *identifier);
/**
* Represents all the capitalization options.
*
* @stable ICU 72
*/
typedef enum UDisplayOptionsCapitalization {
/**
* A possible setting for Capitalization.
* The capitalization context to be used is unknown (this is the default value).
*
* @stable ICU 72
*/
UDISPOPT_CAPITALIZATION_UNDEFINED = 0,
/**
* The capitalization context if a date, date symbol or display name is to be
* formatted with capitalization appropriate for the beginning of a sentence.
*
* @stable ICU 72
*/
UDISPOPT_CAPITALIZATION_BEGINNING_OF_SENTENCE = 1,
/**
* The capitalization context if a date, date symbol or display name is to be
* formatted with capitalization appropriate for the middle of a sentence.
*
* @stable ICU 72
*/
UDISPOPT_CAPITALIZATION_MIDDLE_OF_SENTENCE = 2,
/**
* The capitalization context if a date, date symbol or display name is to be
* formatted with capitalization appropriate for stand-alone usage such as an
* isolated name on a calendar page.
*
* @stable ICU 72
*/
UDISPOPT_CAPITALIZATION_STANDALONE = 3,
/**
* The capitalization context if a date, date symbol or display name is to be
* formatted with capitalization appropriate for a user-interface list or menu item.
*
* @stable ICU 72
*/
UDISPOPT_CAPITALIZATION_UI_LIST_OR_MENU = 4,
} UDisplayOptionsCapitalization;
/**
* Represents all the dialect handlings.
*
* @stable ICU 72
*/
typedef enum UDisplayOptionsNameStyle {
/**
* A possible setting for NameStyle.
* The NameStyle context to be used is unknown (this is the default value).
*
* @stable ICU 72
*/
UDISPOPT_NAME_STYLE_UNDEFINED = 0,
/**
* Use standard names when generating a locale name,
* e.g. en_GB displays as 'English (United Kingdom)'.
*
* @stable ICU 72
*/
UDISPOPT_NAME_STYLE_STANDARD_NAMES = 1,
/**
* Use dialect names, when generating a locale name,
* e.g. en_GB displays as 'British English'.
*
* @stable ICU 72
*/
UDISPOPT_NAME_STYLE_DIALECT_NAMES = 2,
} UDisplayOptionsNameStyle;
/**
* Represents all the display lengths.
*
* @stable ICU 72
*/
typedef enum UDisplayOptionsDisplayLength {
/**
* A possible setting for DisplayLength.
* The DisplayLength context to be used is unknown (this is the default value).
*
* @stable ICU 72
*/
UDISPOPT_DISPLAY_LENGTH_UNDEFINED = 0,
/**
* Uses full names when generating a locale name,
* e.g. "United States" for US.
*
* @stable ICU 72
*/
UDISPOPT_DISPLAY_LENGTH_FULL = 1,
/**
* Use short names when generating a locale name,
* e.g. "U.S." for US.
*
* @stable ICU 72
*/
UDISPOPT_DISPLAY_LENGTH_SHORT = 2,
} UDisplayOptionsDisplayLength;
/**
* Represents all the substitute handling.
*
* @stable ICU 72
*/
typedef enum UDisplayOptionsSubstituteHandling {
/**
* A possible setting for SubstituteHandling.
* The SubstituteHandling context to be used is unknown (this is the default value).
*
* @stable ICU 72
*/
UDISPOPT_SUBSTITUTE_HANDLING_UNDEFINED = 0,
/**
* Returns a fallback value (e.g., the input code) when no data is available.
* This is the default behaviour.
*
* @stable ICU 72
*/
UDISPOPT_SUBSTITUTE_HANDLING_SUBSTITUTE = 1,
/**
* Returns a null value when no data is available.
*
* @stable ICU 72
*/
UDISPOPT_SUBSTITUTE_HANDLING_NO_SUBSTITUTE = 2,
} UDisplayOptionsSubstituteHandling;
#endif /* #if !UCONFIG_NO_FORMATTING */
#endif // __UDISPLAYOPTIONS_H__

View File

@ -0,0 +1,123 @@
// © 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
/*
*****************************************************************************************
* Copyright (C) 2015-2016, International Business Machines
* Corporation and others. All Rights Reserved.
*****************************************************************************************
*/
#ifndef UFIELDPOSITER_H
#define UFIELDPOSITER_H
#include "unicode/utypes.h"
#if !UCONFIG_NO_FORMATTING
#if U_SHOW_CPLUSPLUS_API
#include "unicode/localpointer.h"
#endif // U_SHOW_CPLUSPLUS_API
/**
* \file
* \brief C API: UFieldPositionIterator for use with format APIs.
*
* Usage:
* ufieldpositer_open creates an empty (unset) UFieldPositionIterator.
* This can be passed to format functions such as {@link #udat_formatForFields},
* which will set it to apply to the fields in a particular formatted string.
* ufieldpositer_next can then be used to iterate over those fields,
* providing for each field its type (using values that are specific to the
* particular format type, such as date or number formats), as well as the
* start and end positions of the field in the formatted string.
* A given UFieldPositionIterator can be re-used for different format calls;
* each such call resets it to apply to that format string.
* ufieldpositer_close should be called to dispose of the UFieldPositionIterator
* when it is no longer needed.
*
* @see FieldPositionIterator
*/
/**
* Opaque UFieldPositionIterator object for use in C.
* @stable ICU 55
*/
struct UFieldPositionIterator;
typedef struct UFieldPositionIterator UFieldPositionIterator; /**< C typedef for struct UFieldPositionIterator. @stable ICU 55 */
/**
* Open a new, unset UFieldPositionIterator object.
* @param status
* A pointer to a UErrorCode to receive any errors.
* @return
* A pointer to an empty (unset) UFieldPositionIterator object,
* or NULL if an error occurred.
* @stable ICU 55
*/
U_CAPI UFieldPositionIterator* U_EXPORT2
ufieldpositer_open(UErrorCode* status);
/**
* Close a UFieldPositionIterator object. Once closed it may no longer be used.
* @param fpositer
* A pointer to the UFieldPositionIterator object to close.
* @stable ICU 55
*/
U_CAPI void U_EXPORT2
ufieldpositer_close(UFieldPositionIterator *fpositer);
#if U_SHOW_CPLUSPLUS_API
U_NAMESPACE_BEGIN
/**
* \class LocalUFieldPositionIteratorPointer
* "Smart pointer" class, closes a UFieldPositionIterator via ufieldpositer_close().
* For most methods see the LocalPointerBase base class.
*
* @see LocalPointerBase
* @see LocalPointer
* @stable ICU 55
*/
U_DEFINE_LOCAL_OPEN_POINTER(LocalUFieldPositionIteratorPointer, UFieldPositionIterator, ufieldpositer_close);
U_NAMESPACE_END
#endif
/**
* Get information for the next field in the formatted string to which this
* UFieldPositionIterator currently applies, or return a negative value if there
* are no more fields.
* @param fpositer
* A pointer to the UFieldPositionIterator object containing iteration
* state for the format fields.
* @param beginIndex
* A pointer to an int32_t to receive information about the start offset
* of the field in the formatted string (undefined if the function
* returns a negative value). May be NULL if this information is not needed.
* @param endIndex
* A pointer to an int32_t to receive information about the end offset
* of the field in the formatted string (undefined if the function
* returns a negative value). May be NULL if this information is not needed.
* @return
* The field type (non-negative value), or a negative value if there are
* no more fields for which to provide information. If negative, then any
* values pointed to by beginIndex and endIndex are undefined.
*
* The values for field type depend on what type of formatter the
* UFieldPositionIterator has been set by; for a date formatter, the
* values from the UDateFormatField enum. For more information, see the
* descriptions of format functions that take a UFieldPositionIterator*
* parameter, such as {@link #udat_formatForFields}.
*
* @stable ICU 55
*/
U_CAPI int32_t U_EXPORT2
ufieldpositer_next(UFieldPositionIterator *fpositer,
int32_t *beginIndex, int32_t *endIndex);
#endif /* #if !UCONFIG_NO_FORMATTING */
#endif

View File

@ -0,0 +1,290 @@
// © 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
/*
********************************************************************************
* Copyright (C) 2013-2014, International Business Machines Corporation and others.
* All Rights Reserved.
********************************************************************************
*
* File UFORMATTABLE.H
*
* Modification History:
*
* Date Name Description
* 2013 Jun 7 srl New
********************************************************************************
*/
/**
* \file
* \brief C API: UFormattable is a thin wrapper for primitive types used for formatting and parsing.
*
* This is a C interface to the icu::Formattable class. Static functions on this class convert
* to and from this interface (via reinterpret_cast). Note that Formattables (and thus UFormattables)
* are mutable, and many operations (even getters) may actually modify the internal state. For this
* reason, UFormattables are not thread safe, and should not be shared between threads.
*
* See {@link unum_parseToUFormattable} for example code.
*/
#ifndef UFORMATTABLE_H
#define UFORMATTABLE_H
#include "unicode/utypes.h"
#if !UCONFIG_NO_FORMATTING
#if U_SHOW_CPLUSPLUS_API
#include "unicode/localpointer.h"
#endif // U_SHOW_CPLUSPLUS_API
/**
* Enum designating the type of a UFormattable instance.
* Practically, this indicates which of the getters would return without conversion
* or error.
* @see icu::Formattable::Type
* @stable ICU 52
*/
typedef enum UFormattableType {
UFMT_DATE = 0, /**< ufmt_getDate() will return without conversion. @see ufmt_getDate*/
UFMT_DOUBLE, /**< ufmt_getDouble() will return without conversion. @see ufmt_getDouble*/
UFMT_LONG, /**< ufmt_getLong() will return without conversion. @see ufmt_getLong */
UFMT_STRING, /**< ufmt_getUChars() will return without conversion. @see ufmt_getUChars*/
UFMT_ARRAY, /**< ufmt_countArray() and ufmt_getArray() will return the value. @see ufmt_getArrayItemByIndex */
UFMT_INT64, /**< ufmt_getInt64() will return without conversion. @see ufmt_getInt64 */
UFMT_OBJECT, /**< ufmt_getObject() will return without conversion. @see ufmt_getObject*/
#ifndef U_HIDE_DEPRECATED_API
/**
* One more than the highest normal UFormattableType value.
* @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420.
*/
UFMT_COUNT
#endif /* U_HIDE_DEPRECATED_API */
} UFormattableType;
/**
* Opaque type representing various types of data which may be used for formatting
* and parsing operations.
* @see icu::Formattable
* @stable ICU 52
*/
typedef void *UFormattable;
/**
* Initialize a UFormattable, to type UNUM_LONG, value 0
* may return error if memory allocation failed.
* parameter status error code.
* See {@link unum_parseToUFormattable} for example code.
* @stable ICU 52
* @return the new UFormattable
* @see ufmt_close
* @see icu::Formattable::Formattable()
*/
U_CAPI UFormattable* U_EXPORT2
ufmt_open(UErrorCode* status);
/**
* Cleanup any additional memory allocated by this UFormattable.
* @param fmt the formatter
* @stable ICU 52
* @see ufmt_open
*/
U_CAPI void U_EXPORT2
ufmt_close(UFormattable* fmt);
#if U_SHOW_CPLUSPLUS_API
U_NAMESPACE_BEGIN
/**
* \class LocalUFormattablePointer
* "Smart pointer" class, closes a UFormattable via ufmt_close().
* For most methods see the LocalPointerBase base class.
*
* @see LocalPointerBase
* @see LocalPointer
* @stable ICU 52
*/
U_DEFINE_LOCAL_OPEN_POINTER(LocalUFormattablePointer, UFormattable, ufmt_close);
U_NAMESPACE_END
#endif
/**
* Return the type of this object
* @param fmt the UFormattable object
* @param status status code - U_ILLEGAL_ARGUMENT_ERROR is returned if the UFormattable contains data not supported by
* the API
* @return the value as a UFormattableType
* @see ufmt_isNumeric
* @see icu::Formattable::getType() const
* @stable ICU 52
*/
U_CAPI UFormattableType U_EXPORT2
ufmt_getType(const UFormattable* fmt, UErrorCode *status);
/**
* Return whether the object is numeric.
* @param fmt the UFormattable object
* @return true if the object is a double, long, or int64 value, else false.
* @see ufmt_getType
* @see icu::Formattable::isNumeric() const
* @stable ICU 52
*/
U_CAPI UBool U_EXPORT2
ufmt_isNumeric(const UFormattable* fmt);
/**
* Gets the UDate value of this object. If the type is not of type UFMT_DATE,
* status is set to U_INVALID_FORMAT_ERROR and the return value is
* undefined.
* @param fmt the UFormattable object
* @param status the error code - any conversion or format errors
* @return the value
* @stable ICU 52
* @see icu::Formattable::getDate(UErrorCode&) const
*/
U_CAPI UDate U_EXPORT2
ufmt_getDate(const UFormattable* fmt, UErrorCode *status);
/**
* Gets the double value of this object. If the type is not a UFMT_DOUBLE, or
* if there are additional significant digits than fit in a double type,
* a conversion is performed with possible loss of precision.
* If the type is UFMT_OBJECT and the
* object is a Measure, then the result of
* getNumber().getDouble(status) is returned. If this object is
* neither a numeric type nor a Measure, then 0 is returned and
* the status is set to U_INVALID_FORMAT_ERROR.
* @param fmt the UFormattable object
* @param status the error code - any conversion or format errors
* @return the value
* @stable ICU 52
* @see icu::Formattable::getDouble(UErrorCode&) const
*/
U_CAPI double U_EXPORT2
ufmt_getDouble(UFormattable* fmt, UErrorCode *status);
/**
* Gets the long (int32_t) value of this object. If the magnitude is too
* large to fit in a long, then the maximum or minimum long value,
* as appropriate, is returned and the status is set to
* U_INVALID_FORMAT_ERROR. If this object is of type UFMT_INT64 and
* it fits within a long, then no precision is lost. If it is of
* type kDouble or kDecimalNumber, then a conversion is performed, with
* truncation of any fractional part. If the type is UFMT_OBJECT and
* the object is a Measure, then the result of
* getNumber().getLong(status) is returned. If this object is
* neither a numeric type nor a Measure, then 0 is returned and
* the status is set to U_INVALID_FORMAT_ERROR.
* @param fmt the UFormattable object
* @param status the error code - any conversion or format errors
* @return the value
* @stable ICU 52
* @see icu::Formattable::getLong(UErrorCode&) const
*/
U_CAPI int32_t U_EXPORT2
ufmt_getLong(UFormattable* fmt, UErrorCode *status);
/**
* Gets the int64_t value of this object. If this object is of a numeric
* type and the magnitude is too large to fit in an int64, then
* the maximum or minimum int64 value, as appropriate, is returned
* and the status is set to U_INVALID_FORMAT_ERROR. If the
* magnitude fits in an int64, then a casting conversion is
* performed, with truncation of any fractional part. If the type
* is UFMT_OBJECT and the object is a Measure, then the result of
* getNumber().getDouble(status) is returned. If this object is
* neither a numeric type nor a Measure, then 0 is returned and
* the status is set to U_INVALID_FORMAT_ERROR.
* @param fmt the UFormattable object
* @param status the error code - any conversion or format errors
* @return the value
* @stable ICU 52
* @see icu::Formattable::getInt64(UErrorCode&) const
*/
U_CAPI int64_t U_EXPORT2
ufmt_getInt64(UFormattable* fmt, UErrorCode *status);
/**
* Returns a pointer to the UObject contained within this
* formattable (as a const void*), or NULL if this object
* is not of type UFMT_OBJECT.
* @param fmt the UFormattable object
* @param status the error code - any conversion or format errors
* @return the value as a const void*. It is a polymorphic C++ object.
* @stable ICU 52
* @see icu::Formattable::getObject() const
*/
U_CAPI const void *U_EXPORT2
ufmt_getObject(const UFormattable* fmt, UErrorCode *status);
/**
* Gets the string value of this object as a UChar string. If the type is not a
* string, status is set to U_INVALID_FORMAT_ERROR and a NULL pointer is returned.
* This function is not thread safe and may modify the UFormattable if need be to terminate the string.
* The returned pointer is not valid if any other functions are called on this UFormattable, or if the UFormattable is closed.
* @param fmt the UFormattable object
* @param status the error code - any conversion or format errors
* @param len if non null, contains the string length on return
* @return the null terminated string value - must not be referenced after any other functions are called on this UFormattable.
* @stable ICU 52
* @see icu::Formattable::getString(UnicodeString&)const
*/
U_CAPI const UChar* U_EXPORT2
ufmt_getUChars(UFormattable* fmt, int32_t *len, UErrorCode *status);
/**
* Get the number of array objects contained, if an array type UFMT_ARRAY
* @param fmt the UFormattable object
* @param status the error code - any conversion or format errors. U_ILLEGAL_ARGUMENT_ERROR if not an array type.
* @return the number of array objects or undefined if not an array type
* @stable ICU 52
* @see ufmt_getArrayItemByIndex
*/
U_CAPI int32_t U_EXPORT2
ufmt_getArrayLength(const UFormattable* fmt, UErrorCode *status);
/**
* Get the specified value from the array of UFormattables. Invalid if the object is not an array type UFMT_ARRAY
* @param fmt the UFormattable object
* @param n the number of the array to return (0 based).
* @param status the error code - any conversion or format errors. Returns an error if n is out of bounds.
* @return the nth array value, only valid while the containing UFormattable is valid. NULL if not an array.
* @stable ICU 52
* @see icu::Formattable::getArray(int32_t&, UErrorCode&) const
*/
U_CAPI UFormattable * U_EXPORT2
ufmt_getArrayItemByIndex(UFormattable* fmt, int32_t n, UErrorCode *status);
/**
* Returns a numeric string representation of the number contained within this
* formattable, or NULL if this object does not contain numeric type.
* For values obtained by parsing, the returned decimal number retains
* the full precision and range of the original input, unconstrained by
* the limits of a double floating point or a 64 bit int.
*
* This function is not thread safe, and therefore is not declared const,
* even though it is logically const.
* The resulting buffer is owned by the UFormattable and is invalid if any other functions are
* called on the UFormattable.
*
* Possible errors include U_MEMORY_ALLOCATION_ERROR, and
* U_INVALID_STATE if the formattable object has not been set to
* a numeric type.
* @param fmt the UFormattable object
* @param len if non-null, on exit contains the string length (not including the terminating null)
* @param status the error code
* @return the character buffer as a NULL terminated string, which is owned by the object and must not be accessed if any other functions are called on this object.
* @stable ICU 52
* @see icu::Formattable::getDecimalNumber(UErrorCode&)
*/
U_CAPI const char * U_EXPORT2
ufmt_getDecNumChars(UFormattable *fmt, int32_t *len, UErrorCode *status);
#endif
#endif

View File

@ -0,0 +1,224 @@
// © 2022 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
#ifndef __UFORMATTEDNUMBER_H__
#define __UFORMATTEDNUMBER_H__
#include "unicode/utypes.h"
#if !UCONFIG_NO_FORMATTING
#include "unicode/ufieldpositer.h"
#include "unicode/uformattedvalue.h"
#include "unicode/umisc.h"
/**
* \file
* \brief C API: Formatted number result from various number formatting functions.
*
* Create a `UFormattedNumber` to hold the result of a number formatting operation. The same
* `UFormattedNumber` can be reused multiple times.
*
* <pre>
* LocalUFormattedNumberPointer uresult(unumf_openResult(status));
*
* // pass uresult.getAlias() to your number formatter
*
* int32_t length;
* const UChar* s = ufmtval_getString(unumf_resultAsValue(uresult.getAlias(), status), &length, status));
*
* // The string result is in `s` with the given `length` (it is also NUL-terminated).
* </pre>
*/
struct UFormattedNumber;
/**
* C-compatible version of icu::number::FormattedNumber.
*
* NOTE: This is a C-compatible API; C++ users should build against numberformatter.h instead.
*
* @stable ICU 62
*/
typedef struct UFormattedNumber UFormattedNumber;
/**
* Creates an object to hold the result of a UNumberFormatter
* operation. The object can be used repeatedly; it is cleared whenever
* passed to a format function.
*
* @param ec Set if an error occurs.
* @stable ICU 62
*/
U_CAPI UFormattedNumber* U_EXPORT2
unumf_openResult(UErrorCode* ec);
/**
* Returns a representation of a UFormattedNumber as a UFormattedValue,
* which can be subsequently passed to any API requiring that type.
*
* The returned object is owned by the UFormattedNumber and is valid
* only as long as the UFormattedNumber is present and unchanged in memory.
*
* You can think of this method as a cast between types.
*
* @param uresult The object containing the formatted string.
* @param ec Set if an error occurs.
* @return A UFormattedValue owned by the input object.
* @stable ICU 64
*/
U_CAPI const UFormattedValue* U_EXPORT2
unumf_resultAsValue(const UFormattedNumber* uresult, UErrorCode* ec);
/**
* Extracts the result number string out of a UFormattedNumber to a UChar buffer if possible.
* If bufferCapacity is greater than the required length, a terminating NUL is written.
* If bufferCapacity is less than the required length, an error code is set.
*
* Also see ufmtval_getString, which returns a NUL-terminated string:
*
* int32_t len;
* const UChar* str = ufmtval_getString(unumf_resultAsValue(uresult, &ec), &len, &ec);
*
* NOTE: This is a C-compatible API; C++ users should build against numberformatter.h instead.
*
* @param uresult The object containing the formatted number.
* @param buffer Where to save the string output.
* @param bufferCapacity The number of UChars available in the buffer.
* @param ec Set if an error occurs.
* @return The required length.
* @stable ICU 62
*/
U_CAPI int32_t U_EXPORT2
unumf_resultToString(const UFormattedNumber* uresult, UChar* buffer, int32_t bufferCapacity,
UErrorCode* ec);
/**
* Determines the start and end indices of the next occurrence of the given <em>field</em> in the
* output string. This allows you to determine the locations of, for example, the integer part,
* fraction part, or symbols.
*
* This is a simpler but less powerful alternative to {@link ufmtval_nextPosition}.
*
* If a field occurs just once, calling this method will find that occurrence and return it. If a
* field occurs multiple times, this method may be called repeatedly with the following pattern:
*
* <pre>
* UFieldPosition ufpos = {UNUM_GROUPING_SEPARATOR_FIELD, 0, 0};
* while (unumf_resultNextFieldPosition(uresult, ufpos, &ec)) {
* // do something with ufpos.
* }
* </pre>
*
* This method is useful if you know which field to query. If you want all available field position
* information, use unumf_resultGetAllFieldPositions().
*
* NOTE: All fields of the UFieldPosition must be initialized before calling this method.
*
* @param uresult The object containing the formatted number.
* @param ufpos
* Input+output variable. On input, the "field" property determines which field to look up,
* and the "endIndex" property determines where to begin the search. On output, the
* "beginIndex" field is set to the beginning of the first occurrence of the field after the
* input "endIndex", and "endIndex" is set to the end of that occurrence of the field
* (exclusive index). If a field position is not found, the FieldPosition is not changed and
* the method returns false.
* @param ec Set if an error occurs.
* @stable ICU 62
*/
U_CAPI UBool U_EXPORT2
unumf_resultNextFieldPosition(const UFormattedNumber* uresult, UFieldPosition* ufpos, UErrorCode* ec);
/**
* Populates the given iterator with all fields in the formatted output string. This allows you to
* determine the locations of the integer part, fraction part, and sign.
*
* This is an alternative to the more powerful {@link ufmtval_nextPosition} API.
*
* If you need information on only one field, use {@link ufmtval_nextPosition} or
* {@link unumf_resultNextFieldPosition}.
*
* @param uresult The object containing the formatted number.
* @param ufpositer
* A pointer to a UFieldPositionIterator created by {@link #ufieldpositer_open}. Iteration
* information already present in the UFieldPositionIterator is deleted, and the iterator is reset
* to apply to the fields in the formatted string created by this function call. The field values
* and indexes returned by {@link #ufieldpositer_next} represent fields denoted by
* the UNumberFormatFields enum. Fields are not returned in a guaranteed order. Fields cannot
* overlap, but they may nest. For example, 1234 could format as "1,234" which might consist of a
* grouping separator field for ',' and an integer field encompassing the entire string.
* @param ec Set if an error occurs.
* @stable ICU 62
*/
U_CAPI void U_EXPORT2
unumf_resultGetAllFieldPositions(const UFormattedNumber* uresult, UFieldPositionIterator* ufpositer,
UErrorCode* ec);
/**
* Extracts the formatted number as a "numeric string" conforming to the
* syntax defined in the Decimal Arithmetic Specification, available at
* http://speleotrove.com/decimal
*
* This endpoint is useful for obtaining the exact number being printed
* after scaling and rounding have been applied by the number formatter.
*
* @param uresult The input object containing the formatted number.
* @param dest the 8-bit char buffer into which the decimal number is placed
* @param destCapacity The size, in chars, of the destination buffer. May be zero
* for precomputing the required size.
* @param ec receives any error status.
* If U_BUFFER_OVERFLOW_ERROR: Returns number of chars for
* preflighting.
* @return Number of chars in the data. Does not include a trailing NUL.
* @stable ICU 68
*/
U_CAPI int32_t U_EXPORT2
unumf_resultToDecimalNumber(
const UFormattedNumber* uresult,
char* dest,
int32_t destCapacity,
UErrorCode* ec);
/**
* Releases the UFormattedNumber created by unumf_openResult().
*
* @param uresult An object created by unumf_openResult().
* @stable ICU 62
*/
U_CAPI void U_EXPORT2
unumf_closeResult(UFormattedNumber* uresult);
#if U_SHOW_CPLUSPLUS_API
U_NAMESPACE_BEGIN
/**
* \class LocalUFormattedNumberPointer
* "Smart pointer" class; closes a UFormattedNumber via unumf_closeResult().
* For most methods see the LocalPointerBase base class.
*
* Usage:
* <pre>
* LocalUFormattedNumberPointer uformatter(unumf_openResult(...));
* // no need to explicitly call unumf_closeResult()
* </pre>
*
* @see LocalPointerBase
* @see LocalPointer
* @stable ICU 62
*/
U_DEFINE_LOCAL_OPEN_POINTER(LocalUFormattedNumberPointer, UFormattedNumber, unumf_closeResult);
U_NAMESPACE_END
#endif // U_SHOW_CPLUSPLUS_API
#endif /* #if !UCONFIG_NO_FORMATTING */
#endif //__UFORMATTEDNUMBER_H__

View File

@ -0,0 +1,445 @@
// © 2018 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
#ifndef __UFORMATTEDVALUE_H__
#define __UFORMATTEDVALUE_H__
#include "unicode/utypes.h"
#if !UCONFIG_NO_FORMATTING
#include "unicode/ufieldpositer.h"
/**
* \file
* \brief C API: Abstract operations for localized strings.
*
* This file contains declarations for classes that deal with formatted strings. A number
* of APIs throughout ICU use these classes for expressing their localized output.
*/
/**
* All possible field categories in ICU. Every entry in this enum corresponds
* to another enum that exists in ICU.
*
* In the APIs that take a UFieldCategory, an int32_t type is used. Field
* categories having any of the top four bits turned on are reserved as
* private-use for external APIs implementing FormattedValue. This means that
* categories 2^28 and higher or below zero (with the highest bit turned on)
* are private-use and will not be used by ICU in the future.
*
* @stable ICU 64
*/
typedef enum UFieldCategory {
/**
* For an undefined field category.
*
* @stable ICU 64
*/
UFIELD_CATEGORY_UNDEFINED = 0,
/**
* For fields in UDateFormatField (udat.h), from ICU 3.0.
*
* @stable ICU 64
*/
UFIELD_CATEGORY_DATE,
/**
* For fields in UNumberFormatFields (unum.h), from ICU 49.
*
* @stable ICU 64
*/
UFIELD_CATEGORY_NUMBER,
/**
* For fields in UListFormatterField (ulistformatter.h), from ICU 63.
*
* @stable ICU 64
*/
UFIELD_CATEGORY_LIST,
/**
* For fields in URelativeDateTimeFormatterField (ureldatefmt.h), from ICU 64.
*
* @stable ICU 64
*/
UFIELD_CATEGORY_RELATIVE_DATETIME,
/**
* Reserved for possible future fields in UDateIntervalFormatField.
*
* @internal
*/
UFIELD_CATEGORY_DATE_INTERVAL,
#ifndef U_HIDE_INTERNAL_API
/** @internal */
UFIELD_CATEGORY_COUNT,
#endif /* U_HIDE_INTERNAL_API */
/**
* Category for spans in a list.
*
* @stable ICU 64
*/
UFIELD_CATEGORY_LIST_SPAN = 0x1000 + UFIELD_CATEGORY_LIST,
/**
* Category for spans in a date interval.
*
* @stable ICU 64
*/
UFIELD_CATEGORY_DATE_INTERVAL_SPAN = 0x1000 + UFIELD_CATEGORY_DATE_INTERVAL,
/**
* Category for spans in a number range.
*
* @stable ICU 69
*/
UFIELD_CATEGORY_NUMBER_RANGE_SPAN = 0x1000 + UFIELD_CATEGORY_NUMBER,
} UFieldCategory;
struct UConstrainedFieldPosition;
/**
* Represents a span of a string containing a given field.
*
* This struct differs from UFieldPosition in the following ways:
*
* 1. It has information on the field category.
* 2. It allows you to set constraints to use when iterating over field positions.
* 3. It is used for the newer FormattedValue APIs.
*
* @stable ICU 64
*/
typedef struct UConstrainedFieldPosition UConstrainedFieldPosition;
/**
* Creates a new UConstrainedFieldPosition.
*
* By default, the UConstrainedFieldPosition has no iteration constraints.
*
* @param ec Set if an error occurs.
* @return The new object, or NULL if an error occurs.
* @stable ICU 64
*/
U_CAPI UConstrainedFieldPosition* U_EXPORT2
ucfpos_open(UErrorCode* ec);
/**
* Resets a UConstrainedFieldPosition to its initial state, as if it were newly created.
*
* Removes any constraints that may have been set on the instance.
*
* @param ucfpos The instance of UConstrainedFieldPosition.
* @param ec Set if an error occurs.
* @stable ICU 64
*/
U_CAPI void U_EXPORT2
ucfpos_reset(
UConstrainedFieldPosition* ucfpos,
UErrorCode* ec);
/**
* Destroys a UConstrainedFieldPosition and releases its memory.
*
* @param ucfpos The instance of UConstrainedFieldPosition.
* @stable ICU 64
*/
U_CAPI void U_EXPORT2
ucfpos_close(UConstrainedFieldPosition* ucfpos);
/**
* Sets a constraint on the field category.
*
* When this instance of UConstrainedFieldPosition is passed to ufmtval_nextPosition,
* positions are skipped unless they have the given category.
*
* Any previously set constraints are cleared.
*
* For example, to loop over only the number-related fields:
*
* UConstrainedFieldPosition* ucfpos = ucfpos_open(ec);
* ucfpos_constrainCategory(ucfpos, UFIELDCATEGORY_NUMBER_FORMAT, ec);
* while (ufmtval_nextPosition(ufmtval, ucfpos, ec)) {
* // handle the number-related field position
* }
* ucfpos_close(ucfpos);
*
* Changing the constraint while in the middle of iterating over a FormattedValue
* does not generally have well-defined behavior.
*
* @param ucfpos The instance of UConstrainedFieldPosition.
* @param category The field category to fix when iterating.
* @param ec Set if an error occurs.
* @stable ICU 64
*/
U_CAPI void U_EXPORT2
ucfpos_constrainCategory(
UConstrainedFieldPosition* ucfpos,
int32_t category,
UErrorCode* ec);
/**
* Sets a constraint on the category and field.
*
* When this instance of UConstrainedFieldPosition is passed to ufmtval_nextPosition,
* positions are skipped unless they have the given category and field.
*
* Any previously set constraints are cleared.
*
* For example, to loop over all grouping separators:
*
* UConstrainedFieldPosition* ucfpos = ucfpos_open(ec);
* ucfpos_constrainField(ucfpos, UFIELDCATEGORY_NUMBER_FORMAT, UNUM_GROUPING_SEPARATOR_FIELD, ec);
* while (ufmtval_nextPosition(ufmtval, ucfpos, ec)) {
* // handle the grouping separator position
* }
* ucfpos_close(ucfpos);
*
* Changing the constraint while in the middle of iterating over a FormattedValue
* does not generally have well-defined behavior.
*
* @param ucfpos The instance of UConstrainedFieldPosition.
* @param category The field category to fix when iterating.
* @param field The field to fix when iterating.
* @param ec Set if an error occurs.
* @stable ICU 64
*/
U_CAPI void U_EXPORT2
ucfpos_constrainField(
UConstrainedFieldPosition* ucfpos,
int32_t category,
int32_t field,
UErrorCode* ec);
/**
* Gets the field category for the current position.
*
* If a category or field constraint was set, this function returns the constrained
* category. Otherwise, the return value is well-defined only after
* ufmtval_nextPosition returns true.
*
* @param ucfpos The instance of UConstrainedFieldPosition.
* @param ec Set if an error occurs.
* @return The field category saved in the instance.
* @stable ICU 64
*/
U_CAPI int32_t U_EXPORT2
ucfpos_getCategory(
const UConstrainedFieldPosition* ucfpos,
UErrorCode* ec);
/**
* Gets the field for the current position.
*
* If a field constraint was set, this function returns the constrained
* field. Otherwise, the return value is well-defined only after
* ufmtval_nextPosition returns true.
*
* @param ucfpos The instance of UConstrainedFieldPosition.
* @param ec Set if an error occurs.
* @return The field saved in the instance.
* @stable ICU 64
*/
U_CAPI int32_t U_EXPORT2
ucfpos_getField(
const UConstrainedFieldPosition* ucfpos,
UErrorCode* ec);
/**
* Gets the INCLUSIVE start and EXCLUSIVE end index stored for the current position.
*
* The output values are well-defined only after ufmtval_nextPosition returns true.
*
* @param ucfpos The instance of UConstrainedFieldPosition.
* @param pStart Set to the start index saved in the instance. Ignored if nullptr.
* @param pLimit Set to the end index saved in the instance. Ignored if nullptr.
* @param ec Set if an error occurs.
* @stable ICU 64
*/
U_CAPI void U_EXPORT2
ucfpos_getIndexes(
const UConstrainedFieldPosition* ucfpos,
int32_t* pStart,
int32_t* pLimit,
UErrorCode* ec);
/**
* Gets an int64 that FormattedValue implementations may use for storage.
*
* The initial value is zero.
*
* Users of FormattedValue should not need to call this method.
*
* @param ucfpos The instance of UConstrainedFieldPosition.
* @param ec Set if an error occurs.
* @return The current iteration context from ucfpos_setInt64IterationContext.
* @stable ICU 64
*/
U_CAPI int64_t U_EXPORT2
ucfpos_getInt64IterationContext(
const UConstrainedFieldPosition* ucfpos,
UErrorCode* ec);
/**
* Sets an int64 that FormattedValue implementations may use for storage.
*
* Intended to be used by FormattedValue implementations.
*
* @param ucfpos The instance of UConstrainedFieldPosition.
* @param context The new iteration context.
* @param ec Set if an error occurs.
* @stable ICU 64
*/
U_CAPI void U_EXPORT2
ucfpos_setInt64IterationContext(
UConstrainedFieldPosition* ucfpos,
int64_t context,
UErrorCode* ec);
/**
* Determines whether a given field should be included given the
* constraints.
*
* Intended to be used by FormattedValue implementations.
*
* @param ucfpos The instance of UConstrainedFieldPosition.
* @param category The category to test.
* @param field The field to test.
* @param ec Set if an error occurs.
* @stable ICU 64
*/
U_CAPI UBool U_EXPORT2
ucfpos_matchesField(
const UConstrainedFieldPosition* ucfpos,
int32_t category,
int32_t field,
UErrorCode* ec);
/**
* Sets new values for the primary public getters.
*
* Intended to be used by FormattedValue implementations.
*
* It is up to the implementation to ensure that the user-requested
* constraints are satisfied. This method does not check!
*
* @param ucfpos The instance of UConstrainedFieldPosition.
* @param category The new field category.
* @param field The new field.
* @param start The new inclusive start index.
* @param limit The new exclusive end index.
* @param ec Set if an error occurs.
* @stable ICU 64
*/
U_CAPI void U_EXPORT2
ucfpos_setState(
UConstrainedFieldPosition* ucfpos,
int32_t category,
int32_t field,
int32_t start,
int32_t limit,
UErrorCode* ec);
struct UFormattedValue;
/**
* An abstract formatted value: a string with associated field attributes.
* Many formatters format to types compatible with UFormattedValue.
*
* @stable ICU 64
*/
typedef struct UFormattedValue UFormattedValue;
/**
* Returns a pointer to the formatted string. The pointer is owned by the UFormattedValue. The
* return value is valid only as long as the UFormattedValue is present and unchanged in memory.
*
* The return value is NUL-terminated but could contain internal NULs.
*
* @param ufmtval
* The object containing the formatted string and attributes.
* @param pLength Output variable for the length of the string. Ignored if NULL.
* @param ec Set if an error occurs.
* @return A NUL-terminated char16 string owned by the UFormattedValue.
* @stable ICU 64
*/
U_CAPI const UChar* U_EXPORT2
ufmtval_getString(
const UFormattedValue* ufmtval,
int32_t* pLength,
UErrorCode* ec);
/**
* Iterates over field positions in the UFormattedValue. This lets you determine the position
* of specific types of substrings, like a month or a decimal separator.
*
* To loop over all field positions:
*
* UConstrainedFieldPosition* ucfpos = ucfpos_open(ec);
* while (ufmtval_nextPosition(ufmtval, ucfpos, ec)) {
* // handle the field position; get information from ucfpos
* }
* ucfpos_close(ucfpos);
*
* @param ufmtval
* The object containing the formatted string and attributes.
* @param ucfpos
* The object used for iteration state; can provide constraints to iterate over only
* one specific category or field;
* see ucfpos_constrainCategory
* and ucfpos_constrainField.
* @param ec Set if an error occurs.
* @return true if another position was found; false otherwise.
* @stable ICU 64
*/
U_CAPI UBool U_EXPORT2
ufmtval_nextPosition(
const UFormattedValue* ufmtval,
UConstrainedFieldPosition* ucfpos,
UErrorCode* ec);
#if U_SHOW_CPLUSPLUS_API
U_NAMESPACE_BEGIN
/**
* \class LocalUConstrainedFieldPositionPointer
* "Smart pointer" class; closes a UConstrainedFieldPosition via ucfpos_close().
* For most methods see the LocalPointerBase base class.
*
* Usage:
*
* LocalUConstrainedFieldPositionPointer ucfpos(ucfpos_open(ec));
* // no need to explicitly call ucfpos_close()
*
* @stable ICU 64
*/
U_DEFINE_LOCAL_OPEN_POINTER(LocalUConstrainedFieldPositionPointer,
UConstrainedFieldPosition,
ucfpos_close);
U_NAMESPACE_END
#endif // U_SHOW_CPLUSPLUS_API
#endif /* #if !UCONFIG_NO_FORMATTING */
#endif // __UFORMATTEDVALUE_H__

View File

@ -0,0 +1,86 @@
// © 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
/*
*****************************************************************************************
* Copyright (C) 2010-2013, International Business Machines
* Corporation and others. All Rights Reserved.
*****************************************************************************************
*/
#ifndef UGENDER_H
#define UGENDER_H
#include "unicode/utypes.h"
#if !UCONFIG_NO_FORMATTING
#if U_SHOW_CPLUSPLUS_API
#include "unicode/localpointer.h"
#endif // U_SHOW_CPLUSPLUS_API
/**
* \file
* \brief C API: The purpose of this API is to compute the gender of a list as a
* whole given the gender of each element.
*
*/
/**
* Genders
* @stable ICU 50
*/
enum UGender {
/**
* Male gender.
* @stable ICU 50
*/
UGENDER_MALE,
/**
* Female gender.
* @stable ICU 50
*/
UGENDER_FEMALE,
/**
* Neutral gender.
* @stable ICU 50
*/
UGENDER_OTHER
};
/**
* @stable ICU 50
*/
typedef enum UGender UGender;
struct UGenderInfo;
/**
* Opaque UGenderInfo object for use in C programs.
* @stable ICU 50
*/
typedef struct UGenderInfo UGenderInfo;
/**
* Opens a new UGenderInfo object given locale.
* @param locale The locale for which the rules are desired.
* @param status UErrorCode pointer
* @return A UGenderInfo for the specified locale, or NULL if an error occurred.
* @stable ICU 50
*/
U_CAPI const UGenderInfo* U_EXPORT2
ugender_getInstance(const char *locale, UErrorCode *status);
/**
* Given a list, returns the gender of the list as a whole.
* @param genderInfo pointer that ugender_getInstance returns.
* @param genders the gender of each element in the list.
* @param size the size of the list.
* @param status A pointer to a UErrorCode to receive any errors.
* @return The gender of the list.
* @stable ICU 50
*/
U_CAPI UGender U_EXPORT2
ugender_getListGender(const UGenderInfo* genderInfo, const UGender *genders, int32_t size, UErrorCode *status);
#endif /* #if !UCONFIG_NO_FORMATTING */
#endif

View File

@ -0,0 +1,333 @@
// © 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
/*
*****************************************************************************************
* Copyright (C) 2015-2016, International Business Machines
* Corporation and others. All Rights Reserved.
*****************************************************************************************
*/
#ifndef ULISTFORMATTER_H
#define ULISTFORMATTER_H
#include "unicode/utypes.h"
#if !UCONFIG_NO_FORMATTING
#include "unicode/uformattedvalue.h"
#if U_SHOW_CPLUSPLUS_API
#include "unicode/localpointer.h"
#endif // U_SHOW_CPLUSPLUS_API
/**
* \file
* \brief C API: Format a list in a locale-appropriate way.
*
* A UListFormatter is used to format a list of items in a locale-appropriate way,
* using data from CLDR.
* Example: Input data ["Alice", "Bob", "Charlie", "Delta"] will be formatted
* as "Alice, Bob, Charlie, and Delta" in English.
*/
/**
* Opaque UListFormatter object for use in C
* @stable ICU 55
*/
struct UListFormatter;
typedef struct UListFormatter UListFormatter; /**< C typedef for struct UListFormatter. @stable ICU 55 */
struct UFormattedList;
/**
* Opaque struct to contain the results of a UListFormatter operation.
* @stable ICU 64
*/
typedef struct UFormattedList UFormattedList;
/**
* FieldPosition and UFieldPosition selectors for format fields
* defined by ListFormatter.
* @stable ICU 63
*/
typedef enum UListFormatterField {
/**
* The literal text in the result which came from the resources.
* @stable ICU 63
*/
ULISTFMT_LITERAL_FIELD,
/**
* The element text in the result which came from the input strings.
* @stable ICU 63
*/
ULISTFMT_ELEMENT_FIELD
} UListFormatterField;
/**
* Type of meaning expressed by the list.
*
* @stable ICU 67
*/
typedef enum UListFormatterType {
/**
* Conjunction formatting, e.g. "Alice, Bob, Charlie, and Delta".
*
* @stable ICU 67
*/
ULISTFMT_TYPE_AND,
/**
* Disjunction (or alternative, or simply one of) formatting, e.g.
* "Alice, Bob, Charlie, or Delta".
*
* @stable ICU 67
*/
ULISTFMT_TYPE_OR,
/**
* Formatting of a list of values with units, e.g. "5 pounds, 12 ounces".
*
* @stable ICU 67
*/
ULISTFMT_TYPE_UNITS
} UListFormatterType;
/**
* Verbosity level of the list patterns.
*
* @stable ICU 67
*/
typedef enum UListFormatterWidth {
/**
* Use list formatting with full words (no abbreviations) when possible.
*
* @stable ICU 67
*/
ULISTFMT_WIDTH_WIDE,
/**
* Use list formatting of typical length.
* @stable ICU 67
*/
ULISTFMT_WIDTH_SHORT,
/**
* Use list formatting of the shortest possible length.
* @stable ICU 67
*/
ULISTFMT_WIDTH_NARROW,
} UListFormatterWidth;
/**
* Open a new UListFormatter object using the rules for a given locale.
* The object will be initialized with AND type and WIDE width.
*
* @param locale
* The locale whose rules should be used; may be NULL for
* default locale.
* @param status
* A pointer to a standard ICU UErrorCode (input/output parameter).
* Its input value must pass the U_SUCCESS() test, or else the
* function returns immediately. The caller should check its output
* value with U_FAILURE(), or use with function chaining (see User
* Guide for details).
* @return
* A pointer to a UListFormatter object for the specified locale,
* or NULL if an error occurred.
* @stable ICU 55
*/
U_CAPI UListFormatter* U_EXPORT2
ulistfmt_open(const char* locale,
UErrorCode* status);
/**
* Open a new UListFormatter object appropriate for the given locale, list type,
* and style.
*
* @param locale
* The locale whose rules should be used; may be NULL for
* default locale.
* @param type
* The type of list formatting to use.
* @param width
* The width of formatting to use.
* @param status
* A pointer to a standard ICU UErrorCode (input/output parameter).
* Its input value must pass the U_SUCCESS() test, or else the
* function returns immediately. The caller should check its output
* value with U_FAILURE(), or use with function chaining (see User
* Guide for details).
* @return
* A pointer to a UListFormatter object for the specified locale,
* or NULL if an error occurred.
* @stable ICU 67
*/
U_CAPI UListFormatter* U_EXPORT2
ulistfmt_openForType(const char* locale, UListFormatterType type,
UListFormatterWidth width, UErrorCode* status);
/**
* Close a UListFormatter object. Once closed it may no longer be used.
* @param listfmt
* The UListFormatter object to close.
* @stable ICU 55
*/
U_CAPI void U_EXPORT2
ulistfmt_close(UListFormatter *listfmt);
/**
* Creates an object to hold the result of a UListFormatter
* operation. The object can be used repeatedly; it is cleared whenever
* passed to a format function.
*
* @param ec Set if an error occurs.
* @return A pointer needing ownership.
* @stable ICU 64
*/
U_CAPI UFormattedList* U_EXPORT2
ulistfmt_openResult(UErrorCode* ec);
/**
* Returns a representation of a UFormattedList as a UFormattedValue,
* which can be subsequently passed to any API requiring that type.
*
* The returned object is owned by the UFormattedList and is valid
* only as long as the UFormattedList is present and unchanged in memory.
*
* You can think of this method as a cast between types.
*
* When calling ufmtval_nextPosition():
* The fields are returned from start to end. The special field category
* UFIELD_CATEGORY_LIST_SPAN is used to indicate which argument
* was inserted at the given position. The span category will
* always occur before the corresponding instance of UFIELD_CATEGORY_LIST
* in the ufmtval_nextPosition() iterator.
*
* @param uresult The object containing the formatted string.
* @param ec Set if an error occurs.
* @return A UFormattedValue owned by the input object.
* @stable ICU 64
*/
U_CAPI const UFormattedValue* U_EXPORT2
ulistfmt_resultAsValue(const UFormattedList* uresult, UErrorCode* ec);
/**
* Releases the UFormattedList created by ulistfmt_openResult().
*
* @param uresult The object to release.
* @stable ICU 64
*/
U_CAPI void U_EXPORT2
ulistfmt_closeResult(UFormattedList* uresult);
#if U_SHOW_CPLUSPLUS_API
U_NAMESPACE_BEGIN
/**
* \class LocalUListFormatterPointer
* "Smart pointer" class, closes a UListFormatter via ulistfmt_close().
* For most methods see the LocalPointerBase base class.
*
* @see LocalPointerBase
* @see LocalPointer
* @stable ICU 55
*/
U_DEFINE_LOCAL_OPEN_POINTER(LocalUListFormatterPointer, UListFormatter, ulistfmt_close);
/**
* \class LocalUFormattedListPointer
* "Smart pointer" class, closes a UFormattedList via ulistfmt_closeResult().
* For most methods see the LocalPointerBase base class.
*
* @see LocalPointerBase
* @see LocalPointer
* @stable ICU 64
*/
U_DEFINE_LOCAL_OPEN_POINTER(LocalUFormattedListPointer, UFormattedList, ulistfmt_closeResult);
U_NAMESPACE_END
#endif
/**
* Formats a list of strings using the conventions established for the
* UListFormatter object.
* @param listfmt
* The UListFormatter object specifying the list conventions.
* @param strings
* An array of pointers to UChar strings; the array length is
* specified by stringCount. Must be non-NULL if stringCount > 0.
* @param stringLengths
* An array of string lengths corresponding to the strings[]
* parameter; any individual length value may be negative to indicate
* that the corresponding strings[] entry is 0-terminated, or
* stringLengths itself may be NULL if all of the strings are
* 0-terminated. If non-NULL, the stringLengths array must have
* stringCount entries.
* @param stringCount
* the number of entries in strings[], and the number of entries
* in the stringLengths array if it is not NULL. Must be >= 0.
* @param result
* A pointer to a buffer to receive the formatted list.
* @param resultCapacity
* The maximum size of result.
* @param status
* A pointer to a standard ICU UErrorCode (input/output parameter).
* Its input value must pass the U_SUCCESS() test, or else the
* function returns immediately. The caller should check its output
* value with U_FAILURE(), or use with function chaining (see User
* Guide for details).
* @return
* The total buffer size needed; if greater than resultLength, the
* output was truncated. May be <=0 if unable to determine the
* total buffer size needed (e.g. for illegal arguments).
* @stable ICU 55
*/
U_CAPI int32_t U_EXPORT2
ulistfmt_format(const UListFormatter* listfmt,
const UChar* const strings[],
const int32_t * stringLengths,
int32_t stringCount,
UChar* result,
int32_t resultCapacity,
UErrorCode* status);
/**
* Formats a list of strings to a UFormattedList, which exposes more
* information than the string exported by ulistfmt_format().
*
* @param listfmt
* The UListFormatter object specifying the list conventions.
* @param strings
* An array of pointers to UChar strings; the array length is
* specified by stringCount. Must be non-NULL if stringCount > 0.
* @param stringLengths
* An array of string lengths corresponding to the strings[]
* parameter; any individual length value may be negative to indicate
* that the corresponding strings[] entry is 0-terminated, or
* stringLengths itself may be NULL if all of the strings are
* 0-terminated. If non-NULL, the stringLengths array must have
* stringCount entries.
* @param stringCount
* the number of entries in strings[], and the number of entries
* in the stringLengths array if it is not NULL. Must be >= 0.
* @param uresult
* The object in which to store the result of the list formatting
* operation. See ulistfmt_openResult().
* @param status
* Error code set if an error occurred during formatting.
* @stable ICU 64
*/
U_CAPI void U_EXPORT2
ulistfmt_formatStringsToResult(
const UListFormatter* listfmt,
const UChar* const strings[],
const int32_t * stringLengths,
int32_t stringCount,
UFormattedList* uresult,
UErrorCode* status);
#endif /* #if !UCONFIG_NO_FORMATTING */
#endif

View File

@ -0,0 +1,299 @@
// © 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
/*
******************************************************************************
* *
* Copyright (C) 2003-2015, International Business Machines *
* Corporation and others. All Rights Reserved. *
* *
******************************************************************************
* file name: ulocdata.h
* encoding: UTF-8
* tab size: 8 (not used)
* indentation:4
*
* created on: 2003Oct21
* created by: Ram Viswanadha
*/
#ifndef __ULOCDATA_H__
#define __ULOCDATA_H__
#include "unicode/ures.h"
#include "unicode/uloc.h"
#include "unicode/uset.h"
#if U_SHOW_CPLUSPLUS_API
#include "unicode/localpointer.h"
#endif // U_SHOW_CPLUSPLUS_API
/**
* \file
* \brief C API: Provides access to locale data.
*/
/** Forward declaration of the ULocaleData structure. @stable ICU 3.6 */
struct ULocaleData;
/** A locale data object. @stable ICU 3.6 */
typedef struct ULocaleData ULocaleData;
/** The possible types of exemplar character sets.
* @stable ICU 3.4
*/
typedef enum ULocaleDataExemplarSetType {
/** Basic set @stable ICU 3.4 */
ULOCDATA_ES_STANDARD=0,
/** Auxiliary set @stable ICU 3.4 */
ULOCDATA_ES_AUXILIARY=1,
/** Index Character set @stable ICU 4.8 */
ULOCDATA_ES_INDEX=2,
/** Punctuation set @stable ICU 51 */
ULOCDATA_ES_PUNCTUATION=3,
#ifndef U_HIDE_DEPRECATED_API
/**
* One more than the highest normal ULocaleDataExemplarSetType value.
* @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420.
*/
ULOCDATA_ES_COUNT=4
#endif /* U_HIDE_DEPRECATED_API */
} ULocaleDataExemplarSetType;
/** The possible types of delimiters.
* @stable ICU 3.4
*/
typedef enum ULocaleDataDelimiterType {
/** Quotation start @stable ICU 3.4 */
ULOCDATA_QUOTATION_START = 0,
/** Quotation end @stable ICU 3.4 */
ULOCDATA_QUOTATION_END = 1,
/** Alternate quotation start @stable ICU 3.4 */
ULOCDATA_ALT_QUOTATION_START = 2,
/** Alternate quotation end @stable ICU 3.4 */
ULOCDATA_ALT_QUOTATION_END = 3,
#ifndef U_HIDE_DEPRECATED_API
/**
* One more than the highest normal ULocaleDataDelimiterType value.
* @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420.
*/
ULOCDATA_DELIMITER_COUNT = 4
#endif /* U_HIDE_DEPRECATED_API */
} ULocaleDataDelimiterType;
/**
* Opens a locale data object for the given locale
*
* @param localeID Specifies the locale associated with this locale
* data object.
* @param status Pointer to error status code.
* @stable ICU 3.4
*/
U_CAPI ULocaleData* U_EXPORT2
ulocdata_open(const char *localeID, UErrorCode *status);
/**
* Closes a locale data object.
*
* @param uld The locale data object to close
* @stable ICU 3.4
*/
U_CAPI void U_EXPORT2
ulocdata_close(ULocaleData *uld);
#if U_SHOW_CPLUSPLUS_API
U_NAMESPACE_BEGIN
/**
* \class LocalULocaleDataPointer
* "Smart pointer" class, closes a ULocaleData via ulocdata_close().
* For most methods see the LocalPointerBase base class.
*
* @see LocalPointerBase
* @see LocalPointer
* @stable ICU 4.4
*/
U_DEFINE_LOCAL_OPEN_POINTER(LocalULocaleDataPointer, ULocaleData, ulocdata_close);
U_NAMESPACE_END
#endif
/**
* Sets the "no Substitute" attribute of the locale data
* object. If true, then any methods associated with the
* locale data object will return null when there is no
* data available for that method, given the locale ID
* supplied to ulocdata_open().
*
* @param uld The locale data object to set.
* @param setting Value of the "no substitute" attribute.
* @stable ICU 3.4
*/
U_CAPI void U_EXPORT2
ulocdata_setNoSubstitute(ULocaleData *uld, UBool setting);
/**
* Retrieves the current "no Substitute" value of the locale data
* object. If true, then any methods associated with the
* locale data object will return null when there is no
* data available for that method, given the locale ID
* supplied to ulocdata_open().
*
* @param uld Pointer to the The locale data object to set.
* @return UBool Value of the "no substitute" attribute.
* @stable ICU 3.4
*/
U_CAPI UBool U_EXPORT2
ulocdata_getNoSubstitute(ULocaleData *uld);
/**
* Returns the set of exemplar characters for a locale.
*
* @param uld Pointer to the locale data object from which the
* exemplar character set is to be retrieved.
* @param fillIn Pointer to a USet object to receive the
* exemplar character set for the given locale. Previous
* contents of fillIn are lost. <em>If fillIn is NULL,
* then a new USet is created and returned. The caller
* owns the result and must dispose of it by calling
* uset_close.</em>
* @param options Bitmask for options to apply to the exemplar pattern.
* Specify zero to retrieve the exemplar set as it is
* defined in the locale data. Specify
* USET_CASE_INSENSITIVE to retrieve a case-folded
* exemplar set. See uset_applyPattern for a complete
* list of valid options. The USET_IGNORE_SPACE bit is
* always set, regardless of the value of 'options'.
* @param extype Specifies the type of exemplar set to be retrieved.
* @param status Pointer to an input-output error code value;
* must not be NULL. Will be set to U_MISSING_RESOURCE_ERROR
* if the requested data is not available.
* @return USet* Either fillIn, or if fillIn is NULL, a pointer to
* a newly-allocated USet that the user must close.
* In case of error, NULL is returned.
* @stable ICU 3.4
*/
U_CAPI USet* U_EXPORT2
ulocdata_getExemplarSet(ULocaleData *uld, USet *fillIn,
uint32_t options, ULocaleDataExemplarSetType extype, UErrorCode *status);
/**
* Returns one of the delimiter strings associated with a locale.
*
* @param uld Pointer to the locale data object from which the
* delimiter string is to be retrieved.
* @param type the type of delimiter to be retrieved.
* @param result A pointer to a buffer to receive the result.
* @param resultLength The maximum size of result.
* @param status Pointer to an error code value
* @return int32_t The total buffer size needed; if greater than resultLength,
* the output was truncated.
* @stable ICU 3.4
*/
U_CAPI int32_t U_EXPORT2
ulocdata_getDelimiter(ULocaleData *uld, ULocaleDataDelimiterType type, UChar *result, int32_t resultLength, UErrorCode *status);
/**
* Enumeration for representing the measurement systems.
* @stable ICU 2.8
*/
typedef enum UMeasurementSystem {
UMS_SI, /**< Measurement system specified by SI otherwise known as Metric system. @stable ICU 2.8 */
UMS_US, /**< Measurement system followed in the United States of America. @stable ICU 2.8 */
UMS_UK, /**< Mix of metric and imperial units used in Great Britain. @stable ICU 55 */
#ifndef U_HIDE_DEPRECATED_API
/**
* One more than the highest normal UMeasurementSystem value.
* @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420.
*/
UMS_LIMIT
#endif /* U_HIDE_DEPRECATED_API */
} UMeasurementSystem;
/**
* Returns the measurement system used in the locale specified by the localeID.
* Please note that this API will change in ICU 3.6 and will use an ulocdata object.
*
* @param localeID The id of the locale for which the measurement system to be retrieved.
* @param status Must be a valid pointer to an error code value,
* which must not indicate a failure before the function call.
* @return UMeasurementSystem the measurement system used in the locale.
* @stable ICU 2.8
*/
U_CAPI UMeasurementSystem U_EXPORT2
ulocdata_getMeasurementSystem(const char *localeID, UErrorCode *status);
/**
* Returns the element gives the normal business letter size, and customary units.
* The units for the numbers are always in <em>milli-meters</em>.
* For US since 8.5 and 11 do not yield an integral value when converted to milli-meters,
* the values are rounded off.
* So for A4 size paper the height and width are 297 mm and 210 mm respectively,
* and for US letter size the height and width are 279 mm and 216 mm respectively.
* Please note that this API will change in ICU 3.6 and will use an ulocdata object.
*
* @param localeID The id of the locale for which the paper size information to be retrieved.
* @param height A pointer to int to receive the height information.
* @param width A pointer to int to receive the width information.
* @param status Must be a valid pointer to an error code value,
* which must not indicate a failure before the function call.
* @stable ICU 2.8
*/
U_CAPI void U_EXPORT2
ulocdata_getPaperSize(const char *localeID, int32_t *height, int32_t *width, UErrorCode *status);
/**
* Return the current CLDR version used by the library.
* @param versionArray fill-in that will receive the version number
* @param status error code - could be U_MISSING_RESOURCE_ERROR if the version was not found.
* @stable ICU 4.2
*/
U_CAPI void U_EXPORT2
ulocdata_getCLDRVersion(UVersionInfo versionArray, UErrorCode *status);
/**
* Returns locale display pattern associated with a locale.
*
* @param uld Pointer to the locale data object from which the
* exemplar character set is to be retrieved.
* @param pattern locale display pattern for locale.
* @param patternCapacity the size of the buffer to store the locale display
* pattern with.
* @param status Must be a valid pointer to an error code value,
* which must not indicate a failure before the function call.
* @return the actual buffer size needed for localeDisplayPattern. If it's greater
* than patternCapacity, the returned pattern will be truncated.
*
* @stable ICU 4.2
*/
U_CAPI int32_t U_EXPORT2
ulocdata_getLocaleDisplayPattern(ULocaleData *uld,
UChar *pattern,
int32_t patternCapacity,
UErrorCode *status);
/**
* Returns locale separator associated with a locale.
*
* @param uld Pointer to the locale data object from which the
* exemplar character set is to be retrieved.
* @param separator locale separator for locale.
* @param separatorCapacity the size of the buffer to store the locale
* separator with.
* @param status Must be a valid pointer to an error code value,
* which must not indicate a failure before the function call.
* @return the actual buffer size needed for localeSeparator. If it's greater
* than separatorCapacity, the returned separator will be truncated.
*
* @stable ICU 4.2
*/
U_CAPI int32_t U_EXPORT2
ulocdata_getLocaleSeparator(ULocaleData *uld,
UChar *separator,
int32_t separatorCapacity,
UErrorCode *status);
#endif

View File

@ -0,0 +1,628 @@
// © 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
/********************************************************************
* COPYRIGHT:
* Copyright (c) 1997-2011, International Business Machines Corporation and
* others. All Rights Reserved.
* Copyright (C) 2010 , Yahoo! Inc.
********************************************************************
*
* file name: umsg.h
* encoding: UTF-8
* tab size: 8 (not used)
* indentation:4
*
* Change history:
*
* 08/5/2001 Ram Added C wrappers for C++ API.
********************************************************************/
#ifndef UMSG_H
#define UMSG_H
#include "unicode/utypes.h"
#if !UCONFIG_NO_FORMATTING
#include "unicode/uloc.h"
#include "unicode/parseerr.h"
#include <stdarg.h>
#if U_SHOW_CPLUSPLUS_API
#include "unicode/localpointer.h"
#endif // U_SHOW_CPLUSPLUS_API
/**
* \file
* \brief C API: MessageFormat
*
* <h2>MessageFormat C API </h2>
*
* <p>MessageFormat prepares strings for display to users,
* with optional arguments (variables/placeholders).
* The arguments can occur in any order, which is necessary for translation
* into languages with different grammars.
*
* <p>The opaque UMessageFormat type is a thin C wrapper around
* a C++ MessageFormat. It is constructed from a <em>pattern</em> string
* with arguments in {curly braces} which will be replaced by formatted values.
*
* <p>Currently, the C API supports only numbered arguments.
*
* <p>For details about the pattern syntax and behavior,
* especially about the ASCII apostrophe vs. the
* real apostrophe (single quote) character \htmlonly&#x2019;\endhtmlonly (U+2019),
* see the C++ MessageFormat class documentation.
*
* <p>Here are some examples of C API usage:
* Example 1:
* <pre>
* \code
* UChar *result, *tzID, *str;
* UChar pattern[100];
* int32_t resultLengthOut, resultlength;
* UCalendar *cal;
* UDate d1;
* UDateFormat *def1;
* UErrorCode status = U_ZERO_ERROR;
*
* str=(UChar*)malloc(sizeof(UChar) * (strlen("disturbance in force") +1));
* u_uastrcpy(str, "disturbance in force");
* tzID=(UChar*)malloc(sizeof(UChar) * 4);
* u_uastrcpy(tzID, "PST");
* cal=ucal_open(tzID, u_strlen(tzID), "en_US", UCAL_TRADITIONAL, &status);
* ucal_setDateTime(cal, 1999, UCAL_MARCH, 18, 0, 0, 0, &status);
* d1=ucal_getMillis(cal, &status);
* u_uastrcpy(pattern, "On {0, date, long}, there was a {1} on planet {2,number,integer}");
* resultlength=0;
* resultLengthOut=u_formatMessage( "en_US", pattern, u_strlen(pattern), NULL, resultlength, &status, d1, str, 7);
* if(status==U_BUFFER_OVERFLOW_ERROR){
* status=U_ZERO_ERROR;
* resultlength=resultLengthOut+1;
* result=(UChar*)realloc(result, sizeof(UChar) * resultlength);
* u_formatMessage( "en_US", pattern, u_strlen(pattern), result, resultlength, &status, d1, str, 7);
* }
* printf("%s\n", austrdup(result) );//austrdup( a function used to convert UChar* to char*)
* //output>: "On March 18, 1999, there was a disturbance in force on planet 7
* \endcode
* </pre>
* Typically, the message format will come from resources, and the
* arguments will be dynamically set at runtime.
* <P>
* Example 2:
* <pre>
* \code
* UChar* str;
* UErrorCode status = U_ZERO_ERROR;
* UChar *result;
* UChar pattern[100];
* int32_t resultlength, resultLengthOut, i;
* double testArgs= { 100.0, 1.0, 0.0};
*
* str=(UChar*)malloc(sizeof(UChar) * 10);
* u_uastrcpy(str, "MyDisk");
* u_uastrcpy(pattern, "The disk {1} contains {0,choice,0#no files|1#one file|1<{0,number,integer} files}");
* for(i=0; i<3; i++){
* resultlength=0;
* resultLengthOut=u_formatMessage( "en_US", pattern, u_strlen(pattern), NULL, resultlength, &status, testArgs[i], str);
* if(status==U_BUFFER_OVERFLOW_ERROR){
* status=U_ZERO_ERROR;
* resultlength=resultLengthOut+1;
* result=(UChar*)malloc(sizeof(UChar) * resultlength);
* u_formatMessage( "en_US", pattern, u_strlen(pattern), result, resultlength, &status, testArgs[i], str);
* }
* printf("%s\n", austrdup(result) ); //austrdup( a function used to convert UChar* to char*)
* free(result);
* }
* // output, with different testArgs:
* // output: The disk "MyDisk" contains 100 files.
* // output: The disk "MyDisk" contains one file.
* // output: The disk "MyDisk" contains no files.
* \endcode
* </pre>
*
*
* Example 3:
* <pre>
* \code
* UChar* str;
* UChar* str1;
* UErrorCode status = U_ZERO_ERROR;
* UChar *result;
* UChar pattern[100];
* UChar expected[100];
* int32_t resultlength,resultLengthOut;
* str=(UChar*)malloc(sizeof(UChar) * 25);
* u_uastrcpy(str, "Kirti");
* str1=(UChar*)malloc(sizeof(UChar) * 25);
* u_uastrcpy(str1, "female");
* log_verbose("Testing message format with Select test #1\n:");
* u_uastrcpy(pattern, "{0} est {1, select, female {all\\u00E9e} other {all\\u00E9}} \\u00E0 Paris.");
* u_uastrcpy(expected, "Kirti est all\\u00E9e \\u00E0 Paris.");
* resultlength=0;
* resultLengthOut=u_formatMessage( "fr", pattern, u_strlen(pattern), NULL, resultlength, &status, str , str1);
* if(status==U_BUFFER_OVERFLOW_ERROR)
* {
* status=U_ZERO_ERROR;
* resultlength=resultLengthOut+1;
* result=(UChar*)malloc(sizeof(UChar) * resultlength);
* u_formatMessage( "fr", pattern, u_strlen(pattern), result, resultlength, &status, str , str1);
* if(u_strcmp(result, expected)==0)
* log_verbose("PASS: MessagFormat successful on Select test#1\n");
* else{
* log_err("FAIL: Error in MessageFormat on Select test#1\n GOT %s EXPECTED %s\n", austrdup(result),
* austrdup(expected) );
* }
* free(result);
* }
* \endcode
* </pre>
*/
/**
* Format a message for a locale.
* This function may perform re-ordering of the arguments depending on the
* locale. For all numeric arguments, double is assumed unless the type is
* explicitly integer. All choice format arguments must be of type double.
* @param locale The locale for which the message will be formatted
* @param pattern The pattern specifying the message's format
* @param patternLength The length of pattern
* @param result A pointer to a buffer to receive the formatted message.
* @param resultLength The maximum size of result.
* @param status A pointer to an UErrorCode to receive any errors
* @param ... A variable-length argument list containing the arguments specified
* in pattern.
* @return The total buffer size needed; if greater than resultLength, the
* output was truncated.
* @see u_parseMessage
* @stable ICU 2.0
*/
U_CAPI int32_t U_EXPORT2
u_formatMessage(const char *locale,
const UChar *pattern,
int32_t patternLength,
UChar *result,
int32_t resultLength,
UErrorCode *status,
...);
/**
* Format a message for a locale.
* This function may perform re-ordering of the arguments depending on the
* locale. For all numeric arguments, double is assumed unless the type is
* explicitly integer. All choice format arguments must be of type double.
* @param locale The locale for which the message will be formatted
* @param pattern The pattern specifying the message's format
* @param patternLength The length of pattern
* @param result A pointer to a buffer to receive the formatted message.
* @param resultLength The maximum size of result.
* @param ap A variable-length argument list containing the arguments specified
* @param status A pointer to an UErrorCode to receive any errors
* in pattern.
* @return The total buffer size needed; if greater than resultLength, the
* output was truncated.
* @see u_parseMessage
* @stable ICU 2.0
*/
U_CAPI int32_t U_EXPORT2
u_vformatMessage( const char *locale,
const UChar *pattern,
int32_t patternLength,
UChar *result,
int32_t resultLength,
va_list ap,
UErrorCode *status);
/**
* Parse a message.
* For numeric arguments, this function will always use doubles. Integer types
* should not be passed.
* This function is not able to parse all output from {@link #u_formatMessage }.
* @param locale The locale for which the message is formatted
* @param pattern The pattern specifying the message's format
* @param patternLength The length of pattern
* @param source The text to parse.
* @param sourceLength The length of source, or -1 if null-terminated.
* @param status A pointer to an UErrorCode to receive any errors
* @param ... A variable-length argument list containing the arguments
* specified in pattern.
* @see u_formatMessage
* @stable ICU 2.0
*/
U_CAPI void U_EXPORT2
u_parseMessage( const char *locale,
const UChar *pattern,
int32_t patternLength,
const UChar *source,
int32_t sourceLength,
UErrorCode *status,
...);
/**
* Parse a message.
* For numeric arguments, this function will always use doubles. Integer types
* should not be passed.
* This function is not able to parse all output from {@link #u_formatMessage }.
* @param locale The locale for which the message is formatted
* @param pattern The pattern specifying the message's format
* @param patternLength The length of pattern
* @param source The text to parse.
* @param sourceLength The length of source, or -1 if null-terminated.
* @param ap A variable-length argument list containing the arguments
* @param status A pointer to an UErrorCode to receive any errors
* specified in pattern.
* @see u_formatMessage
* @stable ICU 2.0
*/
U_CAPI void U_EXPORT2
u_vparseMessage(const char *locale,
const UChar *pattern,
int32_t patternLength,
const UChar *source,
int32_t sourceLength,
va_list ap,
UErrorCode *status);
/**
* Format a message for a locale.
* This function may perform re-ordering of the arguments depending on the
* locale. For all numeric arguments, double is assumed unless the type is
* explicitly integer. All choice format arguments must be of type double.
* @param locale The locale for which the message will be formatted
* @param pattern The pattern specifying the message's format
* @param patternLength The length of pattern
* @param result A pointer to a buffer to receive the formatted message.
* @param resultLength The maximum size of result.
* @param status A pointer to an UErrorCode to receive any errors
* @param ... A variable-length argument list containing the arguments specified
* in pattern.
* @param parseError A pointer to UParseError to receive information about errors
* occurred during parsing.
* @return The total buffer size needed; if greater than resultLength, the
* output was truncated.
* @see u_parseMessage
* @stable ICU 2.0
*/
U_CAPI int32_t U_EXPORT2
u_formatMessageWithError( const char *locale,
const UChar *pattern,
int32_t patternLength,
UChar *result,
int32_t resultLength,
UParseError *parseError,
UErrorCode *status,
...);
/**
* Format a message for a locale.
* This function may perform re-ordering of the arguments depending on the
* locale. For all numeric arguments, double is assumed unless the type is
* explicitly integer. All choice format arguments must be of type double.
* @param locale The locale for which the message will be formatted
* @param pattern The pattern specifying the message's format
* @param patternLength The length of pattern
* @param result A pointer to a buffer to receive the formatted message.
* @param resultLength The maximum size of result.
* @param parseError A pointer to UParseError to receive information about errors
* occurred during parsing.
* @param ap A variable-length argument list containing the arguments specified
* @param status A pointer to an UErrorCode to receive any errors
* in pattern.
* @return The total buffer size needed; if greater than resultLength, the
* output was truncated.
* @stable ICU 2.0
*/
U_CAPI int32_t U_EXPORT2
u_vformatMessageWithError( const char *locale,
const UChar *pattern,
int32_t patternLength,
UChar *result,
int32_t resultLength,
UParseError* parseError,
va_list ap,
UErrorCode *status);
/**
* Parse a message.
* For numeric arguments, this function will always use doubles. Integer types
* should not be passed.
* This function is not able to parse all output from {@link #u_formatMessage }.
* @param locale The locale for which the message is formatted
* @param pattern The pattern specifying the message's format
* @param patternLength The length of pattern
* @param source The text to parse.
* @param sourceLength The length of source, or -1 if null-terminated.
* @param parseError A pointer to UParseError to receive information about errors
* occurred during parsing.
* @param status A pointer to an UErrorCode to receive any errors
* @param ... A variable-length argument list containing the arguments
* specified in pattern.
* @see u_formatMessage
* @stable ICU 2.0
*/
U_CAPI void U_EXPORT2
u_parseMessageWithError(const char *locale,
const UChar *pattern,
int32_t patternLength,
const UChar *source,
int32_t sourceLength,
UParseError *parseError,
UErrorCode *status,
...);
/**
* Parse a message.
* For numeric arguments, this function will always use doubles. Integer types
* should not be passed.
* This function is not able to parse all output from {@link #u_formatMessage }.
* @param locale The locale for which the message is formatted
* @param pattern The pattern specifying the message's format
* @param patternLength The length of pattern
* @param source The text to parse.
* @param sourceLength The length of source, or -1 if null-terminated.
* @param ap A variable-length argument list containing the arguments
* @param parseError A pointer to UParseError to receive information about errors
* occurred during parsing.
* @param status A pointer to an UErrorCode to receive any errors
* specified in pattern.
* @see u_formatMessage
* @stable ICU 2.0
*/
U_CAPI void U_EXPORT2
u_vparseMessageWithError(const char *locale,
const UChar *pattern,
int32_t patternLength,
const UChar *source,
int32_t sourceLength,
va_list ap,
UParseError *parseError,
UErrorCode* status);
/*----------------------- New experimental API --------------------------- */
/**
* The message format object
* @stable ICU 2.0
*/
typedef void* UMessageFormat;
/**
* Open a message formatter with given pattern and for the given locale.
* @param pattern A pattern specifying the format to use.
* @param patternLength Length of the pattern to use
* @param locale The locale for which the messages are formatted.
* @param parseError A pointer to UParseError struct to receive any errors
* occurred during parsing. Can be NULL.
* @param status A pointer to an UErrorCode to receive any errors.
* @return A pointer to a UMessageFormat to use for formatting
* messages, or 0 if an error occurred.
* @stable ICU 2.0
*/
U_CAPI UMessageFormat* U_EXPORT2
umsg_open( const UChar *pattern,
int32_t patternLength,
const char *locale,
UParseError *parseError,
UErrorCode *status);
/**
* Close a UMessageFormat.
* Once closed, a UMessageFormat may no longer be used.
* @param format The formatter to close.
* @stable ICU 2.0
*/
U_CAPI void U_EXPORT2
umsg_close(UMessageFormat* format);
#if U_SHOW_CPLUSPLUS_API
U_NAMESPACE_BEGIN
/**
* \class LocalUMessageFormatPointer
* "Smart pointer" class, closes a UMessageFormat via umsg_close().
* For most methods see the LocalPointerBase base class.
*
* @see LocalPointerBase
* @see LocalPointer
* @stable ICU 4.4
*/
U_DEFINE_LOCAL_OPEN_POINTER(LocalUMessageFormatPointer, UMessageFormat, umsg_close);
U_NAMESPACE_END
#endif
/**
* Open a copy of a UMessageFormat.
* This function performs a deep copy.
* @param fmt The formatter to copy
* @param status A pointer to an UErrorCode to receive any errors.
* @return A pointer to a UDateFormat identical to fmt.
* @stable ICU 2.0
*/
U_CAPI UMessageFormat U_EXPORT2
umsg_clone(const UMessageFormat *fmt,
UErrorCode *status);
/**
* Sets the locale. This locale is used for fetching default number or date
* format information.
* @param fmt The formatter to set
* @param locale The locale the formatter should use.
* @stable ICU 2.0
*/
U_CAPI void U_EXPORT2
umsg_setLocale(UMessageFormat *fmt,
const char* locale);
/**
* Gets the locale. This locale is used for fetching default number or date
* format information.
* @param fmt The formatter to querry
* @return the locale.
* @stable ICU 2.0
*/
U_CAPI const char* U_EXPORT2
umsg_getLocale(const UMessageFormat *fmt);
/**
* Sets the pattern.
* @param fmt The formatter to use
* @param pattern The pattern to be applied.
* @param patternLength Length of the pattern to use
* @param parseError Struct to receive information on position
* of error if an error is encountered.Can be NULL.
* @param status Output param set to success/failure code on
* exit. If the pattern is invalid, this will be
* set to a failure result.
* @stable ICU 2.0
*/
U_CAPI void U_EXPORT2
umsg_applyPattern( UMessageFormat *fmt,
const UChar* pattern,
int32_t patternLength,
UParseError* parseError,
UErrorCode* status);
/**
* Gets the pattern.
* @param fmt The formatter to use
* @param result A pointer to a buffer to receive the pattern.
* @param resultLength The maximum size of result.
* @param status Output param set to success/failure code on
* exit. If the pattern is invalid, this will be
* set to a failure result.
* @return the pattern of the format
* @stable ICU 2.0
*/
U_CAPI int32_t U_EXPORT2
umsg_toPattern(const UMessageFormat *fmt,
UChar* result,
int32_t resultLength,
UErrorCode* status);
/**
* Format a message for a locale.
* This function may perform re-ordering of the arguments depending on the
* locale. For all numeric arguments, double is assumed unless the type is
* explicitly integer. All choice format arguments must be of type double.
* @param fmt The formatter to use
* @param result A pointer to a buffer to receive the formatted message.
* @param resultLength The maximum size of result.
* @param status A pointer to an UErrorCode to receive any errors
* @param ... A variable-length argument list containing the arguments
* specified in pattern.
* @return The total buffer size needed; if greater than resultLength,
* the output was truncated.
* @stable ICU 2.0
*/
U_CAPI int32_t U_EXPORT2
umsg_format( const UMessageFormat *fmt,
UChar *result,
int32_t resultLength,
UErrorCode *status,
...);
/**
* Format a message for a locale.
* This function may perform re-ordering of the arguments depending on the
* locale. For all numeric arguments, double is assumed unless the type is
* explicitly integer. All choice format arguments must be of type double.
* @param fmt The formatter to use
* @param result A pointer to a buffer to receive the formatted message.
* @param resultLength The maximum size of result.
* @param ap A variable-length argument list containing the arguments
* @param status A pointer to an UErrorCode to receive any errors
* specified in pattern.
* @return The total buffer size needed; if greater than resultLength,
* the output was truncated.
* @stable ICU 2.0
*/
U_CAPI int32_t U_EXPORT2
umsg_vformat( const UMessageFormat *fmt,
UChar *result,
int32_t resultLength,
va_list ap,
UErrorCode *status);
/**
* Parse a message.
* For numeric arguments, this function will always use doubles. Integer types
* should not be passed.
* This function is not able to parse all output from {@link #umsg_format }.
* @param fmt The formatter to use
* @param source The text to parse.
* @param sourceLength The length of source, or -1 if null-terminated.
* @param count Output param to receive number of elements returned.
* @param status A pointer to an UErrorCode to receive any errors
* @param ... A variable-length argument list containing the arguments
* specified in pattern.
* @stable ICU 2.0
*/
U_CAPI void U_EXPORT2
umsg_parse( const UMessageFormat *fmt,
const UChar *source,
int32_t sourceLength,
int32_t *count,
UErrorCode *status,
...);
/**
* Parse a message.
* For numeric arguments, this function will always use doubles. Integer types
* should not be passed.
* This function is not able to parse all output from {@link #umsg_format }.
* @param fmt The formatter to use
* @param source The text to parse.
* @param sourceLength The length of source, or -1 if null-terminated.
* @param count Output param to receive number of elements returned.
* @param ap A variable-length argument list containing the arguments
* @param status A pointer to an UErrorCode to receive any errors
* specified in pattern.
* @see u_formatMessage
* @stable ICU 2.0
*/
U_CAPI void U_EXPORT2
umsg_vparse(const UMessageFormat *fmt,
const UChar *source,
int32_t sourceLength,
int32_t *count,
va_list ap,
UErrorCode *status);
/**
* Convert an 'apostrophe-friendly' pattern into a standard
* pattern. Standard patterns treat all apostrophes as
* quotes, which is problematic in some languages, e.g.
* French, where apostrophe is commonly used. This utility
* assumes that only an unpaired apostrophe immediately before
* a brace is a true quote. Other unpaired apostrophes are paired,
* and the resulting standard pattern string is returned.
*
* <p><b>Note</b> it is not guaranteed that the returned pattern
* is indeed a valid pattern. The only effect is to convert
* between patterns having different quoting semantics.
*
* @param pattern the 'apostrophe-friendly' patttern to convert
* @param patternLength the length of pattern, or -1 if unknown and pattern is null-terminated
* @param dest the buffer for the result, or NULL if preflight only
* @param destCapacity the length of the buffer, or 0 if preflighting
* @param ec the error code
* @return the length of the resulting text, not including trailing null
* if buffer has room for the trailing null, it is provided, otherwise
* not
* @stable ICU 3.4
*/
U_CAPI int32_t U_EXPORT2
umsg_autoQuoteApostrophe(const UChar* pattern,
int32_t patternLength,
UChar* dest,
int32_t destCapacity,
UErrorCode* ec);
#endif /* #if !UCONFIG_NO_FORMATTING */
#endif

View File

@ -0,0 +1,103 @@
// © 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
/*
**********************************************************************
* Copyright (c) 2002-2005, International Business Machines Corporation
* and others. All Rights Reserved.
**********************************************************************
* Date Name Description
* 01/14/2002 aliu Creation.
**********************************************************************
*/
#ifndef UNIREPL_H
#define UNIREPL_H
#include "unicode/utypes.h"
#if U_SHOW_CPLUSPLUS_API
/**
* \file
* \brief C++ API: UnicodeReplacer
*/
U_NAMESPACE_BEGIN
class Replaceable;
class UnicodeString;
class UnicodeSet;
/**
* <code>UnicodeReplacer</code> defines a protocol for objects that
* replace a range of characters in a Replaceable string with output
* text. The replacement is done via the Replaceable API so as to
* preserve out-of-band data.
*
* <p>This is a mixin class.
* @author Alan Liu
* @stable ICU 2.4
*/
class U_I18N_API UnicodeReplacer /* not : public UObject because this is an interface/mixin class */ {
public:
/**
* Destructor.
* @stable ICU 2.4
*/
virtual ~UnicodeReplacer();
/**
* Replace characters in 'text' from 'start' to 'limit' with the
* output text of this object. Update the 'cursor' parameter to
* give the cursor position and return the length of the
* replacement text.
*
* @param text the text to be matched
* @param start inclusive start index of text to be replaced
* @param limit exclusive end index of text to be replaced;
* must be greater than or equal to start
* @param cursor output parameter for the cursor position.
* Not all replacer objects will update this, but in a complete
* tree of replacer objects, representing the entire output side
* of a transliteration rule, at least one must update it.
* @return the number of 16-bit code units in the text replacing
* the characters at offsets start..(limit-1) in text
* @stable ICU 2.4
*/
virtual int32_t replace(Replaceable& text,
int32_t start,
int32_t limit,
int32_t& cursor) = 0;
/**
* Returns a string representation of this replacer. If the
* result of calling this function is passed to the appropriate
* parser, typically TransliteratorParser, it will produce another
* replacer that is equal to this one.
* @param result the string to receive the pattern. Previous
* contents will be deleted.
* @param escapeUnprintable if true then convert unprintable
* character to their hex escape representations, \\uxxxx or
* \\Uxxxxxxxx. Unprintable characters are defined by
* Utility.isUnprintable().
* @return a reference to 'result'.
* @stable ICU 2.4
*/
virtual UnicodeString& toReplacerPattern(UnicodeString& result,
UBool escapeUnprintable) const = 0;
/**
* Union the set of all characters that may output by this object
* into the given set.
* @param toUnionTo the set into which to union the output characters
* @stable ICU 2.4
*/
virtual void addReplacementSetTo(UnicodeSet& toUnionTo) const = 0;
};
U_NAMESPACE_END
#endif /* U_SHOW_CPLUSPLUS_API */
#endif

1507
deps/icu-small/source/i18n/unicode/unum.h vendored Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,576 @@
// © 2018 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
#ifndef __UNUMBERFORMATTER_H__
#define __UNUMBERFORMATTER_H__
#include "unicode/utypes.h"
#if !UCONFIG_NO_FORMATTING
#include "unicode/parseerr.h"
#include "unicode/unumberoptions.h"
#include "unicode/uformattednumber.h"
/**
* \file
* \brief C API: Localized number formatting; not recommended for C++.
*
* This is the C-compatible version of the NumberFormatter API introduced in ICU 60. C++ users should
* include unicode/numberformatter.h and use the proper C++ APIs.
*
* The C API accepts a number skeleton string for specifying the settings for formatting, which covers a
* very large subset of all possible number formatting features. For more information on number skeleton
* strings, see unicode/numberformatter.h.
*
* When using UNumberFormatter, which is treated as immutable, the results are exported to a mutable
* UFormattedNumber object, which you subsequently use for populating your string buffer or iterating over
* the fields.
*
* Example code:
* <pre>
* // Setup:
* UErrorCode ec = U_ZERO_ERROR;
* UNumberFormatter* uformatter = unumf_openForSkeletonAndLocale(u"precision-integer", -1, "en", &ec);
* UFormattedNumber* uresult = unumf_openResult(&ec);
* if (U_FAILURE(ec)) { return; }
*
* // Format a double:
* unumf_formatDouble(uformatter, 5142.3, uresult, &ec);
* if (U_FAILURE(ec)) { return; }
*
* // Export the string to a malloc'd buffer:
* int32_t len = unumf_resultToString(uresult, NULL, 0, &ec);
* // at this point, ec == U_BUFFER_OVERFLOW_ERROR
* ec = U_ZERO_ERROR;
* UChar* buffer = (UChar*) malloc((len+1)*sizeof(UChar));
* unumf_resultToString(uresult, buffer, len+1, &ec);
* if (U_FAILURE(ec)) { return; }
* // buffer should equal "5,142"
*
* // Cleanup:
* unumf_close(uformatter);
* unumf_closeResult(uresult);
* free(buffer);
* </pre>
*
* If you are a C++ user linking against the C libraries, you can use the LocalPointer versions of these
* APIs. The following example uses LocalPointer with the decimal number and field position APIs:
*
* <pre>
* // Setup:
* LocalUNumberFormatterPointer uformatter(unumf_openForSkeletonAndLocale(u"percent", -1, "en", &ec));
* LocalUFormattedNumberPointer uresult(unumf_openResult(&ec));
* if (U_FAILURE(ec)) { return; }
*
* // Format a decimal number:
* unumf_formatDecimal(uformatter.getAlias(), "9.87E-3", -1, uresult.getAlias(), &ec);
* if (U_FAILURE(ec)) { return; }
*
* // Get the location of the percent sign:
* UFieldPosition ufpos = {UNUM_PERCENT_FIELD, 0, 0};
* unumf_resultNextFieldPosition(uresult.getAlias(), &ufpos, &ec);
* // ufpos should contain beginIndex=7 and endIndex=8 since the string is "0.00987%"
*
* // No need to do any cleanup since we are using LocalPointer.
* </pre>
*/
/**
* An enum declaring how to resolve conflicts between maximum fraction digits and maximum
* significant digits.
*
* There are two modes, RELAXED and STRICT:
*
* - RELAXED: Relax one of the two constraints (fraction digits or significant digits) in order
* to round the number to a higher level of precision.
* - STRICT: Enforce both constraints, resulting in the number being rounded to a lower
* level of precision.
*
* The default settings for compact notation rounding are Max-Fraction = 0 (round to the nearest
* integer), Max-Significant = 2 (round to 2 significant digits), and priority RELAXED (choose
* the constraint that results in more digits being displayed).
*
* Conflicting *minimum* fraction and significant digits are always resolved in the direction that
* results in more trailing zeros.
*
* Example 1: Consider the number 3.141, with various different settings:
*
* - Max-Fraction = 1: "3.1"
* - Max-Significant = 3: "3.14"
*
* The rounding priority determines how to resolve the conflict when both Max-Fraction and
* Max-Significant are set. With RELAXED, the less-strict setting (the one that causes more digits
* to be displayed) will be used; Max-Significant wins. With STRICT, the more-strict setting (the
* one that causes fewer digits to be displayed) will be used; Max-Fraction wins.
*
* Example 2: Consider the number 8317, with various different settings:
*
* - Max-Fraction = 1: "8317"
* - Max-Significant = 3: "8320"
*
* Here, RELAXED favors Max-Fraction and STRICT favors Max-Significant. Note that this larger
* number caused the two modes to favor the opposite result.
*
* @stable ICU 69
*/
typedef enum UNumberRoundingPriority {
/**
* Favor greater precision by relaxing one of the rounding constraints.
*
* @stable ICU 69
*/
UNUM_ROUNDING_PRIORITY_RELAXED,
/**
* Favor adherence to all rounding constraints by producing lower precision.
*
* @stable ICU 69
*/
UNUM_ROUNDING_PRIORITY_STRICT,
} UNumberRoundingPriority;
/**
* An enum declaring how to render units, including currencies. Example outputs when formatting 123 USD and 123
* meters in <em>en-CA</em>:
*
* <p>
* <ul>
* <li>NARROW*: "$123.00" and "123 m"
* <li>SHORT: "US$ 123.00" and "123 m"
* <li>FULL_NAME: "123.00 US dollars" and "123 meters"
* <li>ISO_CODE: "USD 123.00" and undefined behavior
* <li>HIDDEN: "123.00" and "123"
* </ul>
*
* <p>
* This enum is similar to {@link UMeasureFormatWidth}.
*
* @stable ICU 60
*/
typedef enum UNumberUnitWidth {
/**
* Print an abbreviated version of the unit name. Similar to SHORT, but always use the shortest available
* abbreviation or symbol. This option can be used when the context hints at the identity of the unit. For more
* information on the difference between NARROW and SHORT, see SHORT.
*
* <p>
* In CLDR, this option corresponds to the "Narrow" format for measure units and the "¤¤¤¤¤" placeholder for
* currencies.
*
* @stable ICU 60
*/
UNUM_UNIT_WIDTH_NARROW = 0,
/**
* Print an abbreviated version of the unit name. Similar to NARROW, but use a slightly wider abbreviation or
* symbol when there may be ambiguity. This is the default behavior.
*
* <p>
* For example, in <em>es-US</em>, the SHORT form for Fahrenheit is "{0} °F", but the NARROW form is "{0}°",
* since Fahrenheit is the customary unit for temperature in that locale.
*
* <p>
* In CLDR, this option corresponds to the "Short" format for measure units and the "¤" placeholder for
* currencies.
*
* @stable ICU 60
*/
UNUM_UNIT_WIDTH_SHORT = 1,
/**
* Print the full name of the unit, without any abbreviations.
*
* <p>
* In CLDR, this option corresponds to the default format for measure units and the "¤¤¤" placeholder for
* currencies.
*
* @stable ICU 60
*/
UNUM_UNIT_WIDTH_FULL_NAME = 2,
/**
* Use the three-digit ISO XXX code in place of the symbol for displaying currencies. The behavior of this
* option is currently undefined for use with measure units.
*
* <p>
* In CLDR, this option corresponds to the "¤¤" placeholder for currencies.
*
* @stable ICU 60
*/
UNUM_UNIT_WIDTH_ISO_CODE = 3,
/**
* Use the formal variant of the currency symbol; for example, "NT$" for the New Taiwan
* dollar in zh-TW.
*
* <p>
* Behavior of this option with non-currency units is not defined at this time.
*
* @stable ICU 68
*/
UNUM_UNIT_WIDTH_FORMAL = 4,
/**
* Use the alternate variant of the currency symbol; for example, "TL" for the Turkish
* lira (TRY).
*
* <p>
* Behavior of this option with non-currency units is not defined at this time.
*
* @stable ICU 68
*/
UNUM_UNIT_WIDTH_VARIANT = 5,
/**
* Format the number according to the specified unit, but do not display the unit. For currencies, apply
* monetary symbols and formats as with SHORT, but omit the currency symbol. For measure units, the behavior is
* equivalent to not specifying the unit at all.
*
* @stable ICU 60
*/
UNUM_UNIT_WIDTH_HIDDEN = 6,
// Do not conditionalize the following with #ifndef U_HIDE_INTERNAL_API,
// needed for unconditionalized struct MacroProps
/**
* One more than the highest UNumberUnitWidth value.
*
* @internal ICU 60: The numeric value may change over time; see ICU ticket #12420.
*/
UNUM_UNIT_WIDTH_COUNT = 7
} UNumberUnitWidth;
/**
* An enum declaring how to denote positive and negative numbers. Example outputs when formatting
* 123, 0, and -123 in <em>en-US</em>:
*
* <ul>
* <li>AUTO: "123", "0", and "-123"
* <li>ALWAYS: "+123", "+0", and "-123"
* <li>NEVER: "123", "0", and "123"
* <li>ACCOUNTING: "$123", "$0", and "($123)"
* <li>ACCOUNTING_ALWAYS: "+$123", "+$0", and "($123)"
* <li>EXCEPT_ZERO: "+123", "0", and "-123"
* <li>ACCOUNTING_EXCEPT_ZERO: "+$123", "$0", and "($123)"
* </ul>
*
* <p>
* The exact format, including the position and the code point of the sign, differ by locale.
*
* @stable ICU 60
*/
typedef enum UNumberSignDisplay {
/**
* Show the minus sign on negative numbers, and do not show the sign on positive numbers. This is the default
* behavior.
*
* If using this option, a sign will be displayed on negative zero, including negative numbers
* that round to zero. To hide the sign on negative zero, use the NEGATIVE option.
*
* @stable ICU 60
*/
UNUM_SIGN_AUTO,
/**
* Show the minus sign on negative numbers and the plus sign on positive numbers, including zero.
* To hide the sign on zero, see {@link UNUM_SIGN_EXCEPT_ZERO}.
*
* @stable ICU 60
*/
UNUM_SIGN_ALWAYS,
/**
* Do not show the sign on positive or negative numbers.
*
* @stable ICU 60
*/
UNUM_SIGN_NEVER,
/**
* Use the locale-dependent accounting format on negative numbers, and do not show the sign on positive numbers.
*
* <p>
* The accounting format is defined in CLDR and varies by locale; in many Western locales, the format is a pair
* of parentheses around the number.
*
* <p>
* Note: Since CLDR defines the accounting format in the monetary context only, this option falls back to the
* AUTO sign display strategy when formatting without a currency unit. This limitation may be lifted in the
* future.
*
* @stable ICU 60
*/
UNUM_SIGN_ACCOUNTING,
/**
* Use the locale-dependent accounting format on negative numbers, and show the plus sign on
* positive numbers, including zero. For more information on the accounting format, see the
* ACCOUNTING sign display strategy. To hide the sign on zero, see
* {@link UNUM_SIGN_ACCOUNTING_EXCEPT_ZERO}.
*
* @stable ICU 60
*/
UNUM_SIGN_ACCOUNTING_ALWAYS,
/**
* Show the minus sign on negative numbers and the plus sign on positive numbers. Do not show a
* sign on zero, numbers that round to zero, or NaN.
*
* @stable ICU 61
*/
UNUM_SIGN_EXCEPT_ZERO,
/**
* Use the locale-dependent accounting format on negative numbers, and show the plus sign on
* positive numbers. Do not show a sign on zero, numbers that round to zero, or NaN. For more
* information on the accounting format, see the ACCOUNTING sign display strategy.
*
* @stable ICU 61
*/
UNUM_SIGN_ACCOUNTING_EXCEPT_ZERO,
/**
* Same as AUTO, but do not show the sign on negative zero.
*
* @stable ICU 69
*/
UNUM_SIGN_NEGATIVE,
/**
* Same as ACCOUNTING, but do not show the sign on negative zero.
*
* @stable ICU 69
*/
UNUM_SIGN_ACCOUNTING_NEGATIVE,
// Do not conditionalize the following with #ifndef U_HIDE_INTERNAL_API,
// needed for unconditionalized struct MacroProps
/**
* One more than the highest UNumberSignDisplay value.
*
* @internal ICU 60: The numeric value may change over time; see ICU ticket #12420.
*/
UNUM_SIGN_COUNT = 9,
} UNumberSignDisplay;
/**
* An enum declaring how to render the decimal separator.
*
* <p>
* <ul>
* <li>UNUM_DECIMAL_SEPARATOR_AUTO: "1", "1.1"
* <li>UNUM_DECIMAL_SEPARATOR_ALWAYS: "1.", "1.1"
* </ul>
*
* @stable ICU 60
*/
typedef enum UNumberDecimalSeparatorDisplay {
/**
* Show the decimal separator when there are one or more digits to display after the separator, and do not show
* it otherwise. This is the default behavior.
*
* @stable ICU 60
*/
UNUM_DECIMAL_SEPARATOR_AUTO,
/**
* Always show the decimal separator, even if there are no digits to display after the separator.
*
* @stable ICU 60
*/
UNUM_DECIMAL_SEPARATOR_ALWAYS,
// Do not conditionalize the following with #ifndef U_HIDE_INTERNAL_API,
// needed for unconditionalized struct MacroProps
/**
* One more than the highest UNumberDecimalSeparatorDisplay value.
*
* @internal ICU 60: The numeric value may change over time; see ICU ticket #12420.
*/
UNUM_DECIMAL_SEPARATOR_COUNT
} UNumberDecimalSeparatorDisplay;
/**
* An enum declaring how to render trailing zeros.
*
* - UNUM_TRAILING_ZERO_AUTO: 0.90, 1.00, 1.10
* - UNUM_TRAILING_ZERO_HIDE_IF_WHOLE: 0.90, 1, 1.10
*
* @stable ICU 69
*/
typedef enum UNumberTrailingZeroDisplay {
/**
* Display trailing zeros according to the settings for minimum fraction and significant digits.
*
* @stable ICU 69
*/
UNUM_TRAILING_ZERO_AUTO,
/**
* Same as AUTO, but hide trailing zeros after the decimal separator if they are all zero.
*
* @stable ICU 69
*/
UNUM_TRAILING_ZERO_HIDE_IF_WHOLE,
} UNumberTrailingZeroDisplay;
struct UNumberFormatter;
/**
* C-compatible version of icu::number::LocalizedNumberFormatter.
*
* NOTE: This is a C-compatible API; C++ users should build against numberformatter.h instead.
*
* @stable ICU 62
*/
typedef struct UNumberFormatter UNumberFormatter;
/**
* Creates a new UNumberFormatter for the given skeleton string and locale. This is currently the only
* method for creating a new UNumberFormatter.
*
* Objects of type UNumberFormatter returned by this method are threadsafe.
*
* For more details on skeleton strings, see the documentation in numberformatter.h. For more details on
* the usage of this API, see the documentation at the top of unumberformatter.h.
*
* For more information on number skeleton strings, see:
* https://unicode-org.github.io/icu/userguide/format_parse/numbers/skeletons.html
*
* NOTE: This is a C-compatible API; C++ users should build against numberformatter.h instead.
*
* @param skeleton The skeleton string, like u"percent precision-integer"
* @param skeletonLen The number of UChars in the skeleton string, or -1 if it is NUL-terminated.
* @param locale The NUL-terminated locale ID.
* @param ec Set if an error occurs.
* @stable ICU 62
*/
U_CAPI UNumberFormatter* U_EXPORT2
unumf_openForSkeletonAndLocale(const UChar* skeleton, int32_t skeletonLen, const char* locale,
UErrorCode* ec);
/**
* Like unumf_openForSkeletonAndLocale, but accepts a UParseError, which will be populated with the
* location of a skeleton syntax error if such a syntax error exists.
*
* For more information on number skeleton strings, see:
* https://unicode-org.github.io/icu/userguide/format_parse/numbers/skeletons.html
*
* @param skeleton The skeleton string, like u"percent precision-integer"
* @param skeletonLen The number of UChars in the skeleton string, or -1 if it is NUL-terminated.
* @param locale The NUL-terminated locale ID.
* @param perror A parse error struct populated if an error occurs when parsing. Can be NULL.
* If no error occurs, perror->offset will be set to -1.
* @param ec Set if an error occurs.
* @stable ICU 64
*/
U_CAPI UNumberFormatter* U_EXPORT2
unumf_openForSkeletonAndLocaleWithError(
const UChar* skeleton, int32_t skeletonLen, const char* locale, UParseError* perror, UErrorCode* ec);
/**
* Uses a UNumberFormatter to format an integer to a UFormattedNumber. A string, field position, and other
* information can be retrieved from the UFormattedNumber.
*
* The UNumberFormatter can be shared between threads. Each thread should have its own local
* UFormattedNumber, however, for storing the result of the formatting operation.
*
* NOTE: This is a C-compatible API; C++ users should build against numberformatter.h instead.
*
* @param uformatter A formatter object created by unumf_openForSkeletonAndLocale or similar.
* @param value The number to be formatted.
* @param uresult The object that will be mutated to store the result; see unumf_openResult.
* @param ec Set if an error occurs.
* @stable ICU 62
*/
U_CAPI void U_EXPORT2
unumf_formatInt(const UNumberFormatter* uformatter, int64_t value, UFormattedNumber* uresult,
UErrorCode* ec);
/**
* Uses a UNumberFormatter to format a double to a UFormattedNumber. A string, field position, and other
* information can be retrieved from the UFormattedNumber.
*
* The UNumberFormatter can be shared between threads. Each thread should have its own local
* UFormattedNumber, however, for storing the result of the formatting operation.
*
* NOTE: This is a C-compatible API; C++ users should build against numberformatter.h instead.
*
* @param uformatter A formatter object created by unumf_openForSkeletonAndLocale or similar.
* @param value The number to be formatted.
* @param uresult The object that will be mutated to store the result; see unumf_openResult.
* @param ec Set if an error occurs.
* @stable ICU 62
*/
U_CAPI void U_EXPORT2
unumf_formatDouble(const UNumberFormatter* uformatter, double value, UFormattedNumber* uresult,
UErrorCode* ec);
/**
* Uses a UNumberFormatter to format a decimal number to a UFormattedNumber. A string, field position, and
* other information can be retrieved from the UFormattedNumber.
*
* The UNumberFormatter can be shared between threads. Each thread should have its own local
* UFormattedNumber, however, for storing the result of the formatting operation.
*
* The syntax of the unformatted number is a "numeric string" as defined in the Decimal Arithmetic
* Specification, available at http://speleotrove.com/decimal
*
* NOTE: This is a C-compatible API; C++ users should build against numberformatter.h instead.
*
* @param uformatter A formatter object created by unumf_openForSkeletonAndLocale or similar.
* @param value The numeric string to be formatted.
* @param valueLen The length of the numeric string, or -1 if it is NUL-terminated.
* @param uresult The object that will be mutated to store the result; see unumf_openResult.
* @param ec Set if an error occurs.
* @stable ICU 62
*/
U_CAPI void U_EXPORT2
unumf_formatDecimal(const UNumberFormatter* uformatter, const char* value, int32_t valueLen,
UFormattedNumber* uresult, UErrorCode* ec);
/**
* Releases the UNumberFormatter created by unumf_openForSkeletonAndLocale().
*
* @param uformatter An object created by unumf_openForSkeletonAndLocale().
* @stable ICU 62
*/
U_CAPI void U_EXPORT2
unumf_close(UNumberFormatter* uformatter);
#if U_SHOW_CPLUSPLUS_API
U_NAMESPACE_BEGIN
/**
* \class LocalUNumberFormatterPointer
* "Smart pointer" class; closes a UNumberFormatter via unumf_close().
* For most methods see the LocalPointerBase base class.
*
* Usage:
* <pre>
* LocalUNumberFormatterPointer uformatter(unumf_openForSkeletonAndLocale(...));
* // no need to explicitly call unumf_close()
* </pre>
*
* @see LocalPointerBase
* @see LocalPointer
* @stable ICU 62
*/
U_DEFINE_LOCAL_OPEN_POINTER(LocalUNumberFormatterPointer, UNumberFormatter, unumf_close);
U_NAMESPACE_END
#endif // U_SHOW_CPLUSPLUS_API
#endif /* #if !UCONFIG_NO_FORMATTING */
#endif //__UNUMBERFORMATTER_H__

View File

@ -0,0 +1,173 @@
// © 2017 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
#ifndef __UNUMBEROPTIONS_H__
#define __UNUMBEROPTIONS_H__
#include "unicode/utypes.h"
#if !UCONFIG_NO_FORMATTING
/**
* \file
* \brief C API: Header-only input options for various number formatting APIs.
*
* You do not normally need to include this header file directly, because it is included in all
* files that use these enums.
*/
/** The possible number format rounding modes.
*
* <p>
* For more detail on rounding modes, see:
* https://unicode-org.github.io/icu/userguide/format_parse/numbers/rounding-modes
*
* @stable ICU 2.0
*/
typedef enum UNumberFormatRoundingMode {
UNUM_ROUND_CEILING,
UNUM_ROUND_FLOOR,
UNUM_ROUND_DOWN,
UNUM_ROUND_UP,
/**
* Half-even rounding
* @stable, ICU 3.8
*/
UNUM_ROUND_HALFEVEN,
#ifndef U_HIDE_DEPRECATED_API
/**
* Half-even rounding, misspelled name
* @deprecated, ICU 3.8
*/
UNUM_FOUND_HALFEVEN = UNUM_ROUND_HALFEVEN,
#endif /* U_HIDE_DEPRECATED_API */
UNUM_ROUND_HALFDOWN = UNUM_ROUND_HALFEVEN + 1,
UNUM_ROUND_HALFUP,
/**
* ROUND_UNNECESSARY reports an error if formatted result is not exact.
* @stable ICU 4.8
*/
UNUM_ROUND_UNNECESSARY,
/**
* Rounds ties toward the odd number.
* @stable ICU 69
*/
UNUM_ROUND_HALF_ODD,
/**
* Rounds ties toward +∞.
* @stable ICU 69
*/
UNUM_ROUND_HALF_CEILING,
/**
* Rounds ties toward -∞.
* @stable ICU 69
*/
UNUM_ROUND_HALF_FLOOR,
} UNumberFormatRoundingMode;
/**
* An enum declaring the strategy for when and how to display grouping separators (i.e., the
* separator, often a comma or period, after every 2-3 powers of ten). The choices are several
* pre-built strategies for different use cases that employ locale data whenever possible. Example
* outputs for 1234 and 1234567 in <em>en-IN</em>:
*
* <ul>
* <li>OFF: 1234 and 12345
* <li>MIN2: 1234 and 12,34,567
* <li>AUTO: 1,234 and 12,34,567
* <li>ON_ALIGNED: 1,234 and 12,34,567
* <li>THOUSANDS: 1,234 and 1,234,567
* </ul>
*
* <p>
* The default is AUTO, which displays grouping separators unless the locale data says that grouping
* is not customary. To force grouping for all numbers greater than 1000 consistently across locales,
* use ON_ALIGNED. On the other hand, to display grouping less frequently than the default, use MIN2
* or OFF. See the docs of each option for details.
*
* <p>
* Note: This enum specifies the strategy for grouping sizes. To set which character to use as the
* grouping separator, use the "symbols" setter.
*
* @stable ICU 63
*/
typedef enum UNumberGroupingStrategy {
/**
* Do not display grouping separators in any locale.
*
* @stable ICU 61
*/
UNUM_GROUPING_OFF,
/**
* Display grouping using locale defaults, except do not show grouping on values smaller than
* 10000 (such that there is a <em>minimum of two digits</em> before the first separator).
*
* <p>
* Note that locales may restrict grouping separators to be displayed only on 1 million or
* greater (for example, ee and hu) or disable grouping altogether (for example, bg currency).
*
* <p>
* Locale data is used to determine whether to separate larger numbers into groups of 2
* (customary in South Asia) or groups of 3 (customary in Europe and the Americas).
*
* @stable ICU 61
*/
UNUM_GROUPING_MIN2,
/**
* Display grouping using the default strategy for all locales. This is the default behavior.
*
* <p>
* Note that locales may restrict grouping separators to be displayed only on 1 million or
* greater (for example, ee and hu) or disable grouping altogether (for example, bg currency).
*
* <p>
* Locale data is used to determine whether to separate larger numbers into groups of 2
* (customary in South Asia) or groups of 3 (customary in Europe and the Americas).
*
* @stable ICU 61
*/
UNUM_GROUPING_AUTO,
/**
* Always display the grouping separator on values of at least 1000.
*
* <p>
* This option ignores the locale data that restricts or disables grouping, described in MIN2 and
* AUTO. This option may be useful to normalize the alignment of numbers, such as in a
* spreadsheet.
*
* <p>
* Locale data is used to determine whether to separate larger numbers into groups of 2
* (customary in South Asia) or groups of 3 (customary in Europe and the Americas).
*
* @stable ICU 61
*/
UNUM_GROUPING_ON_ALIGNED,
/**
* Use the Western defaults: groups of 3 and enabled for all numbers 1000 or greater. Do not use
* locale data for determining the grouping strategy.
*
* @stable ICU 61
*/
UNUM_GROUPING_THOUSANDS
#ifndef U_HIDE_INTERNAL_API
,
/**
* One more than the highest UNumberGroupingStrategy value.
*
* @internal ICU 62: The numeric value may change over time; see ICU ticket #12420.
*/
UNUM_GROUPING_COUNT
#endif /* U_HIDE_INTERNAL_API */
} UNumberGroupingStrategy;
#endif /* #if !UCONFIG_NO_FORMATTING */
#endif //__UNUMBEROPTIONS_H__

View File

@ -0,0 +1,471 @@
// © 2020 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
#ifndef __UNUMBERRANGEFORMATTER_H__
#define __UNUMBERRANGEFORMATTER_H__
#include "unicode/utypes.h"
#if !UCONFIG_NO_FORMATTING
#include "unicode/parseerr.h"
#include "unicode/ufieldpositer.h"
#include "unicode/umisc.h"
#include "unicode/uformattedvalue.h"
#include "unicode/uformattable.h"
/**
* \file
* \brief C API: Localized number range formatting
*
* This is the C-compatible version of the NumberRangeFormatter API. C++ users
* should include unicode/numberrangeformatter.h and use the proper C++ APIs.
*
* First create a UNumberRangeFormatter, which is immutable, and then format to
* a UFormattedNumberRange.
*
* Example code:
* <pre>
* // Setup:
* UErrorCode ec = U_ZERO_ERROR;
* UNumberRangeFormatter* uformatter = unumrf_openForSkeletonCollapseIdentityFallbackAndLocaleWithError(
* u"currency/USD precision-integer",
* -1,
* UNUM_RANGE_COLLAPSE_AUTO,
* UNUM_IDENTITY_FALLBACK_APPROXIMATELY,
* "en-US",
* NULL,
* &ec);
* UFormattedNumberRange* uresult = unumrf_openResult(&ec);
* if (U_FAILURE(ec)) { return; }
*
* // Format a double range:
* unumrf_formatDoubleRange(uformatter, 3.0, 5.0, uresult, &ec);
* if (U_FAILURE(ec)) { return; }
*
* // Get the result string:
* int32_t len;
* const UChar* str = ufmtval_getString(unumrf_resultAsValue(uresult, &ec), &len, &ec);
* if (U_FAILURE(ec)) { return; }
* // str should equal "$3 $5"
*
* // Cleanup:
* unumf_close(uformatter);
* unumf_closeResult(uresult);
* </pre>
*
* If you are a C++ user linking against the C libraries, you can use the LocalPointer versions of these
* APIs. The following example uses LocalPointer with the decimal number and field position APIs:
*
* <pre>
* // Setup:
* LocalUNumberRangeFormatterPointer uformatter(
* unumrf_openForSkeletonCollapseIdentityFallbackAndLocaleWithError(...));
* LocalUFormattedNumberRangePointer uresult(unumrf_openResult(&ec));
* if (U_FAILURE(ec)) { return; }
*
* // Format a double number range:
* unumrf_formatDoubleRange(uformatter.getAlias(), 3.0, 5.0, uresult.getAlias(), &ec);
* if (U_FAILURE(ec)) { return; }
*
* // No need to do any cleanup since we are using LocalPointer.
* </pre>
*
* You can also get field positions. For more information, see uformattedvalue.h.
*/
/**
* Defines how to merge fields that are identical across the range sign.
*
* @stable ICU 63
*/
typedef enum UNumberRangeCollapse {
/**
* Use locale data and heuristics to determine how much of the string to collapse. Could end up collapsing none,
* some, or all repeated pieces in a locale-sensitive way.
*
* The heuristics used for this option are subject to change over time.
*
* @stable ICU 63
*/
UNUM_RANGE_COLLAPSE_AUTO,
/**
* Do not collapse any part of the number. Example: "3.2 thousand kilograms 5.3 thousand kilograms"
*
* @stable ICU 63
*/
UNUM_RANGE_COLLAPSE_NONE,
/**
* Collapse the unit part of the number, but not the notation, if present. Example: "3.2 thousand 5.3 thousand
* kilograms"
*
* @stable ICU 63
*/
UNUM_RANGE_COLLAPSE_UNIT,
/**
* Collapse any field that is equal across the range sign. May introduce ambiguity on the magnitude of the
* number. Example: "3.2 5.3 thousand kilograms"
*
* @stable ICU 63
*/
UNUM_RANGE_COLLAPSE_ALL
} UNumberRangeCollapse;
/**
* Defines the behavior when the two numbers in the range are identical after rounding. To programmatically detect
* when the identity fallback is used, compare the lower and upper BigDecimals via FormattedNumber.
*
* @stable ICU 63
* @see NumberRangeFormatter
*/
typedef enum UNumberRangeIdentityFallback {
/**
* Show the number as a single value rather than a range. Example: "$5"
*
* @stable ICU 63
*/
UNUM_IDENTITY_FALLBACK_SINGLE_VALUE,
/**
* Show the number using a locale-sensitive approximation pattern. If the numbers were the same before rounding,
* show the single value. Example: "~$5" or "$5"
*
* @stable ICU 63
*/
UNUM_IDENTITY_FALLBACK_APPROXIMATELY_OR_SINGLE_VALUE,
/**
* Show the number using a locale-sensitive approximation pattern. Use the range pattern always, even if the
* inputs are the same. Example: "~$5"
*
* @stable ICU 63
*/
UNUM_IDENTITY_FALLBACK_APPROXIMATELY,
/**
* Show the number as the range of two equal values. Use the range pattern always, even if the inputs are the
* same. Example (with RangeCollapse.NONE): "$5 $5"
*
* @stable ICU 63
*/
UNUM_IDENTITY_FALLBACK_RANGE
} UNumberRangeIdentityFallback;
/**
* Used in the result class FormattedNumberRange to indicate to the user whether the numbers formatted in the range
* were equal or not, and whether or not the identity fallback was applied.
*
* @stable ICU 63
* @see NumberRangeFormatter
*/
typedef enum UNumberRangeIdentityResult {
/**
* Used to indicate that the two numbers in the range were equal, even before any rounding rules were applied.
*
* @stable ICU 63
* @see NumberRangeFormatter
*/
UNUM_IDENTITY_RESULT_EQUAL_BEFORE_ROUNDING,
/**
* Used to indicate that the two numbers in the range were equal, but only after rounding rules were applied.
*
* @stable ICU 63
* @see NumberRangeFormatter
*/
UNUM_IDENTITY_RESULT_EQUAL_AFTER_ROUNDING,
/**
* Used to indicate that the two numbers in the range were not equal, even after rounding rules were applied.
*
* @stable ICU 63
* @see NumberRangeFormatter
*/
UNUM_IDENTITY_RESULT_NOT_EQUAL,
#ifndef U_HIDE_INTERNAL_API
/**
* The number of entries in this enum.
* @internal
*/
UNUM_IDENTITY_RESULT_COUNT
#endif /* U_HIDE_INTERNAL_API */
} UNumberRangeIdentityResult;
struct UNumberRangeFormatter;
/**
* C-compatible version of icu::number::LocalizedNumberRangeFormatter.
*
* NOTE: This is a C-compatible API; C++ users should build against numberrangeformatter.h instead.
*
* @stable ICU 68
*/
typedef struct UNumberRangeFormatter UNumberRangeFormatter;
struct UFormattedNumberRange;
/**
* C-compatible version of icu::number::FormattedNumberRange.
*
* NOTE: This is a C-compatible API; C++ users should build against numberrangeformatter.h instead.
*
* @stable ICU 68
*/
typedef struct UFormattedNumberRange UFormattedNumberRange;
/**
* Creates a new UNumberFormatter for the given skeleton string, collapse option, identity fallback
* option, and locale. This is currently the only method for creating a new UNumberRangeFormatter.
*
* Objects of type UNumberRangeFormatter returned by this method are threadsafe.
*
* For more details on skeleton strings, see the documentation in numberrangeformatter.h. For more
* details on the usage of this API, see the documentation at the top of unumberrangeformatter.h.
*
* NOTE: This is a C-compatible API; C++ users should build against numberrangeformatter.h instead.
*
* @param skeleton The skeleton string, like u"percent precision-integer"
* @param skeletonLen The number of UChars in the skeleton string, or -1 if it is NUL-terminated.
* @param collapse Option for how to merge affixes (if unsure, use UNUM_RANGE_COLLAPSE_AUTO)
* @param identityFallback Option for resolving when both sides of the range are equal.
* @param locale The NUL-terminated locale ID.
* @param perror A parse error struct populated if an error occurs when parsing. Can be NULL.
* If no error occurs, perror->offset will be set to -1.
* @param ec Set if an error occurs.
* @stable ICU 68
*/
U_CAPI UNumberRangeFormatter* U_EXPORT2
unumrf_openForSkeletonWithCollapseAndIdentityFallback(
const UChar* skeleton,
int32_t skeletonLen,
UNumberRangeCollapse collapse,
UNumberRangeIdentityFallback identityFallback,
const char* locale,
UParseError* perror,
UErrorCode* ec);
/**
* Creates an object to hold the result of a UNumberRangeFormatter
* operation. The object can be used repeatedly; it is cleared whenever
* passed to a format function.
*
* @param ec Set if an error occurs.
* @stable ICU 68
*/
U_CAPI UFormattedNumberRange* U_EXPORT2
unumrf_openResult(UErrorCode* ec);
/**
* Uses a UNumberRangeFormatter to format a range of doubles.
*
* The UNumberRangeFormatter can be shared between threads. Each thread should have its own local
* UFormattedNumberRange, however, for storing the result of the formatting operation.
*
* NOTE: This is a C-compatible API; C++ users should build against numberrangeformatter.h instead.
*
* @param uformatter A formatter object; see unumberrangeformatter.h.
* @param first The first (usually smaller) number in the range.
* @param second The second (usually larger) number in the range.
* @param uresult The object that will be mutated to store the result; see unumrf_openResult.
* @param ec Set if an error occurs.
* @stable ICU 68
*/
U_CAPI void U_EXPORT2
unumrf_formatDoubleRange(
const UNumberRangeFormatter* uformatter,
double first,
double second,
UFormattedNumberRange* uresult,
UErrorCode* ec);
/**
* Uses a UNumberRangeFormatter to format a range of decimal numbers.
*
* With a decimal number string, you can specify an input with arbitrary precision.
*
* The UNumberRangeFormatter can be shared between threads. Each thread should have its own local
* UFormattedNumberRange, however, for storing the result of the formatting operation.
*
* NOTE: This is a C-compatible API; C++ users should build against numberrangeformatter.h instead.
*
* @param uformatter A formatter object; see unumberrangeformatter.h.
* @param first The first (usually smaller) number in the range.
* @param firstLen The length of the first decimal number string.
* @param second The second (usually larger) number in the range.
* @param secondLen The length of the second decimal number string.
* @param uresult The object that will be mutated to store the result; see unumrf_openResult.
* @param ec Set if an error occurs.
* @stable ICU 68
*/
U_CAPI void U_EXPORT2
unumrf_formatDecimalRange(
const UNumberRangeFormatter* uformatter,
const char* first,
int32_t firstLen,
const char* second,
int32_t secondLen,
UFormattedNumberRange* uresult,
UErrorCode* ec);
/**
* Returns a representation of a UFormattedNumberRange as a UFormattedValue,
* which can be subsequently passed to any API requiring that type.
*
* The returned object is owned by the UFormattedNumberRange and is valid
* only as long as the UFormattedNumber is present and unchanged in memory.
*
* You can think of this method as a cast between types.
*
* @param uresult The object containing the formatted number range.
* @param ec Set if an error occurs.
* @return A UFormattedValue owned by the input object.
* @stable ICU 68
*/
U_CAPI const UFormattedValue* U_EXPORT2
unumrf_resultAsValue(const UFormattedNumberRange* uresult, UErrorCode* ec);
/**
* Extracts the identity result from a UFormattedNumberRange.
*
* NOTE: This is a C-compatible API; C++ users should build against numberformatter.h instead.
*
* @param uresult The object containing the formatted number range.
* @param ec Set if an error occurs.
* @return The identity result; see UNumberRangeIdentityResult.
* @stable ICU 68
*/
U_CAPI UNumberRangeIdentityResult U_EXPORT2
unumrf_resultGetIdentityResult(
const UFormattedNumberRange* uresult,
UErrorCode* ec);
/**
* Extracts the first formatted number as a decimal number. This endpoint
* is useful for obtaining the exact number being printed after scaling
* and rounding have been applied by the number range formatting pipeline.
*
* The syntax of the unformatted number is a "numeric string"
* as defined in the Decimal Arithmetic Specification, available at
* http://speleotrove.com/decimal
*
* @param uresult The input object containing the formatted number range.
* @param dest the 8-bit char buffer into which the decimal number is placed
* @param destCapacity The size, in chars, of the destination buffer. May be zero
* for precomputing the required size.
* @param ec receives any error status.
* If U_BUFFER_OVERFLOW_ERROR: Returns number of chars for
* preflighting.
* @return Number of chars in the data. Does not include a trailing NUL.
* @stable ICU 68
*/
U_CAPI int32_t U_EXPORT2
unumrf_resultGetFirstDecimalNumber(
const UFormattedNumberRange* uresult,
char* dest,
int32_t destCapacity,
UErrorCode* ec);
/**
* Extracts the second formatted number as a decimal number. This endpoint
* is useful for obtaining the exact number being printed after scaling
* and rounding have been applied by the number range formatting pipeline.
*
* The syntax of the unformatted number is a "numeric string"
* as defined in the Decimal Arithmetic Specification, available at
* http://speleotrove.com/decimal
*
* @param uresult The input object containing the formatted number range.
* @param dest the 8-bit char buffer into which the decimal number is placed
* @param destCapacity The size, in chars, of the destination buffer. May be zero
* for precomputing the required size.
* @param ec receives any error status.
* If U_BUFFER_OVERFLOW_ERROR: Returns number of chars for
* preflighting.
* @return Number of chars in the data. Does not include a trailing NUL.
* @stable ICU 68
*/
U_CAPI int32_t U_EXPORT2
unumrf_resultGetSecondDecimalNumber(
const UFormattedNumberRange* uresult,
char* dest,
int32_t destCapacity,
UErrorCode* ec);
/**
* Releases the UNumberFormatter created by unumf_openForSkeletonAndLocale().
*
* @param uformatter An object created by unumf_openForSkeletonAndLocale().
* @stable ICU 68
*/
U_CAPI void U_EXPORT2
unumrf_close(UNumberRangeFormatter* uformatter);
/**
* Releases the UFormattedNumber created by unumf_openResult().
*
* @param uresult An object created by unumf_openResult().
* @stable ICU 68
*/
U_CAPI void U_EXPORT2
unumrf_closeResult(UFormattedNumberRange* uresult);
#if U_SHOW_CPLUSPLUS_API
U_NAMESPACE_BEGIN
/**
* \class LocalUNumberRangeFormatterPointer
* "Smart pointer" class; closes a UNumberFormatter via unumf_close().
* For most methods see the LocalPointerBase base class.
*
* Usage:
* <pre>
* LocalUNumberRangeFormatterPointer uformatter(
* unumrf_openForSkeletonCollapseIdentityFallbackAndLocaleWithError(...));
* // no need to explicitly call unumrf_close()
* </pre>
*
* @see LocalPointerBase
* @see LocalPointer
* @stable ICU 68
*/
U_DEFINE_LOCAL_OPEN_POINTER(LocalUNumberRangeFormatterPointer, UNumberRangeFormatter, unumrf_close);
/**
* \class LocalUFormattedNumberPointer
* "Smart pointer" class; closes a UFormattedNumber via unumf_closeResult().
* For most methods see the LocalPointerBase base class.
*
* Usage:
* <pre>
* LocalUFormattedNumberRangePointer uresult(unumrf_openResult(...));
* // no need to explicitly call unumrf_closeResult()
* </pre>
*
* @see LocalPointerBase
* @see LocalPointer
* @stable ICU 68
*/
U_DEFINE_LOCAL_OPEN_POINTER(LocalUFormattedNumberRangePointer, UFormattedNumberRange, unumrf_closeResult);
U_NAMESPACE_END
#endif // U_SHOW_CPLUSPLUS_API
#endif /* #if !UCONFIG_NO_FORMATTING */
#endif //__UNUMBERRANGEFORMATTER_H__

View File

@ -0,0 +1,176 @@
// © 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
/*
*****************************************************************************************
* Copyright (C) 2013-2014, International Business Machines
* Corporation and others. All Rights Reserved.
*****************************************************************************************
*/
#ifndef UNUMSYS_H
#define UNUMSYS_H
#include "unicode/utypes.h"
#if !UCONFIG_NO_FORMATTING
#include "unicode/uenum.h"
#if U_SHOW_CPLUSPLUS_API
#include "unicode/localpointer.h"
#endif // U_SHOW_CPLUSPLUS_API
/**
* \file
* \brief C API: UNumberingSystem, information about numbering systems
*
* Defines numbering systems. A numbering system describes the scheme by which
* numbers are to be presented to the end user. In its simplest form, a numbering
* system describes the set of digit characters that are to be used to display
* numbers, such as Western digits, Thai digits, Arabic-Indic digits, etc., in a
* positional numbering system with a specified radix (typically 10).
* More complicated numbering systems are algorithmic in nature, and require use
* of an RBNF formatter (rule based number formatter), in order to calculate
* the characters to be displayed for a given number. Examples of algorithmic
* numbering systems include Roman numerals, Chinese numerals, and Hebrew numerals.
* Formatting rules for many commonly used numbering systems are included in
* the ICU package, based on the numbering system rules defined in CLDR.
* Alternate numbering systems can be specified to a locale by using the
* numbers locale keyword.
*/
/**
* Opaque UNumberingSystem object for use in C programs.
* @stable ICU 52
*/
struct UNumberingSystem;
typedef struct UNumberingSystem UNumberingSystem; /**< C typedef for struct UNumberingSystem. @stable ICU 52 */
/**
* Opens a UNumberingSystem object using the default numbering system for the specified
* locale.
* @param locale The locale for which the default numbering system should be opened.
* @param status A pointer to a UErrorCode to receive any errors. For example, this
* may be U_UNSUPPORTED_ERROR for a locale such as "en@numbers=xyz" that
* specifies a numbering system unknown to ICU.
* @return A UNumberingSystem for the specified locale, or NULL if an error
* occurred.
* @stable ICU 52
*/
U_CAPI UNumberingSystem * U_EXPORT2
unumsys_open(const char *locale, UErrorCode *status);
/**
* Opens a UNumberingSystem object using the name of one of the predefined numbering
* systems specified by CLDR and known to ICU, such as "latn", "arabext", or "hanidec";
* the full list is returned by unumsys_openAvailableNames. Note that some of the names
* listed at http://unicode.org/repos/cldr/tags/latest/common/bcp47/number.xml - e.g.
* default, native, traditional, finance - do not identify specific numbering systems,
* but rather key values that may only be used as part of a locale, which in turn
* defines how they are mapped to a specific numbering system such as "latn" or "hant".
*
* @param name The name of the numbering system for which a UNumberingSystem object
* should be opened.
* @param status A pointer to a UErrorCode to receive any errors. For example, this
* may be U_UNSUPPORTED_ERROR for a numbering system such as "xyz" that
* is unknown to ICU.
* @return A UNumberingSystem for the specified name, or NULL if an error
* occurred.
* @stable ICU 52
*/
U_CAPI UNumberingSystem * U_EXPORT2
unumsys_openByName(const char *name, UErrorCode *status);
/**
* Close a UNumberingSystem object. Once closed it may no longer be used.
* @param unumsys The UNumberingSystem object to close.
* @stable ICU 52
*/
U_CAPI void U_EXPORT2
unumsys_close(UNumberingSystem *unumsys);
#if U_SHOW_CPLUSPLUS_API
U_NAMESPACE_BEGIN
/**
* \class LocalUNumberingSystemPointer
* "Smart pointer" class, closes a UNumberingSystem via unumsys_close().
* For most methods see the LocalPointerBase base class.
* @see LocalPointerBase
* @see LocalPointer
* @stable ICU 52
*/
U_DEFINE_LOCAL_OPEN_POINTER(LocalUNumberingSystemPointer, UNumberingSystem, unumsys_close);
U_NAMESPACE_END
#endif
/**
* Returns an enumeration over the names of all of the predefined numbering systems known
* to ICU.
* The numbering system names will be in alphabetical (invariant) order.
* @param status A pointer to a UErrorCode to receive any errors.
* @return A pointer to a UEnumeration that must be closed with uenum_close(),
* or NULL if an error occurred.
* @stable ICU 52
*/
U_CAPI UEnumeration * U_EXPORT2
unumsys_openAvailableNames(UErrorCode *status);
/**
* Returns the name of the specified UNumberingSystem object (if it is one of the
* predefined names known to ICU).
* @param unumsys The UNumberingSystem whose name is desired.
* @return A pointer to the name of the specified UNumberingSystem object, or
* NULL if the name is not one of the ICU predefined names. The pointer
* is only valid for the lifetime of the UNumberingSystem object.
* @stable ICU 52
*/
U_CAPI const char * U_EXPORT2
unumsys_getName(const UNumberingSystem *unumsys);
/**
* Returns whether the given UNumberingSystem object is for an algorithmic (not purely
* positional) system.
* @param unumsys The UNumberingSystem whose algorithmic status is desired.
* @return true if the specified UNumberingSystem object is for an algorithmic
* system.
* @stable ICU 52
*/
U_CAPI UBool U_EXPORT2
unumsys_isAlgorithmic(const UNumberingSystem *unumsys);
/**
* Returns the radix of the specified UNumberingSystem object. Simple positional
* numbering systems typically have radix 10, but might have a radix of e.g. 16 for
* hexadecimal. The radix is less well-defined for non-positional algorithmic systems.
* @param unumsys The UNumberingSystem whose radix is desired.
* @return The radix of the specified UNumberingSystem object.
* @stable ICU 52
*/
U_CAPI int32_t U_EXPORT2
unumsys_getRadix(const UNumberingSystem *unumsys);
/**
* Get the description string of the specified UNumberingSystem object. For simple
* positional systems this is the ordered string of digits (with length matching
* the radix), e.g. "\u3007\u4E00\u4E8C\u4E09\u56DB\u4E94\u516D\u4E03\u516B\u4E5D"
* for "hanidec"; it would be "0123456789ABCDEF" for hexadecimal. For
* algorithmic systems this is the name of the RBNF ruleset used for formatting,
* e.g. "zh/SpelloutRules/%spellout-cardinal" for "hans" or "%greek-upper" for
* "grek".
* @param unumsys The UNumberingSystem whose description string is desired.
* @param result A pointer to a buffer to receive the description string.
* @param resultLength The maximum size of result.
* @param status A pointer to a UErrorCode to receive any errors.
* @return The total buffer size needed; if greater than resultLength, the
* output was truncated.
* @stable ICU 52
*/
U_CAPI int32_t U_EXPORT2
unumsys_getDescription(const UNumberingSystem *unumsys, UChar *result,
int32_t resultLength, UErrorCode *status);
#endif /* #if !UCONFIG_NO_FORMATTING */
#endif

View File

@ -0,0 +1,249 @@
// © 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
/*
*****************************************************************************************
* Copyright (C) 2010-2013, International Business Machines
* Corporation and others. All Rights Reserved.
*****************************************************************************************
*/
#ifndef UPLURALRULES_H
#define UPLURALRULES_H
#include "unicode/utypes.h"
#if !UCONFIG_NO_FORMATTING
#include "unicode/uenum.h"
#if U_SHOW_CPLUSPLUS_API
#include "unicode/localpointer.h"
#endif // U_SHOW_CPLUSPLUS_API
#ifndef U_HIDE_INTERNAL_API
#include "unicode/unum.h"
#endif /* U_HIDE_INTERNAL_API */
// Forward-declaration
struct UFormattedNumber;
struct UFormattedNumberRange;
/**
* \file
* \brief C API: Plural rules, select plural keywords for numeric values.
*
* A UPluralRules object defines rules for mapping non-negative numeric
* values onto a small set of keywords. Rules are constructed from a text
* description, consisting of a series of keywords and conditions.
* The uplrules_select function examines each condition in order and
* returns the keyword for the first condition that matches the number.
* If none match, the default rule(other) is returned.
*
* For more information, see the
* LDML spec, Part 3.5 Language Plural Rules:
* https://www.unicode.org/reports/tr35/tr35-numbers.html#Language_Plural_Rules
*
* Keywords: ICU locale data has 6 predefined values -
* 'zero', 'one', 'two', 'few', 'many' and 'other'. Callers need to check
* the value of keyword returned by the uplrules_select function.
*
* These are based on CLDR <i>Language Plural Rules</i>. For these
* predefined rules, see the CLDR page at
* https://unicode-org.github.io/cldr-staging/charts/latest/supplemental/language_plural_rules.html
*/
/**
* Type of plurals and PluralRules.
* @stable ICU 50
*/
enum UPluralType {
/**
* Plural rules for cardinal numbers: 1 file vs. 2 files.
* @stable ICU 50
*/
UPLURAL_TYPE_CARDINAL,
/**
* Plural rules for ordinal numbers: 1st file, 2nd file, 3rd file, 4th file, etc.
* @stable ICU 50
*/
UPLURAL_TYPE_ORDINAL,
#ifndef U_HIDE_DEPRECATED_API
/**
* One more than the highest normal UPluralType value.
* @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420.
*/
UPLURAL_TYPE_COUNT
#endif /* U_HIDE_DEPRECATED_API */
};
/**
* @stable ICU 50
*/
typedef enum UPluralType UPluralType;
/**
* Opaque UPluralRules object for use in C programs.
* @stable ICU 4.8
*/
struct UPluralRules;
typedef struct UPluralRules UPluralRules; /**< C typedef for struct UPluralRules. @stable ICU 4.8 */
/**
* Opens a new UPluralRules object using the predefined cardinal-number plural rules for a
* given locale.
* Same as uplrules_openForType(locale, UPLURAL_TYPE_CARDINAL, status).
* @param locale The locale for which the rules are desired.
* @param status A pointer to a UErrorCode to receive any errors.
* @return A UPluralRules for the specified locale, or NULL if an error occurred.
* @stable ICU 4.8
*/
U_CAPI UPluralRules* U_EXPORT2
uplrules_open(const char *locale, UErrorCode *status);
/**
* Opens a new UPluralRules object using the predefined plural rules for a
* given locale and the plural type.
* @param locale The locale for which the rules are desired.
* @param type The plural type (e.g., cardinal or ordinal).
* @param status A pointer to a UErrorCode to receive any errors.
* @return A UPluralRules for the specified locale, or NULL if an error occurred.
* @stable ICU 50
*/
U_CAPI UPluralRules* U_EXPORT2
uplrules_openForType(const char *locale, UPluralType type, UErrorCode *status);
/**
* Closes a UPluralRules object. Once closed it may no longer be used.
* @param uplrules The UPluralRules object to close.
* @stable ICU 4.8
*/
U_CAPI void U_EXPORT2
uplrules_close(UPluralRules *uplrules);
#if U_SHOW_CPLUSPLUS_API
U_NAMESPACE_BEGIN
/**
* \class LocalUPluralRulesPointer
* "Smart pointer" class, closes a UPluralRules via uplrules_close().
* For most methods see the LocalPointerBase base class.
*
* @see LocalPointerBase
* @see LocalPointer
* @stable ICU 4.8
*/
U_DEFINE_LOCAL_OPEN_POINTER(LocalUPluralRulesPointer, UPluralRules, uplrules_close);
U_NAMESPACE_END
#endif
/**
* Given a floating-point number, returns the keyword of the first rule that
* applies to the number, according to the supplied UPluralRules object.
* @param uplrules The UPluralRules object specifying the rules.
* @param number The number for which the rule has to be determined.
* @param keyword An output buffer to write the keyword of the rule that
* applies to number.
* @param capacity The capacity of the keyword buffer.
* @param status A pointer to a UErrorCode to receive any errors.
* @return The length of the keyword.
* @stable ICU 4.8
*/
U_CAPI int32_t U_EXPORT2
uplrules_select(const UPluralRules *uplrules,
double number,
UChar *keyword, int32_t capacity,
UErrorCode *status);
/**
* Given a formatted number, returns the keyword of the first rule
* that applies to the number, according to the supplied UPluralRules object.
*
* A UFormattedNumber allows you to specify an exponent or trailing zeros,
* which can affect the plural category. To get a UFormattedNumber, see
* {@link UNumberFormatter}.
*
* @param uplrules The UPluralRules object specifying the rules.
* @param number The formatted number for which the rule has to be determined.
* @param keyword The destination buffer for the keyword of the rule that
* applies to the number.
* @param capacity The capacity of the keyword buffer.
* @param status A pointer to a UErrorCode to receive any errors.
* @return The length of the keyword.
* @stable ICU 64
*/
U_CAPI int32_t U_EXPORT2
uplrules_selectFormatted(const UPluralRules *uplrules,
const struct UFormattedNumber* number,
UChar *keyword, int32_t capacity,
UErrorCode *status);
/**
* Given a formatted number range, returns the overall plural form of the
* range. For example, "3-5" returns "other" in English.
*
* To get a UFormattedNumberRange, see UNumberRangeFormatter.
*
* @param uplrules The UPluralRules object specifying the rules.
* @param urange The number range onto which the rules will be applied.
* @param keyword The destination buffer for the keyword of the rule that
* applies to the number range.
* @param capacity The capacity of the keyword buffer.
* @param status A pointer to a UErrorCode to receive any errors.
* @return The length of the keyword.
* @stable ICU 68
*/
U_CAPI int32_t U_EXPORT2
uplrules_selectForRange(const UPluralRules *uplrules,
const struct UFormattedNumberRange* urange,
UChar *keyword, int32_t capacity,
UErrorCode *status);
#ifndef U_HIDE_INTERNAL_API
/**
* Given a number, returns the keyword of the first rule that applies to the
* number, according to the UPluralRules object and given the number format
* specified by the UNumberFormat object.
* Note: This internal preview interface may be removed in the future if
* an architecturally cleaner solution reaches stable status.
* @param uplrules The UPluralRules object specifying the rules.
* @param number The number for which the rule has to be determined.
* @param fmt The UNumberFormat specifying how the number will be formatted
* (this can affect the plural form, e.g. "1 dollar" vs "1.0 dollars").
* If this is NULL, the function behaves like uplrules_select.
* @param keyword An output buffer to write the keyword of the rule that
* applies to number.
* @param capacity The capacity of the keyword buffer.
* @param status A pointer to a UErrorCode to receive any errors.
* @return The length of keyword.
* @internal ICU 59 technology preview, may be removed in the future
*/
U_CAPI int32_t U_EXPORT2
uplrules_selectWithFormat(const UPluralRules *uplrules,
double number,
const UNumberFormat *fmt,
UChar *keyword, int32_t capacity,
UErrorCode *status);
#endif /* U_HIDE_INTERNAL_API */
/**
* Creates a string enumeration of all plural rule keywords used in this
* UPluralRules object. The rule "other" is always present by default.
* @param uplrules The UPluralRules object specifying the rules for
* a given locale.
* @param status A pointer to a UErrorCode to receive any errors.
* @return a string enumeration over plural rule keywords, or NULL
* upon error. The caller is responsible for closing the result.
* @stable ICU 59
*/
U_CAPI UEnumeration* U_EXPORT2
uplrules_getKeywords(const UPluralRules *uplrules,
UErrorCode *status);
#endif /* #if !UCONFIG_NO_FORMATTING */
#endif

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,252 @@
// © 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
/*
*****************************************************************************************
* Copyright (C) 2014, International Business Machines
* Corporation and others. All Rights Reserved.
*****************************************************************************************
*/
#ifndef UREGION_H
#define UREGION_H
#include "unicode/utypes.h"
#include "unicode/uenum.h"
/**
* \file
* \brief C API: URegion (territory containment and mapping)
*
* URegion objects represent data associated with a particular Unicode Region Code, also known as a
* Unicode Region Subtag, which is defined based upon the BCP 47 standard. These include:
* * Two-letter codes defined by ISO 3166-1, with special LDML treatment of certain private-use or
* reserved codes;
* * A subset of 3-digit numeric codes defined by UN M.49.
* URegion objects can also provide mappings to and from additional codes. There are different types
* of regions that are important to distinguish:
* <p>
* Macroregion - A code for a "macro geographical (continental) region, geographical sub-region, or
* selected economic and other grouping" as defined in UN M.49. These are typically 3-digit codes,
* but contain some 2-letter codes for LDML extensions, such as "QO" for Outlying Oceania.
* Macroregions are represented in ICU by one of three region types: WORLD (code 001),
* CONTINENTS (regions contained directly by WORLD), and SUBCONTINENTS (regions contained directly
* by a continent ).
* <p>
* TERRITORY - A Region that is not a Macroregion. These are typically codes for countries, but also
* include areas that are not separate countries, such as the code "AQ" for Antarctica or the code
* "HK" for Hong Kong (SAR China). Overseas dependencies of countries may or may not have separate
* codes. The codes are typically 2-letter codes aligned with ISO 3166, but BCP47 allows for the use
* of 3-digit codes in the future.
* <p>
* UNKNOWN - The code ZZ is defined by Unicode LDML for use in indicating that region is unknown,
* or that the value supplied as a region was invalid.
* <p>
* DEPRECATED - Region codes that have been defined in the past but are no longer in modern usage,
* usually due to a country splitting into multiple territories or changing its name.
* <p>
* GROUPING - A widely understood grouping of territories that has a well defined membership such
* that a region code has been assigned for it. Some of these are UN M.49 codes that don't fall into
* the world/continent/sub-continent hierarchy, while others are just well-known groupings that have
* their own region code. Region "EU" (European Union) is one such region code that is a grouping.
* Groupings will never be returned by the uregion_getContainingRegion, since a different type of region
* (WORLD, CONTINENT, or SUBCONTINENT) will always be the containing region instead.
*
* URegion objects are const/immutable, owned and maintained by ICU itself, so there are not functions
* to open or close them.
*/
/**
* URegionType is an enumeration defining the different types of regions. Current possible
* values are URGN_WORLD, URGN_CONTINENT, URGN_SUBCONTINENT, URGN_TERRITORY, URGN_GROUPING,
* URGN_DEPRECATED, and URGN_UNKNOWN.
*
* @stable ICU 51
*/
typedef enum URegionType {
/**
* Type representing the unknown region.
* @stable ICU 51
*/
URGN_UNKNOWN,
/**
* Type representing a territory.
* @stable ICU 51
*/
URGN_TERRITORY,
/**
* Type representing the whole world.
* @stable ICU 51
*/
URGN_WORLD,
/**
* Type representing a continent.
* @stable ICU 51
*/
URGN_CONTINENT,
/**
* Type representing a sub-continent.
* @stable ICU 51
*/
URGN_SUBCONTINENT,
/**
* Type representing a grouping of territories that is not to be used in
* the normal WORLD/CONTINENT/SUBCONTINENT/TERRITORY containment tree.
* @stable ICU 51
*/
URGN_GROUPING,
/**
* Type representing a region whose code has been deprecated, usually
* due to a country splitting into multiple territories or changing its name.
* @stable ICU 51
*/
URGN_DEPRECATED,
#ifndef U_HIDE_DEPRECATED_API
/**
* One more than the highest normal URegionType value.
* @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420.
*/
URGN_LIMIT
#endif /* U_HIDE_DEPRECATED_API */
} URegionType;
#if !UCONFIG_NO_FORMATTING
/**
* Opaque URegion object for use in C programs.
* @stable ICU 52
*/
struct URegion;
typedef struct URegion URegion; /**< @stable ICU 52 */
/**
* Returns a pointer to a URegion for the specified region code: A 2-letter or 3-letter ISO 3166
* code, UN M.49 numeric code (superset of ISO 3166 numeric codes), or other valid Unicode Region
* Code as defined by the LDML specification. The code will be canonicalized internally. If the
* region code is NULL or not recognized, the appropriate error code will be set
* (U_ILLEGAL_ARGUMENT_ERROR).
* @stable ICU 52
*/
U_CAPI const URegion* U_EXPORT2
uregion_getRegionFromCode(const char *regionCode, UErrorCode *status);
/**
* Returns a pointer to a URegion for the specified numeric region code. If the numeric region
* code is not recognized, the appropriate error code will be set (U_ILLEGAL_ARGUMENT_ERROR).
* @stable ICU 52
*/
U_CAPI const URegion* U_EXPORT2
uregion_getRegionFromNumericCode (int32_t code, UErrorCode *status);
/**
* Returns an enumeration over the canonical codes of all known regions that match the given type.
* The enumeration must be closed with with uenum_close().
* @stable ICU 52
*/
U_CAPI UEnumeration* U_EXPORT2
uregion_getAvailable(URegionType type, UErrorCode *status);
/**
* Returns true if the specified uregion is equal to the specified otherRegion.
* @stable ICU 52
*/
U_CAPI UBool U_EXPORT2
uregion_areEqual(const URegion* uregion, const URegion* otherRegion);
/**
* Returns a pointer to the URegion that contains the specified uregion. Returns NULL if the
* specified uregion is code "001" (World) or "ZZ" (Unknown region). For example, calling
* this method with region "IT" (Italy) returns the URegion for "039" (Southern Europe).
* @stable ICU 52
*/
U_CAPI const URegion* U_EXPORT2
uregion_getContainingRegion(const URegion* uregion);
/**
* Return a pointer to the URegion that geographically contains this uregion and matches the
* specified type, moving multiple steps up the containment chain if necessary. Returns NULL if no
* containing region can be found that matches the specified type. Will return NULL if URegionType
* is URGN_GROUPING, URGN_DEPRECATED, or URGN_UNKNOWN which are not appropriate for this API.
* For example, calling this method with uregion "IT" (Italy) for type URGN_CONTINENT returns the
* URegion "150" (Europe).
* @stable ICU 52
*/
U_CAPI const URegion* U_EXPORT2
uregion_getContainingRegionOfType(const URegion* uregion, URegionType type);
/**
* Return an enumeration over the canonical codes of all the regions that are immediate children
* of the specified uregion in the region hierarchy. These returned regions could be either macro
* regions, territories, or a mixture of the two, depending on the containment data as defined in
* CLDR. This API returns NULL if this uregion doesn't have any sub-regions. For example, calling
* this function for uregion "150" (Europe) returns an enumeration containing the various
* sub-regions of Europe: "039" (Southern Europe), "151" (Eastern Europe), "154" (Northern Europe),
* and "155" (Western Europe). The enumeration must be closed with with uenum_close().
* @stable ICU 52
*/
U_CAPI UEnumeration* U_EXPORT2
uregion_getContainedRegions(const URegion* uregion, UErrorCode *status);
/**
* Returns an enumeration over the canonical codes of all the regions that are children of the
* specified uregion anywhere in the region hierarchy and match the given type. This API may return
* an empty enumeration if this uregion doesn't have any sub-regions that match the given type.
* For example, calling this method with region "150" (Europe) and type URGN_TERRITORY" returns an
* enumeration containing all the territories in Europe: "FR" (France), "IT" (Italy), "DE" (Germany),
* etc. The enumeration must be closed with with uenum_close().
* @stable ICU 52
*/
U_CAPI UEnumeration* U_EXPORT2
uregion_getContainedRegionsOfType(const URegion* uregion, URegionType type, UErrorCode *status);
/**
* Returns true if the specified uregion contains the specified otherRegion anywhere in the region
* hierarchy.
* @stable ICU 52
*/
U_CAPI UBool U_EXPORT2
uregion_contains(const URegion* uregion, const URegion* otherRegion);
/**
* If the specified uregion is deprecated, returns an enumeration over the canonical codes of the
* regions that are the preferred replacement regions for the specified uregion. If the specified
* uregion is not deprecated, returns NULL. For example, calling this method with uregion
* "SU" (Soviet Union) returns a list of the regions containing "RU" (Russia), "AM" (Armenia),
* "AZ" (Azerbaijan), etc... The enumeration must be closed with with uenum_close().
* @stable ICU 52
*/
U_CAPI UEnumeration* U_EXPORT2
uregion_getPreferredValues(const URegion* uregion, UErrorCode *status);
/**
* Returns the specified uregion's canonical code.
* @stable ICU 52
*/
U_CAPI const char* U_EXPORT2
uregion_getRegionCode(const URegion* uregion);
/**
* Returns the specified uregion's numeric code, or a negative value if there is no numeric code
* for the specified uregion.
* @stable ICU 52
*/
U_CAPI int32_t U_EXPORT2
uregion_getNumericCode(const URegion* uregion);
/**
* Returns the URegionType of the specified uregion.
* @stable ICU 52
*/
U_CAPI URegionType U_EXPORT2
uregion_getType(const URegion* uregion);
#endif /* #if !UCONFIG_NO_FORMATTING */
#endif

View File

@ -0,0 +1,510 @@
// © 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
/*
*****************************************************************************************
* Copyright (C) 2016, International Business Machines
* Corporation and others. All Rights Reserved.
*****************************************************************************************
*/
#ifndef URELDATEFMT_H
#define URELDATEFMT_H
#include "unicode/utypes.h"
#if !UCONFIG_NO_FORMATTING
#include "unicode/unum.h"
#include "unicode/udisplaycontext.h"
#include "unicode/uformattedvalue.h"
#if U_SHOW_CPLUSPLUS_API
#include "unicode/localpointer.h"
#endif // U_SHOW_CPLUSPLUS_API
/**
* \file
* \brief C API: URelativeDateTimeFormatter, relative date formatting of unit + numeric offset.
*
* Provides simple formatting of relative dates, in two ways
* <ul>
* <li>relative dates with a quantity e.g "in 5 days"</li>
* <li>relative dates without a quantity e.g "next Tuesday"</li>
* </ul>
* <p>
* This does not provide compound formatting for multiple units,
* other than the ability to combine a time string with a relative date,
* as in "next Tuesday at 3:45 PM". It also does not provide support
* for determining which unit to use, such as deciding between "in 7 days"
* and "in 1 week".
*
* @stable ICU 57
*/
/**
* The formatting style
* @stable ICU 54
*/
typedef enum UDateRelativeDateTimeFormatterStyle {
/**
* Everything spelled out.
* @stable ICU 54
*/
UDAT_STYLE_LONG,
/**
* Abbreviations used when possible.
* @stable ICU 54
*/
UDAT_STYLE_SHORT,
/**
* Use the shortest possible form.
* @stable ICU 54
*/
UDAT_STYLE_NARROW,
#ifndef U_HIDE_DEPRECATED_API
/**
* One more than the highest normal UDateRelativeDateTimeFormatterStyle value.
* @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420.
*/
UDAT_STYLE_COUNT
#endif /* U_HIDE_DEPRECATED_API */
} UDateRelativeDateTimeFormatterStyle;
/**
* Represents the unit for formatting a relative date. e.g "in 5 days"
* or "next year"
* @stable ICU 57
*/
typedef enum URelativeDateTimeUnit {
/**
* Specifies that relative unit is year, e.g. "last year",
* "in 5 years".
* @stable ICU 57
*/
UDAT_REL_UNIT_YEAR,
/**
* Specifies that relative unit is quarter, e.g. "last quarter",
* "in 5 quarters".
* @stable ICU 57
*/
UDAT_REL_UNIT_QUARTER,
/**
* Specifies that relative unit is month, e.g. "last month",
* "in 5 months".
* @stable ICU 57
*/
UDAT_REL_UNIT_MONTH,
/**
* Specifies that relative unit is week, e.g. "last week",
* "in 5 weeks".
* @stable ICU 57
*/
UDAT_REL_UNIT_WEEK,
/**
* Specifies that relative unit is day, e.g. "yesterday",
* "in 5 days".
* @stable ICU 57
*/
UDAT_REL_UNIT_DAY,
/**
* Specifies that relative unit is hour, e.g. "1 hour ago",
* "in 5 hours".
* @stable ICU 57
*/
UDAT_REL_UNIT_HOUR,
/**
* Specifies that relative unit is minute, e.g. "1 minute ago",
* "in 5 minutes".
* @stable ICU 57
*/
UDAT_REL_UNIT_MINUTE,
/**
* Specifies that relative unit is second, e.g. "1 second ago",
* "in 5 seconds".
* @stable ICU 57
*/
UDAT_REL_UNIT_SECOND,
/**
* Specifies that relative unit is Sunday, e.g. "last Sunday",
* "this Sunday", "next Sunday", "in 5 Sundays".
* @stable ICU 57
*/
UDAT_REL_UNIT_SUNDAY,
/**
* Specifies that relative unit is Monday, e.g. "last Monday",
* "this Monday", "next Monday", "in 5 Mondays".
* @stable ICU 57
*/
UDAT_REL_UNIT_MONDAY,
/**
* Specifies that relative unit is Tuesday, e.g. "last Tuesday",
* "this Tuesday", "next Tuesday", "in 5 Tuesdays".
* @stable ICU 57
*/
UDAT_REL_UNIT_TUESDAY,
/**
* Specifies that relative unit is Wednesday, e.g. "last Wednesday",
* "this Wednesday", "next Wednesday", "in 5 Wednesdays".
* @stable ICU 57
*/
UDAT_REL_UNIT_WEDNESDAY,
/**
* Specifies that relative unit is Thursday, e.g. "last Thursday",
* "this Thursday", "next Thursday", "in 5 Thursdays".
* @stable ICU 57
*/
UDAT_REL_UNIT_THURSDAY,
/**
* Specifies that relative unit is Friday, e.g. "last Friday",
* "this Friday", "next Friday", "in 5 Fridays".
* @stable ICU 57
*/
UDAT_REL_UNIT_FRIDAY,
/**
* Specifies that relative unit is Saturday, e.g. "last Saturday",
* "this Saturday", "next Saturday", "in 5 Saturdays".
* @stable ICU 57
*/
UDAT_REL_UNIT_SATURDAY,
#ifndef U_HIDE_DEPRECATED_API
/**
* One more than the highest normal URelativeDateTimeUnit value.
* @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420.
*/
UDAT_REL_UNIT_COUNT
#endif /* U_HIDE_DEPRECATED_API */
} URelativeDateTimeUnit;
/**
* FieldPosition and UFieldPosition selectors for format fields
* defined by RelativeDateTimeFormatter.
* @stable ICU 64
*/
typedef enum URelativeDateTimeFormatterField {
/**
* Represents a literal text string, like "tomorrow" or "days ago".
* @stable ICU 64
*/
UDAT_REL_LITERAL_FIELD,
/**
* Represents a number quantity, like "3" in "3 days ago".
* @stable ICU 64
*/
UDAT_REL_NUMERIC_FIELD,
} URelativeDateTimeFormatterField;
/**
* Opaque URelativeDateTimeFormatter object for use in C programs.
* @stable ICU 57
*/
struct URelativeDateTimeFormatter;
typedef struct URelativeDateTimeFormatter URelativeDateTimeFormatter; /**< C typedef for struct URelativeDateTimeFormatter. @stable ICU 57 */
/**
* Open a new URelativeDateTimeFormatter object for a given locale using the
* specified width and capitalizationContext, along with a number formatter
* (if desired) to override the default formatter that would be used for
* display of numeric field offsets. The default formatter typically rounds
* toward 0 and has a minimum of 0 fraction digits and a maximum of 3
* fraction digits (i.e. it will show as many decimal places as necessary
* up to 3, without showing trailing 0s).
*
* @param locale
* The locale
* @param nfToAdopt
* A number formatter to set for this URelativeDateTimeFormatter
* object (instead of the default decimal formatter). Ownership of
* this UNumberFormat object will pass to the URelativeDateTimeFormatter
* object (the URelativeDateTimeFormatter adopts the UNumberFormat),
* which becomes responsible for closing it. If the caller wishes to
* retain ownership of the UNumberFormat object, the caller must clone
* it (with unum_clone) and pass the clone to ureldatefmt_open. May be
* NULL to use the default decimal formatter.
* @param width
* The width - wide, short, narrow, etc.
* @param capitalizationContext
* A value from UDisplayContext that pertains to capitalization, e.g.
* UDISPCTX_CAPITALIZATION_FOR_BEGINNING_OF_SENTENCE.
* @param status
* A pointer to a UErrorCode to receive any errors.
* @return
* A pointer to a URelativeDateTimeFormatter object for the specified locale,
* or NULL if an error occurred.
* @stable ICU 57
*/
U_CAPI URelativeDateTimeFormatter* U_EXPORT2
ureldatefmt_open( const char* locale,
UNumberFormat* nfToAdopt,
UDateRelativeDateTimeFormatterStyle width,
UDisplayContext capitalizationContext,
UErrorCode* status );
/**
* Close a URelativeDateTimeFormatter object. Once closed it may no longer be used.
* @param reldatefmt
* The URelativeDateTimeFormatter object to close.
* @stable ICU 57
*/
U_CAPI void U_EXPORT2
ureldatefmt_close(URelativeDateTimeFormatter *reldatefmt);
struct UFormattedRelativeDateTime;
/**
* Opaque struct to contain the results of a URelativeDateTimeFormatter operation.
* @stable ICU 64
*/
typedef struct UFormattedRelativeDateTime UFormattedRelativeDateTime;
/**
* Creates an object to hold the result of a URelativeDateTimeFormatter
* operation. The object can be used repeatedly; it is cleared whenever
* passed to a format function.
*
* @param ec Set if an error occurs.
* @return A pointer needing ownership.
* @stable ICU 64
*/
U_CAPI UFormattedRelativeDateTime* U_EXPORT2
ureldatefmt_openResult(UErrorCode* ec);
/**
* Returns a representation of a UFormattedRelativeDateTime as a UFormattedValue,
* which can be subsequently passed to any API requiring that type.
*
* The returned object is owned by the UFormattedRelativeDateTime and is valid
* only as long as the UFormattedRelativeDateTime is present and unchanged in memory.
*
* You can think of this method as a cast between types.
*
* @param ufrdt The object containing the formatted string.
* @param ec Set if an error occurs.
* @return A UFormattedValue owned by the input object.
* @stable ICU 64
*/
U_CAPI const UFormattedValue* U_EXPORT2
ureldatefmt_resultAsValue(const UFormattedRelativeDateTime* ufrdt, UErrorCode* ec);
/**
* Releases the UFormattedRelativeDateTime created by ureldatefmt_openResult.
*
* @param ufrdt The object to release.
* @stable ICU 64
*/
U_CAPI void U_EXPORT2
ureldatefmt_closeResult(UFormattedRelativeDateTime* ufrdt);
#if U_SHOW_CPLUSPLUS_API
U_NAMESPACE_BEGIN
/**
* \class LocalURelativeDateTimeFormatterPointer
* "Smart pointer" class, closes a URelativeDateTimeFormatter via ureldatefmt_close().
* For most methods see the LocalPointerBase base class.
*
* @see LocalPointerBase
* @see LocalPointer
* @stable ICU 57
*/
U_DEFINE_LOCAL_OPEN_POINTER(LocalURelativeDateTimeFormatterPointer, URelativeDateTimeFormatter, ureldatefmt_close);
/**
* \class LocalUFormattedRelativeDateTimePointer
* "Smart pointer" class, closes a UFormattedRelativeDateTime via ureldatefmt_closeResult().
* For most methods see the LocalPointerBase base class.
*
* @see LocalPointerBase
* @see LocalPointer
* @stable ICU 64
*/
U_DEFINE_LOCAL_OPEN_POINTER(LocalUFormattedRelativeDateTimePointer, UFormattedRelativeDateTime, ureldatefmt_closeResult);
U_NAMESPACE_END
#endif
/**
* Format a combination of URelativeDateTimeUnit and numeric
* offset using a numeric style, e.g. "1 week ago", "in 1 week",
* "5 weeks ago", "in 5 weeks".
*
* @param reldatefmt
* The URelativeDateTimeFormatter object specifying the
* format conventions.
* @param offset
* The signed offset for the specified unit. This will
* be formatted according to this object's UNumberFormat
* object.
* @param unit
* The unit to use when formatting the relative
* date, e.g. UDAT_REL_UNIT_WEEK, UDAT_REL_UNIT_FRIDAY.
* @param result
* A pointer to a buffer to receive the formatted result.
* @param resultCapacity
* The maximum size of result.
* @param status
* A pointer to a UErrorCode to receive any errors. In
* case of error status, the contents of result are
* undefined.
* @return
* The length of the formatted result; may be greater
* than resultCapacity, in which case an error is returned.
* @stable ICU 57
*/
U_CAPI int32_t U_EXPORT2
ureldatefmt_formatNumeric( const URelativeDateTimeFormatter* reldatefmt,
double offset,
URelativeDateTimeUnit unit,
UChar* result,
int32_t resultCapacity,
UErrorCode* status);
/**
* Format a combination of URelativeDateTimeUnit and numeric
* offset using a numeric style, e.g. "1 week ago", "in 1 week",
* "5 weeks ago", "in 5 weeks".
*
* @param reldatefmt
* The URelativeDateTimeFormatter object specifying the
* format conventions.
* @param offset
* The signed offset for the specified unit. This will
* be formatted according to this object's UNumberFormat
* object.
* @param unit
* The unit to use when formatting the relative
* date, e.g. UDAT_REL_UNIT_WEEK, UDAT_REL_UNIT_FRIDAY.
* @param result
* A pointer to a UFormattedRelativeDateTime to populate.
* @param status
* A pointer to a UErrorCode to receive any errors. In
* case of error status, the contents of result are
* undefined.
* @stable ICU 64
*/
U_CAPI void U_EXPORT2
ureldatefmt_formatNumericToResult(
const URelativeDateTimeFormatter* reldatefmt,
double offset,
URelativeDateTimeUnit unit,
UFormattedRelativeDateTime* result,
UErrorCode* status);
/**
* Format a combination of URelativeDateTimeUnit and numeric offset
* using a text style if possible, e.g. "last week", "this week",
* "next week", "yesterday", "tomorrow". Falls back to numeric
* style if no appropriate text term is available for the specified
* offset in the object's locale.
*
* @param reldatefmt
* The URelativeDateTimeFormatter object specifying the
* format conventions.
* @param offset
* The signed offset for the specified unit.
* @param unit
* The unit to use when formatting the relative
* date, e.g. UDAT_REL_UNIT_WEEK, UDAT_REL_UNIT_FRIDAY.
* @param result
* A pointer to a buffer to receive the formatted result.
* @param resultCapacity
* The maximum size of result.
* @param status
* A pointer to a UErrorCode to receive any errors. In
* case of error status, the contents of result are
* undefined.
* @return
* The length of the formatted result; may be greater
* than resultCapacity, in which case an error is returned.
* @stable ICU 57
*/
U_CAPI int32_t U_EXPORT2
ureldatefmt_format( const URelativeDateTimeFormatter* reldatefmt,
double offset,
URelativeDateTimeUnit unit,
UChar* result,
int32_t resultCapacity,
UErrorCode* status);
/**
* Format a combination of URelativeDateTimeUnit and numeric offset
* using a text style if possible, e.g. "last week", "this week",
* "next week", "yesterday", "tomorrow". Falls back to numeric
* style if no appropriate text term is available for the specified
* offset in the object's locale.
*
* This method populates a UFormattedRelativeDateTime, which exposes more
* information than the string populated by format().
*
* @param reldatefmt
* The URelativeDateTimeFormatter object specifying the
* format conventions.
* @param offset
* The signed offset for the specified unit.
* @param unit
* The unit to use when formatting the relative
* date, e.g. UDAT_REL_UNIT_WEEK, UDAT_REL_UNIT_FRIDAY.
* @param result
* A pointer to a UFormattedRelativeDateTime to populate.
* @param status
* A pointer to a UErrorCode to receive any errors. In
* case of error status, the contents of result are
* undefined.
* @stable ICU 64
*/
U_CAPI void U_EXPORT2
ureldatefmt_formatToResult(
const URelativeDateTimeFormatter* reldatefmt,
double offset,
URelativeDateTimeUnit unit,
UFormattedRelativeDateTime* result,
UErrorCode* status);
/**
* Combines a relative date string and a time string in this object's
* locale. This is done with the same date-time separator used for the
* default calendar in this locale to produce a result such as
* "yesterday at 3:45 PM".
*
* @param reldatefmt
* The URelativeDateTimeFormatter object specifying the format conventions.
* @param relativeDateString
* The relative date string.
* @param relativeDateStringLen
* The length of relativeDateString; may be -1 if relativeDateString
* is zero-terminated.
* @param timeString
* The time string.
* @param timeStringLen
* The length of timeString; may be -1 if timeString is zero-terminated.
* @param result
* A pointer to a buffer to receive the formatted result.
* @param resultCapacity
* The maximum size of result.
* @param status
* A pointer to a UErrorCode to receive any errors. In case of error status,
* the contents of result are undefined.
* @return
* The length of the formatted result; may be greater than resultCapacity,
* in which case an error is returned.
* @stable ICU 57
*/
U_CAPI int32_t U_EXPORT2
ureldatefmt_combineDateAndTime( const URelativeDateTimeFormatter* reldatefmt,
const UChar * relativeDateString,
int32_t relativeDateStringLen,
const UChar * timeString,
int32_t timeStringLen,
UChar* result,
int32_t resultCapacity,
UErrorCode* status );
#endif /* !UCONFIG_NO_FORMATTING */
#endif

View File

@ -0,0 +1,911 @@
// © 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
/*
**********************************************************************
* Copyright (C) 2001-2011,2014 IBM and others. All rights reserved.
**********************************************************************
* Date Name Description
* 06/28/2001 synwee Creation.
**********************************************************************
*/
#ifndef USEARCH_H
#define USEARCH_H
#include "unicode/utypes.h"
#if !UCONFIG_NO_COLLATION && !UCONFIG_NO_BREAK_ITERATION
#include "unicode/ucol.h"
#include "unicode/ucoleitr.h"
#include "unicode/ubrk.h"
#if U_SHOW_CPLUSPLUS_API
#include "unicode/localpointer.h"
#endif // U_SHOW_CPLUSPLUS_API
/**
* \file
* \brief C API: StringSearch
*
* C APIs for an engine that provides language-sensitive text searching based
* on the comparison rules defined in a <code>UCollator</code> data struct,
* see <code>ucol.h</code>. This ensures that language eccentricity can be
* handled, e.g. for the German collator, characters &szlig; and SS will be matched
* if case is chosen to be ignored.
* See the <a href="https://htmlpreview.github.io/?https://github.com/unicode-org/icu-docs/blob/main/design/collation/ICU_collation_design.htm">
* "ICU Collation Design Document"</a> for more information.
* <p>
* As of ICU4C 4.0 / ICU4J 53, the implementation uses a linear search. In previous versions,
* a modified form of the Boyer-Moore searching algorithm was used. For more information
* on the modified Boyer-Moore algorithm see
* <a href="http://icu-project.org/docs/papers/efficient_text_searching_in_java.html">
* "Efficient Text Searching in Java"</a>, published in <i>Java Report</i>
* in February, 1999.
* <p>
* There are 2 match options for selection:<br>
* Let S' be the sub-string of a text string S between the offsets start and
* end <start, end>.
* <br>
* A pattern string P matches a text string S at the offsets <start, end>
* if
* <pre>
* option 1. Some canonical equivalent of P matches some canonical equivalent
* of S'
* option 2. P matches S' and if P starts or ends with a combining mark,
* there exists no non-ignorable combining mark before or after S'
* in S respectively.
* </pre>
* Option 2. will be the default.
* <p>
* This search has APIs similar to that of other text iteration mechanisms
* such as the break iterators in <code>ubrk.h</code>. Using these
* APIs, it is easy to scan through text looking for all occurrences of
* a given pattern. This search iterator allows changing of direction by
* calling a <code>reset</code> followed by a <code>next</code> or <code>previous</code>.
* Though a direction change can occur without calling <code>reset</code> first,
* this operation comes with some speed penalty.
* Generally, match results in the forward direction will match the result
* matches in the backwards direction in the reverse order
* <p>
* <code>usearch.h</code> provides APIs to specify the starting position
* within the text string to be searched, e.g. <code>usearch_setOffset</code>,
* <code>usearch_preceding</code> and <code>usearch_following</code>. Since the
* starting position will be set as it is specified, please take note that
* there are some dangerous positions which the search may render incorrect
* results:
* <ul>
* <li> The midst of a substring that requires normalization.
* <li> If the following match is to be found, the position should not be the
* second character which requires to be swapped with the preceding
* character. Vice versa, if the preceding match is to be found,
* position to search from should not be the first character which
* requires to be swapped with the next character. E.g certain Thai and
* Lao characters require swapping.
* <li> If a following pattern match is to be found, any position within a
* contracting sequence except the first will fail. Vice versa if a
* preceding pattern match is to be found, a invalid starting point
* would be any character within a contracting sequence except the last.
* </ul>
* <p>
* A breakiterator can be used if only matches at logical breaks are desired.
* Using a breakiterator will only give you results that exactly matches the
* boundaries given by the breakiterator. For instance the pattern "e" will
* not be found in the string "\u00e9" if a character break iterator is used.
* <p>
* Options are provided to handle overlapping matches.
* E.g. In English, overlapping matches produces the result 0 and 2
* for the pattern "abab" in the text "ababab", where else mutually
* exclusive matches only produce the result of 0.
* <p>
* Options are also provided to implement "asymmetric search" as described in
* <a href="http://www.unicode.org/reports/tr10/#Asymmetric_Search">
* UTS #10 Unicode Collation Algorithm</a>, specifically the USearchAttribute
* USEARCH_ELEMENT_COMPARISON and its values.
* <p>
* Though collator attributes will be taken into consideration while
* performing matches, there are no APIs here for setting and getting the
* attributes. These attributes can be set by getting the collator
* from <code>usearch_getCollator</code> and using the APIs in <code>ucol.h</code>.
* Lastly to update String Search to the new collator attributes,
* usearch_reset() has to be called.
* <p>
* Restriction: <br>
* Currently there are no composite characters that consists of a
* character with combining class > 0 before a character with combining
* class == 0. However, if such a character exists in the future, the
* search mechanism does not guarantee the results for option 1.
*
* <p>
* Example of use:<br>
* <pre><code>
* char *tgtstr = "The quick brown fox jumped over the lazy fox";
* char *patstr = "fox";
* UChar target[64];
* UChar pattern[16];
* UErrorCode status = U_ZERO_ERROR;
* u_uastrcpy(target, tgtstr);
* u_uastrcpy(pattern, patstr);
*
* UStringSearch *search = usearch_open(pattern, -1, target, -1, "en_US",
* NULL, &status);
* if (U_SUCCESS(status)) {
* for (int pos = usearch_first(search, &status);
* pos != USEARCH_DONE;
* pos = usearch_next(search, &status))
* {
* printf("Found match at %d pos, length is %d\n", pos,
* usearch_getMatchedLength(search));
* }
* }
*
* usearch_close(search);
* </code></pre>
* @stable ICU 2.4
*/
/**
* DONE is returned by previous() and next() after all valid matches have
* been returned, and by first() and last() if there are no matches at all.
* @stable ICU 2.4
*/
#define USEARCH_DONE -1
/**
* Data structure for searching
* @stable ICU 2.4
*/
struct UStringSearch;
/**
* Data structure for searching
* @stable ICU 2.4
*/
typedef struct UStringSearch UStringSearch;
/**
* @stable ICU 2.4
*/
typedef enum {
/**
* Option for overlapping matches
* @stable ICU 2.4
*/
USEARCH_OVERLAP = 0,
#ifndef U_HIDE_DEPRECATED_API
/**
* Option for canonical matches; option 1 in header documentation.
* The default value will be USEARCH_OFF.
* Note: Setting this option to USEARCH_ON currently has no effect on
* search behavior, and this option is deprecated. Instead, to control
* canonical match behavior, you must set UCOL_NORMALIZATION_MODE
* appropriately (to UCOL_OFF or UCOL_ON) in the UCollator used by
* the UStringSearch object.
* @see usearch_openFromCollator
* @see usearch_getCollator
* @see usearch_setCollator
* @see ucol_getAttribute
* @deprecated ICU 53
*/
USEARCH_CANONICAL_MATCH = 1,
#endif /* U_HIDE_DEPRECATED_API */
/**
* Option to control how collation elements are compared.
* The default value will be USEARCH_STANDARD_ELEMENT_COMPARISON.
* @stable ICU 4.4
*/
USEARCH_ELEMENT_COMPARISON = 2,
#ifndef U_HIDE_DEPRECATED_API
/**
* One more than the highest normal USearchAttribute value.
* @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420.
*/
USEARCH_ATTRIBUTE_COUNT = 3
#endif /* U_HIDE_DEPRECATED_API */
} USearchAttribute;
/**
* @stable ICU 2.4
*/
typedef enum {
/**
* Default value for any USearchAttribute
* @stable ICU 2.4
*/
USEARCH_DEFAULT = -1,
/**
* Value for USEARCH_OVERLAP and USEARCH_CANONICAL_MATCH
* @stable ICU 2.4
*/
USEARCH_OFF,
/**
* Value for USEARCH_OVERLAP and USEARCH_CANONICAL_MATCH
* @stable ICU 2.4
*/
USEARCH_ON,
/**
* Value (default) for USEARCH_ELEMENT_COMPARISON;
* standard collation element comparison at the specified collator
* strength.
* @stable ICU 4.4
*/
USEARCH_STANDARD_ELEMENT_COMPARISON,
/**
* Value for USEARCH_ELEMENT_COMPARISON;
* collation element comparison is modified to effectively provide
* behavior between the specified strength and strength - 1. Collation
* elements in the pattern that have the base weight for the specified
* strength are treated as "wildcards" that match an element with any
* other weight at that collation level in the searched text. For
* example, with a secondary-strength English collator, a plain 'e' in
* the pattern will match a plain e or an e with any diacritic in the
* searched text, but an e with diacritic in the pattern will only
* match an e with the same diacritic in the searched text.
*
* This supports "asymmetric search" as described in
* <a href="http://www.unicode.org/reports/tr10/#Asymmetric_Search">
* UTS #10 Unicode Collation Algorithm</a>.
*
* @stable ICU 4.4
*/
USEARCH_PATTERN_BASE_WEIGHT_IS_WILDCARD,
/**
* Value for USEARCH_ELEMENT_COMPARISON.
* collation element comparison is modified to effectively provide
* behavior between the specified strength and strength - 1. Collation
* elements in either the pattern or the searched text that have the
* base weight for the specified strength are treated as "wildcards"
* that match an element with any other weight at that collation level.
* For example, with a secondary-strength English collator, a plain 'e'
* in the pattern will match a plain e or an e with any diacritic in the
* searched text, but an e with diacritic in the pattern will only
* match an e with the same diacritic or a plain e in the searched text.
*
* This option is similar to "asymmetric search" as described in
* [UTS #10 Unicode Collation Algorithm](http://www.unicode.org/reports/tr10/#Asymmetric_Search),
* but also allows unmarked characters in the searched text to match
* marked or unmarked versions of that character in the pattern.
*
* @stable ICU 4.4
*/
USEARCH_ANY_BASE_WEIGHT_IS_WILDCARD,
#ifndef U_HIDE_DEPRECATED_API
/**
* One more than the highest normal USearchAttributeValue value.
* @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420.
*/
USEARCH_ATTRIBUTE_VALUE_COUNT
#endif /* U_HIDE_DEPRECATED_API */
} USearchAttributeValue;
/* open and close ------------------------------------------------------ */
/**
* Creates a String Search iterator data struct using the argument locale language
* rule set. A collator will be created in the process, which will be owned by
* this String Search and will be deleted in <code>usearch_close</code>.
*
* The UStringSearch retains a pointer to both the pattern and text strings.
* The caller must not modify or delete them while using the UStringSearch.
*
* @param pattern for matching
* @param patternlength length of the pattern, -1 for null-termination
* @param text text string
* @param textlength length of the text string, -1 for null-termination
* @param locale name of locale for the rules to be used
* @param breakiter A BreakIterator that will be used to restrict the points
* at which matches are detected. If a match is found, but
* the match's start or end index is not a boundary as
* determined by the <code>BreakIterator</code>, the match will
* be rejected and another will be searched for.
* If this parameter is <code>NULL</code>, no break detection is
* attempted.
* @param status for errors if it occurs. If pattern or text is NULL, or if
* patternlength or textlength is 0 then an
* U_ILLEGAL_ARGUMENT_ERROR is returned.
* @return search iterator data structure, or NULL if there is an error.
* @stable ICU 2.4
*/
U_CAPI UStringSearch * U_EXPORT2 usearch_open(const UChar *pattern,
int32_t patternlength,
const UChar *text,
int32_t textlength,
const char *locale,
UBreakIterator *breakiter,
UErrorCode *status);
/**
* Creates a String Search iterator data struct using the argument collator language
* rule set. Note, user retains the ownership of this collator, thus the
* responsibility of deletion lies with the user.
* NOTE: String Search cannot be instantiated from a collator that has
* collate digits as numbers (CODAN) turned on (UCOL_NUMERIC_COLLATION).
*
* The UStringSearch retains a pointer to both the pattern and text strings.
* The caller must not modify or delete them while using the UStringSearch.
*
* @param pattern for matching
* @param patternlength length of the pattern, -1 for null-termination
* @param text text string
* @param textlength length of the text string, -1 for null-termination
* @param collator used for the language rules
* @param breakiter A BreakIterator that will be used to restrict the points
* at which matches are detected. If a match is found, but
* the match's start or end index is not a boundary as
* determined by the <code>BreakIterator</code>, the match will
* be rejected and another will be searched for.
* If this parameter is <code>NULL</code>, no break detection is
* attempted.
* @param status for errors if it occurs. If collator, pattern or text is NULL,
* or if patternlength or textlength is 0 then an
* U_ILLEGAL_ARGUMENT_ERROR is returned.
* @return search iterator data structure, or NULL if there is an error.
* @stable ICU 2.4
*/
U_CAPI UStringSearch * U_EXPORT2 usearch_openFromCollator(
const UChar *pattern,
int32_t patternlength,
const UChar *text,
int32_t textlength,
const UCollator *collator,
UBreakIterator *breakiter,
UErrorCode *status);
/**
* Destroys and cleans up the String Search iterator data struct.
* If a collator was created in <code>usearch_open</code>, then it will be destroyed here.
* @param searchiter The UStringSearch to clean up
* @stable ICU 2.4
*/
U_CAPI void U_EXPORT2 usearch_close(UStringSearch *searchiter);
#if U_SHOW_CPLUSPLUS_API
U_NAMESPACE_BEGIN
/**
* \class LocalUStringSearchPointer
* "Smart pointer" class, closes a UStringSearch via usearch_close().
* For most methods see the LocalPointerBase base class.
*
* @see LocalPointerBase
* @see LocalPointer
* @stable ICU 4.4
*/
U_DEFINE_LOCAL_OPEN_POINTER(LocalUStringSearchPointer, UStringSearch, usearch_close);
U_NAMESPACE_END
#endif
/* get and set methods -------------------------------------------------- */
/**
* Sets the current position in the text string which the next search will
* start from. Clears previous states.
* This method takes the argument index and sets the position in the text
* string accordingly without checking if the index is pointing to a
* valid starting point to begin searching.
* Search positions that may render incorrect results are highlighted in the
* header comments
* @param strsrch search iterator data struct
* @param position position to start next search from. If position is less
* than or greater than the text range for searching,
* an U_INDEX_OUTOFBOUNDS_ERROR will be returned
* @param status error status if any.
* @stable ICU 2.4
*/
U_CAPI void U_EXPORT2 usearch_setOffset(UStringSearch *strsrch,
int32_t position,
UErrorCode *status);
/**
* Return the current index in the string text being searched.
* If the iteration has gone past the end of the text (or past the beginning
* for a backwards search), <code>USEARCH_DONE</code> is returned.
* @param strsrch search iterator data struct
* @see #USEARCH_DONE
* @stable ICU 2.4
*/
U_CAPI int32_t U_EXPORT2 usearch_getOffset(const UStringSearch *strsrch);
/**
* Sets the text searching attributes located in the enum USearchAttribute
* with values from the enum USearchAttributeValue.
* <code>USEARCH_DEFAULT</code> can be used for all attributes for resetting.
* @param strsrch search iterator data struct
* @param attribute text attribute to be set
* @param value text attribute value
* @param status for errors if it occurs
* @see #usearch_getAttribute
* @stable ICU 2.4
*/
U_CAPI void U_EXPORT2 usearch_setAttribute(UStringSearch *strsrch,
USearchAttribute attribute,
USearchAttributeValue value,
UErrorCode *status);
/**
* Gets the text searching attributes.
* @param strsrch search iterator data struct
* @param attribute text attribute to be retrieve
* @return text attribute value
* @see #usearch_setAttribute
* @stable ICU 2.4
*/
U_CAPI USearchAttributeValue U_EXPORT2 usearch_getAttribute(
const UStringSearch *strsrch,
USearchAttribute attribute);
/**
* Returns the index to the match in the text string that was searched.
* This call returns a valid result only after a successful call to
* <code>usearch_first</code>, <code>usearch_next</code>, <code>usearch_previous</code>,
* or <code>usearch_last</code>.
* Just after construction, or after a searching method returns
* <code>USEARCH_DONE</code>, this method will return <code>USEARCH_DONE</code>.
* <p>
* Use <code>usearch_getMatchedLength</code> to get the matched string length.
* @param strsrch search iterator data struct
* @return index to a substring within the text string that is being
* searched.
* @see #usearch_first
* @see #usearch_next
* @see #usearch_previous
* @see #usearch_last
* @see #USEARCH_DONE
* @stable ICU 2.4
*/
U_CAPI int32_t U_EXPORT2 usearch_getMatchedStart(
const UStringSearch *strsrch);
/**
* Returns the length of text in the string which matches the search pattern.
* This call returns a valid result only after a successful call to
* <code>usearch_first</code>, <code>usearch_next</code>, <code>usearch_previous</code>,
* or <code>usearch_last</code>.
* Just after construction, or after a searching method returns
* <code>USEARCH_DONE</code>, this method will return 0.
* @param strsrch search iterator data struct
* @return The length of the match in the string text, or 0 if there is no
* match currently.
* @see #usearch_first
* @see #usearch_next
* @see #usearch_previous
* @see #usearch_last
* @see #USEARCH_DONE
* @stable ICU 2.4
*/
U_CAPI int32_t U_EXPORT2 usearch_getMatchedLength(
const UStringSearch *strsrch);
/**
* Returns the text that was matched by the most recent call to
* <code>usearch_first</code>, <code>usearch_next</code>, <code>usearch_previous</code>,
* or <code>usearch_last</code>.
* If the iterator is not pointing at a valid match (e.g. just after
* construction or after <code>USEARCH_DONE</code> has been returned, returns
* an empty string. If result is not large enough to store the matched text,
* result will be filled with the partial text and an U_BUFFER_OVERFLOW_ERROR
* will be returned in status. result will be null-terminated whenever
* possible. If the buffer fits the matched text exactly, a null-termination
* is not possible, then a U_STRING_NOT_TERMINATED_ERROR set in status.
* Pre-flighting can be either done with length = 0 or the API
* <code>usearch_getMatchedLength</code>.
* @param strsrch search iterator data struct
* @param result UChar buffer to store the matched string
* @param resultCapacity length of the result buffer
* @param status error returned if result is not large enough
* @return exact length of the matched text, not counting the null-termination
* @see #usearch_first
* @see #usearch_next
* @see #usearch_previous
* @see #usearch_last
* @see #USEARCH_DONE
* @stable ICU 2.4
*/
U_CAPI int32_t U_EXPORT2 usearch_getMatchedText(const UStringSearch *strsrch,
UChar *result,
int32_t resultCapacity,
UErrorCode *status);
#if !UCONFIG_NO_BREAK_ITERATION
/**
* Set the BreakIterator that will be used to restrict the points at which
* matches are detected.
* @param strsrch search iterator data struct
* @param breakiter A BreakIterator that will be used to restrict the points
* at which matches are detected. If a match is found, but
* the match's start or end index is not a boundary as
* determined by the <code>BreakIterator</code>, the match will
* be rejected and another will be searched for.
* If this parameter is <code>NULL</code>, no break detection is
* attempted.
* @param status for errors if it occurs
* @see #usearch_getBreakIterator
* @stable ICU 2.4
*/
U_CAPI void U_EXPORT2 usearch_setBreakIterator(UStringSearch *strsrch,
UBreakIterator *breakiter,
UErrorCode *status);
/**
* Returns the BreakIterator that is used to restrict the points at which
* matches are detected. This will be the same object that was passed to the
* constructor or to <code>usearch_setBreakIterator</code>. Note that
* <code>NULL</code>
* is a legal value; it means that break detection should not be attempted.
* @param strsrch search iterator data struct
* @return break iterator used
* @see #usearch_setBreakIterator
* @stable ICU 2.4
*/
U_CAPI const UBreakIterator * U_EXPORT2 usearch_getBreakIterator(
const UStringSearch *strsrch);
#endif
/**
* Set the string text to be searched. Text iteration will hence begin at the
* start of the text string. This method is useful if you want to re-use an
* iterator to search for the same pattern within a different body of text.
*
* The UStringSearch retains a pointer to the text string. The caller must not
* modify or delete the string while using the UStringSearch.
*
* @param strsrch search iterator data struct
* @param text new string to look for match
* @param textlength length of the new string, -1 for null-termination
* @param status for errors if it occurs. If text is NULL, or textlength is 0
* then an U_ILLEGAL_ARGUMENT_ERROR is returned with no change
* done to strsrch.
* @see #usearch_getText
* @stable ICU 2.4
*/
U_CAPI void U_EXPORT2 usearch_setText( UStringSearch *strsrch,
const UChar *text,
int32_t textlength,
UErrorCode *status);
/**
* Return the string text to be searched.
* @param strsrch search iterator data struct
* @param length returned string text length
* @return string text
* @see #usearch_setText
* @stable ICU 2.4
*/
U_CAPI const UChar * U_EXPORT2 usearch_getText(const UStringSearch *strsrch,
int32_t *length);
/**
* Gets the collator used for the language rules.
* <p>
* Deleting the returned <code>UCollator</code> before calling
* <code>usearch_close</code> would cause the string search to fail.
* <code>usearch_close</code> will delete the collator if this search owns it.
* @param strsrch search iterator data struct
* @return collator
* @stable ICU 2.4
*/
U_CAPI UCollator * U_EXPORT2 usearch_getCollator(
const UStringSearch *strsrch);
/**
* Sets the collator used for the language rules. User retains the ownership
* of this collator, thus the responsibility of deletion lies with the user.
* This method causes internal data such as the pattern collation elements
* and shift tables to be recalculated, but the iterator's position is unchanged.
* @param strsrch search iterator data struct
* @param collator to be used
* @param status for errors if it occurs
* @stable ICU 2.4
*/
U_CAPI void U_EXPORT2 usearch_setCollator( UStringSearch *strsrch,
const UCollator *collator,
UErrorCode *status);
/**
* Sets the pattern used for matching.
* Internal data like the pattern collation elements will be recalculated, but the
* iterator's position is unchanged.
*
* The UStringSearch retains a pointer to the pattern string. The caller must not
* modify or delete the string while using the UStringSearch.
*
* @param strsrch search iterator data struct
* @param pattern string
* @param patternlength pattern length, -1 for null-terminated string
* @param status for errors if it occurs. If text is NULL, or textlength is 0
* then an U_ILLEGAL_ARGUMENT_ERROR is returned with no change
* done to strsrch.
* @stable ICU 2.4
*/
U_CAPI void U_EXPORT2 usearch_setPattern( UStringSearch *strsrch,
const UChar *pattern,
int32_t patternlength,
UErrorCode *status);
/**
* Gets the search pattern
* @param strsrch search iterator data struct
* @param length return length of the pattern, -1 indicates that the pattern
* is null-terminated
* @return pattern string
* @stable ICU 2.4
*/
U_CAPI const UChar * U_EXPORT2 usearch_getPattern(
const UStringSearch *strsrch,
int32_t *length);
/* methods ------------------------------------------------------------- */
/**
* Returns the first index at which the string text matches the search
* pattern.
* The iterator is adjusted so that its current index (as returned by
* <code>usearch_getOffset</code>) is the match position if one was found.
* If a match is not found, <code>USEARCH_DONE</code> will be returned and
* the iterator will be adjusted to the index <code>USEARCH_DONE</code>.
* @param strsrch search iterator data struct
* @param status for errors if it occurs
* @return The character index of the first match, or
* <code>USEARCH_DONE</code> if there are no matches.
* @see #usearch_getOffset
* @see #USEARCH_DONE
* @stable ICU 2.4
*/
U_CAPI int32_t U_EXPORT2 usearch_first(UStringSearch *strsrch,
UErrorCode *status);
/**
* Returns the first index equal or greater than <code>position</code> at which
* the string text
* matches the search pattern. The iterator is adjusted so that its current
* index (as returned by <code>usearch_getOffset</code>) is the match position if
* one was found.
* If a match is not found, <code>USEARCH_DONE</code> will be returned and
* the iterator will be adjusted to the index <code>USEARCH_DONE</code>
* <p>
* Search positions that may render incorrect results are highlighted in the
* header comments. If position is less than or greater than the text range
* for searching, an U_INDEX_OUTOFBOUNDS_ERROR will be returned
* @param strsrch search iterator data struct
* @param position to start the search at
* @param status for errors if it occurs
* @return The character index of the first match following <code>pos</code>,
* or <code>USEARCH_DONE</code> if there are no matches.
* @see #usearch_getOffset
* @see #USEARCH_DONE
* @stable ICU 2.4
*/
U_CAPI int32_t U_EXPORT2 usearch_following(UStringSearch *strsrch,
int32_t position,
UErrorCode *status);
/**
* Returns the last index in the target text at which it matches the search
* pattern. The iterator is adjusted so that its current
* index (as returned by <code>usearch_getOffset</code>) is the match position if
* one was found.
* If a match is not found, <code>USEARCH_DONE</code> will be returned and
* the iterator will be adjusted to the index <code>USEARCH_DONE</code>.
* @param strsrch search iterator data struct
* @param status for errors if it occurs
* @return The index of the first match, or <code>USEARCH_DONE</code> if there
* are no matches.
* @see #usearch_getOffset
* @see #USEARCH_DONE
* @stable ICU 2.4
*/
U_CAPI int32_t U_EXPORT2 usearch_last(UStringSearch *strsrch,
UErrorCode *status);
/**
* Returns the first index less than <code>position</code> at which the string text
* matches the search pattern. The iterator is adjusted so that its current
* index (as returned by <code>usearch_getOffset</code>) is the match position if
* one was found.
* If a match is not found, <code>USEARCH_DONE</code> will be returned and
* the iterator will be adjusted to the index <code>USEARCH_DONE</code>
* <p>
* Search positions that may render incorrect results are highlighted in the
* header comments. If position is less than or greater than the text range
* for searching, an U_INDEX_OUTOFBOUNDS_ERROR will be returned.
* <p>
* When <code>USEARCH_OVERLAP</code> option is off, the last index of the
* result match is always less than <code>position</code>.
* When <code>USERARCH_OVERLAP</code> is on, the result match may span across
* <code>position</code>.
* @param strsrch search iterator data struct
* @param position index position the search is to begin at
* @param status for errors if it occurs
* @return The character index of the first match preceding <code>pos</code>,
* or <code>USEARCH_DONE</code> if there are no matches.
* @see #usearch_getOffset
* @see #USEARCH_DONE
* @stable ICU 2.4
*/
U_CAPI int32_t U_EXPORT2 usearch_preceding(UStringSearch *strsrch,
int32_t position,
UErrorCode *status);
/**
* Returns the index of the next point at which the string text matches the
* search pattern, starting from the current position.
* The iterator is adjusted so that its current
* index (as returned by <code>usearch_getOffset</code>) is the match position if
* one was found.
* If a match is not found, <code>USEARCH_DONE</code> will be returned and
* the iterator will be adjusted to the index <code>USEARCH_DONE</code>
* @param strsrch search iterator data struct
* @param status for errors if it occurs
* @return The index of the next match after the current position, or
* <code>USEARCH_DONE</code> if there are no more matches.
* @see #usearch_first
* @see #usearch_getOffset
* @see #USEARCH_DONE
* @stable ICU 2.4
*/
U_CAPI int32_t U_EXPORT2 usearch_next(UStringSearch *strsrch,
UErrorCode *status);
/**
* Returns the index of the previous point at which the string text matches
* the search pattern, starting at the current position.
* The iterator is adjusted so that its current
* index (as returned by <code>usearch_getOffset</code>) is the match position if
* one was found.
* If a match is not found, <code>USEARCH_DONE</code> will be returned and
* the iterator will be adjusted to the index <code>USEARCH_DONE</code>
* @param strsrch search iterator data struct
* @param status for errors if it occurs
* @return The index of the previous match before the current position,
* or <code>USEARCH_DONE</code> if there are no more matches.
* @see #usearch_last
* @see #usearch_getOffset
* @see #USEARCH_DONE
* @stable ICU 2.4
*/
U_CAPI int32_t U_EXPORT2 usearch_previous(UStringSearch *strsrch,
UErrorCode *status);
/**
* Reset the iteration.
* Search will begin at the start of the text string if a forward iteration
* is initiated before a backwards iteration. Otherwise if a backwards
* iteration is initiated before a forwards iteration, the search will begin
* at the end of the text string.
* @param strsrch search iterator data struct
* @see #usearch_first
* @stable ICU 2.4
*/
U_CAPI void U_EXPORT2 usearch_reset(UStringSearch *strsrch);
#ifndef U_HIDE_INTERNAL_API
/**
* Simple forward search for the pattern, starting at a specified index,
* and using a default set search options.
*
* This is an experimental function, and is not an official part of the
* ICU API.
*
* The collator options, such as UCOL_STRENGTH and UCOL_NORMALIZTION, are honored.
*
* The UStringSearch options USEARCH_CANONICAL_MATCH, USEARCH_OVERLAP and
* any Break Iterator are ignored.
*
* Matches obey the following constraints:
*
* Characters at the start or end positions of a match that are ignorable
* for collation are not included as part of the match, unless they
* are part of a combining sequence, as described below.
*
* A match will not include a partial combining sequence. Combining
* character sequences are considered to be inseparable units,
* and either match the pattern completely, or are considered to not match
* at all. Thus, for example, an A followed a combining accent mark will
* not be found when searching for a plain (unaccented) A. (unless
* the collation strength has been set to ignore all accents).
*
* When beginning a search, the initial starting position, startIdx,
* is assumed to be an acceptable match boundary with respect to
* combining characters. A combining sequence that spans across the
* starting point will not suppress a match beginning at startIdx.
*
* Characters that expand to multiple collation elements
* (German sharp-S becoming 'ss', or the composed forms of accented
* characters, for example) also must match completely.
* Searching for a single 's' in a string containing only a sharp-s will
* find no match.
*
*
* @param strsrch the UStringSearch struct, which references both
* the text to be searched and the pattern being sought.
* @param startIdx The index into the text to begin the search.
* @param matchStart An out parameter, the starting index of the matched text.
* This parameter may be NULL.
* A value of -1 will be returned if no match was found.
* @param matchLimit Out parameter, the index of the first position following the matched text.
* The matchLimit will be at a suitable position for beginning a subsequent search
* in the input text.
* This parameter may be NULL.
* A value of -1 will be returned if no match was found.
*
* @param status Report any errors. Note that no match found is not an error.
* @return true if a match was found, false otherwise.
*
* @internal
*/
U_CAPI UBool U_EXPORT2 usearch_search(UStringSearch *strsrch,
int32_t startIdx,
int32_t *matchStart,
int32_t *matchLimit,
UErrorCode *status);
/**
* Simple backwards search for the pattern, starting at a specified index,
* and using using a default set search options.
*
* This is an experimental function, and is not an official part of the
* ICU API.
*
* The collator options, such as UCOL_STRENGTH and UCOL_NORMALIZTION, are honored.
*
* The UStringSearch options USEARCH_CANONICAL_MATCH, USEARCH_OVERLAP and
* any Break Iterator are ignored.
*
* Matches obey the following constraints:
*
* Characters at the start or end positions of a match that are ignorable
* for collation are not included as part of the match, unless they
* are part of a combining sequence, as described below.
*
* A match will not include a partial combining sequence. Combining
* character sequences are considered to be inseparable units,
* and either match the pattern completely, or are considered to not match
* at all. Thus, for example, an A followed a combining accent mark will
* not be found when searching for a plain (unaccented) A. (unless
* the collation strength has been set to ignore all accents).
*
* When beginning a search, the initial starting position, startIdx,
* is assumed to be an acceptable match boundary with respect to
* combining characters. A combining sequence that spans across the
* starting point will not suppress a match beginning at startIdx.
*
* Characters that expand to multiple collation elements
* (German sharp-S becoming 'ss', or the composed forms of accented
* characters, for example) also must match completely.
* Searching for a single 's' in a string containing only a sharp-s will
* find no match.
*
*
* @param strsrch the UStringSearch struct, which references both
* the text to be searched and the pattern being sought.
* @param startIdx The index into the text to begin the search.
* @param matchStart An out parameter, the starting index of the matched text.
* This parameter may be NULL.
* A value of -1 will be returned if no match was found.
* @param matchLimit Out parameter, the index of the first position following the matched text.
* The matchLimit will be at a suitable position for beginning a subsequent search
* in the input text.
* This parameter may be NULL.
* A value of -1 will be returned if no match was found.
*
* @param status Report any errors. Note that no match found is not an error.
* @return true if a match was found, false otherwise.
*
* @internal
*/
U_CAPI UBool U_EXPORT2 usearch_searchBackwards(UStringSearch *strsrch,
int32_t startIdx,
int32_t *matchStart,
int32_t *matchLimit,
UErrorCode *status);
#endif /* U_HIDE_INTERNAL_API */
#endif /* #if !UCONFIG_NO_COLLATION && !UCONFIG_NO_BREAK_ITERATION */
#endif

View File

@ -0,0 +1,295 @@
// © 2022 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
#ifndef __USIMPLENUMBERFORMATTER_H__
#define __USIMPLENUMBERFORMATTER_H__
#include "unicode/utypes.h"
#if !UCONFIG_NO_FORMATTING
#include "unicode/uformattednumber.h"
#include "unicode/unumberoptions.h"
/**
* \file
* \brief C API: Simple number formatting focused on low memory and code size.
*
* These functions render locale-aware number strings but without the bells and whistles found in
* other number formatting APIs such as those in unumberformatter.h, like units and currencies.
*
* Example using C++ helpers:
*
* <pre>
* LocalUSimpleNumberFormatterPointer uformatter(usnumf_openForLocale("de-CH", status));
* LocalUFormattedNumberPointer uresult(unumf_openResult(status));
* usnumf_formatInt64(uformatter.getAlias(), 55, uresult.getAlias(), status);
* assertEquals("",
* u"55",
* ufmtval_getString(unumf_resultAsValue(uresult.getAlias(), status), nullptr, status));
* </pre>
*
* Example using pure C:
*
* <pre>
* UErrorCode ec = U_ZERO_ERROR;
* USimpleNumberFormatter* uformatter = usnumf_openForLocale("bn", &ec);
* USimpleNumber* unumber = usnum_openForInt64(1000007, &ec);
* UFormattedNumber* uresult = unumf_openResult(&ec);
* usnumf_format(uformatter, unumber, uresult, &ec);
* int32_t len;
* const UChar* str = ufmtval_getString(unumf_resultAsValue(uresult, &ec), &len, &ec);
* if (assertSuccess("Formatting end-to-end", &ec)) {
* assertUEquals("Should produce a result in Bangla digits", u"১০,,", str);
* }
* // Cleanup:
* unumf_closeResult(uresult);
* usnum_close(unumber);
* usnumf_close(uformatter);
* </pre>
*/
/**
* An explicit sign option for a SimpleNumber.
*
* @stable ICU 73
*/
typedef enum USimpleNumberSign {
/**
* Render a plus sign.
*
* @stable ICU 73
*/
UNUM_SIMPLE_NUMBER_PLUS_SIGN,
/**
* Render no sign.
*
* @stable ICU 73
*/
UNUM_SIMPLE_NUMBER_NO_SIGN,
/**
* Render a minus sign.
*
* @stable ICU 73
*/
UNUM_SIMPLE_NUMBER_MINUS_SIGN,
} USimpleNumberSign;
struct USimpleNumber;
/**
* C-compatible version of icu::number::SimpleNumber.
*
* @stable ICU 73
*/
typedef struct USimpleNumber USimpleNumber;
struct USimpleNumberFormatter;
/**
* C-compatible version of icu::number::SimpleNumberFormatter.
*
* @stable ICU 73
*/
typedef struct USimpleNumberFormatter USimpleNumberFormatter;
/**
* Creates a new USimpleNumber to be formatted with a USimpleNumberFormatter.
*
* @stable ICU 73
*/
U_CAPI USimpleNumber* U_EXPORT2
usnum_openForInt64(int64_t value, UErrorCode* ec);
/**
* Overwrites the value in a USimpleNumber to an int64_t.
*
* This can be used to reset the number value after formatting.
*
* @stable ICU 73
*/
U_CAPI void U_EXPORT2
usnum_setToInt64(USimpleNumber* unumber, int64_t value, UErrorCode* ec);
/**
* Changes the value of the USimpleNumber by a power of 10.
*
* This function immediately mutates the inner value.
*
* @stable ICU 73
*/
U_CAPI void U_EXPORT2
usnum_multiplyByPowerOfTen(USimpleNumber* unumber, int32_t power, UErrorCode* ec);
/**
* Rounds the value currently stored in the USimpleNumber to the given power of 10,
* which can be before or after the decimal separator.
*
* This function does not change minimum integer digits.
*
* @stable ICU 73
*/
U_CAPI void U_EXPORT2
usnum_roundTo(USimpleNumber* unumber, int32_t power, UNumberFormatRoundingMode roundingMode, UErrorCode* ec);
/**
* Pads the beginning of the number with zeros up to the given minimum number of integer digits.
*
* @stable ICU 73
*/
U_CAPI void U_EXPORT2
usnum_setMinimumIntegerDigits(USimpleNumber* unumber, int32_t minimumIntegerDigits, UErrorCode* ec);
/**
* Pads the end of the number with zeros up to the given minimum number of fraction digits.
*
* @stable ICU 73
*/
U_CAPI void U_EXPORT2
usnum_setMinimumFractionDigits(USimpleNumber* unumber, int32_t minimumFractionDigits, UErrorCode* ec);
/**
* Sets the number of integer digits to the given amount, truncating if necessary.
*
* @stable ICU 75
*/
U_CAPI void U_EXPORT2
usnum_setMaximumIntegerDigits(USimpleNumber* unumber, int32_t maximumIntegerDigits, UErrorCode* ec);
/**
* Sets the sign of the number: an explicit plus sign, explicit minus sign, or no sign.
*
* This setting is applied upon formatting the number.
*
* NOTE: This does not support accounting sign notation.
*
* @stable ICU 73
*/
U_CAPI void U_EXPORT2
usnum_setSign(USimpleNumber* unumber, USimpleNumberSign sign, UErrorCode* ec);
/**
* Creates a new USimpleNumberFormatter with all locale defaults.
*
* @stable ICU 73
*/
U_CAPI USimpleNumberFormatter* U_EXPORT2
usnumf_openForLocale(const char* locale, UErrorCode* ec);
/**
* Creates a new USimpleNumberFormatter, overriding the grouping strategy.
*
* @stable ICU 73
*/
U_CAPI USimpleNumberFormatter* U_EXPORT2
usnumf_openForLocaleAndGroupingStrategy(
const char* locale, UNumberGroupingStrategy groupingStrategy, UErrorCode* ec);
/**
* Formats a number using this SimpleNumberFormatter.
*
* The USimpleNumber is cleared after calling this function. It can be re-used via
* usnum_setToInt64.
*
* @stable ICU 73
*/
U_CAPI void U_EXPORT2
usnumf_format(
const USimpleNumberFormatter* uformatter,
USimpleNumber* unumber,
UFormattedNumber* uresult,
UErrorCode* ec);
/**
* Formats an integer using this SimpleNumberFormatter.
*
* For more control over the formatting, use USimpleNumber.
*
* @stable ICU 73
*/
U_CAPI void U_EXPORT2
usnumf_formatInt64(
const USimpleNumberFormatter* uformatter,
int64_t value,
UFormattedNumber* uresult,
UErrorCode* ec);
/**
* Frees the memory held by a USimpleNumber.
*
* NOTE: Normally, a USimpleNumber should be adopted by usnumf_formatAndAdoptNumber.
*
* @stable ICU 73
*/
U_CAPI void U_EXPORT2
usnum_close(USimpleNumber* unumber);
/**
* Frees the memory held by a USimpleNumberFormatter.
*
* @stable ICU 73
*/
U_CAPI void U_EXPORT2
usnumf_close(USimpleNumberFormatter* uformatter);
#if U_SHOW_CPLUSPLUS_API
U_NAMESPACE_BEGIN
/**
* \class LocalUSimpleNumberPointer
* "Smart pointer" class; closes a USimpleNumber via usnum_close().
* For most methods see the LocalPointerBase base class.
*
* NOTE: Normally, a USimpleNumber should be adopted by usnumf_formatAndAdoptNumber.
* If you use LocalUSimpleNumberPointer, call `.orphan()` when passing to that function.
*
* Usage:
* <pre>
* LocalUSimpleNumberPointer uformatter(usnumf_openForInteger(...));
* // no need to explicitly call usnum_close()
* </pre>
*
* @see LocalPointerBase
* @see LocalPointer
* @stable ICU 73
*/
U_DEFINE_LOCAL_OPEN_POINTER(LocalUSimpleNumberPointer, USimpleNumber, usnum_close);
/**
* \class LocalUSimpleNumberFormatterPointer
* "Smart pointer" class; closes a USimpleNumberFormatter via usnumf_close().
* For most methods see the LocalPointerBase base class.
*
* Usage:
* <pre>
* LocalUSimpleNumberFormatterPointer uformatter(usnumf_openForLocale(...));
* // no need to explicitly call usnumf_close()
* </pre>
*
* @see LocalPointerBase
* @see LocalPointer
* @stable ICU 73
*/
U_DEFINE_LOCAL_OPEN_POINTER(LocalUSimpleNumberFormatterPointer, USimpleNumberFormatter, usnumf_close);
U_NAMESPACE_END
#endif // U_SHOW_CPLUSPLUS_API
#endif /* #if !UCONFIG_NO_FORMATTING */
#endif //__USIMPLENUMBERFORMATTER_H__

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,490 @@
// © 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
/*
*******************************************************************************
* Copyright (C) 2004 - 2008, International Business Machines Corporation and
* others. All Rights Reserved.
*******************************************************************************
*/
#ifndef UTMSCALE_H
#define UTMSCALE_H
#include "unicode/utypes.h"
#if !UCONFIG_NO_FORMATTING
/**
* \file
* \brief C API: Universal Time Scale
*
* There are quite a few different conventions for binary datetime, depending on different
* platforms and protocols. Some of these have severe drawbacks. For example, people using
* Unix time (seconds since Jan 1, 1970) think that they are safe until near the year 2038.
* But cases can and do arise where arithmetic manipulations causes serious problems. Consider
* the computation of the average of two datetimes, for example: if one calculates them with
* <code>averageTime = (time1 + time2)/2</code>, there will be overflow even with dates
* around the present. Moreover, even if these problems don't occur, there is the issue of
* conversion back and forth between different systems.
*
* <p>
* Binary datetimes differ in a number of ways: the datatype, the unit,
* and the epoch (origin). We'll refer to these as time scales. For example:
*
* <table border="1" cellspacing="0" cellpadding="4">
* <caption>Table 1: Binary Time Scales</caption>
* <tr>
* <th align="left">Source</th>
* <th align="left">Datatype</th>
* <th align="left">Unit</th>
* <th align="left">Epoch</th>
* </tr>
*
* <tr>
* <td>UDTS_JAVA_TIME</td>
* <td>int64_t</td>
* <td>milliseconds</td>
* <td>Jan 1, 1970</td>
* </tr>
* <tr>
*
* <td>UDTS_UNIX_TIME</td>
* <td>int32_t or int64_t</td>
* <td>seconds</td>
* <td>Jan 1, 1970</td>
* </tr>
* <tr>
* <td>UDTS_ICU4C_TIME</td>
*
* <td>double</td>
* <td>milliseconds</td>
* <td>Jan 1, 1970</td>
* </tr>
* <tr>
* <td>UDTS_WINDOWS_FILE_TIME</td>
* <td>int64_t</td>
*
* <td>ticks (100 nanoseconds)</td>
* <td>Jan 1, 1601</td>
* </tr>
* <tr>
* <td>UDTS_DOTNET_DATE_TIME</td>
* <td>int64_t</td>
* <td>ticks (100 nanoseconds)</td>
*
* <td>Jan 1, 0001</td>
* </tr>
* <tr>
* <td>UDTS_MAC_OLD_TIME</td>
* <td>int32_t or int64_t</td>
* <td>seconds</td>
* <td>Jan 1, 1904</td>
*
* </tr>
* <tr>
* <td>UDTS_MAC_TIME</td>
* <td>double</td>
* <td>seconds</td>
* <td>Jan 1, 2001</td>
* </tr>
*
* <tr>
* <td>UDTS_EXCEL_TIME</td>
* <td>?</td>
* <td>days</td>
* <td>Dec 31, 1899</td>
* </tr>
* <tr>
*
* <td>UDTS_DB2_TIME</td>
* <td>?</td>
* <td>days</td>
* <td>Dec 31, 1899</td>
* </tr>
*
* <tr>
* <td>UDTS_UNIX_MICROSECONDS_TIME</td>
* <td>int64_t</td>
* <td>microseconds</td>
* <td>Jan 1, 1970</td>
* </tr>
* </table>
*
* <p>
* All of the epochs start at 00:00 am (the earliest possible time on the day in question),
* and are assumed to be UTC.
*
* <p>
* The ranges for different datatypes are given in the following table (all values in years).
* The range of years includes the entire range expressible with positive and negative
* values of the datatype. The range of years for double is the range that would be allowed
* without losing precision to the corresponding unit.
*
* <table border="1" cellspacing="0" cellpadding="4">
* <tr>
* <th align="left">Units</th>
* <th align="left">int64_t</th>
* <th align="left">double</th>
* <th align="left">int32_t</th>
* </tr>
*
* <tr>
* <td>1 sec</td>
* <td align="right">5.84542x10<sup>11</sup></td>
* <td align="right">285,420,920.94</td>
* <td align="right">136.10</td>
* </tr>
* <tr>
*
* <td>1 millisecond</td>
* <td align="right">584,542,046.09</td>
* <td align="right">285,420.92</td>
* <td align="right">0.14</td>
* </tr>
* <tr>
* <td>1 microsecond</td>
*
* <td align="right">584,542.05</td>
* <td align="right">285.42</td>
* <td align="right">0.00</td>
* </tr>
* <tr>
* <td>100 nanoseconds (tick)</td>
* <td align="right">58,454.20</td>
* <td align="right">28.54</td>
* <td align="right">0.00</td>
* </tr>
* <tr>
* <td>1 nanosecond</td>
* <td align="right">584.5420461</td>
* <td align="right">0.2854</td>
* <td align="right">0.00</td>
* </tr>
* </table>
*
* <p>
* These functions implement a universal time scale which can be used as a 'pivot',
* and provide conversion functions to and from all other major time scales.
* This datetimes to be converted to the pivot time, safely manipulated,
* and converted back to any other datetime time scale.
*
*<p>
* So what to use for this pivot? Java time has plenty of range, but cannot represent
* .NET <code>System.DateTime</code> values without severe loss of precision. ICU4C time addresses this by using a
* <code>double</code> that is otherwise equivalent to the Java time. However, there are disadvantages
* with <code>doubles</code>. They provide for much more graceful degradation in arithmetic operations.
* But they only have 53 bits of accuracy, which means that they will lose precision when
* converting back and forth to ticks. What would really be nice would be a
* <code>long double</code> (80 bits -- 64 bit mantissa), but that is not supported on most systems.
*
*<p>
* The Unix extended time uses a structure with two components: time in seconds and a
* fractional field (microseconds). However, this is clumsy, slow, and
* prone to error (you always have to keep track of overflow and underflow in the
* fractional field). <code>BigDecimal</code> would allow for arbitrary precision and arbitrary range,
* but we do not want to use this as the normal type, because it is slow and does not
* have a fixed size.
*
*<p>
* Because of these issues, we ended up concluding that the .NET framework's
* <code>System.DateTime</code> would be the best pivot. However, we use the full range
* allowed by the datatype, allowing for datetimes back to 29,000 BC and up to 29,000 AD.
* This time scale is very fine grained, does not lose precision, and covers a range that
* will meet almost all requirements. It will not handle the range that Java times do,
* but frankly, being able to handle dates before 29,000 BC or after 29,000 AD is of very limited interest.
*
*/
/**
* <code>UDateTimeScale</code> values are used to specify the time scale used for
* conversion into or out if the universal time scale.
*
* @stable ICU 3.2
*/
typedef enum UDateTimeScale {
/**
* Used in the JDK. Data is a Java <code>long</code> (<code>int64_t</code>). Value
* is milliseconds since January 1, 1970.
*
* @stable ICU 3.2
*/
UDTS_JAVA_TIME = 0,
/**
* Used on Unix systems. Data is <code>int32_t</code> or <code>int64_t</code>. Value
* is seconds since January 1, 1970.
*
* @stable ICU 3.2
*/
UDTS_UNIX_TIME,
/**
* Used in IUC4C. Data is a <code>double</code>. Value
* is milliseconds since January 1, 1970.
*
* @stable ICU 3.2
*/
UDTS_ICU4C_TIME,
/**
* Used in Windows for file times. Data is an <code>int64_t</code>. Value
* is ticks (1 tick == 100 nanoseconds) since January 1, 1601.
*
* @stable ICU 3.2
*/
UDTS_WINDOWS_FILE_TIME,
/**
* Used in the .NET framework's <code>System.DateTime</code> structure. Data is an <code>int64_t</code>. Value
* is ticks (1 tick == 100 nanoseconds) since January 1, 0001.
*
* @stable ICU 3.2
*/
UDTS_DOTNET_DATE_TIME,
/**
* Used in older Macintosh systems. Data is <code>int32_t</code> or <code>int64_t</code>. Value
* is seconds since January 1, 1904.
*
* @stable ICU 3.2
*/
UDTS_MAC_OLD_TIME,
/**
* Used in newer Macintosh systems. Data is a <code>double</code>. Value
* is seconds since January 1, 2001.
*
* @stable ICU 3.2
*/
UDTS_MAC_TIME,
/**
* Used in Excel. Data is an <code>?unknown?</code>. Value
* is days since December 31, 1899.
*
* @stable ICU 3.2
*/
UDTS_EXCEL_TIME,
/**
* Used in DB2. Data is an <code>?unknown?</code>. Value
* is days since December 31, 1899.
*
* @stable ICU 3.2
*/
UDTS_DB2_TIME,
/**
* Data is a <code>long</code>. Value is microseconds since January 1, 1970.
* Similar to Unix time (linear value from 1970) and struct timeval
* (microseconds resolution).
*
* @stable ICU 3.8
*/
UDTS_UNIX_MICROSECONDS_TIME,
#ifndef U_HIDE_DEPRECATED_API
/**
* The first unused time scale value. The limit of this enum
* @deprecated ICU 59 The numeric value may change over time, see ICU ticket #12420.
*/
UDTS_MAX_SCALE
#endif /* U_HIDE_DEPRECATED_API */
} UDateTimeScale;
/**
* <code>UTimeScaleValue</code> values are used to specify the time scale values
* to <code>utmscale_getTimeScaleValue</code>.
*
* @see utmscale_getTimeScaleValue
*
* @stable ICU 3.2
*/
typedef enum UTimeScaleValue {
/**
* The constant used to select the units vale
* for a time scale.
*
* @see utmscale_getTimeScaleValue
*
* @stable ICU 3.2
*/
UTSV_UNITS_VALUE = 0,
/**
* The constant used to select the epoch offset value
* for a time scale.
*
* @see utmscale_getTimeScaleValue
*
* @stable ICU 3.2
*/
UTSV_EPOCH_OFFSET_VALUE=1,
/**
* The constant used to select the minimum from value
* for a time scale.
*
* @see utmscale_getTimeScaleValue
*
* @stable ICU 3.2
*/
UTSV_FROM_MIN_VALUE=2,
/**
* The constant used to select the maximum from value
* for a time scale.
*
* @see utmscale_getTimeScaleValue
*
* @stable ICU 3.2
*/
UTSV_FROM_MAX_VALUE=3,
/**
* The constant used to select the minimum to value
* for a time scale.
*
* @see utmscale_getTimeScaleValue
*
* @stable ICU 3.2
*/
UTSV_TO_MIN_VALUE=4,
/**
* The constant used to select the maximum to value
* for a time scale.
*
* @see utmscale_getTimeScaleValue
*
* @stable ICU 3.2
*/
UTSV_TO_MAX_VALUE=5,
#ifndef U_HIDE_INTERNAL_API
/**
* The constant used to select the epoch plus one value
* for a time scale.
*
* NOTE: This is an internal value. DO NOT USE IT. May not
* actually be equal to the epoch offset value plus one.
*
* @see utmscale_getTimeScaleValue
*
* @internal ICU 3.2
*/
UTSV_EPOCH_OFFSET_PLUS_1_VALUE=6,
/**
* The constant used to select the epoch plus one value
* for a time scale.
*
* NOTE: This is an internal value. DO NOT USE IT. May not
* actually be equal to the epoch offset value plus one.
*
* @see utmscale_getTimeScaleValue
*
* @internal ICU 3.2
*/
UTSV_EPOCH_OFFSET_MINUS_1_VALUE=7,
/**
* The constant used to select the units round value
* for a time scale.
*
* NOTE: This is an internal value. DO NOT USE IT.
*
* @see utmscale_getTimeScaleValue
*
* @internal ICU 3.2
*/
UTSV_UNITS_ROUND_VALUE=8,
/**
* The constant used to select the minimum safe rounding value
* for a time scale.
*
* NOTE: This is an internal value. DO NOT USE IT.
*
* @see utmscale_getTimeScaleValue
*
* @internal ICU 3.2
*/
UTSV_MIN_ROUND_VALUE=9,
/**
* The constant used to select the maximum safe rounding value
* for a time scale.
*
* NOTE: This is an internal value. DO NOT USE IT.
*
* @see utmscale_getTimeScaleValue
*
* @internal ICU 3.2
*/
UTSV_MAX_ROUND_VALUE=10,
#endif /* U_HIDE_INTERNAL_API */
#ifndef U_HIDE_DEPRECATED_API
/**
* The number of time scale values, in other words limit of this enum.
*
* @see utmscale_getTimeScaleValue
* @deprecated ICU 59 The numeric value may change over time, see ICU ticket #12420.
*/
UTSV_MAX_SCALE_VALUE=11
#endif /* U_HIDE_DEPRECATED_API */
} UTimeScaleValue;
/**
* Get a value associated with a particular time scale.
*
* @param timeScale The time scale
* @param value A constant representing the value to get
* @param status The status code. Set to <code>U_ILLEGAL_ARGUMENT_ERROR</code> if arguments are invalid.
* @return - the value.
*
* @stable ICU 3.2
*/
U_CAPI int64_t U_EXPORT2
utmscale_getTimeScaleValue(UDateTimeScale timeScale, UTimeScaleValue value, UErrorCode *status);
/* Conversion to 'universal time scale' */
/**
* Convert a <code>int64_t</code> datetime from the given time scale to the universal time scale.
*
* @param otherTime The <code>int64_t</code> datetime
* @param timeScale The time scale to convert from
* @param status The status code. Set to <code>U_ILLEGAL_ARGUMENT_ERROR</code> if the conversion is out of range.
*
* @return The datetime converted to the universal time scale
*
* @stable ICU 3.2
*/
U_CAPI int64_t U_EXPORT2
utmscale_fromInt64(int64_t otherTime, UDateTimeScale timeScale, UErrorCode *status);
/* Conversion from 'universal time scale' */
/**
* Convert a datetime from the universal time scale to a <code>int64_t</code> in the given time scale.
*
* @param universalTime The datetime in the universal time scale
* @param timeScale The time scale to convert to
* @param status The status code. Set to <code>U_ILLEGAL_ARGUMENT_ERROR</code> if the conversion is out of range.
*
* @return The datetime converted to the given time scale
*
* @stable ICU 3.2
*/
U_CAPI int64_t U_EXPORT2
utmscale_toInt64(int64_t universalTime, UDateTimeScale timeScale, UErrorCode *status);
#endif /* #if !UCONFIG_NO_FORMATTING */
#endif

View File

@ -0,0 +1,660 @@
// © 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
/*
*******************************************************************************
* Copyright (C) 1997-2011,2014-2015 International Business Machines
* Corporation and others. All Rights Reserved.
*******************************************************************************
* Date Name Description
* 06/21/00 aliu Creation.
*******************************************************************************
*/
#ifndef UTRANS_H
#define UTRANS_H
#include "unicode/utypes.h"
#if !UCONFIG_NO_TRANSLITERATION
#include "unicode/urep.h"
#include "unicode/parseerr.h"
#include "unicode/uenum.h"
#include "unicode/uset.h"
#if U_SHOW_CPLUSPLUS_API
#include "unicode/localpointer.h"
#endif // U_SHOW_CPLUSPLUS_API
/********************************************************************
* General Notes
********************************************************************
*/
/**
* \file
* \brief C API: Transliterator
*
* <h2> Transliteration </h2>
* The data structures and functions described in this header provide
* transliteration services. Transliteration services are implemented
* as C++ classes. The comments and documentation in this header
* assume the reader is familiar with the C++ headers translit.h and
* associated documentation.
*
* A significant but incomplete subset of the C++ transliteration
* services are available to C code through this header. In order to
* access more complex transliteration services, refer to the C++
* headers and documentation.
*
* There are two sets of functions for working with transliterator IDs:
*
* An old, deprecated set uses char * IDs, which works for true and pure
* identifiers that these APIs were designed for,
* for example "Cyrillic-Latin".
* It does not work when the ID contains filters ("[:Script=Cyrl:]")
* or even a complete set of rules because then the ID string contains more
* than just "invariant" characters (see utypes.h).
*
* A new set of functions replaces the old ones and uses UChar * IDs,
* paralleling the UnicodeString IDs in the C++ API. (New in ICU 2.8.)
*/
/********************************************************************
* Data Structures
********************************************************************/
/**
* An opaque transliterator for use in C. Open with utrans_openxxx()
* and close with utrans_close() when done. Equivalent to the C++ class
* Transliterator and its subclasses.
* @see Transliterator
* @stable ICU 2.0
*/
typedef void* UTransliterator;
/**
* Direction constant indicating the direction in a transliterator,
* e.g., the forward or reverse rules of a RuleBasedTransliterator.
* Specified when a transliterator is opened. An "A-B" transliterator
* transliterates A to B when operating in the forward direction, and
* B to A when operating in the reverse direction.
* @stable ICU 2.0
*/
typedef enum UTransDirection {
/**
* UTRANS_FORWARD means from &lt;source&gt; to &lt;target&gt; for a
* transliterator with ID &lt;source&gt;-&lt;target&gt;. For a transliterator
* opened using a rule, it means forward direction rules, e.g.,
* "A > B".
*/
UTRANS_FORWARD,
/**
* UTRANS_REVERSE means from &lt;target&gt; to &lt;source&gt; for a
* transliterator with ID &lt;source&gt;-&lt;target&gt;. For a transliterator
* opened using a rule, it means reverse direction rules, e.g.,
* "A < B".
*/
UTRANS_REVERSE
} UTransDirection;
/**
* Position structure for utrans_transIncremental() incremental
* transliteration. This structure defines two substrings of the text
* being transliterated. The first region, [contextStart,
* contextLimit), defines what characters the transliterator will read
* as context. The second region, [start, limit), defines what
* characters will actually be transliterated. The second region
* should be a subset of the first.
*
* <p>After a transliteration operation, some of the indices in this
* structure will be modified. See the field descriptions for
* details.
*
* <p>contextStart <= start <= limit <= contextLimit
*
* <p>Note: All index values in this structure must be at code point
* boundaries. That is, none of them may occur between two code units
* of a surrogate pair. If any index does split a surrogate pair,
* results are unspecified.
*
* @stable ICU 2.0
*/
typedef struct UTransPosition {
/**
* Beginning index, inclusive, of the context to be considered for
* a transliteration operation. The transliterator will ignore
* anything before this index. INPUT/OUTPUT parameter: This parameter
* is updated by a transliteration operation to reflect the maximum
* amount of antecontext needed by a transliterator.
* @stable ICU 2.4
*/
int32_t contextStart;
/**
* Ending index, exclusive, of the context to be considered for a
* transliteration operation. The transliterator will ignore
* anything at or after this index. INPUT/OUTPUT parameter: This
* parameter is updated to reflect changes in the length of the
* text, but points to the same logical position in the text.
* @stable ICU 2.4
*/
int32_t contextLimit;
/**
* Beginning index, inclusive, of the text to be transliterated.
* INPUT/OUTPUT parameter: This parameter is advanced past
* characters that have already been transliterated by a
* transliteration operation.
* @stable ICU 2.4
*/
int32_t start;
/**
* Ending index, exclusive, of the text to be transliterated.
* INPUT/OUTPUT parameter: This parameter is updated to reflect
* changes in the length of the text, but points to the same
* logical position in the text.
* @stable ICU 2.4
*/
int32_t limit;
} UTransPosition;
/********************************************************************
* General API
********************************************************************/
/**
* Open a custom transliterator, given a custom rules string
* OR
* a system transliterator, given its ID.
* Any non-NULL result from this function should later be closed with
* utrans_close().
*
* @param id a valid transliterator ID
* @param idLength the length of the ID string, or -1 if NUL-terminated
* @param dir the desired direction
* @param rules the transliterator rules. See the C++ header rbt.h for
* rules syntax. If NULL then a system transliterator matching
* the ID is returned.
* @param rulesLength the length of the rules, or -1 if the rules
* are NUL-terminated.
* @param parseError a pointer to a UParseError struct to receive the details
* of any parsing errors. This parameter may be NULL if no
* parsing error details are desired.
* @param pErrorCode a pointer to the UErrorCode
* @return a transliterator pointer that may be passed to other
* utrans_xxx() functions, or NULL if the open call fails.
* @stable ICU 2.8
*/
U_CAPI UTransliterator* U_EXPORT2
utrans_openU(const UChar *id,
int32_t idLength,
UTransDirection dir,
const UChar *rules,
int32_t rulesLength,
UParseError *parseError,
UErrorCode *pErrorCode);
/**
* Open an inverse of an existing transliterator. For this to work,
* the inverse must be registered with the system. For example, if
* the Transliterator "A-B" is opened, and then its inverse is opened,
* the result is the Transliterator "B-A", if such a transliterator is
* registered with the system. Otherwise the result is NULL and a
* failing UErrorCode is set. Any non-NULL result from this function
* should later be closed with utrans_close().
*
* @param trans the transliterator to open the inverse of.
* @param status a pointer to the UErrorCode
* @return a pointer to a newly-opened transliterator that is the
* inverse of trans, or NULL if the open call fails.
* @stable ICU 2.0
*/
U_CAPI UTransliterator* U_EXPORT2
utrans_openInverse(const UTransliterator* trans,
UErrorCode* status);
/**
* Create a copy of a transliterator. Any non-NULL result from this
* function should later be closed with utrans_close().
*
* @param trans the transliterator to be copied.
* @param status a pointer to the UErrorCode
* @return a transliterator pointer that may be passed to other
* utrans_xxx() functions, or NULL if the clone call fails.
* @stable ICU 2.0
*/
U_CAPI UTransliterator* U_EXPORT2
utrans_clone(const UTransliterator* trans,
UErrorCode* status);
/**
* Close a transliterator. Any non-NULL pointer returned by
* utrans_openXxx() or utrans_clone() should eventually be closed.
* @param trans the transliterator to be closed.
* @stable ICU 2.0
*/
U_CAPI void U_EXPORT2
utrans_close(UTransliterator* trans);
#if U_SHOW_CPLUSPLUS_API
U_NAMESPACE_BEGIN
/**
* \class LocalUTransliteratorPointer
* "Smart pointer" class, closes a UTransliterator via utrans_close().
* For most methods see the LocalPointerBase base class.
*
* @see LocalPointerBase
* @see LocalPointer
* @stable ICU 4.4
*/
U_DEFINE_LOCAL_OPEN_POINTER(LocalUTransliteratorPointer, UTransliterator, utrans_close);
U_NAMESPACE_END
#endif
/**
* Return the programmatic identifier for this transliterator.
* If this identifier is passed to utrans_openU(), it will open
* a transliterator equivalent to this one, if the ID has been
* registered.
*
* @param trans the transliterator to return the ID of.
* @param resultLength pointer to an output variable receiving the length
* of the ID string; can be NULL
* @return the NUL-terminated ID string. This pointer remains
* valid until utrans_close() is called on this transliterator.
*
* @stable ICU 2.8
*/
U_CAPI const UChar * U_EXPORT2
utrans_getUnicodeID(const UTransliterator *trans,
int32_t *resultLength);
/**
* Register an open transliterator with the system. When
* utrans_open() is called with an ID string that is equal to that
* returned by utrans_getID(adoptedTrans,...), then
* utrans_clone(adoptedTrans,...) is returned.
*
* <p>NOTE: After this call the system owns the adoptedTrans and will
* close it. The user must not call utrans_close() on adoptedTrans.
*
* @param adoptedTrans a transliterator, typically the result of
* utrans_openRules(), to be registered with the system.
* @param status a pointer to the UErrorCode
* @stable ICU 2.0
*/
U_CAPI void U_EXPORT2
utrans_register(UTransliterator* adoptedTrans,
UErrorCode* status);
/**
* Unregister a transliterator from the system. After this call the
* system will no longer recognize the given ID when passed to
* utrans_open(). If the ID is invalid then nothing is done.
*
* @param id an ID to unregister
* @param idLength the length of id, or -1 if id is zero-terminated
* @stable ICU 2.8
*/
U_CAPI void U_EXPORT2
utrans_unregisterID(const UChar* id, int32_t idLength);
/**
* Set the filter used by a transliterator. A filter can be used to
* make the transliterator pass certain characters through untouched.
* The filter is expressed using a UnicodeSet pattern. If the
* filterPattern is NULL or the empty string, then the transliterator
* will be reset to use no filter.
*
* @param trans the transliterator
* @param filterPattern a pattern string, in the form accepted by
* UnicodeSet, specifying which characters to apply the
* transliteration to. May be NULL or the empty string to indicate no
* filter.
* @param filterPatternLen the length of filterPattern, or -1 if
* filterPattern is zero-terminated
* @param status a pointer to the UErrorCode
* @see UnicodeSet
* @stable ICU 2.0
*/
U_CAPI void U_EXPORT2
utrans_setFilter(UTransliterator* trans,
const UChar* filterPattern,
int32_t filterPatternLen,
UErrorCode* status);
/**
* Return the number of system transliterators.
* It is recommended to use utrans_openIDs() instead.
*
* @return the number of system transliterators.
* @stable ICU 2.0
*/
U_CAPI int32_t U_EXPORT2
utrans_countAvailableIDs(void);
/**
* Return a UEnumeration for the available transliterators.
*
* @param pErrorCode Pointer to the UErrorCode in/out parameter.
* @return UEnumeration for the available transliterators.
* Close with uenum_close().
*
* @stable ICU 2.8
*/
U_CAPI UEnumeration * U_EXPORT2
utrans_openIDs(UErrorCode *pErrorCode);
/********************************************************************
* Transliteration API
********************************************************************/
/**
* Transliterate a segment of a UReplaceable string. The string is
* passed in as a UReplaceable pointer rep and a UReplaceableCallbacks
* function pointer struct repFunc. Functions in the repFunc struct
* will be called in order to modify the rep string.
*
* @param trans the transliterator
* @param rep a pointer to the string. This will be passed to the
* repFunc functions.
* @param repFunc a set of function pointers that will be used to
* modify the string pointed to by rep.
* @param start the beginning index, inclusive; <code>0 <= start <=
* limit</code>.
* @param limit pointer to the ending index, exclusive; <code>start <=
* limit <= repFunc->length(rep)</code>. Upon return, *limit will
* contain the new limit index. The text previously occupying
* <code>[start, limit)</code> has been transliterated, possibly to a
* string of a different length, at <code>[start,
* </code><em>new-limit</em><code>)</code>, where <em>new-limit</em>
* is the return value.
* @param status a pointer to the UErrorCode
* @stable ICU 2.0
*/
U_CAPI void U_EXPORT2
utrans_trans(const UTransliterator* trans,
UReplaceable* rep,
const UReplaceableCallbacks* repFunc,
int32_t start,
int32_t* limit,
UErrorCode* status);
/**
* Transliterate the portion of the UReplaceable text buffer that can
* be transliterated unambiguously. This method is typically called
* after new text has been inserted, e.g. as a result of a keyboard
* event. The transliterator will try to transliterate characters of
* <code>rep</code> between <code>index.cursor</code> and
* <code>index.limit</code>. Characters before
* <code>index.cursor</code> will not be changed.
*
* <p>Upon return, values in <code>index</code> will be updated.
* <code>index.start</code> will be advanced to the first
* character that future calls to this method will read.
* <code>index.cursor</code> and <code>index.limit</code> will
* be adjusted to delimit the range of text that future calls to
* this method may change.
*
* <p>Typical usage of this method begins with an initial call
* with <code>index.start</code> and <code>index.limit</code>
* set to indicate the portion of <code>text</code> to be
* transliterated, and <code>index.cursor == index.start</code>.
* Thereafter, <code>index</code> can be used without
* modification in future calls, provided that all changes to
* <code>text</code> are made via this method.
*
* <p>This method assumes that future calls may be made that will
* insert new text into the buffer. As a result, it only performs
* unambiguous transliterations. After the last call to this method,
* there may be untransliterated text that is waiting for more input
* to resolve an ambiguity. In order to perform these pending
* transliterations, clients should call utrans_trans() with a start
* of index.start and a limit of index.end after the last call to this
* method has been made.
*
* @param trans the transliterator
* @param rep a pointer to the string. This will be passed to the
* repFunc functions.
* @param repFunc a set of function pointers that will be used to
* modify the string pointed to by rep.
* @param pos a struct containing the start and limit indices of the
* text to be read and the text to be transliterated
* @param status a pointer to the UErrorCode
* @stable ICU 2.0
*/
U_CAPI void U_EXPORT2
utrans_transIncremental(const UTransliterator* trans,
UReplaceable* rep,
const UReplaceableCallbacks* repFunc,
UTransPosition* pos,
UErrorCode* status);
/**
* Transliterate a segment of a UChar* string. The string is passed
* in in a UChar* buffer. The string is modified in place. If the
* result is longer than textCapacity, it is truncated. The actual
* length of the result is returned in *textLength, if textLength is
* non-NULL. *textLength may be greater than textCapacity, but only
* textCapacity UChars will be written to *text, including the zero
* terminator.
*
* @param trans the transliterator
* @param text a pointer to a buffer containing the text to be
* transliterated on input and the result text on output.
* @param textLength a pointer to the length of the string in text.
* If the length is -1 then the string is assumed to be
* zero-terminated. Upon return, the new length is stored in
* *textLength. If textLength is NULL then the string is assumed to
* be zero-terminated.
* @param textCapacity the length of the text buffer
* @param start the beginning index, inclusive; <code>0 <= start <=
* limit</code>.
* @param limit pointer to the ending index, exclusive; <code>start <=
* limit <= repFunc->length(rep)</code>. Upon return, *limit will
* contain the new limit index. The text previously occupying
* <code>[start, limit)</code> has been transliterated, possibly to a
* string of a different length, at <code>[start,
* </code><em>new-limit</em><code>)</code>, where <em>new-limit</em>
* is the return value.
* @param status a pointer to the UErrorCode
* @stable ICU 2.0
*/
U_CAPI void U_EXPORT2
utrans_transUChars(const UTransliterator* trans,
UChar* text,
int32_t* textLength,
int32_t textCapacity,
int32_t start,
int32_t* limit,
UErrorCode* status);
/**
* Transliterate the portion of the UChar* text buffer that can be
* transliterated unambiguously. See utrans_transIncremental(). The
* string is passed in in a UChar* buffer. The string is modified in
* place. If the result is longer than textCapacity, it is truncated.
* The actual length of the result is returned in *textLength, if
* textLength is non-NULL. *textLength may be greater than
* textCapacity, but only textCapacity UChars will be written to
* *text, including the zero terminator. See utrans_transIncremental()
* for usage details.
*
* @param trans the transliterator
* @param text a pointer to a buffer containing the text to be
* transliterated on input and the result text on output.
* @param textLength a pointer to the length of the string in text.
* If the length is -1 then the string is assumed to be
* zero-terminated. Upon return, the new length is stored in
* *textLength. If textLength is NULL then the string is assumed to
* be zero-terminated.
* @param textCapacity the length of the text buffer
* @param pos a struct containing the start and limit indices of the
* text to be read and the text to be transliterated
* @param status a pointer to the UErrorCode
* @see utrans_transIncremental
* @stable ICU 2.0
*/
U_CAPI void U_EXPORT2
utrans_transIncrementalUChars(const UTransliterator* trans,
UChar* text,
int32_t* textLength,
int32_t textCapacity,
UTransPosition* pos,
UErrorCode* status);
/**
* Create a rule string that can be passed to utrans_openU to recreate this
* transliterator.
*
* @param trans The transliterator
* @param escapeUnprintable if true then convert unprintable characters to their
* hex escape representations, \\uxxxx or \\Uxxxxxxxx.
* Unprintable characters are those other than
* U+000A, U+0020..U+007E.
* @param result A pointer to a buffer to receive the rules.
* @param resultLength The maximum size of result.
* @param status A pointer to the UErrorCode. In case of error status, the
* contents of result are undefined.
* @return int32_t The length of the rule string (may be greater than resultLength,
* in which case an error is returned).
* @stable ICU 53
*/
U_CAPI int32_t U_EXPORT2
utrans_toRules( const UTransliterator* trans,
UBool escapeUnprintable,
UChar* result, int32_t resultLength,
UErrorCode* status);
/**
* Returns the set of all characters that may be modified in the input text by
* this UTransliterator, optionally ignoring the transliterator's current filter.
* @param trans The transliterator.
* @param ignoreFilter If false, the returned set incorporates the
* UTransliterator's current filter; if the filter is changed,
* the return value of this function will change. If true, the
* returned set ignores the effect of the UTransliterator's
* current filter.
* @param fillIn Pointer to a USet object to receive the modifiable characters
* set. Previous contents of fillIn are lost. <em>If fillIn is
* NULL, then a new USet is created and returned. The caller
* owns the result and must dispose of it by calling uset_close.</em>
* @param status A pointer to the UErrorCode.
* @return USet* Either fillIn, or if fillIn is NULL, a pointer to a
* newly-allocated USet that the user must close. In case of
* error, NULL is returned.
* @stable ICU 53
*/
U_CAPI USet* U_EXPORT2
utrans_getSourceSet(const UTransliterator* trans,
UBool ignoreFilter,
USet* fillIn,
UErrorCode* status);
/* deprecated API ----------------------------------------------------------- */
#ifndef U_HIDE_DEPRECATED_API
/* see utrans.h documentation for why these functions are deprecated */
/**
* Deprecated, use utrans_openU() instead.
* Open a custom transliterator, given a custom rules string
* OR
* a system transliterator, given its ID.
* Any non-NULL result from this function should later be closed with
* utrans_close().
*
* @param id a valid ID, as returned by utrans_getAvailableID()
* @param dir the desired direction
* @param rules the transliterator rules. See the C++ header rbt.h
* for rules syntax. If NULL then a system transliterator matching
* the ID is returned.
* @param rulesLength the length of the rules, or -1 if the rules
* are zero-terminated.
* @param parseError a pointer to a UParseError struct to receive the
* details of any parsing errors. This parameter may be NULL if no
* parsing error details are desired.
* @param status a pointer to the UErrorCode
* @return a transliterator pointer that may be passed to other
* utrans_xxx() functions, or NULL if the open call fails.
* @deprecated ICU 2.8 Use utrans_openU() instead, see utrans.h
*/
U_DEPRECATED UTransliterator* U_EXPORT2
utrans_open(const char* id,
UTransDirection dir,
const UChar* rules, /* may be Null */
int32_t rulesLength, /* -1 if null-terminated */
UParseError* parseError, /* may be Null */
UErrorCode* status);
/**
* Deprecated, use utrans_getUnicodeID() instead.
* Return the programmatic identifier for this transliterator.
* If this identifier is passed to utrans_open(), it will open
* a transliterator equivalent to this one, if the ID has been
* registered.
* @param trans the transliterator to return the ID of.
* @param buf the buffer in which to receive the ID. This may be
* NULL, in which case no characters are copied.
* @param bufCapacity the capacity of the buffer. Ignored if buf is
* NULL.
* @return the actual length of the ID, not including
* zero-termination. This may be greater than bufCapacity.
* @deprecated ICU 2.8 Use utrans_getUnicodeID() instead, see utrans.h
*/
U_DEPRECATED int32_t U_EXPORT2
utrans_getID(const UTransliterator* trans,
char* buf,
int32_t bufCapacity);
/**
* Deprecated, use utrans_unregisterID() instead.
* Unregister a transliterator from the system. After this call the
* system will no longer recognize the given ID when passed to
* utrans_open(). If the id is invalid then nothing is done.
*
* @param id a zero-terminated ID
* @deprecated ICU 2.8 Use utrans_unregisterID() instead, see utrans.h
*/
U_DEPRECATED void U_EXPORT2
utrans_unregister(const char* id);
/**
* Deprecated, use utrans_openIDs() instead.
* Return the ID of the index-th system transliterator. The result
* is placed in the given buffer. If the given buffer is too small,
* the initial substring is copied to buf. The result in buf is
* always zero-terminated.
*
* @param index the number of the transliterator to return. Must
* satisfy 0 <= index < utrans_countAvailableIDs(). If index is out
* of range then it is treated as if it were 0.
* @param buf the buffer in which to receive the ID. This may be
* NULL, in which case no characters are copied.
* @param bufCapacity the capacity of the buffer. Ignored if buf is
* NULL.
* @return the actual length of the index-th ID, not including
* zero-termination. This may be greater than bufCapacity.
* @deprecated ICU 2.8 Use utrans_openIDs() instead, see utrans.h
*/
U_DEPRECATED int32_t U_EXPORT2
utrans_getAvailableID(int32_t index,
char* buf,
int32_t bufCapacity);
#endif /* U_HIDE_DEPRECATED_API */
#endif /* #if !UCONFIG_NO_TRANSLITERATION */
#endif

View File

@ -0,0 +1,471 @@
// © 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
/*
*******************************************************************************
* Copyright (C) 2007-2013, International Business Machines Corporation and
* others. All Rights Reserved.
*******************************************************************************
*/
#ifndef VTZONE_H
#define VTZONE_H
#include "unicode/utypes.h"
#if U_SHOW_CPLUSPLUS_API
/**
* \file
* \brief C++ API: RFC2445 VTIMEZONE support
*/
#if !UCONFIG_NO_FORMATTING
#include "unicode/basictz.h"
U_NAMESPACE_BEGIN
class VTZWriter;
class VTZReader;
class UVector;
/**
* <code>VTimeZone</code> is a class implementing RFC2445 VTIMEZONE. You can create a
* <code>VTimeZone</code> instance from a time zone ID supported by <code>TimeZone</code>.
* With the <code>VTimeZone</code> instance created from the ID, you can write out the rule
* in RFC2445 VTIMEZONE format. Also, you can create a <code>VTimeZone</code> instance
* from RFC2445 VTIMEZONE data stream, which allows you to calculate time
* zone offset by the rules defined by the data. Or, you can create a
* <code>VTimeZone</code> from any other ICU <code>BasicTimeZone</code>.
* <br><br>
* Note: The consumer of this class reading or writing VTIMEZONE data is responsible to
* decode or encode Non-ASCII text. Methods reading/writing VTIMEZONE data in this class
* do nothing with MIME encoding.
* @stable ICU 3.8
*/
class U_I18N_API VTimeZone : public BasicTimeZone {
public:
/**
* Copy constructor.
* @param source The <code>VTimeZone</code> object to be copied.
* @stable ICU 3.8
*/
VTimeZone(const VTimeZone& source);
/**
* Destructor.
* @stable ICU 3.8
*/
virtual ~VTimeZone();
/**
* Assignment operator.
* @param right The object to be copied.
* @stable ICU 3.8
*/
VTimeZone& operator=(const VTimeZone& right);
/**
* Return true if the given <code>TimeZone</code> objects are
* semantically equal. Objects of different subclasses are considered unequal.
* @param that The object to be compared with.
* @return true if the given <code>TimeZone</code> objects are
*semantically equal.
* @stable ICU 3.8
*/
virtual bool operator==(const TimeZone& that) const override;
/**
* Return true if the given <code>TimeZone</code> objects are
* semantically unequal. Objects of different subclasses are considered unequal.
* @param that The object to be compared with.
* @return true if the given <code>TimeZone</code> objects are
* semantically unequal.
* @stable ICU 3.8
*/
virtual bool operator!=(const TimeZone& that) const;
/**
* Create a <code>VTimeZone</code> instance by the time zone ID.
* @param ID The time zone ID, such as America/New_York
* @return A <code>VTimeZone</code> object initialized by the time zone ID,
* or nullptr when the ID is unknown.
* @stable ICU 3.8
*/
static VTimeZone* createVTimeZoneByID(const UnicodeString& ID);
/**
* Create a <code>VTimeZone</code> instance using a basic time zone.
* @param basicTZ The basic time zone instance
* @param status Output param to filled in with a success or an error.
* @return A <code>VTimeZone</code> object initialized by the basic time zone.
* @stable ICU 4.6
*/
static VTimeZone* createVTimeZoneFromBasicTimeZone(const BasicTimeZone& basicTZ,
UErrorCode &status);
/**
* Create a <code>VTimeZone</code> instance by RFC2445 VTIMEZONE data
*
* @param vtzdata The string including VTIMEZONE data block
* @param status Output param to filled in with a success or an error.
* @return A <code>VTimeZone</code> initialized by the VTIMEZONE data or
* nullptr if failed to load the rule from the VTIMEZONE data.
* @stable ICU 3.8
*/
static VTimeZone* createVTimeZone(const UnicodeString& vtzdata, UErrorCode& status);
/**
* Gets the RFC2445 TZURL property value. When a <code>VTimeZone</code> instance was
* created from VTIMEZONE data, the initial value is set by the TZURL property value
* in the data. Otherwise, the initial value is not set.
* @param url Receives the RFC2445 TZURL property value.
* @return true if TZURL attribute is available and value is set.
* @stable ICU 3.8
*/
UBool getTZURL(UnicodeString& url) const;
/**
* Sets the RFC2445 TZURL property value.
* @param url The TZURL property value.
* @stable ICU 3.8
*/
void setTZURL(const UnicodeString& url);
/**
* Gets the RFC2445 LAST-MODIFIED property value. When a <code>VTimeZone</code> instance
* was created from VTIMEZONE data, the initial value is set by the LAST-MODIFIED property
* value in the data. Otherwise, the initial value is not set.
* @param lastModified Receives the last modified date.
* @return true if lastModified attribute is available and value is set.
* @stable ICU 3.8
*/
UBool getLastModified(UDate& lastModified) const;
/**
* Sets the RFC2445 LAST-MODIFIED property value.
* @param lastModified The LAST-MODIFIED date.
* @stable ICU 3.8
*/
void setLastModified(UDate lastModified);
/**
* Writes RFC2445 VTIMEZONE data for this time zone
* @param result Output param to filled in with the VTIMEZONE data.
* @param status Output param to filled in with a success or an error.
* @stable ICU 3.8
*/
void write(UnicodeString& result, UErrorCode& status) const;
/**
* Writes RFC2445 VTIMEZONE data for this time zone applicable
* for dates after the specified start time.
* @param start The start date.
* @param result Output param to filled in with the VTIMEZONE data.
* @param status Output param to filled in with a success or an error.
* @stable ICU 3.8
*/
void write(UDate start, UnicodeString& result, UErrorCode& status) const;
/**
* Writes RFC2445 VTIMEZONE data applicable for the specified date.
* Some common iCalendar implementations can only handle a single time
* zone property or a pair of standard and daylight time properties using
* BYDAY rule with day of week (such as BYDAY=1SUN). This method produce
* the VTIMEZONE data which can be handled these implementations. The rules
* produced by this method can be used only for calculating time zone offset
* around the specified date.
* @param time The date used for rule extraction.
* @param result Output param to filled in with the VTIMEZONE data.
* @param status Output param to filled in with a success or an error.
* @stable ICU 3.8
*/
void writeSimple(UDate time, UnicodeString& result, UErrorCode& status) const;
/**
* Clones TimeZone objects polymorphically. Clients are responsible for deleting
* the TimeZone object cloned.
* @return A new copy of this TimeZone object.
* @stable ICU 3.8
*/
virtual VTimeZone* clone() const override;
/**
* Returns the TimeZone's adjusted GMT offset (i.e., the number of milliseconds to add
* to GMT to get local time in this time zone, taking daylight savings time into
* account) as of a particular reference date. The reference date is used to determine
* whether daylight savings time is in effect and needs to be figured into the offset
* that is returned (in other words, what is the adjusted GMT offset in this time zone
* at this particular date and time?). For the time zones produced by createTimeZone(),
* the reference data is specified according to the Gregorian calendar, and the date
* and time fields are local standard time.
*
* <p>Note: Don't call this method. Instead, call the getOffset(UDate...) overload,
* which returns both the raw and the DST offset for a given time. This method
* is retained only for backward compatibility.
*
* @param era The reference date's era
* @param year The reference date's year
* @param month The reference date's month (0-based; 0 is January)
* @param day The reference date's day-in-month (1-based)
* @param dayOfWeek The reference date's day-of-week (1-based; 1 is Sunday)
* @param millis The reference date's milliseconds in day, local standard time
* @param status Output param to filled in with a success or an error.
* @return The offset in milliseconds to add to GMT to get local time.
* @stable ICU 3.8
*/
virtual int32_t getOffset(uint8_t era, int32_t year, int32_t month, int32_t day,
uint8_t dayOfWeek, int32_t millis, UErrorCode& status) const override;
/**
* Gets the time zone offset, for current date, modified in case of
* daylight savings. This is the offset to add *to* UTC to get local time.
*
* <p>Note: Don't call this method. Instead, call the getOffset(UDate...) overload,
* which returns both the raw and the DST offset for a given time. This method
* is retained only for backward compatibility.
*
* @param era The reference date's era
* @param year The reference date's year
* @param month The reference date's month (0-based; 0 is January)
* @param day The reference date's day-in-month (1-based)
* @param dayOfWeek The reference date's day-of-week (1-based; 1 is Sunday)
* @param millis The reference date's milliseconds in day, local standard time
* @param monthLength The length of the given month in days.
* @param status Output param to filled in with a success or an error.
* @return The offset in milliseconds to add to GMT to get local time.
* @stable ICU 3.8
*/
virtual int32_t getOffset(uint8_t era, int32_t year, int32_t month, int32_t day,
uint8_t dayOfWeek, int32_t millis,
int32_t monthLength, UErrorCode& status) const override;
/**
* Returns the time zone raw and GMT offset for the given moment
* in time. Upon return, local-millis = GMT-millis + rawOffset +
* dstOffset. All computations are performed in the proleptic
* Gregorian calendar. The default implementation in the TimeZone
* class delegates to the 8-argument getOffset().
*
* @param date moment in time for which to return offsets, in
* units of milliseconds from January 1, 1970 0:00 GMT, either GMT
* time or local wall time, depending on `local'.
* @param local if true, `date' is local wall time; otherwise it
* is in GMT time.
* @param rawOffset output parameter to receive the raw offset, that
* is, the offset not including DST adjustments
* @param dstOffset output parameter to receive the DST offset,
* that is, the offset to be added to `rawOffset' to obtain the
* total offset between local and GMT time. If DST is not in
* effect, this value is zero; otherwise it is a positive value,
* typically one hour.
* @param ec input-output error code
* @stable ICU 3.8
*/
virtual void getOffset(UDate date, UBool local, int32_t& rawOffset,
int32_t& dstOffset, UErrorCode& ec) const override;
/**
* Get time zone offsets from local wall time.
* @stable ICU 69
*/
virtual void getOffsetFromLocal(
UDate date, UTimeZoneLocalOption nonExistingTimeOpt,
UTimeZoneLocalOption duplicatedTimeOpt,
int32_t& rawOffset, int32_t& dstOffset, UErrorCode& status) const override;
/**
* Sets the TimeZone's raw GMT offset (i.e., the number of milliseconds to add
* to GMT to get local time, before taking daylight savings time into account).
*
* @param offsetMillis The new raw GMT offset for this time zone.
* @stable ICU 3.8
*/
virtual void setRawOffset(int32_t offsetMillis) override;
/**
* Returns the TimeZone's raw GMT offset (i.e., the number of milliseconds to add
* to GMT to get local time, before taking daylight savings time into account).
*
* @return The TimeZone's raw GMT offset.
* @stable ICU 3.8
*/
virtual int32_t getRawOffset() const override;
/**
* Queries if this time zone uses daylight savings time.
* @return true if this time zone uses daylight savings time,
* false, otherwise.
* @stable ICU 3.8
*/
virtual UBool useDaylightTime() const override;
#ifndef U_FORCE_HIDE_DEPRECATED_API
/**
* Queries if the given date is in daylight savings time in
* this time zone.
* This method is wasteful since it creates a new GregorianCalendar and
* deletes it each time it is called. This is a deprecated method
* and provided only for Java compatibility.
*
* @param date the given UDate.
* @param status Output param filled in with success/error code.
* @return true if the given date is in daylight savings time,
* false, otherwise.
* @deprecated ICU 2.4. Use Calendar::inDaylightTime() instead.
*/
virtual UBool inDaylightTime(UDate date, UErrorCode& status) const override;
#endif // U_FORCE_HIDE_DEPRECATED_API
/**
* Returns true if this zone has the same rule and offset as another zone.
* That is, if this zone differs only in ID, if at all.
* @param other the <code>TimeZone</code> object to be compared with
* @return true if the given zone is the same as this one,
* with the possible exception of the ID
* @stable ICU 3.8
*/
virtual UBool hasSameRules(const TimeZone& other) const override;
/**
* Gets the first time zone transition after the base time.
* @param base The base time.
* @param inclusive Whether the base time is inclusive or not.
* @param result Receives the first transition after the base time.
* @return true if the transition is found.
* @stable ICU 3.8
*/
virtual UBool getNextTransition(UDate base, UBool inclusive, TimeZoneTransition& result) const override;
/**
* Gets the most recent time zone transition before the base time.
* @param base The base time.
* @param inclusive Whether the base time is inclusive or not.
* @param result Receives the most recent transition before the base time.
* @return true if the transition is found.
* @stable ICU 3.8
*/
virtual UBool getPreviousTransition(UDate base, UBool inclusive, TimeZoneTransition& result) const override;
/**
* Returns the number of <code>TimeZoneRule</code>s which represents time transitions,
* for this time zone, that is, all <code>TimeZoneRule</code>s for this time zone except
* <code>InitialTimeZoneRule</code>. The return value range is 0 or any positive value.
* @param status Receives error status code.
* @return The number of <code>TimeZoneRule</code>s representing time transitions.
* @stable ICU 3.8
*/
virtual int32_t countTransitionRules(UErrorCode& status) const override;
/**
* Gets the <code>InitialTimeZoneRule</code> and the set of <code>TimeZoneRule</code>
* which represent time transitions for this time zone. On successful return,
* the argument initial points to non-nullptr <code>InitialTimeZoneRule</code> and
* the array trsrules is filled with 0 or multiple <code>TimeZoneRule</code>
* instances up to the size specified by trscount. The results are referencing the
* rule instance held by this time zone instance. Therefore, after this time zone
* is destructed, they are no longer available.
* @param initial Receives the initial timezone rule
* @param trsrules Receives the timezone transition rules
* @param trscount On input, specify the size of the array 'transitions' receiving
* the timezone transition rules. On output, actual number of
* rules filled in the array will be set.
* @param status Receives error status code.
* @stable ICU 3.8
*/
virtual void getTimeZoneRules(const InitialTimeZoneRule*& initial,
const TimeZoneRule* trsrules[], int32_t& trscount, UErrorCode& status) const override;
private:
enum { DEFAULT_VTIMEZONE_LINES = 100 };
/**
* Default constructor.
*/
VTimeZone();
void write(VTZWriter& writer, UErrorCode& status) const;
void write(UDate start, VTZWriter& writer, UErrorCode& status) const;
void writeSimple(UDate time, VTZWriter& writer, UErrorCode& status) const;
void load(VTZReader& reader, UErrorCode& status);
void parse(UErrorCode& status);
void writeZone(VTZWriter& w, BasicTimeZone& basictz, UVector* customProps,
UErrorCode& status) const;
void writeHeaders(VTZWriter& w, UErrorCode& status) const;
void writeFooter(VTZWriter& writer, UErrorCode& status) const;
void writeZonePropsByTime(VTZWriter& writer, UBool isDst, const UnicodeString& zonename,
int32_t fromOffset, int32_t toOffset, UDate time, UBool withRDATE,
UErrorCode& status) const;
void writeZonePropsByDOM(VTZWriter& writer, UBool isDst, const UnicodeString& zonename,
int32_t fromOffset, int32_t toOffset,
int32_t month, int32_t dayOfMonth, UDate startTime, UDate untilTime,
UErrorCode& status) const;
void writeZonePropsByDOW(VTZWriter& writer, UBool isDst, const UnicodeString& zonename,
int32_t fromOffset, int32_t toOffset,
int32_t month, int32_t weekInMonth, int32_t dayOfWeek,
UDate startTime, UDate untilTime, UErrorCode& status) const;
void writeZonePropsByDOW_GEQ_DOM(VTZWriter& writer, UBool isDst, const UnicodeString& zonename,
int32_t fromOffset, int32_t toOffset,
int32_t month, int32_t dayOfMonth, int32_t dayOfWeek,
UDate startTime, UDate untilTime, UErrorCode& status) const;
void writeZonePropsByDOW_GEQ_DOM_sub(VTZWriter& writer, int32_t month, int32_t dayOfMonth,
int32_t dayOfWeek, int32_t numDays,
UDate untilTime, int32_t fromOffset, UErrorCode& status) const;
void writeZonePropsByDOW_LEQ_DOM(VTZWriter& writer, UBool isDst, const UnicodeString& zonename,
int32_t fromOffset, int32_t toOffset,
int32_t month, int32_t dayOfMonth, int32_t dayOfWeek,
UDate startTime, UDate untilTime, UErrorCode& status) const;
void writeFinalRule(VTZWriter& writer, UBool isDst, const AnnualTimeZoneRule* rule,
int32_t fromRawOffset, int32_t fromDSTSavings,
UDate startTime, UErrorCode& status) const;
void beginZoneProps(VTZWriter& writer, UBool isDst, const UnicodeString& zonename,
int32_t fromOffset, int32_t toOffset, UDate startTime, UErrorCode& status) const;
void endZoneProps(VTZWriter& writer, UBool isDst, UErrorCode& status) const;
void beginRRULE(VTZWriter& writer, int32_t month, UErrorCode& status) const;
void appendUNTIL(VTZWriter& writer, const UnicodeString& until, UErrorCode& status) const;
BasicTimeZone *tz;
UVector *vtzlines;
UnicodeString tzurl;
UDate lastmod;
UnicodeString olsonzid;
UnicodeString icutzver;
public:
/**
* Return the class ID for this class. This is useful only for comparing to
* a return value from getDynamicClassID(). For example:
* <pre>
* . Base* polymorphic_pointer = createPolymorphicObject();
* . if (polymorphic_pointer->getDynamicClassID() ==
* . erived::getStaticClassID()) ...
* </pre>
* @return The class ID for all objects of this class.
* @stable ICU 3.8
*/
static UClassID U_EXPORT2 getStaticClassID();
/**
* Returns a unique class ID POLYMORPHICALLY. Pure virtual override. This
* method is to implement a simple version of RTTI, since not all C++
* compilers support genuine RTTI. Polymorphic operator==() and clone()
* methods call this method.
*
* @return The class ID for this object. All objects of a
* given class have the same class ID. Objects of
* other classes have different class IDs.
* @stable ICU 3.8
*/
virtual UClassID getDynamicClassID() const override;
};
U_NAMESPACE_END
#endif /* #if !UCONFIG_NO_FORMATTING */
#endif /* U_SHOW_CPLUSPLUS_API */
#endif // VTZONE_H
//eof