* reintegrated gsoc-locale-kit branch into trunk - there's more

work to do, but it's about time to give this code more exposure.



git-svn-id: file:///srv/svn/repos/haiku/haiku/trunk@33176 a95241bf-73f2-0310-859d-f6bbb57e9c96
This commit is contained in:
Oliver Tappe
2009-09-18 22:23:34 +00:00
parent e7443fd575
commit 75f1522155
3330 changed files with 2093685 additions and 921 deletions
+117 -2
View File
@@ -204,8 +204,10 @@ rule ResComp
DEFINES on $(1) = $(defines) ;
CCDEFS on $(1) = [ FDefines $(defines) ] ;
HDRS on $(1) = [ FIncludes $(SEARCH_SOURCE) $(SUBDIRHDRS) $(HDRS) : $(localIncludesOption) ] ;
RCHDRS on $(1) = [ FIncludes $(SEARCH_SOURCE) $(SUBDIRHDRS) $(HDRS) : "-I " ] ;
HDRS on $(1) = [ FIncludes $(SEARCH_SOURCE) $(SUBDIRHDRS) $(HDRS)
: $(localIncludesOption) ] ;
RCHDRS on $(1) = [ FIncludes $(SEARCH_SOURCE) $(SUBDIRHDRS) $(HDRS)
: "-I " ] ;
CC on $(1) = $(cc) ;
# set up other vars
@@ -266,3 +268,116 @@ actions ResAttr1
fi
$(2[1]) -O -o "$(1)" "$(2[2-])"
}
# Localization rules
# Extract catalog entries from the sourcefile and put the output textfile in
# target. This output file is then used to create the binary catalog with
# linkcatkeys.
rule ExtractCatalogEntries target : source : signature
{
# get compiler and defines for the platform
local headers ;
local sysHeaders ;
local cc ;
local defines ;
local localIncludesOption ;
local systemIncludesOption ;
on $(target) { # use on $(target) variable values
headers = $(HAIKU_CONFIG_HEADERS) $(SEARCH_SOURCE) $(SUBDIRHDRS)
$(HDRS) ;
sysHeaders = $(SUBDIRSYSHDRS) $(SYSHDRS) ;
defines = $(DEFINES) ;
if $(PLATFORM) = host {
sysHeaders += $(HOST_HDRS) ;
defines += $(HOST_DEFINES) ;
if $(USES_BE_API) {
sysHeaders += $(HOST_BE_API_HEADERS) ;
}
defines += $(HOST_DEFINES) ;
cc = $(HOST_CC) ;
localIncludesOption = $(HOST_LOCAL_INCLUDES_OPTION) ;
systemIncludesOption = $(HOST_SYSTEM_INCLUDES_OPTION) ;
} else {
sysHeaders += $(TARGET_HDRS) ;
defines += $(TARGET_DEFINES) ;
defines += $(TARGET_DEFINES) ;
cc = $(TARGET_CC) ;
localIncludesOption = $(TARGET_LOCAL_INCLUDES_OPTION) ;
systemIncludesOption = $(TARGET_SYSTEM_INCLUDES_OPTION) ;
}
}
DEFINES on $(target) = $(defines) ;
CCDEFS on $(target) = [ FDefines $(defines) ] ;
HDRS on $(target) = [ FIncludes $(headers) : $(localIncludesOption) ]
$(includesSeparator)
[ FSysIncludes $(sysHeaders) : $(systemIncludesOption) ] ;
CC on $(target) = $(cc) ;
LOCALE_KIT_SIGNATURE on $(target) = $(signature) ;
SEARCH on $(source) += $(SEARCH_SOURCE) ;
MakeLocatePlatform $(target) ;
Depends $(target) : $(source) <build>collectcatkeys ;
LocalClean clean : $(target) ;
ExtractCatalogEntries1 $(target) : <build>collectcatkeys $(source) ;
}
actions ExtractCatalogEntries1
{
$(HOST_ADD_BUILD_COMPATIBILITY_LIB_DIR)
cat "$(2[2-])" | $(CC) -E $(CCDEFS) $(HDRS) - > "$(1)".pre
$(2[1]) -s $(LOCALE_KIT_SIGNATURE) -p -o "$(1)" "$(1)".pre
}
# Link catalog entries from given catkey file into output compiled catalog file.
# Compiled catalog file will then be copied into the image, but only if the
# fingerprint matches the one from the untranslated catalog for the same file.
rule LinkApplicationCatalog target : sources : signature : language
{
MakeLocateArch $(target) ;
LOCALE_KIT_SIGNATURE on $(target) = $(signature) ;
Depends $(target) : $(sources) <build>linkcatkeys ;
LocalClean clean : $(target) ;
LinkApplicationCatalog1 $(target)
: <build>linkcatkeys $(language) $(sources) ;
}
actions LinkApplicationCatalog1
{
$(HOST_ADD_BUILD_COMPATIBILITY_LIB_DIR)
$(2[1]) "$(2[3-])" -l $(2[2]:B) -v -s $(LOCALE_KIT_SIGNATURE) -o "$(1)"
}
# General rules to invoke from jamfiles and that do (almost) everything related
# to localization
rule DoCatalogs appName # Application name
: signature # Application MIME signature (must match the one
# declared in the sourcecode)
: sources # List of cpp files where to search keys
: generatedCatalog # Name of the generated catalog (most probably
# english.catalog)
: translatedCatalogs # List of available translations
{
genCat = [ FGristFiles $(generatedCatalog) ] ;
ExtractCatalogEntries $(genCat:S=.catkeys) : $(sources) : $(signature) ;
LinkApplicationCatalog $(genCat) : $(genCat:S=.catkeys)
: $(signature) : $(genCat:B) ;
for catalog in $(translatedCatalogs)
{
LinkApplicationCatalog $(catalog:B).catalog : $(catalog)
: $(signature) : $(catalog:B) ;
}
AddFilesToHaikuImage system etc locale catalogs $(signature) :
$(genCat) $(translatedCatalogs:B).catalog ;
}
+33 -15
View File
@@ -29,20 +29,18 @@ if $(HAIKU_ATA_STACK) = 1 {
SYSTEM_BIN = "[" addattr alert arp base64 basename bash bc beep bootman bzip2
cal cat catattr checkfs chgrp chmod chop chown chroot cksum clear
clockconfig cmp comm compress copyattr CortexAddOnHost cp
clockconfig cmp collectcatkeys comm compress copyattr CortexAddOnHost cp
csplit ctags cut date dc dd desklink df diff diff3 dircolors dirname
draggers driveinfo dstcheck du
draggers driveinfo dstcheck du dumpcatalog
echo eject env error expand expr
factor false fdinfo ffm filepanel find finddir fmt fold fortune frcode
ftp ftpd
funzip fwcontrol
ftp ftpd funzip fwcontrol
gawk $(X86_ONLY)gdb getlimits grep groups gzip gzexe
hd head hey hostname
id ident ifconfig <bin>install installsound iroster isvolume
$(IDE_ONLY)ideinfo $(IDE_ONLY)idestatus
join
keymap kill less lessecho lesskey link listarea listattr
listimage listdev
join keymap kill
less lessecho lesskey link linkcatkeys listarea listattr listimage listdev
listport listres listsem listusb ln locate logger login logname ls lsindex
makebootable md5sum merge message mimeset mkdos mkdir mkfifo mkfs mkindex
modifiers mount mount_nfs mountvolume mv
@@ -71,19 +69,31 @@ SYSTEM_APPS = AboutSystem ActivityMonitor CharacterMap CodyCam DeskCalc DiskProb
ShowImage SoundRecorder StyledEdit Terminal TextSearch TV Workspaces
;
SYSTEM_PREFERENCES = Appearance Backgrounds CPUFrequency DataTranslations E-mail
FileTypes Fonts Keyboard Keymap Media Mouse Network OpenGL Printers
FileTypes Fonts Keyboard Keymap Locale Media Mouse Network OpenGL Printers
Screen ScreenSaver Sounds Time Touchpad <preference>Tracker VirtualMemory
;
SYSTEM_DEMOS = BSnow Chart Clock Cortex FontDemo
GLTeapot Haiku3d Mandelbrot Pairs Playground Pulse Sudoku Gradients
;
SYSTEM_LIBS = libalm.so libbe.so libbsd.so libbnetapi.so libdebug.so
libdevice.so libfluidsynth.so libfreetype.so libgame.so libGL.so libgnu.so
libilmimf.so libjpeg.so liblinprog.so liblpsolve55.so libmail.so libmedia.so
libmidi.so libmidi2.so libnetwork.so libpng.so <revisioned>libroot.so
libscreensaver.so libtextencoding.so libtracker.so libtranslation.so
ICU_LIBS = libicu-common.so libicu-data.so libicu-i18n.so
;
SYSTEM_LIBS =
libalm.so
libbe.so libbsd.so libbnetapi.so
libdebug.so libdevice.so
libfluidsynth.so libfreetype.so
libgame.so libGL.so libgnu.so
libilmimf.so
libjpeg.so
liblinprog.so liblocale.so liblpsolve55.so
libmail.so libmedia.so libmidi.so libmidi2.so
libnetwork.so
libpng.so
<revisioned>libroot.so
libscreensaver.so
libtextencoding.so libtracker.so libtranslation.so
libz.so
$(HAIKU_SHARED_LIBSTDC++) $(HAIKU_SHARED_LIBSUPC++)
$(HAIKU_SHARED_LIBSTDC++) $(HAIKU_SHARED_LIBSUPC++) $(ICU_LIBS)
;
SYSTEM_SERVERS = app_server cddb_daemon debug_server input_server mail_daemon
media_addon_server media_server midi_server net_server print_server
@@ -109,6 +119,7 @@ SYSTEM_ADD_ONS_TRANSLATORS = BMPTranslator EXRTranslator GIFTranslator
RAWTranslator RTF-Translator SGITranslator STXTTranslator TGATranslator
TIFFTranslator WonderBrushTranslator
;
SYSTEM_ADD_ONS_LOCALE_CATALOGS = <catalog-addon>zeta <catalog-addon>plaintext ;
SYSTEM_ADD_ONS_MEDIA = cortex_audioadapter.media_addon cortex_flanger.media_addon
dvb.media_addon
hmulti_audio.media_addon
@@ -352,7 +363,8 @@ AddFilesToHaikuImage system data artwork : $(logoArtwork) ;
AddDirectoryToHaikuImage system data sounds ;
# Add mail provider infos.
AddFilesToHaikuImage home config settings Mail ProviderInfo : $(HAIKU_PROVIDER_INFOS) ;
AddFilesToHaikuImage home config settings Mail ProviderInfo :
$(HAIKU_PROVIDER_INFOS) ;
# Mail spell check dictionaries
local spellFiles = words geekspeak ;
@@ -361,6 +373,11 @@ SEARCH on $(spellFiles)
= [ FDirName $(HAIKU_TOP) src apps mail ] ;
AddFilesToHaikuImage system etc word_dictionary : $(spellFiles) ;
# Locale kit language files
local languageDir = [ FDirName $(HAIKU_TOP) src data etc locale languages ] ;
local languages = [ Glob $(languageDir) : *.language ] ;
AddFilesToHaikuImage system data locale languages : $(languages) ;
local etcFiles = bash_completion inputrc profile teapot.data ;
etcFiles = $(etcFiles:G=etc) ;
SEARCH on $(etcFiles) = [ FDirName $(HAIKU_TOP) data etc ] ;
@@ -462,6 +479,7 @@ AddFilesToHaikuImage system add-ons opengl
: Mesa\ Software\ Renderer ;
AddFilesToHaikuHybridImage system add-ons Translators
: $(SYSTEM_ADD_ONS_TRANSLATORS) : : true ;
AddFilesToHaikuImage system add-ons locale catalogs : $(SYSTEM_ADD_ONS_LOCALE_CATALOGS) ;
AddFilesToHaikuImage system add-ons mail_daemon inbound_protocols : POP3 IMAP ;
AddFilesToHaikuImage system add-ons mail_daemon outbound_protocols : SMTP ;
AddFilesToHaikuImage system add-ons mail_daemon inbound_filters : Match\ Header Spam\ Filter R5\ Daemon\ Filter ;
+4 -4
View File
@@ -354,8 +354,8 @@ rule FStandardOSHeaders
add-ons/input_server add-ons/registrar
add-ons/screen_saver
add-ons/tracker app device drivers game interface
kernel media mail midi midi2 net opengl storage support
translation ;
kernel locale media mail midi midi2 net opengl storage
support translation ;
return [ FDirName $(HAIKU_TOP) headers os ]
[ PublicHeaders $(osIncludes) ] ;
@@ -367,8 +367,8 @@ rule FStandardHeaders
add-ons/input_server add-ons/registrar
add-ons/screen_saver
add-ons/tracker app device drivers game interface
kernel media mail midi midi2 net opengl storage support
translation ;
kernel locale media mail midi midi2 net opengl storage
support translation ;
local headers = ;
+1 -1
View File
@@ -24,7 +24,7 @@ esac
BELIBRARIES="$BUILDHOME/abi/current/library-paths/common:$BUILDHOME/lib/$BE_HOST_CPU"
BH=$BUILDHOME/headers
BEINCLUDES="$BH;$BH/be;$BH/posix;$BH/glibc;$BH/cpp;$BH/be/app;$BH/be/device;$BH/be/interface;$BH/be/media;$BH/be/midi;$BH/be/midi2;$BH/be/net;$BH/be/kernel;$BH/be/storage;$BH/be/support;$BH/be/game;$BH/be/opengl;$BH/be/drivers;$BH/gnu;$BH/be/mail;$BH/be/translation;$BH/be/devel;$BH/be/add-ons/graphics;$BH/be/be_apps/Deskbar;$BH/be/be_apps/NetPositive;$BH/be/be_apps/Tracker"
BEINCLUDES="$BH;$BH/be;$BH/posix;$BH/glibc;$BH/cpp;$BH/be/app;$BH/be/device;$BH/be/interface;$BH/be/locale;$BH/be/media;$BH/be/midi;$BH/be/midi2;$BH/be/net;$BH/be/kernel;$BH/be/storage;$BH/be/support;$BH/be/game;$BH/be/opengl;$BH/be/drivers;$BH/gnu;$BH/be/mail;$BH/be/translation;$BH/be/devel;$BH/be/add-ons/graphics;$BH/be/be_apps/Deskbar;$BH/be/be_apps/NetPositive;$BH/be/be_apps/Tracker"
export BUILDHOME
export BETOOLS
+2
View File
@@ -16,6 +16,8 @@ public:
BApplication(const char* signature,
status_t* error);
virtual ~BApplication();
status_t GetAppInfo(app_info* info);
};
// Global Objects
+210
View File
@@ -0,0 +1,210 @@
/*
*******************************************************************************
* Copyright (C) 2007-2008, 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 !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();
/**
* 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 transtion 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-NULL <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 NULL.
* @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, NULL 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, NULL 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*/;
/**
* The time type option bit flags used by getOffsetFromLocal
* @internal
*/
enum {
kStandard = 0x01,
kDaylight = 0x03,
kFormer = 0x04,
kLatter = 0x0C
};
/**
* Get time zone offsets from local wall time.
* @internal
*/
virtual void getOffsetFromLocal(UDate date, int32_t nonExistingTimeOpt, int32_t duplicatedTimeOpt,
int32_t& rawOffset, int32_t& dstOffset, UErrorCode& status) /*const*/;
protected:
/**
* The time type option bit masks used by getOffsetFromLocal
* @internal
*/
enum {
kStdDstMask = kDaylight,
kFormerLatterMask = kLatter
};
/**
* 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);
/**
* 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 Receives the InitialTimeZone, always not NULL
* @param transitionRules Receives the transition rules, could be NULL
* @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 // BASICTZ_H
//eof
+273
View File
@@ -0,0 +1,273 @@
/*
* Copyright (C) 1996-2009, International Business Machines Corporation and Others.
* All rights reserved.
*/
/**
* \file
* \brief C API: Boyer-Moore StringSearch prototype.
* \internal
*/
#ifndef _BMS_H
#define _BMS_H
#include "unicode/utypes.h"
#if !UCONFIG_NO_COLLATION
#include "unicode/ucol.h"
/**
* A <code>UCD</code> object holds the Collator-specific data needed to
* compute the length of the shortest string that can
* generate a partcular list of CEs.
*
* <code>UCD</code> objects are quite expensive to compute. Because
* of this, they are cached. When you call <code>ucd_open</code> it
* returns a reference counted cached object. When you call <code>ucd_close</code>
* the reference count on the object is decremented but the object is not deleted.
*
* If you do not need to reuse any unreferenced objects in the cache, you can call
* <code>ucd_flushCCache</code>. If you no longer need any <code>UCD</code>
* objects, you can call <code>ucd_freeCache</code>
*/
typedef void UCD;
/**
* Open a <code>UCD</code> object.
*
* @param coll - the collator
* @param status - will be set if any errors occur.
*
* @return the <code>UCD</code> object. You must call
* <code>ucd_close</code> when you are done using the object.
*
* Note: if on return status is set to an error, the only safe
* thing to do with the returned object is to call <code>ucd_close</code>.
*
* @internal ICU 4.0.1 technology preview
*/
U_CAPI UCD * U_EXPORT2
ucd_open(UCollator *coll, UErrorCode *status);
/**
* Release a <code>UCD</code> object.
*
* @param ucd - the object
*
* @internal ICU 4.0.1 technology preview
*/
U_CAPI void U_EXPORT2
ucd_close(UCD *ucd);
/**
* Get the <code>UCollator</code> object used to create a <code>UCD</code> object.
* The <code>UCollator</code> object returned may not be the exact
* object that was used to create this object, but it will have the
* same behavior.
*
* @param ucd - the <code>UCD</code> object
*
* @return the <code>UCollator</code> used to create the given
* <code>UCD</code> object.
*
* @internal ICU 4.0.1 technology preview
*/
U_CAPI UCollator * U_EXPORT2
ucd_getCollator(UCD *ucd);
/**
* <code>UCD</code> objects are expensive to compute, and so
* may be cached. This routine will free the cached objects and delete
* the cache.
*
* WARNING: Don't call this until you are have called <code>close</code>
* for each <code>UCD</code> object that you have used. also,
* DO NOT call this if another thread may be calling <code>ucd_flushCache</code>
* at the same time.
*
* @internal ICU 4.0.1 technology preview
*/
U_CAPI void U_EXPORT2
ucd_freeCache();
/**
* <code>UCD</code> objects are expensive to compute, and so
* may be cached. This routine will remove any unused <code>UCD</code>
* objects from the cache.
*
* @internal 4.0.1 technology preview
*/
U_CAPI void U_EXPORT2
ucd_flushCache();
/**
* BMS
*
* This object holds the information needed to do a Collation sensitive Boyer-Moore search. It encapulates
* the pattern, the "bad character" and "good suffix" tables, the Collator-based data needed to compute them,
* and a reference to the text being searched.
*
* To do a search, you first need to get a <code>UCD</code> object by calling <code>ucd_open</code>.
* Then you construct a <code>BMS</code> object from the <code>UCD</code> object, the pattern
* string and the target string. Then you call the <code>search</code> method. Here's a code sample:
*
* <pre>
* void boyerMooreExample(UCollator *collator, UChar *pattern, int32_t patternLen, UChar *target, int32_t targetLength)
* {
* UErrorCode status = U_ZERO_ERROR;
* int32_t offset = 0, start = -1, end = -1;
* UCD *ucd = NULL);
* BMS *bms = NULL;
*
* ucd = ucd_open(collator, &status);
* if (U_FAILURE(status)) {
* // could not create a UCD object
* return;
* }
*
* BMS *bms = bms_open(ucd, pattern, patternLength, target, targetlength, &status);
* if (U_FAILURE(status)) {
* // could not create a BMS object
* ucd_close(ucd);
* return;
* }
*
*
* // Find all matches
* while (bms_search(bms, offset, &start, &end)) {
* // process the match between start and end
* ...
*
* // advance past the match
* offset = end;
* }
*
* // at this point, if offset == 0, there were no matches
* if (offset == 0) {
* // handle the case of no matches
* }
*
* bms_close(bms);
* ucd_close(ucd);
*
* // UCD objects are cached, so the call to
* // ucd_close doesn't delete the object.
* // Call this if you don't need the object any more.
* ucd_flushCache();
* }
* </pre>
*
* NOTE: This is a technology preview. The final version of this API may not bear any resenblence to this API.
*
* Knows linitations:
* 1) Backwards searching has not been implemented.
*
* 2) For Han and Hangul characters, this code ignores any Collation tailorings. In general,
* this isn't a problem, but in Korean locals, at strength 1, Hangul characters are tailored
* to be equal to Han characters with the same pronounciation. Because this code ignroes
* tailorings, searching for a Hangul character will not find a Han character and visa-versa.
*
* 3) In some cases, searching for a pattern that needs to be normalized and ends
* in a discontiguous contraction may fail. The only known cases of this are with
* the Tibetan script. For example searching for the pattern
* "\u0F7F\u0F80\u0F81\u0F82\u0F83\u0F84\u0F85" will fail. (This case is artificial. We've
* been unable to find a pratical, real-world example of this failure.)
*
* NOTE: This is a technology preview. The final version of this API may not bear any resenblence to this API.
*
* @internal ICU 4.0.1 technology preview
*/
struct BMS;
typedef struct BMS BMS; /**< @see BMS */
/**
* Construct a <code>MBS</code> object.
*
* @param ucd - A <code>UCD</code> object holding the Collator-sensitive data
* @param pattern - the string for which to search
* @param patternLength - the length of the string for which to search
* @param target - the string in which to search
* @param targetLength - the length of the string in which to search
* @param status - will be set if any errors occur.
*
* @return the <code>BMS</code> object.
*
* Note: if on return status is set to an error, the only safe
* thing to do with the returned object is to call
* <code>bms_close</code>.
*
* @internal ICU 4.0.1 technology preview
*/
U_CAPI BMS * U_EXPORT2
bms_open(UCD *ucd,
const UChar *pattern, int32_t patternLength,
const UChar *target, int32_t targetLength,
UErrorCode *status);
/**
* Close a <code>BMS</code> object and release all the
* storage associated with it.
*
* @param bms - the <code>BMS</code> object to close.
*/
U_CAPI void U_EXPORT2
bms_close(BMS *bms);
/**
* Test the pattern to see if it generates any CEs.
*
* @param bms - the <code>BMS</code> object
* @return <code>TRUE</code> if the pattern string did not generate any CEs
*
* @internal ICU 4.0.1 technology preview
*/
U_CAPI UBool U_EXPORT2
bms_empty(BMS *bms);
/**
* Get the <code>UCD</code> object used to create
* a given <code>BMS</code> object.
*
* @param bms - the <code>BMS</code> object
*
* @return - the <code>UCD</code> object used to create
* the given <code>BMS</code> object.
*
* @internal ICU 4.0.1 technology preview
*/
U_CAPI UCD * U_EXPORT2
bms_getData(BMS *bms);
/**
* Search for the pattern string in the target string.
*
* @param bms - the <code>BMS</code> object
* @param offset - the offset in the target string at which to begin the search
* @param start - will be set to the starting offset of the match, or -1 if there's no match
* @param end - will be set to the ending offset of the match, or -1 if there's no match
*
* @return <code>TRUE</code> if the match succeeds, <code>FALSE</code> otherwise.
*
* @internal ICU 4.0.1 technology preview
*/
U_CAPI UBool U_EXPORT2
bms_search(BMS *bms, int32_t offset, int32_t *start, int32_t *end);
/**
* Set the target string for the match.
*
* @param bms - the <code>BMS</code> object
* @param target - the new target string
* @param targetLength - the length of the new target string
* @param status - will be set if any errors occur.
*
* @internal ICU 4.0.1 technology preview
*/
U_CAPI void U_EXPORT2
bms_setTargetString(BMS *bms, const UChar *target, int32_t targetLength, UErrorCode *status);
#endif
#endif /* _BMS_H */
+224
View File
@@ -0,0 +1,224 @@
/*
******************************************************************************
* Copyright (C) 1996-2009, International Business Machines *
* Corporation and others. All Rights Reserved. *
******************************************************************************
*/
/**
* \file
* \brief C++ API: Boyer-Moore StringSearch technology preview
* \internal ICU 4.0.1 technology preview
*/
#ifndef B_M_SEARCH_H
#define B_M_SEARCH_H
#include "unicode/utypes.h"
#if !UCONFIG_NO_COLLATION
#include "unicode/uobject.h"
#include "unicode/ucol.h"
#include "unicode/colldata.h"
U_NAMESPACE_BEGIN
class BadCharacterTable;
class GoodSuffixTable;
class Target;
/**
* BoyerMooreSearch
*
* This object holds the information needed to do a Collation sensitive Boyer-Moore search. It encapulates
* the pattern, the "bad character" and "good suffix" tables, the Collator-based data needed to compute them,
* and a reference to the text being searched.
*
* To do a search, you fist need to get a <code>CollData</code> object by calling <code>CollData::open</code>.
* Then you construct a <code>BoyerMooreSearch</code> object from the <code>CollData</code> object, the pattern
* string and the target string. Then you call the <code>search</code> method. Here's a code sample:
*
* <pre>
* void boyerMooreExample(UCollator *collator, UnicodeString *pattern, UnicodeString *target)
* {
* UErrorCode status = U_ZERO_ERROR;
* CollData *collData = CollData::open(collator, status);
*
* if (U_FAILURE(status)) {
* // could not create a CollData object
* return;
* }
*
* BoyerMooreSearch *search = new BoyerMooreSearch(collData, *patternString, target, status);
*
* if (U_FAILURE(status)) {
* // could not create a BoyerMooreSearch object
* CollData::close(collData);
* return;
* }
*
* int32_t offset = 0, start = -1, end = -1;
*
* // Find all matches
* while (search->search(offset, start, end)) {
* // process the match between start and end
* ...
* // advance past the match
* offset = end;
* }
*
* // at this point, if offset == 0, there were no matches
* if (offset == 0) {
* // handle the case of no matches
* }
*
* delete search;
* CollData::close(collData);
*
* // CollData objects are cached, so the call to
* // CollData::close doesn't delete the object.
* // Call this if you don't need the object any more.
* CollData::flushCollDataCache();
* }
* </pre>
*
* NOTE: This is a technology preview. The final version of this API may not bear any resenblence to this API.
*
* Knows linitations:
* 1) Backwards searching has not been implemented.
*
* 2) For Han and Hangul characters, this code ignores any Collation tailorings. In general,
* this isn't a problem, but in Korean locals, at strength 1, Hangul characters are tailored
* to be equal to Han characters with the same pronounciation. Because this code ignroes
* tailorings, searching for a Hangul character will not find a Han character and visa-versa.
*
* 3) In some cases, searching for a pattern that needs to be normalized and ends
* in a discontiguous contraction may fail. The only known cases of this are with
* the Tibetan script. For example searching for the pattern
* "\u0F7F\u0F80\u0F81\u0F82\u0F83\u0F84\u0F85" will fail. (This case is artificial. We've
* been unable to find a pratical, real-world example of this failure.)
*
* @internal ICU 4.0.1 technology preview
*
* @see CollData
*/
class U_I18N_API BoyerMooreSearch : public UObject
{
public:
/**
* Construct a <code>BoyerMooreSearch</code> object.
*
* @param theData - A <code>CollData</code> object holding the Collator-sensitive data
* @param patternString - the string for which to search
* @param targetString - the string in which to search or <code>NULL</code> if youu will
* set it later by calling <code>setTargetString</code>.
* @param status - will be set if any errors occur.
*
* Note: if on return, status is set to an error code,
* the only safe thing to do with this object is to call
* the destructor.
*
* @internal ICU 4.0.1 technology preview
*/
BoyerMooreSearch(CollData *theData, const UnicodeString &patternString, const UnicodeString *targetString, UErrorCode &status);
/**
* The desstructor
*
* @internal ICU 4.0.1 technology preview
*/
~BoyerMooreSearch();
/**
* Test the pattern to see if it generates any CEs.
*
* @return <code>TRUE</code> if the pattern string did not generate any CEs
*
* @internal ICU 4.0.1 technology preview
*/
UBool empty();
/**
* Search for the pattern string in the target string.
*
* @param offset - the offset in the target string at which to begin the search
* @param start - will be set to the starting offset of the match, or -1 if there's no match
* @param end - will be set to the ending offset of the match, or -1 if there's no match
*
* @return <code>TRUE</code> if the match succeeds, <code>FALSE</code> otherwise.
*
* @internal ICU 4.0.1 technology preview
*/
UBool search(int32_t offset, int32_t &start, int32_t &end);
/**
* Set the target string for the match.
*
* @param targetString - the new target string
* @param status - will be set if any errors occur.
*
* @internal ICU 4.0.1 technology preview
*/
void setTargetString(const UnicodeString *targetString, UErrorCode &status);
// **** no longer need these? ****
/**
* Return the <code>CollData</code> object used for searching
*
* @return the <code>CollData</code> object used for searching
*
* @internal ICU 4.0.1 technology preview
*/
CollData *getData();
/**
* Return the CEs generated by the pattern string.
*
* @return a <code>CEList</code> object holding the CEs generated by the pattern string.
*
* @internal ICU 4.0.1 technology preview
*/
CEList *getPatternCEs();
/**
* Return the <code>BadCharacterTable</code> object computed for the pattern string.
*
* @return the <code>BadCharacterTable</code> object.
*
* @internal ICU 4.0.1 technology preview
*/
BadCharacterTable *getBadCharacterTable();
/**
* Return the <code>GoodSuffixTable</code> object computed for the pattern string.
*
* @return the <code>GoodSuffixTable</code> object computed for the pattern string.
*
* @internal ICU 4.0.1 technology preview
*/
GoodSuffixTable *getGoodSuffixTable();
/**
* UObject glue...
*/
virtual UClassID getDynamicClassID() const;
/**
* UObject glue...
*/
static UClassID getStaticClassID();
private:
CollData *data;
CEList *patCEs;
BadCharacterTable *badCharacterTable;
GoodSuffixTable *goodSuffixTable;
UnicodeString pattern;
Target *target;
};
U_NAMESPACE_END
#endif // #if !UCONFIG_NO_COLLATION
#endif // #ifndef B_M_SEARCH_H
+557
View File
@@ -0,0 +1,557 @@
/*
********************************************************************************
* Copyright (C) 1997-2007, International Business Machines
* Corporation and others. All Rights Reserved.
********************************************************************************
*
* File brkiter.h
*
* Modification History:
*
* Date Name Description
* 02/18/97 aliu Added typedef for TextCount. Made DONE const.
* 05/07/97 aliu Fixed DLL declaration.
* 07/09/97 jfitz Renamed BreakIterator and interface synced with JDK
* 08/11/98 helena Sync-up JDK1.2.
* 01/13/2000 helena Added UErrorCode parameter to createXXXInstance methods.
********************************************************************************
*/
#ifndef BRKITER_H
#define BRKITER_H
#include "unicode/utypes.h"
/**
* \file
* \brief C++ API: Break Iterator.
*/
#if UCONFIG_NO_BREAK_ITERATION
U_NAMESPACE_BEGIN
/*
* Allow the declaration of APIs with pointers to BreakIterator
* even when break iteration is removed from the build.
*/
class BreakIterator;
U_NAMESPACE_END
#else
#include "unicode/uobject.h"
#include "unicode/unistr.h"
#include "unicode/chariter.h"
#include "unicode/locid.h"
#include "unicode/ubrk.h"
#include "unicode/strenum.h"
#include "unicode/utext.h"
#include "unicode/umisc.h"
U_NAMESPACE_BEGIN
/**
* The BreakIterator class implements methods for finding the location
* of boundaries in text. BreakIterator is an abstract base class.
* Instances of BreakIterator maintain a current position and scan over
* text returning the index of characters where boundaries occur.
* <p>
* Line boundary analysis determines where a text string can be broken
* when line-wrapping. The mechanism correctly handles punctuation and
* hyphenated words.
* <p>
* Sentence boundary analysis allows selection with correct
* interpretation of periods within numbers and abbreviations, and
* trailing punctuation marks such as quotation marks and parentheses.
* <p>
* Word boundary analysis is used by search and replace functions, as
* well as within text editing applications that allow the user to
* select words with a double click. Word selection provides correct
* interpretation of punctuation marks within and following
* words. Characters that are not part of a word, such as symbols or
* punctuation marks, have word-breaks on both sides.
* <p>
* Character boundary analysis allows users to interact with
* characters as they expect to, for example, when moving the cursor
* through a text string. Character boundary analysis provides correct
* navigation of through character strings, regardless of how the
* character is stored. For example, an accented character might be
* stored as a base character and a diacritical mark. What users
* consider to be a character can differ between languages.
* <p>
* The text boundary positions are found according to the rules
* described in Unicode Standard Annex #29, Text Boundaries, and
* Unicode Standard Annex #14, Line Breaking Properties. These
* are available at http://www.unicode.org/reports/tr14/ and
* http://www.unicode.org/reports/tr29/.
* <p>
* In addition to the C++ API defined in this header file, a
* plain C API with equivalent functionality is defined in the
* file ubrk.h
* <p>
* Code snippits illustrating the use of the Break Iterator APIs
* are available in the ICU User Guide,
* http://icu-project.org/userguide/boundaryAnalysis.html
* and in the sample program icu/source/samples/break/break.cpp"
*
*/
class U_COMMON_API BreakIterator : public UObject {
public:
/**
* destructor
* @stable ICU 2.0
*/
virtual ~BreakIterator();
/**
* Return true if another object is semantically equal to this
* one. The other object should be an instance of the same subclass of
* BreakIterator. Objects of different subclasses are considered
* unequal.
* <P>
* Return true if this BreakIterator is at the same position in the
* same text, and is the same class and type (word, line, etc.) of
* BreakIterator, as the argument. Text is considered the same if
* it contains the same characters, it need not be the same
* object, and styles are not considered.
* @stable ICU 2.0
*/
virtual UBool operator==(const BreakIterator&) const = 0;
/**
* Returns the complement of the result of operator==
* @param rhs The BreakIterator to be compared for inequality
* @return the complement of the result of operator==
* @stable ICU 2.0
*/
UBool operator!=(const BreakIterator& rhs) const { return !operator==(rhs); }
/**
* Return a polymorphic copy of this object. This is an abstract
* method which subclasses implement.
* @stable ICU 2.0
*/
virtual BreakIterator* clone(void) const = 0;
/**
* Return a polymorphic class ID for this object. Different subclasses
* will return distinct unequal values.
* @stable ICU 2.0
*/
virtual UClassID getDynamicClassID(void) const = 0;
/**
* Return a CharacterIterator over the text being analyzed.
* @stable ICU 2.0
*/
virtual CharacterIterator& getText(void) const = 0;
/**
* Get a UText for the text being analyzed.
* The returned UText is a shallow clone of the UText used internally
* by the break iterator implementation. It can safely be used to
* access the text without impacting any break iterator operations,
* but the underlying text itself must not be altered.
*
* @param fillIn A UText to be filled in. If NULL, a new UText will be
* allocated to hold the result.
* @param status receives any error codes.
* @return The current UText for this break iterator. If an input
* UText was provided, it will always be returned.
* @stable ICU 3.4
*/
virtual UText *getUText(UText *fillIn, UErrorCode &status) const = 0;
/**
* Change the text over which this operates. The text boundary is
* reset to the start.
* @param text The UnicodeString used to change the text.
* @stable ICU 2.0
*/
virtual void setText(const UnicodeString &text) = 0;
/**
* Reset the break iterator to operate over the text represented by
* the UText. The iterator position is reset to the start.
*
* This function makes a shallow clone of the supplied UText. This means
* that the caller is free to immediately close or otherwise reuse the
* Utext that was passed as a parameter, but that the underlying text itself
* must not be altered while being referenced by the break iterator.
*
* @param text The UText used to change the text.
* @param status receives any error codes.
* @stable ICU 3.4
*/
virtual void setText(UText *text, UErrorCode &status) = 0;
/**
* Change the text over which this operates. The text boundary is
* reset to the start.
* Note that setText(UText *) provides similar functionality to this function,
* and is more efficient.
* @param it The CharacterIterator used to change the text.
* @stable ICU 2.0
*/
virtual void adoptText(CharacterIterator* it) = 0;
enum {
/**
* DONE is returned by previous() and next() after all valid
* boundaries have been returned.
* @stable ICU 2.0
*/
DONE = (int32_t)-1
};
/**
* Return the index of the first character in the text being scanned.
* @stable ICU 2.0
*/
virtual int32_t first(void) = 0;
/**
* Return the index immediately BEYOND the last character in the text being scanned.
* @stable ICU 2.0
*/
virtual int32_t last(void) = 0;
/**
* Return the boundary preceding the current boundary.
* @return The character index of the previous text boundary or DONE if all
* boundaries have been returned.
* @stable ICU 2.0
*/
virtual int32_t previous(void) = 0;
/**
* Return the boundary following the current boundary.
* @return The character index of the next text boundary or DONE if all
* boundaries have been returned.
* @stable ICU 2.0
*/
virtual int32_t next(void) = 0;
/**
* Return character index of the current interator position within the text.
* @return The boundary most recently returned.
* @stable ICU 2.0
*/
virtual int32_t current(void) const = 0;
/**
* Return the first boundary following the specified offset.
* The value returned is always greater than the offset or
* the value BreakIterator.DONE
* @param offset the offset to begin scanning.
* @return The first boundary after the specified offset.
* @stable ICU 2.0
*/
virtual int32_t following(int32_t offset) = 0;
/**
* Return the first boundary preceding the specified offset.
* The value returned is always smaller than the offset or
* the value BreakIterator.DONE
* @param offset the offset to begin scanning.
* @return The first boundary before the specified offset.
* @stable ICU 2.0
*/
virtual int32_t preceding(int32_t offset) = 0;
/**
* Return true if the specfied position is a boundary position.
* As a side effect, the current position of the iterator is set
* to the first boundary position at or following the specified offset.
* @param offset the offset to check.
* @return True if "offset" is a boundary position.
* @stable ICU 2.0
*/
virtual UBool isBoundary(int32_t offset) = 0;
/**
* Return the nth boundary from the current boundary
* @param n which boundary to return. A value of 0
* does nothing. Negative values move to previous boundaries
* and positive values move to later boundaries.
* @return The index of the nth boundary from the current position, or
* DONE if there are fewer than |n| boundaries in the specfied direction.
* @stable ICU 2.0
*/
virtual int32_t next(int32_t n) = 0;
/**
* Create BreakIterator for word-breaks using the given locale.
* Returns an instance of a BreakIterator implementing word breaks.
* WordBreak is useful for word selection (ex. double click)
* @param where the locale.
* @param status the error code
* @return A BreakIterator for word-breaks. The UErrorCode& status
* parameter is used to return status information to the user.
* To check whether the construction succeeded or not, you should check
* the value of U_SUCCESS(err). If you wish more detailed information, you
* can check for informational error results which still indicate success.
* U_USING_FALLBACK_WARNING indicates that a fall back locale was used. For
* example, 'de_CH' was requested, but nothing was found there, so 'de' was
* used. U_USING_DEFAULT_WARNING indicates that the default locale data was
* used; neither the requested locale nor any of its fall back locales
* could be found.
* The caller owns the returned object and is responsible for deleting it.
* @stable ICU 2.0
*/
static BreakIterator* U_EXPORT2
createWordInstance(const Locale& where, UErrorCode& status);
/**
* Create BreakIterator for line-breaks using specified locale.
* Returns an instance of a BreakIterator implementing line breaks. Line
* breaks are logically possible line breaks, actual line breaks are
* usually determined based on display width.
* LineBreak is useful for word wrapping text.
* @param where the locale.
* @param status The error code.
* @return A BreakIterator for line-breaks. The UErrorCode& status
* parameter is used to return status information to the user.
* To check whether the construction succeeded or not, you should check
* the value of U_SUCCESS(err). If you wish more detailed information, you
* can check for informational error results which still indicate success.
* U_USING_FALLBACK_WARNING indicates that a fall back locale was used. For
* example, 'de_CH' was requested, but nothing was found there, so 'de' was
* used. U_USING_DEFAULT_WARNING indicates that the default locale data was
* used; neither the requested locale nor any of its fall back locales
* could be found.
* The caller owns the returned object and is responsible for deleting it.
* @stable ICU 2.0
*/
static BreakIterator* U_EXPORT2
createLineInstance(const Locale& where, UErrorCode& status);
/**
* Create BreakIterator for character-breaks using specified locale
* Returns an instance of a BreakIterator implementing character breaks.
* Character breaks are boundaries of combining character sequences.
* @param where the locale.
* @param status The error code.
* @return A BreakIterator for character-breaks. The UErrorCode& status
* parameter is used to return status information to the user.
* To check whether the construction succeeded or not, you should check
* the value of U_SUCCESS(err). If you wish more detailed information, you
* can check for informational error results which still indicate success.
* U_USING_FALLBACK_WARNING indicates that a fall back locale was used. For
* example, 'de_CH' was requested, but nothing was found there, so 'de' was
* used. U_USING_DEFAULT_WARNING indicates that the default locale data was
* used; neither the requested locale nor any of its fall back locales
* could be found.
* The caller owns the returned object and is responsible for deleting it.
* @stable ICU 2.0
*/
static BreakIterator* U_EXPORT2
createCharacterInstance(const Locale& where, UErrorCode& status);
/**
* Create BreakIterator for sentence-breaks using specified locale
* Returns an instance of a BreakIterator implementing sentence breaks.
* @param where the locale.
* @param status The error code.
* @return A BreakIterator for sentence-breaks. The UErrorCode& status
* parameter is used to return status information to the user.
* To check whether the construction succeeded or not, you should check
* the value of U_SUCCESS(err). If you wish more detailed information, you
* can check for informational error results which still indicate success.
* U_USING_FALLBACK_WARNING indicates that a fall back locale was used. For
* example, 'de_CH' was requested, but nothing was found there, so 'de' was
* used. U_USING_DEFAULT_WARNING indicates that the default locale data was
* used; neither the requested locale nor any of its fall back locales
* could be found.
* The caller owns the returned object and is responsible for deleting it.
* @stable ICU 2.0
*/
static BreakIterator* U_EXPORT2
createSentenceInstance(const Locale& where, UErrorCode& status);
/**
* Create BreakIterator for title-casing breaks using the specified locale
* Returns an instance of a BreakIterator implementing title breaks.
* The iterator returned locates title boundaries as described for
* Unicode 3.2 only. For Unicode 4.0 and above title boundary iteration,
* please use Word Boundary iterator.{@link #createWordInstance }
*
* @param where the locale.
* @param status The error code.
* @return A BreakIterator for title-breaks. The UErrorCode& status
* parameter is used to return status information to the user.
* To check whether the construction succeeded or not, you should check
* the value of U_SUCCESS(err). If you wish more detailed information, you
* can check for informational error results which still indicate success.
* U_USING_FALLBACK_WARNING indicates that a fall back locale was used. For
* example, 'de_CH' was requested, but nothing was found there, so 'de' was
* used. U_USING_DEFAULT_WARNING indicates that the default locale data was
* used; neither the requested locale nor any of its fall back locales
* could be found.
* The caller owns the returned object and is responsible for deleting it.
* @stable ICU 2.1
*/
static BreakIterator* U_EXPORT2
createTitleInstance(const Locale& where, UErrorCode& status);
/**
* Get the set of Locales for which TextBoundaries are installed.
* <p><b>Note:</b> this will not return locales added through the register
* call. To see the registered locales too, use the getAvailableLocales
* function that returns a StringEnumeration object </p>
* @param count the output parameter of number of elements in the locale list
* @return available locales
* @stable ICU 2.0
*/
static const Locale* U_EXPORT2 getAvailableLocales(int32_t& count);
/**
* Get name of the object for the desired Locale, in the desired langauge.
* @param objectLocale must be from getAvailableLocales.
* @param displayLocale specifies the desired locale for output.
* @param name the fill-in parameter of the return value
* Uses best match.
* @return user-displayable name
* @stable ICU 2.0
*/
static UnicodeString& U_EXPORT2 getDisplayName(const Locale& objectLocale,
const Locale& displayLocale,
UnicodeString& name);
/**
* Get name of the object for the desired Locale, in the langauge of the
* default locale.
* @param objectLocale must be from getMatchingLocales
* @param name the fill-in parameter of the return value
* @return user-displayable name
* @stable ICU 2.0
*/
static UnicodeString& U_EXPORT2 getDisplayName(const Locale& objectLocale,
UnicodeString& name);
/**
* Thread safe client-buffer-based cloning operation
* Do NOT call delete on a safeclone, since 'new' is not used to create it.
* @param stackBuffer user allocated space for the new clone. If NULL new memory will be allocated.
* If buffer is not large enough, new memory will be allocated.
* @param BufferSize reference to size of allocated space.
* If BufferSize == 0, a sufficient size for use in cloning will
* be returned ('pre-flighting')
* If BufferSize is not enough for a stack-based safe clone,
* new memory will be allocated.
* @param status to indicate whether the operation went on smoothly or there were errors
* An informational status value, U_SAFECLONE_ALLOCATED_ERROR, is used if any allocations were
* necessary.
* @return pointer to the new clone
*
* @stable ICU 2.0
*/
virtual BreakIterator * createBufferClone(void *stackBuffer,
int32_t &BufferSize,
UErrorCode &status) = 0;
/**
* Determine whether the BreakIterator was created in user memory by
* createBufferClone(), and thus should not be deleted. Such objects
* must be closed by an explicit call to the destructor (not delete).
* @stable ICU 2.0
*/
inline UBool isBufferClone(void);
#if !UCONFIG_NO_SERVICE
/**
* Register a new break iterator of the indicated kind, to use in the given locale.
* The break iterator will be adopted. Clones of the iterator will be returned
* if a request for a break iterator of the given kind matches or falls back to
* this locale.
* @param toAdopt the BreakIterator instance to be adopted
* @param locale the Locale for which this instance is to be registered
* @param kind the type of iterator for which this instance is to be registered
* @param status the in/out status code, no special meanings are assigned
* @return a registry key that can be used to unregister this instance
* @stable ICU 2.4
*/
static URegistryKey U_EXPORT2 registerInstance(BreakIterator* toAdopt,
const Locale& locale,
UBreakIteratorType kind,
UErrorCode& status);
/**
* Unregister a previously-registered BreakIterator using the key returned from the
* register call. Key becomes invalid after a successful call and should not be used again.
* The BreakIterator corresponding to the key will be deleted.
* @param key the registry key returned by a previous call to registerInstance
* @param status the in/out status code, no special meanings are assigned
* @return TRUE if the iterator for the key was successfully unregistered
* @stable ICU 2.4
*/
static UBool U_EXPORT2 unregister(URegistryKey key, UErrorCode& status);
/**
* Return a StringEnumeration over the locales available at the time of the call,
* including registered locales.
* @return a StringEnumeration over the locales available at the time of the call
* @stable ICU 2.4
*/
static StringEnumeration* U_EXPORT2 getAvailableLocales(void);
#endif
/**
* Returns the locale for this break iterator. Two flavors are available: valid and
* actual locale.
* @stable ICU 2.8
*/
Locale getLocale(ULocDataLocaleType type, UErrorCode& status) const;
/** Get the locale for this break iterator 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;
private:
static BreakIterator* buildInstance(const Locale& loc, const char *type, int32_t kind, UErrorCode& status);
static BreakIterator* createInstance(const Locale& loc, int32_t kind, UErrorCode& status);
static BreakIterator* makeInstance(const Locale& loc, int32_t kind, UErrorCode& status);
friend class ICUBreakIteratorFactory;
friend class ICUBreakIteratorService;
protected:
/** @internal */
BreakIterator();
/** @internal */
UBool fBufferClone;
/** @internal */
BreakIterator (const BreakIterator &other) : UObject(other), fBufferClone(FALSE) {}
private:
/** @internal */
char actualLocale[ULOC_FULLNAME_CAPACITY];
char validLocale[ULOC_FULLNAME_CAPACITY];
/**
* The assignment operator has no real implementation.
* It's provided to make the compiler happy. Do not call.
*/
BreakIterator& operator=(const BreakIterator&);
};
inline UBool BreakIterator::isBufferClone()
{
return fBufferClone;
}
U_NAMESPACE_END
#endif /* #if !UCONFIG_NO_BREAK_ITERATION */
#endif // _BRKITER
//eof
+233
View File
@@ -0,0 +1,233 @@
// Copyright (C) 2009, International Business Machines
// Corporation and others. All Rights Reserved.
//
// Copyright 2007 Google Inc. All Rights Reserved.
// Author: [email protected] (Sanjay Ghemawat)
//
// Abstract interface that consumes a sequence of bytes (ByteSink).
//
// Used so that we can write a single piece of code that can operate
// on a variety of output string types.
//
// Various implementations of this interface are provided:
// ByteSink:
// CheckedArrayByteSink Write to a flat array, with bounds checking
// StringByteSink Write to an STL string
// This code is a contribution of Google code, and the style used here is
// a compromise between the original Google code and the ICU coding guidelines.
// For example, data types are ICU-ified (size_t,int->int32_t),
// and API comments doxygen-ified, but function names and behavior are
// as in the original, if possible.
// Assertion-style error handling, not available in ICU, was changed to
// parameter "pinning" similar to UnicodeString.
//
// In addition, this is only a partial port of the original Google code,
// limited to what was needed so far. The (nearly) complete original code
// is in the ICU svn repository at icuhtml/trunk/design/strings/contrib
// (see ICU ticket 6765, r25517).
#ifndef __BYTESTREAM_H__
#define __BYTESTREAM_H__
/**
* \file
* \brief C++ API: Interface for writing bytes, and implementation classes.
*/
#include "unicode/utypes.h"
#include "unicode/uobject.h"
#include "unicode/std_string.h"
U_NAMESPACE_BEGIN
/**
* A ByteSink can be filled with bytes.
* @draft ICU 4.2
*/
class U_COMMON_API ByteSink : public UMemory {
public:
/**
* Default constructor.
* @draft ICU 4.2
*/
ByteSink() { }
/**
* Virtual destructor.
* @draft ICU 4.2
*/
virtual ~ByteSink() { }
/**
* Append "bytes[0,n-1]" to this.
* @param bytes the pointer to the bytes
* @param n the number of bytes; must be non-negative
* @draft ICU 4.2
*/
virtual void Append(const char* bytes, int32_t n) = 0;
/**
* Returns a writable buffer for appending and writes the buffer's capacity to
* *result_capacity. Guarantees *result_capacity>=min_capacity.
* May return a pointer to the caller-owned scratch buffer which must have
* scratch_capacity>=min_capacity.
* The returned buffer is only valid until the next operation
* on this ByteSink.
*
* After writing at most *result_capacity bytes, call Append() with the
* pointer returned from this function and the number of bytes written.
* Many Append() implementations will avoid copying bytes if this function
* returned an internal buffer.
*
* Partial usage example:
* int32_t capacity;
* char* buffer = sink->GetAppendBuffer(..., &capacity);
* ... Write n bytes into buffer, with n <= capacity.
* sink->Append(buffer, n);
* In many implementations, that call to Append will avoid copying bytes.
*
* If the ByteSink allocates or reallocates an internal buffer, it should use
* the desired_capacity_hint if appropriate.
* If a caller cannot provide a reasonable guess at the desired capacity,
* it should pass desired_capacity_hint=0.
*
* If a non-scratch buffer is returned, the caller may only pass
* a prefix to it to Append().
* That is, it is not correct to pass an interior pointer to Append().
*
* The default implementation always returns the scratch buffer.
*
* @param min_capacity required minimum capacity of the returned buffer;
* must be non-negative
* @param desired_capacity_hint desired capacity of the returned buffer;
* must be non-negative
* @param scratch default caller-owned buffer
* @param scratch_capacity capacity of the scratch buffer
* @param result_capacity pointer to an integer which will be set to the
* capacity of the returned buffer
* @return a buffer with *result_capacity>=min_capacity
* @draft ICU 4.2
*/
virtual char* GetAppendBuffer(int32_t min_capacity,
int32_t desired_capacity_hint,
char* scratch, int32_t scratch_capacity,
int32_t* result_capacity);
/**
* Flush internal buffers.
* Some byte sinks use internal buffers or provide buffering
* and require calling Flush() at the end of the stream.
* The default implementation of Flush() does nothing.
* @draft ICU 4.2
*/
virtual void Flush();
private:
ByteSink(const ByteSink &); // copy constructor not implemented
ByteSink &operator=(const ByteSink &); // assignment operator not implemented
};
// -------------------------------------------------------------
// Some standard implementations
/**
* Implementation of ByteSink that writes to a flat byte array,
* with bounds-checking:
* This sink will not write more than capacity bytes to outbuf.
* If more than capacity bytes are Append()ed, then excess bytes are ignored,
* and Overflowed() will return true.
* Overflow does not cause a runtime error.
* @draft ICU 4.2
*/
class U_COMMON_API CheckedArrayByteSink : public ByteSink {
public:
/**
* Constructs a ByteSink that will write to outbuf[0..capacity-1].
* @param outbuf buffer to write to
* @param capacity size of the buffer
* @draft ICU 4.2
*/
CheckedArrayByteSink(char* outbuf, int32_t capacity);
/**
* Append "bytes[0,n-1]" to this.
* @param bytes the pointer to the bytes
* @param n the number of bytes; must be non-negative
* @draft ICU 4.2
*/
virtual void Append(const char* bytes, int32_t n);
/**
* Returns a writable buffer for appending and writes the buffer's capacity to
* *result_capacity. For details see the base class documentation.
* @param min_capacity required minimum capacity of the returned buffer;
* must be non-negative
* @param desired_capacity_hint desired capacity of the returned buffer;
* must be non-negative
* @param scratch default caller-owned buffer
* @param scratch_capacity capacity of the scratch buffer
* @param result_capacity pointer to an integer which will be set to the
* capacity of the returned buffer
* @return a buffer with *result_capacity>=min_capacity
* @draft ICU 4.2
*/
virtual char* GetAppendBuffer(int32_t min_capacity,
int32_t desired_capacity_hint,
char* scratch, int32_t scratch_capacity,
int32_t* result_capacity);
/**
* Returns the number of bytes actually written to the sink.
* @return number of bytes written to the buffer
* @draft ICU 4.2
*/
int32_t NumberOfBytesWritten() const { return size_; }
/**
* Returns true if any bytes were discarded, i.e., if there was an
* attempt to write more than 'capacity' bytes.
* @return TRUE if more than 'capacity' bytes were Append()ed
* @draft ICU 4.2
*/
UBool Overflowed() const { return overflowed_; }
private:
char* outbuf_;
const int32_t capacity_;
int32_t size_;
bool overflowed_;
CheckedArrayByteSink(); ///< default constructor not implemented
CheckedArrayByteSink(const CheckedArrayByteSink &); ///< copy constructor not implemented
CheckedArrayByteSink &operator=(const CheckedArrayByteSink &); ///< assignment operator not implemented
};
#if U_HAVE_STD_STRING
/**
* Implementation of ByteSink that writes to a "string".
* The StringClass is usually instantiated with a std::string.
* @draft ICU 4.2
*/
template<typename StringClass>
class StringByteSink : public ByteSink {
public:
/**
* Constructs a ByteSink that will append bytes to the dest string.
* @param dest pointer to string object to append to
* @draft ICU 4.2
*/
StringByteSink(StringClass* dest) : dest_(dest) { }
/**
* Append "bytes[0,n-1]" to this.
* @param bytes the pointer to the bytes
* @param n the number of bytes; must be non-negative
* @draft ICU 4.2
*/
virtual void Append(const char* data, int32_t n) { dest_->append(data, n); }
private:
StringClass* dest_;
StringByteSink(); ///< default constructor not implemented
StringByteSink(const StringByteSink &); ///< copy constructor not implemented
StringByteSink &operator=(const StringByteSink &); ///< assignment operator not implemented
};
#endif
U_NAMESPACE_END
#endif // __BYTESTREAM_H__
File diff suppressed because it is too large Load Diff
+201
View File
@@ -0,0 +1,201 @@
/*
*******************************************************************************
* Copyright (C) 1996-2006, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
*/
#ifndef CANITER_H
#define CANITER_H
#include "unicode/utypes.h"
#if !UCONFIG_NO_NORMALIZATION
#include "unicode/uobject.h"
#include "unicode/unistr.h"
/**
* \file
* \brief C++ API: Canonical Iterator
*/
/** Should permutation skip characters with combining class zero
* Should be either TRUE or FALSE. This is a compile time option
* @stable ICU 2.4
*/
#ifndef CANITER_SKIP_ZEROES
#define CANITER_SKIP_ZEROES TRUE
#endif
U_NAMESPACE_BEGIN
class Hashtable;
/**
* This class allows one to iterate through all the strings that are canonically equivalent to a given
* string. For example, here are some sample results:
Results for: {LATIN CAPITAL LETTER A WITH RING ABOVE}{LATIN SMALL LETTER D}{COMBINING DOT ABOVE}{COMBINING CEDILLA}
1: \\u0041\\u030A\\u0064\\u0307\\u0327
= {LATIN CAPITAL LETTER A}{COMBINING RING ABOVE}{LATIN SMALL LETTER D}{COMBINING DOT ABOVE}{COMBINING CEDILLA}
2: \\u0041\\u030A\\u0064\\u0327\\u0307
= {LATIN CAPITAL LETTER A}{COMBINING RING ABOVE}{LATIN SMALL LETTER D}{COMBINING CEDILLA}{COMBINING DOT ABOVE}
3: \\u0041\\u030A\\u1E0B\\u0327
= {LATIN CAPITAL LETTER A}{COMBINING RING ABOVE}{LATIN SMALL LETTER D WITH DOT ABOVE}{COMBINING CEDILLA}
4: \\u0041\\u030A\\u1E11\\u0307
= {LATIN CAPITAL LETTER A}{COMBINING RING ABOVE}{LATIN SMALL LETTER D WITH CEDILLA}{COMBINING DOT ABOVE}
5: \\u00C5\\u0064\\u0307\\u0327
= {LATIN CAPITAL LETTER A WITH RING ABOVE}{LATIN SMALL LETTER D}{COMBINING DOT ABOVE}{COMBINING CEDILLA}
6: \\u00C5\\u0064\\u0327\\u0307
= {LATIN CAPITAL LETTER A WITH RING ABOVE}{LATIN SMALL LETTER D}{COMBINING CEDILLA}{COMBINING DOT ABOVE}
7: \\u00C5\\u1E0B\\u0327
= {LATIN CAPITAL LETTER A WITH RING ABOVE}{LATIN SMALL LETTER D WITH DOT ABOVE}{COMBINING CEDILLA}
8: \\u00C5\\u1E11\\u0307
= {LATIN CAPITAL LETTER A WITH RING ABOVE}{LATIN SMALL LETTER D WITH CEDILLA}{COMBINING DOT ABOVE}
9: \\u212B\\u0064\\u0307\\u0327
= {ANGSTROM SIGN}{LATIN SMALL LETTER D}{COMBINING DOT ABOVE}{COMBINING CEDILLA}
10: \\u212B\\u0064\\u0327\\u0307
= {ANGSTROM SIGN}{LATIN SMALL LETTER D}{COMBINING CEDILLA}{COMBINING DOT ABOVE}
11: \\u212B\\u1E0B\\u0327
= {ANGSTROM SIGN}{LATIN SMALL LETTER D WITH DOT ABOVE}{COMBINING CEDILLA}
12: \\u212B\\u1E11\\u0307
= {ANGSTROM SIGN}{LATIN SMALL LETTER D WITH CEDILLA}{COMBINING DOT ABOVE}
*<br>Note: the code is intended for use with small strings, and is not suitable for larger ones,
* since it has not been optimized for that situation.
* Note, CanonicalIterator is not intended to be subclassed.
* @author M. Davis
* @author C++ port by V. Weinstein
* @stable ICU 2.4
*/
class U_COMMON_API CanonicalIterator : public UObject {
public:
/**
* Construct a CanonicalIterator object
* @param source string to get results for
* @param status Fill-in parameter which receives the status of this operation.
* @stable ICU 2.4
*/
CanonicalIterator(const UnicodeString &source, UErrorCode &status);
/** Destructor
* Cleans pieces
* @stable ICU 2.4
*/
virtual ~CanonicalIterator();
/**
* Gets the NFD form of the current source we are iterating over.
* @return gets the source: NOTE: it is the NFD form of source
* @stable ICU 2.4
*/
UnicodeString getSource();
/**
* Resets the iterator so that one can start again from the beginning.
* @stable ICU 2.4
*/
void reset();
/**
* Get the next canonically equivalent string.
* <br><b>Warning: The strings are not guaranteed to be in any particular order.</b>
* @return the next string that is canonically equivalent. A bogus string is returned when
* the iteration is done.
* @stable ICU 2.4
*/
UnicodeString next();
/**
* Set a new source for this iterator. Allows object reuse.
* @param newSource the source string to iterate against. This allows the same iterator to be used
* while changing the source string, saving object creation.
* @param status Fill-in parameter which receives the status of this operation.
* @stable ICU 2.4
*/
void setSource(const UnicodeString &newSource, UErrorCode &status);
/**
* Dumb recursive implementation of permutation.
* TODO: optimize
* @param source the string to find permutations for
* @param skipZeros determine if skip zeros
* @param result the results in a set.
* @param status Fill-in parameter which receives the status of this operation.
* @internal
*/
static void U_EXPORT2 permute(UnicodeString &source, UBool skipZeros, Hashtable *result, UErrorCode &status);
/**
* ICU "poor man's RTTI", returns a UClassID for this class.
*
* @stable ICU 2.2
*/
static UClassID U_EXPORT2 getStaticClassID();
/**
* ICU "poor man's RTTI", returns a UClassID for the actual class.
*
* @stable ICU 2.2
*/
virtual UClassID getDynamicClassID() const;
private:
// ===================== PRIVATES ==============================
// private default constructor
CanonicalIterator();
/**
* Copy constructor. Private for now.
* @internal
*/
CanonicalIterator(const CanonicalIterator& other);
/**
* Assignment operator. Private for now.
* @internal
*/
CanonicalIterator& operator=(const CanonicalIterator& other);
// fields
UnicodeString source;
UBool done;
// 2 dimensional array holds the pieces of the string with
// their different canonically equivalent representations
UnicodeString **pieces;
int32_t pieces_length;
int32_t *pieces_lengths;
// current is used in iterating to combine pieces
int32_t *current;
int32_t current_length;
// transient fields
UnicodeString buffer;
// we have a segment, in NFD. Find all the strings that are canonically equivalent to it.
UnicodeString *getEquivalents(const UnicodeString &segment, int32_t &result_len, UErrorCode &status); //private String[] getEquivalents(String segment)
//Set getEquivalents2(String segment);
Hashtable *getEquivalents2(Hashtable *fillinResult, const UChar *segment, int32_t segLen, UErrorCode &status);
//Hashtable *getEquivalents2(const UnicodeString &segment, int32_t segLen, UErrorCode &status);
/**
* See if the decomposition of cp2 is at segment starting at segmentPos
* (with canonical rearrangment!)
* If so, take the remainder, and return the equivalents
*/
//Set extract(int comp, String segment, int segmentPos, StringBuffer buffer);
Hashtable *extract(Hashtable *fillinResult, UChar32 comp, const UChar *segment, int32_t segLen, int32_t segmentPos, UErrorCode &status);
//Hashtable *extract(UChar32 comp, const UnicodeString &segment, int32_t segLen, int32_t segmentPos, UErrorCode &status);
void cleanPieces();
};
U_NAMESPACE_END
#endif /* #if !UCONFIG_NO_NORMALIZATION */
#endif
+716
View File
@@ -0,0 +1,716 @@
/*
********************************************************************
*
* Copyright (C) 1997-2005, International Business Machines
* Corporation and others. All Rights Reserved.
*
********************************************************************
*/
#ifndef CHARITER_H
#define CHARITER_H
#include "unicode/utypes.h"
#include "unicode/uobject.h"
#include "unicode/unistr.h"
/**
* \file
* \brief C++ API: Character Iterator
*/
U_NAMESPACE_BEGIN
/**
* Abstract class that defines an API for forward-only iteration
* on text objects.
* This is a minimal interface for iteration without random access
* or backwards iteration. It is especially useful for wrapping
* streams with converters into an object for collation or
* normalization.
*
* <p>Characters can be accessed in two ways: as code units or as
* code points.
* Unicode code points are 21-bit integers and are the scalar values
* of Unicode characters. ICU uses the type UChar32 for them.
* Unicode code units are the storage units of a given
* Unicode/UCS Transformation Format (a character encoding scheme).
* With UTF-16, all code points can be represented with either one
* or two code units ("surrogates").
* String storage is typically based on code units, while properties
* of characters are typically determined using code point values.
* Some processes may be designed to work with sequences of code units,
* or it may be known that all characters that are important to an
* algorithm can be represented with single code units.
* Other processes will need to use the code point access functions.</p>
*
* <p>ForwardCharacterIterator provides nextPostInc() to access
* a code unit and advance an internal position into the text object,
* similar to a <code>return text[position++]</code>.<br>
* It provides next32PostInc() to access a code point and advance an internal
* position.</p>
*
* <p>next32PostInc() assumes that the current position is that of
* the beginning of a code point, i.e., of its first code unit.
* After next32PostInc(), this will be true again.
* In general, access to code units and code points in the same
* iteration loop should not be mixed. In UTF-16, if the current position
* is on a second code unit (Low Surrogate), then only that code unit
* is returned even by next32PostInc().</p>
*
* <p>For iteration with either function, there are two ways to
* check for the end of the iteration. When there are no more
* characters in the text object:
* <ul>
* <li>The hasNext() function returns FALSE.</li>
* <li>nextPostInc() and next32PostInc() return DONE
* when one attempts to read beyond the end of the text object.</li>
* </ul>
*
* Example:
* \code
* void function1(ForwardCharacterIterator &it) {
* UChar32 c;
* while(it.hasNext()) {
* c=it.next32PostInc();
* // use c
* }
* }
*
* void function1(ForwardCharacterIterator &it) {
* UChar c;
* while((c=it.nextPostInc())!=ForwardCharacterIterator::DONE) {
* // use c
* }
* }
* \endcode
* </p>
*
* @stable ICU 2.0
*/
class U_COMMON_API ForwardCharacterIterator : public UObject {
public:
/**
* Value returned by most of ForwardCharacterIterator's functions
* when the iterator has reached the limits of its iteration.
* @stable ICU 2.0
*/
enum { DONE = 0xffff };
/**
* Destructor.
* @stable ICU 2.0
*/
virtual ~ForwardCharacterIterator();
/**
* Returns true when both iterators refer to the same
* character in the same character-storage object.
* @param that The ForwardCharacterIterator to be compared for equality
* @return true when both iterators refer to the same
* character in the same character-storage object
* @stable ICU 2.0
*/
virtual UBool operator==(const ForwardCharacterIterator& that) const = 0;
/**
* Returns true when the iterators refer to different
* text-storage objects, or to different characters in the
* same text-storage object.
* @param that The ForwardCharacterIterator to be compared for inequality
* @return true when the iterators refer to different
* text-storage objects, or to different characters in the
* same text-storage object
* @stable ICU 2.0
*/
inline UBool operator!=(const ForwardCharacterIterator& that) const;
/**
* Generates a hash code for this iterator.
* @return the hash code.
* @stable ICU 2.0
*/
virtual int32_t hashCode(void) const = 0;
/**
* Returns a UClassID for this ForwardCharacterIterator ("poor man's
* RTTI").<P> Despite the fact that this function is public,
* DO NOT CONSIDER IT PART OF CHARACTERITERATOR'S API!
* @return a UClassID for this ForwardCharacterIterator
* @stable ICU 2.0
*/
virtual UClassID getDynamicClassID(void) const = 0;
/**
* Gets the current code unit for returning and advances to the next code unit
* in the iteration range
* (toward endIndex()). If there are
* no more code units to return, returns DONE.
* @return the current code unit.
* @stable ICU 2.0
*/
virtual UChar nextPostInc(void) = 0;
/**
* Gets the current code point for returning and advances to the next code point
* in the iteration range
* (toward endIndex()). If there are
* no more code points to return, returns DONE.
* @return the current code point.
* @stable ICU 2.0
*/
virtual UChar32 next32PostInc(void) = 0;
/**
* Returns FALSE if there are no more code units or code points
* at or after the current position in the iteration range.
* This is used with nextPostInc() or next32PostInc() in forward
* iteration.
* @returns FALSE if there are no more code units or code points
* at or after the current position in the iteration range.
* @stable ICU 2.0
*/
virtual UBool hasNext() = 0;
protected:
/** Default constructor to be overridden in the implementing class. @stable ICU 2.0*/
ForwardCharacterIterator();
/** Copy constructor to be overridden in the implementing class. @stable ICU 2.0*/
ForwardCharacterIterator(const ForwardCharacterIterator &other);
/**
* Assignment operator to be overridden in the implementing class.
* @stable ICU 2.0
*/
ForwardCharacterIterator &operator=(const ForwardCharacterIterator&) { return *this; }
};
/**
* Abstract class that defines an API for iteration
* on text objects.
* This is an interface for forward and backward iteration
* and random access into a text object.
*
* <p>The API provides backward compatibility to the Java and older ICU
* CharacterIterator classes but extends them significantly:
* <ol>
* <li>CharacterIterator is now a subclass of ForwardCharacterIterator.</li>
* <li>While the old API functions provided forward iteration with
* "pre-increment" semantics, the new one also provides functions
* with "post-increment" semantics. They are more efficient and should
* be the preferred iterator functions for new implementations.
* The backward iteration always had "pre-decrement" semantics, which
* are efficient.</li>
* <li>Just like ForwardCharacterIterator, it provides access to
* both code units and code points. Code point access versions are available
* for the old and the new iteration semantics.</li>
* <li>There are new functions for setting and moving the current position
* without returning a character, for efficiency.</li>
* </ol>
*
* See ForwardCharacterIterator for examples for using the new forward iteration
* functions. For backward iteration, there is also a hasPrevious() function
* that can be used analogously to hasNext().
* The old functions work as before and are shown below.</p>
*
* <p>Examples for some of the new functions:</p>
*
* Forward iteration with hasNext():
* \code
* void forward1(CharacterIterator &it) {
* UChar32 c;
* for(it.setToStart(); it.hasNext();) {
* c=it.next32PostInc();
* // use c
* }
* }
* \endcode
* Forward iteration more similar to loops with the old forward iteration,
* showing a way to convert simple for() loops:
* \code
* void forward2(CharacterIterator &it) {
* UChar c;
* for(c=it.firstPostInc(); c!=CharacterIterator::DONE; c=it.nextPostInc()) {
* // use c
* }
* }
* \endcode
* Backward iteration with setToEnd() and hasPrevious():
* \code
* void backward1(CharacterIterator &it) {
* UChar32 c;
* for(it.setToEnd(); it.hasPrevious();) {
* c=it.previous32();
* // use c
* }
* }
* \endcode
* Backward iteration with a more traditional for() loop:
* \code
* void backward2(CharacterIterator &it) {
* UChar c;
* for(c=it.last(); c!=CharacterIterator::DONE; c=it.previous()) {
* // use c
* }
* }
* \endcode
*
* Example for random access:
* \code
* void random(CharacterIterator &it) {
* // set to the third code point from the beginning
* it.move32(3, CharacterIterator::kStart);
* // get a code point from here without moving the position
* UChar32 c=it.current32();
* // get the position
* int32_t pos=it.getIndex();
* // get the previous code unit
* UChar u=it.previous();
* // move back one more code unit
* it.move(-1, CharacterIterator::kCurrent);
* // set the position back to where it was
* // and read the same code point c and move beyond it
* it.setIndex(pos);
* if(c!=it.next32PostInc()) {
* exit(1); // CharacterIterator inconsistent
* }
* }
* \endcode
*
* <p>Examples, especially for the old API:</p>
*
* Function processing characters, in this example simple output
* <pre>
* \code
* void processChar( UChar c )
* {
* cout << " " << c;
* }
* \endcode
* </pre>
* Traverse the text from start to finish
* <pre>
* \code
* void traverseForward(CharacterIterator& iter)
* {
* for(UChar c = iter.first(); c != CharacterIterator.DONE; c = iter.next()) {
* processChar(c);
* }
* }
* \endcode
* </pre>
* Traverse the text backwards, from end to start
* <pre>
* \code
* void traverseBackward(CharacterIterator& iter)
* {
* for(UChar c = iter.last(); c != CharacterIterator.DONE; c = iter.previous()) {
* processChar(c);
* }
* }
* \endcode
* </pre>
* Traverse both forward and backward from a given position in the text.
* Calls to notBoundary() in this example represents some additional stopping criteria.
* <pre>
* \code
* void traverseOut(CharacterIterator& iter, int32_t pos)
* {
* UChar c;
* for (c = iter.setIndex(pos);
* c != CharacterIterator.DONE && (Unicode::isLetter(c) || Unicode::isDigit(c));
* c = iter.next()) {}
* int32_t end = iter.getIndex();
* for (c = iter.setIndex(pos);
* c != CharacterIterator.DONE && (Unicode::isLetter(c) || Unicode::isDigit(c));
* c = iter.previous()) {}
* int32_t start = iter.getIndex() + 1;
*
* cout << "start: " << start << " end: " << end << endl;
* for (c = iter.setIndex(start); iter.getIndex() < end; c = iter.next() ) {
* processChar(c);
* }
* }
* \endcode
* </pre>
* Creating a StringCharacterIterator and calling the test functions
* <pre>
* \code
* void CharacterIterator_Example( void )
* {
* cout << endl << "===== CharacterIterator_Example: =====" << endl;
* UnicodeString text("Ein kleiner Satz.");
* StringCharacterIterator iterator(text);
* cout << "----- traverseForward: -----------" << endl;
* traverseForward( iterator );
* cout << endl << endl << "----- traverseBackward: ----------" << endl;
* traverseBackward( iterator );
* cout << endl << endl << "----- traverseOut: ---------------" << endl;
* traverseOut( iterator, 7 );
* cout << endl << endl << "-----" << endl;
* }
* \endcode
* </pre>
*
* @stable ICU 2.0
*/
class U_COMMON_API CharacterIterator : public ForwardCharacterIterator {
public:
/**
* Origin enumeration for the move() and move32() functions.
* @stable ICU 2.0
*/
enum EOrigin { kStart, kCurrent, kEnd };
/**
* Returns a pointer to a new CharacterIterator of the same
* concrete class as this one, and referring to the same
* character in the same text-storage object as this one. The
* caller is responsible for deleting the new clone.
* @return a pointer to a new CharacterIterator
* @stable ICU 2.0
*/
virtual CharacterIterator* clone(void) const = 0;
/**
* Sets the iterator to refer to the first code unit in its
* iteration range, and returns that code unit.
* This can be used to begin an iteration with next().
* @return the first code unit in its iteration range.
* @stable ICU 2.0
*/
virtual UChar first(void) = 0;
/**
* Sets the iterator to refer to the first code unit in its
* iteration range, returns that code unit, and moves the position
* to the second code unit. This is an alternative to setToStart()
* for forward iteration with nextPostInc().
* @return the first code unit in its iteration range.
* @stable ICU 2.0
*/
virtual UChar firstPostInc(void);
/**
* Sets the iterator to refer to the first code point in its
* iteration range, and returns that code unit,
* This can be used to begin an iteration with next32().
* Note that an iteration with next32PostInc(), beginning with,
* e.g., setToStart() or firstPostInc(), is more efficient.
* @return the first code point in its iteration range.
* @stable ICU 2.0
*/
virtual UChar32 first32(void) = 0;
/**
* Sets the iterator to refer to the first code point in its
* iteration range, returns that code point, and moves the position
* to the second code point. This is an alternative to setToStart()
* for forward iteration with next32PostInc().
* @return the first code point in its iteration range.
* @stable ICU 2.0
*/
virtual UChar32 first32PostInc(void);
/**
* Sets the iterator to refer to the first code unit or code point in its
* iteration range. This can be used to begin a forward
* iteration with nextPostInc() or next32PostInc().
* @return the start position of the iteration range
* @stable ICU 2.0
*/
inline int32_t setToStart();
/**
* Sets the iterator to refer to the last code unit in its
* iteration range, and returns that code unit.
* This can be used to begin an iteration with previous().
* @return the last code unit.
* @stable ICU 2.0
*/
virtual UChar last(void) = 0;
/**
* Sets the iterator to refer to the last code point in its
* iteration range, and returns that code unit.
* This can be used to begin an iteration with previous32().
* @return the last code point.
* @stable ICU 2.0
*/
virtual UChar32 last32(void) = 0;
/**
* Sets the iterator to the end of its iteration range, just behind
* the last code unit or code point. This can be used to begin a backward
* iteration with previous() or previous32().
* @return the end position of the iteration range
* @stable ICU 2.0
*/
inline int32_t setToEnd();
/**
* Sets the iterator to refer to the "position"-th code unit
* in the text-storage object the iterator refers to, and
* returns that code unit.
* @param position the "position"-th code unit in the text-storage object
* @return the "position"-th code unit.
* @stable ICU 2.0
*/
virtual UChar setIndex(int32_t position) = 0;
/**
* Sets the iterator to refer to the beginning of the code point
* that contains the "position"-th code unit
* in the text-storage object the iterator refers to, and
* returns that code point.
* The current position is adjusted to the beginning of the code point
* (its first code unit).
* @param position the "position"-th code unit in the text-storage object
* @return the "position"-th code point.
* @stable ICU 2.0
*/
virtual UChar32 setIndex32(int32_t position) = 0;
/**
* Returns the code unit the iterator currently refers to.
* @return the current code unit.
* @stable ICU 2.0
*/
virtual UChar current(void) const = 0;
/**
* Returns the code point the iterator currently refers to.
* @return the current code point.
* @stable ICU 2.0
*/
virtual UChar32 current32(void) const = 0;
/**
* Advances to the next code unit in the iteration range
* (toward endIndex()), and returns that code unit. If there are
* no more code units to return, returns DONE.
* @return the next code unit.
* @stable ICU 2.0
*/
virtual UChar next(void) = 0;
/**
* Advances to the next code point in the iteration range
* (toward endIndex()), and returns that code point. If there are
* no more code points to return, returns DONE.
* Note that iteration with "pre-increment" semantics is less
* efficient than iteration with "post-increment" semantics
* that is provided by next32PostInc().
* @return the next code point.
* @stable ICU 2.0
*/
virtual UChar32 next32(void) = 0;
/**
* Advances to the previous code unit in the iteration range
* (toward startIndex()), and returns that code unit. If there are
* no more code units to return, returns DONE.
* @return the previous code unit.
* @stable ICU 2.0
*/
virtual UChar previous(void) = 0;
/**
* Advances to the previous code point in the iteration range
* (toward startIndex()), and returns that code point. If there are
* no more code points to return, returns DONE.
* @return the previous code point.
* @stable ICU 2.0
*/
virtual UChar32 previous32(void) = 0;
/**
* Returns FALSE if there are no more code units or code points
* before the current position in the iteration range.
* This is used with previous() or previous32() in backward
* iteration.
* @return FALSE if there are no more code units or code points
* before the current position in the iteration range, return TRUE otherwise.
* @stable ICU 2.0
*/
virtual UBool hasPrevious() = 0;
/**
* Returns the numeric index in the underlying text-storage
* object of the character returned by first(). Since it's
* possible to create an iterator that iterates across only
* part of a text-storage object, this number isn't
* necessarily 0.
* @returns the numeric index in the underlying text-storage
* object of the character returned by first().
* @stable ICU 2.0
*/
inline int32_t startIndex(void) const;
/**
* Returns the numeric index in the underlying text-storage
* object of the position immediately BEYOND the character
* returned by last().
* @return the numeric index in the underlying text-storage
* object of the position immediately BEYOND the character
* returned by last().
* @stable ICU 2.0
*/
inline int32_t endIndex(void) const;
/**
* Returns the numeric index in the underlying text-storage
* object of the character the iterator currently refers to
* (i.e., the character returned by current()).
* @return the numberic index in the text-storage object of
* the character the iterator currently refers to
* @stable ICU 2.0
*/
inline int32_t getIndex(void) const;
/**
* Returns the length of the entire text in the underlying
* text-storage object.
* @return the length of the entire text in the text-storage object
* @stable ICU 2.0
*/
inline int32_t getLength() const;
/**
* Moves the current position relative to the start or end of the
* iteration range, or relative to the current position itself.
* The movement is expressed in numbers of code units forward
* or backward by specifying a positive or negative delta.
* @param delta the position relative to origin. A positive delta means forward;
* a negative delta means backward.
* @param origin Origin enumeration {kStart, kCurrent, kEnd}
* @return the new position
* @stable ICU 2.0
*/
virtual int32_t move(int32_t delta, EOrigin origin) = 0;
/**
* Moves the current position relative to the start or end of the
* iteration range, or relative to the current position itself.
* The movement is expressed in numbers of code points forward
* or backward by specifying a positive or negative delta.
* @param delta the position relative to origin. A positive delta means forward;
* a negative delta means backward.
* @param origin Origin enumeration {kStart, kCurrent, kEnd}
* @return the new position
* @stable ICU 2.0
*/
virtual int32_t move32(int32_t delta, EOrigin origin) = 0;
/**
* Copies the text under iteration into the UnicodeString
* referred to by "result".
* @param result Receives a copy of the text under iteration.
* @stable ICU 2.0
*/
virtual void getText(UnicodeString& result) = 0;
protected:
/**
* Empty constructor.
* @stable ICU 2.0
*/
CharacterIterator();
/**
* Constructor, just setting the length field in this base class.
* @stable ICU 2.0
*/
CharacterIterator(int32_t length);
/**
* Constructor, just setting the length and position fields in this base class.
* @stable ICU 2.0
*/
CharacterIterator(int32_t length, int32_t position);
/**
* Constructor, just setting the length, start, end, and position fields in this base class.
* @stable ICU 2.0
*/
CharacterIterator(int32_t length, int32_t textBegin, int32_t textEnd, int32_t position);
/**
* Copy constructor.
*
* @param that The CharacterIterator to be copied
* @stable ICU 2.0
*/
CharacterIterator(const CharacterIterator &that);
/**
* Assignment operator. Sets this CharacterIterator to have the same behavior,
* as the one passed in.
* @param that The CharacterIterator passed in.
* @return the newly set CharacterIterator.
* @stable ICU 2.0
*/
CharacterIterator &operator=(const CharacterIterator &that);
/**
* Base class text length field.
* Necessary this for correct getText() and hashCode().
* @stable ICU 2.0
*/
int32_t textLength;
/**
* Base class field for the current position.
* @stable ICU 2.0
*/
int32_t pos;
/**
* Base class field for the start of the iteration range.
* @stable ICU 2.0
*/
int32_t begin;
/**
* Base class field for the end of the iteration range.
* @stable ICU 2.0
*/
int32_t end;
};
inline UBool
ForwardCharacterIterator::operator!=(const ForwardCharacterIterator& that) const {
return !operator==(that);
}
inline int32_t
CharacterIterator::setToStart() {
return move(0, kStart);
}
inline int32_t
CharacterIterator::setToEnd() {
return move(0, kEnd);
}
inline int32_t
CharacterIterator::startIndex(void) const {
return begin;
}
inline int32_t
CharacterIterator::endIndex(void) const {
return end;
}
inline int32_t
CharacterIterator::getIndex(void) const {
return pos;
}
inline int32_t
CharacterIterator::getLength(void) const {
return textLength;
}
U_NAMESPACE_END
#endif
+746
View File
@@ -0,0 +1,746 @@
/*
********************************************************************************
* Copyright (C) 1997-2008, 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"
/**
* \file
* \brief C++ API: Choice Format.
*/
#if !UCONFIG_NO_FORMATTING
#include "unicode/unistr.h"
#include "unicode/numfmt.h"
#include "unicode/fieldpos.h"
#include "unicode/format.h"
U_NAMESPACE_BEGIN
class MessageFormat;
/**
* ChoiceFormat converts between ranges of numeric values
* and string names for those ranges. A <code>ChoiceFormat</code> splits
* the real number line <code>-Inf</code> to <code>+Inf</code> into two
* or more contiguous ranges. Each range is mapped to a
* string. <code>ChoiceFormat</code> is generally used in a
* <code>MessageFormat</code> for displaying grammatically correct
* plurals such as &quot;There are 2 files.&quot;</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 make up the
* <code>ChoiceFormat</code>.</p>
*
* <p><strong>Patterns</strong></p>
*
* <p>In most cases, the preferred way to define a
* <code>ChoiceFormat</code> is with a pattern. Here is an example of a
* <code>ChoiceFormat</code> pattern:</p>
*
* \htmlonly<pre> 0&#x2264;are no files|1&#x2264;is one file|1&lt;are many files</pre>\endhtmlonly
*
* <p>or equivalently,</p>
*
* \htmlonly<pre> 0#are no files|1#is one file|1&lt;are many files</pre>\endhtmlonly
*
* <p>The pattern consists of a number or <em>range specifiers</em>
* separated by vertical bars '|' (U+007C). There is no
* vertical bar after the last range. Each range specifier is of the
* form:</p>
*
* \htmlonly<blockquote><em>Number Separator String</em></blockquote>\endhtmlonly
*
* <p><em>Number</em> is a floating point number that can be parsed by a
* default <code>NumberFormat</code> for the US locale. It gives the
* lower limit of this range. The lower limit is either inclusive or
* exclusive, depending on the <em>separator</em>. The upper limit is
* given by the lower limit of the next range. The Unicode infinity
* sign \htmlonly&#x221E \endhtmlonly (U+221E) is recognized for positive infinity. It may be preceded by
* '-' (U+002D) to indicate negative infinity.</p>
*
* <p><em>String</em> is the format string for this range, with special
* characters enclosed in single quotes (<code>'The #
* sign'</code>). Single quotes themselves are indicated by two single
* quotes in a row (<code>'o''clock'</code>).</p>
*
* <p><em>Separator</em> is one of the following single characters:
*
* <ul>
* <li>\htmlonly'&#x2264;' \endhtmlonly (U+2264) or '#' (U+0023)
* indicates that the lower limit given by <em>Number</em> is
* inclusive. (The two characters are equivalent to ChoiceFormat.)
* This means that the limit value <em>Number</em> belongs to this
* range. Another way of saying this is that the corresponding
* closure is <code>FALSE</code>.</li>
*
* <li>'<' (U+003C) indicates that the lower limit given by
* <em>Number</em> is exclusive. This means that the value
* <em>Number</em> belongs to the prior range.</li> Another way of
* saying this is that the corresponding closure is
* <code>TRUE</code>.
* </ul>
*
* <p>See below for more information about closures.</p>
*
* <p><strong>Arrays</strong></p>
*
* <p>A <code>ChoiceFormat</code> defining <code>n</code> intervals
* (<code>n</code> &gt;= 2) is specified by three arrays of
* <code>n</code> items:
*
* <ul>
* <li><code>double limits[]</code> gives the start of each
* interval. This must be a non-decreasing list of values, none of
* which may be <code>NaN</code>.</li>
* <li><code>UBool closures[]</code> determines whether each limit
* value is contained in the interval below it or in the interval
* above it. If <code>closures[i]</code> is <code>FALSE</code>, then
* <code>limits[i]</code> is a member of interval
* <code>i</code>. Otherwise it is a member of interval
* <code>i+1</code>. If no closures array is specified, this is
* equivalent to having all closures be <code>FALSE</code>. Closures
* allow one to specify half-open, open, or closed intervals.</li>
* <li><code>UnicodeString formats[]</code> gives the string label
* associated with each interval.</li>
* </ul>
*
* <p><strong>Formatting and Parsing</strong></p>
*
* <p>During formatting, a number is converted to a
* string. <code>ChoiceFormat</code> accomplishes this by mapping the
* number to an interval using the following rule. Given a number
* <code>X</code> and and index value <code>j</code> in the range
* <code>0..n-1</code>, where <code>n</code> is the number of ranges:</p>
*
* \htmlonly<blockquote>\endhtmlonly<code>X</code> matches <code>j</code> if and only if
* <code>limit[j] &lt;= X &lt; limit[j+1]</code>
* \htmlonly</blockquote>\endhtmlonly
*
* <p>(This assumes that all closures are <code>FALSE</code>. If some
* closures are <code>TRUE</code> then the relations must be changed to
* <code>&lt;=</code> or <code>&lt;</code> as appropriate.) If there is
* no match, then either the first or last index is used, depending on
* whether the number is too low or too high. Once a number is mapped to
* an interval <code>j</code>, the string <code>formats[j]</code> is
* output.</p>
*
* <p>During parsing, a string is converted to a
* number. <code>ChoiceFormat</code> finds the element
* <code>formats[j]</code> equal to the string, and returns
* <code>limits[j]</code> as the parsed value.</p>
*
* <p><strong>Notes</strong></p>
*
* <p>The first limit value does not define a range boundary. For
* example, in the pattern \htmlonly&quot;<code>1.0#a|2.0#b</code>&quot;\endhtmlonly, the
* intervals are [-Inf, 2.0) and [2.0, +Inf]. It appears that the first
* interval should be [1.0, 2.0). However, since all values that are too
* small are mapped to range zero, the first interval is effectively
* [-Inf, 2.0). However, the first limit value <em>is</em> used during
* formatting. In this example, <code>parse(&quot;a&quot;)</code> returns
* 1.0.</p>
*
* <p>There are no gaps between intervals and the entire number line is
* covered. A <code>ChoiceFormat</code> maps <em>all</em> possible
* double values to a finite set of intervals.</p>
*
* <p>The non-number <code>NaN</code> is mapped to interval zero during
* formatting.</p>
*
* <p><strong>Examples</strong></p>
*
* <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.</p>
*
* <pre> {0, 1, 1},
* {FALSE, FALSE, TRUE},
* {&quot;no files&quot;, &quot;one file&quot;, &quot;many files&quot;}</pre>
*
* <p>Here is a simple 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>Here is a more complex example using a <code>ChoiceFormat</code>
* constructed from a pattern together with a
* <code>MessageFormat</code>.</p>
*
* \code
* #include <unicode/choicfmt.h>
* #include <unicode/msgfmt.h>
* #include <unicode/unistr.h>
* #include <iostream.h>
*
* int main(int argc, char *argv[]) {
* UErrorCode status = U_ZERO_ERROR;
* double filelimits[] = {0,1,2};
* UnicodeString filepart[] =
* {"are no files","is one file","are {0} files"};
* ChoiceFormat* fileform = new ChoiceFormat(filelimits, filepart, 3 );
* Format* testFormats[] =
* {fileform, NULL, NumberFormat::createInstance(status)};
* MessageFormat pattform("There {0} on {1}", status );
* pattform.adoptFormats(testFormats, 3);
* Formattable testArgs[] = {0L, "Disk A"};
* FieldPosition fp(0);
* UnicodeString str;
* char buf[256];
* for (int32_t i = 0; i < 4; ++i) {
* Formattable fInt(i);
* testArgs[0] = fInt;
* pattform.format(testArgs, 2, str, fp, status );
* str.extract(0, str.length(), buf, "");
* str.truncate(0);
* cout << "Output for i=" << i << " : " << 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.
*/
class U_I18N_API ChoiceFormat: public NumberFormat {
public:
/**
* Construct a new ChoiceFormat with the limits and the corresponding formats
* based on the pattern.
*
* @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.
* @stable ICU 2.0
*/
ChoiceFormat(const UnicodeString& pattern,
UErrorCode& status);
/**
* Construct a new ChoiceFormat with the given limits and formats. Copy
* 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.
* @stable ICU 2.0
*/
ChoiceFormat(const double* limits,
const UnicodeString* formats,
int32_t count );
/**
* Construct a new ChoiceFormat with the given limits and formats.
* Copy the limits and formats (instead of adopting them). By
* default, each limit in the array specifies the inclusive lower
* bound of its range, and the exclusive upper bound of the previous
* range. However, if the isLimitOpen element corresponding to a
* limit is TRUE, then the limit is the exclusive lower bound of its
* range, and the inclusive upper bound of the previous range.
* @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 is a member of the range above it. If TRUE,
* then the limit belongs to the range below it.
* @param formats Array of formats
* @param count Size of 'limits', 'closures', and 'formats' arrays
* @stable ICU 2.4
*/
ChoiceFormat(const double* limits,
const UBool* closures,
const UnicodeString* formats,
int32_t count);
/**
* Copy constructor.
*
* @param that ChoiceFormat object to be copied from
* @stable ICU 2.0
*/
ChoiceFormat(const ChoiceFormat& that);
/**
* Assignment operator.
*
* @param that ChoiceFormat object to be copied
* @stable ICU 2.0
*/
const ChoiceFormat& operator=(const ChoiceFormat& that);
/**
* Destructor.
* @stable ICU 2.0
*/
virtual ~ChoiceFormat();
/**
* Clone this Format object polymorphically. The caller owns the
* result and should delete it when done.
*
* @return a copy of this object
* @stable ICU 2.0
*/
virtual Format* clone(void) const;
/**
* Return 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.
* @stable ICU 2.0
*/
virtual UBool operator==(const Format& other) const;
/**
* 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.
* @stable ICU 2.0
*/
virtual void applyPattern(const UnicodeString& pattern,
UErrorCode& status);
/**
* Sets the pattern.
* @param pattern The pattern to be applied.
* @param parseError Struct to recieve 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.
* @stable ICU 2.0
*/
virtual void applyPattern(const UnicodeString& pattern,
UParseError& parseError,
UErrorCode& status);
/**
* Gets the pattern.
*
* @param pattern Output param which will recieve the pattern
* Previous contents are deleted.
* @return A reference to 'pattern'
* @stable ICU 2.0
*/
virtual UnicodeString& toPattern(UnicodeString &pattern) const;
/**
* Set the choices to be used in formatting.
*
* @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.
* @stable ICU 2.0
*/
virtual void setChoices(const double* limitsToCopy,
const UnicodeString* formatsToCopy,
int32_t count );
/**
* Set the choices to be used in formatting. See class description
* for documenatation of the limits, closures, and formats arrays.
* @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
* @stable ICU 2.4
*/
virtual void setChoices(const double* limits,
const UBool* closures,
const UnicodeString* formats,
int32_t count);
/**
* Get the limits passed in the constructor.
*
* @param count The size of the limits arrays
* @return the limits.
* @stable ICU 2.0
*/
virtual const double* getLimits(int32_t& count) const;
/**
* Get the limit booleans passed in the constructor. The caller
* must not delete the result.
*
* @param count The size of the arrays
* @return the closures
* @stable ICU 2.4
*/
virtual const UBool* getClosures(int32_t& count) const;
/**
* Get the formats passed in the constructor.
*
* @param count The size of the arrays
* @return the formats.
* @stable ICU 2.0
*/
virtual const UnicodeString* getFormats(int32_t& count) const;
/**
* Format a double or long 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.
* @stable ICU 2.0
*/
virtual UnicodeString& format(double number,
UnicodeString& appendTo,
FieldPosition& pos) const;
/**
* Format a int_32t 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.
* @stable ICU 2.0
*/
virtual UnicodeString& format(int32_t number,
UnicodeString& appendTo,
FieldPosition& pos) const;
/**
* Format 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.
* @stable ICU 2.8
*/
virtual UnicodeString& format(int64_t number,
UnicodeString& appendTo,
FieldPosition& pos) const;
/**
* Format 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.
* @stable ICU 2.0
*/
virtual UnicodeString& format(const Formattable* objs,
int32_t cnt,
UnicodeString& appendTo,
FieldPosition& pos,
UErrorCode& success) const;
/**
* Format an object using this object's choices.
*
*
* @param obj The object 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.
* @param status Output param set to success/failure code on
* exit.
* @return Reference to 'appendTo' parameter.
* @stable ICU 2.0
*/
virtual UnicodeString& format(const Formattable& obj,
UnicodeString& appendTo,
FieldPosition& pos,
UErrorCode& status) const;
/**
* Redeclared NumberFormat method.
*
* @param obj The object to be formatted.
* @param appendTo Output parameter to receive result.
* Result is appended to existing contents.
* @param status Output param set to success/failure code on
* exit.
* @return Reference to 'appendTo' parameter.
* @stable ICU 2.0
*/
UnicodeString& format(const Formattable& obj,
UnicodeString& appendTo,
UErrorCode& status) const;
/**
* Redeclared NumberFormat method.
* Format a double number. These methods call the NumberFormat
* pure virtual format() methods with the default FieldPosition.
*
* @param number The value to be formatted.
* @param appendTo Output parameter to receive result.
* Result is appended to existing contents.
* @return Reference to 'appendTo' parameter.
* @stable ICU 2.0
*/
UnicodeString& format( double number,
UnicodeString& appendTo) const;
/**
* Redeclared NumberFormat method.
* Format a long number. These methods call the NumberFormat
* pure virtual format() methods with the default FieldPosition.
*
* @param number The value to be formatted.
* @param appendTo Output parameter to receive result.
* Result is appended to existing contents.
* @return Reference to 'appendTo' parameter.
* @stable ICU 2.0
*/
UnicodeString& format( int32_t number,
UnicodeString& appendTo) const;
/**
* Return a long if possible (e.g. within range LONG_MAX,
* LONG_MAX], and with no decimals), otherwise a double. If
* IntegerOnly is set, will stop at a decimal point (or equivalent;
* e.g. for rational numbers "1 2/3", will stop after the 1).
* <P>
* If no object can be parsed, parsePosition is unchanged, and NULL is
* returned.
*
* @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.
* @see NumberFormat::isParseIntegerOnly
* @stable ICU 2.0
*/
virtual void parse(const UnicodeString& text,
Formattable& result,
ParsePosition& parsePosition) const;
/**
* Return a long if possible (e.g. within range LONG_MAX,
* LONG_MAX], and with no decimals), otherwise a double. If
* IntegerOnly is set, will stop at a decimal point (or equivalent;
* e.g. for rational numbers "1 2/3", will stop after the 1).
* <P>
* If no object can be parsed, parsePosition is unchanged, and NULL is
* returned.
*
* @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 status Output param with the formatted string.
* @see NumberFormat::isParseIntegerOnly
* @stable ICU 2.0
*/
virtual void parse(const UnicodeString& text,
Formattable& result,
UErrorCode& status) const;
public:
/**
* 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(void) 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() ==
* . Derived::getStaticClassID()) ...
* </pre>
* @return The class ID for all objects of this class.
* @stable ICU 2.0
*/
static UClassID U_EXPORT2 getStaticClassID(void);
private:
// static cache management (thread-safe)
// static NumberFormat* getNumberFormat(UErrorCode &status); // call this function to 'check out' a numberformat from the cache.
// static void releaseNumberFormat(NumberFormat *adopt); // call this function to 'return' the number format to the cache.
/**
* Converts a string to a double value using a default NumberFormat object
* which is static (shared by all ChoiceFormat instances).
* @param string the string to be converted with.
* @return the converted double number.
*/
static double stod(const UnicodeString& string);
/**
* Converts a double value to a string using a default NumberFormat object
* which is static (shared by all ChoiceFormat instances).
* @param value the double number to be converted with.
* @param string the result string.
* @return the converted string.
*/
static UnicodeString& dtos(double value, UnicodeString& string);
ChoiceFormat(); // 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 recieve 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.
* @stable ICU 2.0
*/
ChoiceFormat(const UnicodeString& newPattern,
UParseError& parseError,
UErrorCode& status);
friend class MessageFormat;
/**
* 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;
};
inline UnicodeString&
ChoiceFormat::format(const Formattable& obj,
UnicodeString& appendTo,
UErrorCode& status) const {
// Don't use Format:: - use immediate base class only,
// in case immediate base modifies behavior later.
return NumberFormat::format(obj, appendTo, status);
}
inline UnicodeString&
ChoiceFormat::format(double number,
UnicodeString& appendTo) const {
return NumberFormat::format(number, appendTo);
}
inline UnicodeString&
ChoiceFormat::format(int32_t number,
UnicodeString& appendTo) const {
return NumberFormat::format(number, appendTo);
}
U_NAMESPACE_END
#endif /* #if !UCONFIG_NO_FORMATTING */
#endif // _CHOICFMT
//eof
+400
View File
@@ -0,0 +1,400 @@
/*
******************************************************************************
* Copyright (C) 1997-2008, 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
*/
#ifndef COLEITR_H
#define COLEITR_H
#include "unicode/utypes.h"
#if !UCONFIG_NO_COLLATION
#include "unicode/uobject.h"
#include "unicode/tblcoll.h"
#include "unicode/ucoleitr.h"
/**
* The UCollationElements struct.
* For usage in C programs.
* @stable ICU 2.0
*/
typedef struct UCollationElements UCollationElements;
U_NAMESPACE_BEGIN
/**
* 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 Spanish:
* <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,
* <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>
* CollationElementIterator::next returns the collation order of the next
* character based on the comparison level of the collator.
* CollationElementIterator::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
* CollationElementIterator::reset. That is, CollationElementIterator::next()
* and CollationElementIterator::previous can not be inter-used. Whenever
* CollationElementIterator::previous is to be called after
* CollationElementIterator::next() or vice versa,
* CollationElementIterator::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 CollationElementIterator::previous or
* CollationElementIterator::next(), the first or last collation order will be
* returned.
* If a change of direction is done without a CollationElementIterator::reset(),
* the result is undefined.
* The result of a forward iterate (CollationElementIterator::next) and
* reversed result of the backward iterate (CollationElementIterator::previous)
* on the same string are equivalent, if collation orders with the value
* UCOL_IGNORABLE 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>t_int32</strong>.
*
* Note, CollationElementIterator should not be subclassed.
* @see Collator
* @see RuleBasedCollator
* @version 1.8 Jan 16 2001
*/
class U_I18N_API CollationElementIterator : public UObject {
public:
// CollationElementIterator public data member ------------------------------
enum {
/**
* NULLORDER indicates that an error has occured while processing
* @stable ICU 2.0
*/
NULLORDER = (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
*/
UBool 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
*/
UBool operator!=(const CollationElementIterator& other) const;
/**
* Resets the cursor to the beginning of the string.
* @stable ICU 2.0
*/
void reset(void);
/**
* 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 occured 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 occured 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(void) 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;
/**
* ICU "poor man's RTTI", returns a UClassID for this class.
*
* @stable ICU 2.2
*/
static UClassID U_EXPORT2 getStaticClassID();
protected:
// CollationElementIterator protected constructors --------------------------
/**
* @stable ICU 2.0
*/
friend class RuleBasedCollator;
/**
* 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.
* @stable ICU 2.0
*/
CollationElementIterator(const UnicodeString& sourceText,
const RuleBasedCollator* order, UErrorCode& status);
/**
* 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.
* @stable ICU 2.0
*/
CollationElementIterator(const CharacterIterator& sourceText,
const RuleBasedCollator* order, UErrorCode& status);
// CollationElementIterator protected methods -------------------------------
/**
* Assignment operator
*
* @param other the object to be copied
* @stable ICU 2.0
*/
const CollationElementIterator&
operator=(const CollationElementIterator& other);
private:
CollationElementIterator(); // default constructor not implemented
// CollationElementIterator private data members ----------------------------
/**
* Data wrapper for collation elements
*/
UCollationElements *m_data_;
/**
* Indicates if m_data_ belongs to this object.
*/
UBool isDataOwned_;
};
// CollationElementIterator inline method defination --------------------------
/**
* Get the primary order of a collation order.
* @param order the collation order
* @return the primary order of a collation order.
*/
inline int32_t CollationElementIterator::primaryOrder(int32_t order)
{
order &= RuleBasedCollator::PRIMARYORDERMASK;
return (order >> RuleBasedCollator::PRIMARYORDERSHIFT);
}
/**
* Get the secondary order of a collation order.
* @param order the collation order
* @return the secondary order of a collation order.
*/
inline int32_t CollationElementIterator::secondaryOrder(int32_t order)
{
order = order & RuleBasedCollator::SECONDARYORDERMASK;
return (order >> RuleBasedCollator::SECONDARYORDERSHIFT);
}
/**
* Get the tertiary order of a collation order.
* @param order the collation order
* @return the tertiary order of a collation order.
*/
inline int32_t CollationElementIterator::tertiaryOrder(int32_t order)
{
return (order &= RuleBasedCollator::TERTIARYORDERMASK);
}
inline int32_t CollationElementIterator::getMaxExpansion(int32_t order) const
{
return ucol_getMaxExpansion(m_data_, (uint32_t)order);
}
inline UBool CollationElementIterator::isIgnorable(int32_t order)
{
return (primaryOrder(order) == RuleBasedCollator::PRIMIGNORABLE);
}
U_NAMESPACE_END
#endif /* #if !UCONFIG_NO_COLLATION */
#endif
File diff suppressed because it is too large Load Diff
+437
View File
@@ -0,0 +1,437 @@
/*
******************************************************************************
* Copyright (C) 1996-2009, International Business Machines *
* Corporation and others. All Rights Reserved. *
******************************************************************************
*/
/**
* \file
* \brief C++ API: Collation data used to compute minLengthInChars.
* \internal
*/
#ifndef COLL_DATA_H
#define COLL_DATA_H
#include "unicode/utypes.h"
#if !UCONFIG_NO_COLLATION
#include "unicode/uobject.h"
#include "unicode/ucol.h"
U_NAMESPACE_BEGIN
/**
* The size of the internal buffer for the Collator's short description string.
*/
#define KEY_BUFFER_SIZE 64
/**
* The size of the internal CE buffer in a <code>CEList</code> object
*/
#define CELIST_BUFFER_SIZE 4
/**
* Define this to enable the <code>CEList</code> objects to collect
* statistics.
*/
//#define INSTRUMENT_CELIST
/**
* The size of the initial list in a <code>StringList</code> object.
*/
#define STRING_LIST_BUFFER_SIZE 16
/**
* Define this to enable the <code>StringList</code> objects to
* collect statistics.
*/
//#define INSTRUMENT_STRING_LIST
/**
* This object holds a list of CEs generated from a particular
* <code>UnicodeString</code>
*
* @internal ICU 4.0.1 technology preview
*/
class U_I18N_API CEList : public UObject
{
public:
/**
* Construct a <code>CEList</code> object.
*
* @param coll - the Collator used to collect the CEs.
* @param string - the string for which to collect the CEs.
* @param status - will be set if any errors occur.
*
* Note: if on return, status is set to an error code,
* the only safe thing to do with this object is to call
* the destructor.
*
* @internal ICU 4.0.1 technology preview
*/
CEList(UCollator *coll, const UnicodeString &string, UErrorCode &status);
/**
* The destructor.
*/
~CEList();
/**
* Return the number of CEs in the list.
*
* @return the number of CEs in the list.
*
* @internal ICU 4.0.1 technology preview
*/
int32_t size() const;
/**
* Get a particular CE from the list.
*
* @param index - the index of the CE to return
*
* @return the CE, or <code>0</code> if <code>index</code> is out of range
*
* @internal ICU 4.0.1 technology preview
*/
uint32_t get(int32_t index) const;
/**
* Check if the CEs in another <code>CEList</code> match the
* suffix of this list starting at a give offset.
*
* @param offset - the offset of the suffix
* @param other - the other <code>CEList</code>
*
* @return <code>TRUE</code> if the CEs match, <code>FALSE</code> otherwise.
*
* @internal ICU 4.0.1 technology preview
*/
UBool matchesAt(int32_t offset, const CEList *other) const;
/**
* The index operator.
*
* @param index - the index
*
* @return a reference to the given CE in the list
*
* @internal ICU 4.0.1 technology preview
*/
uint32_t &operator[](int32_t index) const;
/**
* UObject glue...
*/
virtual UClassID getDynamicClassID() const;
/**
* UObject glue...
*/
static UClassID getStaticClassID();
private:
void add(uint32_t ce, UErrorCode &status);
uint32_t ceBuffer[CELIST_BUFFER_SIZE];
uint32_t *ces;
int32_t listMax;
int32_t listSize;
#ifdef INSTRUMENT_CELIST
static int32_t _active;
static int32_t _histogram[10];
#endif
};
/**
* StringList
*
* This object holds a list of <code>UnicodeString</code> objects.
*
* @internal ICU 4.0.1 technology preview
*/
class U_I18N_API StringList : public UObject
{
public:
/**
* Construct an empty <code>StringList</code>
*
* @param status - will be set if any errors occur.
*
* Note: if on return, status is set to an error code,
* the only safe thing to do with this object is to call
* the destructor.
*
* @internal ICU 4.0.1 technology preview
*/
StringList(UErrorCode &status);
/**
* The destructor.
*
* @internal ICU 4.0.1 technology preview
*/
~StringList();
/**
* Add a string to the list.
*
* @param string - the string to add
* @param status - will be set if any errors occur.
*
* @internal ICU 4.0.1 technology preview
*/
void add(const UnicodeString *string, UErrorCode &status);
/**
* Add an array of Unicode code points to the list.
*
* @param chars - the address of the array of code points
* @param count - the number of code points in the array
* @param status - will be set if any errors occur.
*
* @internal ICU 4.0.1 technology preview
*/
void add(const UChar *chars, int32_t count, UErrorCode &status);
/**
* Get a particular string from the list.
*
* @param index - the index of the string
*
* @return a pointer to the <code>UnicodeString</code> or <code>NULL</code>
* if <code>index</code> is out of bounds.
*
* @internal ICU 4.0.1 technology preview
*/
const UnicodeString *get(int32_t index) const;
/**
* Get the number of stings in the list.
*
* @return the number of strings in the list.
*
* @internal ICU 4.0.1 technology preview
*/
int32_t size() const;
/**
* the UObject glue...
*/
virtual UClassID getDynamicClassID() const;
/**
* the UObject glue...
*/
static UClassID getStaticClassID();
private:
UnicodeString *strings;
int32_t listMax;
int32_t listSize;
#ifdef INSTRUMENT_STRING_LIST
static int32_t _lists;
static int32_t _strings;
static int32_t _histogram[101];
#endif
};
/*
* Forward references to internal classes.
*/
class StringToCEsMap;
class CEToStringsMap;
class CollDataCache;
/**
* CollData
*
* This class holds the Collator-specific data needed to
* compute the length of the shortest string that can
* generate a partcular list of CEs.
*
* <code>CollData</code> objects are quite expensive to compute. Because
* of this, they are cached. When you call <code>CollData::open</code> it
* returns a reference counted cached object. When you call <code>CollData::close</code>
* the reference count on the object is decremented but the object is not deleted.
*
* If you do not need to reuse any unreferenced objects in the cache, you can call
* <code>CollData::flushCollDataCache</code>. If you no longer need any <code>CollData</code>
* objects, you can call <code>CollData::freeCollDataCache</code>
*
* @internal ICU 4.0.1 technology preview
*/
class U_I18N_API CollData : public UObject
{
public:
/**
* Construct a <code>CollData</code> object.
*
* @param collator - the collator
* @param status - will be set if any errors occur.
*
* @return the <code>CollData</code> object. You must call
* <code>close</code> when you are done using the object.
*
* Note: if on return, status is set to an error code,
* the only safe thing to do with this object is to call
* <code>CollData::close</code>.
*
* @internal ICU 4.0.1 technology preview
*/
static CollData *open(UCollator *collator, UErrorCode &status);
/**
* Release a <code>CollData</code> object.
*
* @param collData - the object
*
* @internal ICU 4.0.1 technology preview
*/
static void close(CollData *collData);
/**
* Get the <code>UCollator</code> object used to create this object.
* The object returned may not be the exact object that was used to
* create this object, but it will have the same behavior.
*/
UCollator *getCollator() const;
/**
* Get a list of all the strings which generate a list
* of CEs starting with a given CE.
*
* @param ce - the CE
*
* return a <code>StringList</code> object containing all
* the stirngs, or <code>NULL</code> if there are
* no such strings.
*
* @internal ICU 4.0.1 technology preview.
*/
const StringList *getStringList(int32_t ce) const;
/**
* Get a list of the CEs generated by a partcular stirng.
*
* @param string - the string
*
* @return a <code>CEList</code> object containt the CEs. You
* must call <code>freeCEList</code> when you are finished
* using the <code>CEList</code>/
*
* @internal ICU 4.0.1 technology preview.
*/
const CEList *getCEList(const UnicodeString *string) const;
/**
* Release a <code>CEList</code> returned by <code>getCEList</code>.
*
* @param list - the <code>CEList</code> to free.
*
* @internal ICU 4.0.1 technology preview
*/
void freeCEList(const CEList *list);
/**
* Return the length of the shortest string that will generate
* the given list of CEs.
*
* @param ces - the CEs
* @param offset - the offset of the first CE in the list to use.
*
* @return the length of the shortest string.
*
* @internal ICU 4.0.1 technology preview
*/
int32_t minLengthInChars(const CEList *ces, int32_t offset) const;
/**
* Return the length of the shortest string that will generate
* the given list of CEs.
*
* Note: the algorithm used to do this computation is recursive. To
* limit the amount of recursion, a "history" list is used to record
* the best answer starting at a particular offset in the list of CEs.
* If the same offset is visited again during the recursion, the answer
* in the history list is used.
*
* @param ces - the CEs
* @param offset - the offset of the first CE in the list to use.
* @param history - the history list. Must be at least as long as
* the number of cEs in the <code>CEList</code>
*
* @return the length of the shortest string.
*
* @internal ICU 4.0.1 technology preview
*/
int32_t minLengthInChars(const CEList *ces, int32_t offset, int32_t *history) const;
/**
* UObject glue...
*/
virtual UClassID getDynamicClassID() const;
/**
* UObject glue...
*/
static UClassID getStaticClassID();
/**
* <code>CollData</code> objects are expensive to compute, and so
* may be cached. This routine will free the cached objects and delete
* the cache.
*
* WARNING: Don't call this until you are have called <code>close</code>
* for each <code>CollData</code> object that you have used. also,
* DO NOT call this if another thread may be calling <code>flushCollDataCache</code>
* at the same time.
*
* @internal 4.0.1 technology preview
*/
static void freeCollDataCache();
/**
* <code>CollData</code> objects are expensive to compute, and so
* may be cached. This routine will remove any unused <code>CollData</code>
* objects from the cache.
*
* @internal 4.0.1 technology preview
*/
static void flushCollDataCache();
private:
friend class CollDataCache;
friend class CollDataCacheEntry;
CollData(UCollator *collator, char *cacheKey, int32_t cachekeyLength, UErrorCode &status);
~CollData();
CollData();
static char *getCollatorKey(UCollator *collator, char *buffer, int32_t bufferLength);
static CollDataCache *getCollDataCache();
UCollator *coll;
StringToCEsMap *charsToCEList;
CEToStringsMap *ceToCharsStartingWith;
char keyBuffer[KEY_BUFFER_SIZE];
char *key;
static CollDataCache *collDataCache;
uint32_t minHan;
uint32_t maxHan;
uint32_t jamoLimits[4];
};
U_NAMESPACE_END
#endif // #if !UCONFIG_NO_COLLATION
#endif // #ifndef COLL_DATA_H
+130
View File
@@ -0,0 +1,130 @@
/*
**********************************************************************
* 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 !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
* NULL 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, const UChar* 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
* NULL 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, const UChar* 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 UObject* clone() const;
/**
* 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;
/**
* 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
*/
inline const CurrencyUnit& getCurrency() const;
/**
* Return the ISO currency code of this object.
* @stable ICU 3.0
*/
inline const UChar* getISOCurrency() const;
};
inline const CurrencyUnit& CurrencyAmount::getCurrency() const {
return (const CurrencyUnit&) getUnit();
}
inline const UChar* CurrencyAmount::getISOCurrency() const {
return getCurrency().getISOCurrency();
}
U_NAMESPACE_END
#endif // !UCONFIG_NO_FORMATTING
#endif // __CURRENCYAMOUNT_H__
+259
View File
@@ -0,0 +1,259 @@
/*
*******************************************************************************
* Copyright (C) 2009, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
*/
#ifndef CURRPINF_H
#define CURRPINF_H
#include "unicode/utypes.h"
/**
* \file
* \brief C++ API: Currency Plural Information used by Decimal Format
*/
#if !UCONFIG_NO_FORMATTING
#include "unicode/unistr.h"
union UHashTok;
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.
*
* @draft 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
* @draft 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
* @draft ICU 4.2
*/
CurrencyPluralInfo(const Locale& locale, UErrorCode& status);
/**
* Copy constructor
*
* @draft ICU 4.2
*/
CurrencyPluralInfo(const CurrencyPluralInfo& info);
/**
* Assignment operator
*
* @draft ICU 4.2
*/
CurrencyPluralInfo& operator=(const CurrencyPluralInfo& info);
/**
* Destructor
*
* @draft ICU 4.2
*/
virtual ~CurrencyPluralInfo();
/**
* Equal operator.
*
* @draft ICU 4.2
*/
UBool operator==(const CurrencyPluralInfo& info) const;
/**
* Not equal operator
*
* @draft ICU 4.2
*/
UBool operator!=(const CurrencyPluralInfo& info) const;
/**
* Clone
*
* @draft ICU 4.2
*/
CurrencyPluralInfo* clone() const;
/**
* Gets plural rules of this locale, used for currency plural format
*
* @return plural rule
* @draft 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
* @draft ICU 4.2
*/
UnicodeString& getCurrencyPluralPattern(const UnicodeString& pluralCount,
UnicodeString& result) const;
/**
* Get locale
*
* @return locale
* @draft 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
* @draft 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
* @draft 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
* @draft ICU 4.2
*/
void setLocale(const Locale& loc, UErrorCode& status);
/**
* ICU "poor man's RTTI", returns a UClassID for the actual class.
*
* @draft ICU 4.2
*/
virtual UClassID getDynamicClassID() const;
/**
* ICU "poor man's RTTI", returns a UClassID for this class.
*
* @draft ICU 4.2
*/
static UClassID U_EXPORT2 getStaticClassID();
private:
friend class DecimalFormat;
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
*/
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 patttern,
* the 3 currency signs will be replaced by currency plural name.
*/
PluralRules* fPluralRules;
// locale
Locale* fLocale;
};
inline UBool
CurrencyPluralInfo::operator!=(const CurrencyPluralInfo& info) const { return !operator==(info); }
U_NAMESPACE_END
#endif /* #if !UCONFIG_NO_FORMATTING */
#endif // _CURRPINFO
//eof
+117
View File
@@ -0,0 +1,117 @@
/*
**********************************************************************
* 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 __CURRENCYUNIT_H__
#define __CURRENCYUNIT_H__
#include "unicode/utypes.h"
#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 UChar 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:
/**
* Construct an object with the given ISO currency code.
* @param isoCode the 3-letter ISO 4217 currency code; must not be
* NULL 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
*/
CurrencyUnit(const UChar* isoCode, UErrorCode &ec);
/**
* Copy constructor
* @stable ICU 3.0
*/
CurrencyUnit(const CurrencyUnit& other);
/**
* 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 UObject* clone() const;
/**
* Destructor
* @stable ICU 3.0
*/
virtual ~CurrencyUnit();
/**
* Equality operator. Return true if this object is equal
* to the given object.
* @stable ICU 3.0
*/
UBool operator==(const UObject& other) const;
/**
* 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;
/**
* 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 UChar* getISOCurrency() const;
private:
/**
* The ISO 4217 code of this object.
*/
UChar isoCode[4];
};
inline const UChar* CurrencyUnit::getISOCurrency() const {
return isoCode;
}
U_NAMESPACE_END
#endif // !UCONFIG_NO_FORMATTING
#endif // __CURRENCYUNIT_H__
+690
View File
@@ -0,0 +1,690 @@
/*
********************************************************************************
* Copyright (C) 1997-2009, 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 !UCONFIG_NO_FORMATTING
#include "unicode/udat.h"
#include "unicode/calendar.h"
#include "unicode/numfmt.h"
#include "unicode/format.h"
#include "unicode/locid.h"
/**
* \file
* \brief C++ API: Abstract class for converting dates.
*/
U_NAMESPACE_BEGIN
class TimeZone;
class DateTimePatternGenerator;
/**
* 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 chck 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();
/**
* Equality operator. Returns true if the two formats have the same behavior.
* @stable ICU 2.0
*/
virtual UBool operator==(const Format&) const;
/**
* 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;
/**
* 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 occurence 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
* occurence 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 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 occurence 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
* occurence 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. 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;
/**
* Redeclared Format method.
*
* @param obj The object to be formatted into a string.
* @param appendTo Output parameter to receive result.
* Result is appended to existing contents.
* @param status Output param filled with success/failure status.
* @return Reference to 'appendTo' parameter.
* @stable ICU 2.0
*/
UnicodeString& format(const Formattable& obj,
UnicodeString& appendTo,
UErrorCode& status) const;
/**
* Parse a date/time string.
*
* @param text The 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.
* @result 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 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, calendar field values will be
* parsed based on the internal calendar, then the result
* (time in 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.
* @return A valid UDate if the input could be parsed.
* @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)
*
* @param text The date/time string to be parsed
* @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.
* @return A newly created Formattable* object, or NULL
* on failure. The caller owns this and should
* delete it when done.
* @stable ICU 2.0
*/
virtual void parseObject(const UnicodeString& source,
Formattable& result,
ParsePosition& parse_pos) const;
/**
* 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(void);
/**
* 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.
* @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.
* @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());
/**
* 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 true if the formatter is set for lenient parsing.
* @stable ICU 2.0
*/
virtual UBool isLenient(void) const;
/**
* Specify whether or not 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. With strict parsing, inputs must
* match this object's format.
*
* @param lenient True specifies date/time interpretation to be lenient.
* @see Calendar::setLenient
* @stable ICU 2.0
*/
virtual void setLenient(UBool lenient);
/**
* Gets the calendar associated with this date/time formatter.
* @return the calendar associated with this date/time formatter.
* @stable ICU 2.0
*/
virtual const Calendar* getCalendar(void) 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(void) 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(void) 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);
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&);
public:
/**
* 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
};
};
inline UnicodeString&
DateFormat::format(const Formattable& obj,
UnicodeString& appendTo,
UErrorCode& status) const {
return Format::format(obj, appendTo, status);
}
U_NAMESPACE_END
#endif /* #if !UCONFIG_NO_FORMATTING */
#endif // _DATEFMT
//eof
+41
View File
@@ -0,0 +1,41 @@
/*
**********************************************************************
* Copyright (C) 1999-2006 IBM Corp. All rights reserved.
**********************************************************************
* Date Name Description
* 12/1/99 rgillam Complete port from Java.
* 01/13/2000 helena Added UErrorCode to ctors.
**********************************************************************
*/
#ifndef DBBI_H
#define DBBI_H
#include "unicode/rbbi.h"
#if !UCONFIG_NO_BREAK_ITERATION
/**
* \file
* \brief C++ API: Dictionary Based Break Iterator
*/
U_NAMESPACE_BEGIN
/**
* An obsolete subclass of RuleBasedBreakIterator. Handling of dictionary-
* based break iteration has been folded into the base class. This class
* is deprecated as of ICU 3.6.
*/
#ifndef U_HIDE_DEPRECATED_API
typedef RuleBasedBreakIterator DictionaryBasedBreakIterator;
#endif
U_NAMESPACE_END
#endif /* #if !UCONFIG_NO_BREAK_ITERATION */
#endif
+417
View File
@@ -0,0 +1,417 @@
/*
********************************************************************************
* Copyright (C) 1997-2009, 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 !UCONFIG_NO_FORMATTING
#include "unicode/uobject.h"
#include "unicode/locid.h"
/**
* \file
* \brief C++ API: Symbols for formatting numbers.
*/
U_NAMESPACE_BEGIN
/**
* 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 "#,##,###,####" == "######,####" == "##,####,####".
* <P>
* This class only handles localized digits where the 10 digits are
* contiguous in Unicode, from 0 to 9. Other digits sets (such as
* superscripts) would need a different subclass.
*/
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,
/** count symbol constants */
kFormatSymbolCount
};
/**
* Constants for specifying currency spacing
* @draft ICU 4.2
*/
enum ECurrencySpacing {
kCurrencyMatch,
kSurroundingMatch,
kInsert,
kCurrencySpacingCount
};
/**
* 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);
/**
* 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);
/**
* 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
*/
UBool 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
*/
UBool 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 modifyer 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 modifyer letters) can be used.
*
* @param symbol Constant to indicate a number format symbol.
* @param value value of the format sybmol
* @stable ICU 2.0
*/
void setSymbol(ENumberFormatSymbol symbol, const UnicodeString &value);
/**
* 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 : kCurrencyMatch, kSurroundingMatch or kInsert.
* @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.
* @draft ICU 4.2
*/
const UnicodeString& getPatternForCurrencySpacing(ECurrencySpacing type,
UBool beforeCurrency,
UErrorCode& status) const;
/**
* Set pattern string for 'CurrencySpacing' that can be applied to
* currency format.
*
* @param type : kCurrencyMatch, kSurroundingMatch or kInsert.
* @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.
* @draft ICU 4.2
*/
void setPatternForCurrencySpacing(ECurrencySpacing 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;
/**
* ICU "poor man's RTTI", returns a UClassID for this class.
*
* @stable ICU 2.2
*/
static UClassID U_EXPORT2 getStaticClassID();
private:
DecimalFormatSymbols(); // default constructor not implemented
/**
* 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
*/
void initialize(const Locale& locale, UErrorCode& success, UBool useLastResortData = FALSE);
/**
* Initialize the symbols from the given array of UnicodeStrings.
* The array must be of the correct size.
*
* @param numberElements the number format symbols
* @param numberElementsLength length of numberElements
*/
void initialize(const UChar** numberElements, int32_t *numberElementsStrLen, int32_t numberElementsLength);
/**
* Initialize the symbols with default values.
*/
void initialize();
void setCurrencyForSymbols();
public:
/**
* _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.
* ### TODO markus 2002oct11: Consider proposing getConstSymbol() to be really public.
*
* @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;
/**
* Returns that pattern stored in currecy info. Internal API for use by NumberFormat API.
* @internal
*/
inline const UChar* getCurrencyPattern(void) const;
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().
*
* @internal
*/
UnicodeString fSymbols[kFormatSymbolCount];
/**
* Non-symbol variable for getConstSymbol(). Always empty.
* @internal
*/
UnicodeString fNoSymbol;
Locale locale;
char actualLocale[ULOC_FULLNAME_CAPACITY];
char validLocale[ULOC_FULLNAME_CAPACITY];
const UChar* currPattern;
UnicodeString currencySpcBeforeSym[kCurrencySpacingCount];
UnicodeString currencySpcAfterSym[kCurrencySpacingCount];
};
// -------------------------------------
inline UnicodeString
DecimalFormatSymbols::getSymbol(ENumberFormatSymbol symbol) const {
const UnicodeString *strPtr;
if(symbol < kFormatSymbolCount) {
strPtr = &fSymbols[symbol];
} else {
strPtr = &fNoSymbol;
}
return *strPtr;
}
inline const UnicodeString &
DecimalFormatSymbols::getConstSymbol(ENumberFormatSymbol symbol) const {
const UnicodeString *strPtr;
if(symbol < kFormatSymbolCount) {
strPtr = &fSymbols[symbol];
} else {
strPtr = &fNoSymbol;
}
return *strPtr;
}
// -------------------------------------
inline void
DecimalFormatSymbols::setSymbol(ENumberFormatSymbol symbol, const UnicodeString &value) {
if(symbol<kFormatSymbolCount) {
fSymbols[symbol]=value;
}
}
// -------------------------------------
inline Locale
DecimalFormatSymbols::getLocale() const {
return locale;
}
inline const UChar*
DecimalFormatSymbols::getCurrencyPattern() const {
return currPattern;
}
U_NAMESPACE_END
#endif /* #if !UCONFIG_NO_FORMATTING */
#endif // _DCFMTSYM
//eof
File diff suppressed because it is too large Load Diff
+203
View File
@@ -0,0 +1,203 @@
/********************************************************************
* COPYRIGHT:
* Copyright (c) 1997-2009, International Business Machines Corporation and
* others. All Rights Reserved.
*
* FILE NAME: DOCMAIN.h
*
* Date Name Description
* 12/11/2000 Ram Creation.
*/
/* This file contains documentation for Doxygen and doesnot have
* any significance with respect to C or C++ API
*/
/*! \mainpage
*
* \section API API Reference Usage
*
* <h3>C++ Programmers:</h3>
* <p>Use <a href="hierarchy.html">Class Hierarchy</a> or <a href="classes.html"> Alphabetical List </a>
* or <a href="annotated.html"> Compound List</a>
* to find the class you are interested in. For example, to find BreakIterator,
* you can go to the <a href="classes.html"> Alphabetical List</a>, then click on
* "BreakIterator". Once you are at the class, you will find an inheritance
* chart, a list of the public members, a detailed description of the class,
* then detailed member descriptions.</p>
*
* <h3>C Programmers:</h3>
* <p>Use <a href="#Module">Module List</a> or <a href="globals.html">File Members</a>
* to find a list of all the functions and constants.
* For example, to find BreakIterator functions you would click on
* <a href="files.html"> File List</a>,
* then find "ubrk.h" and click on it. You will find descriptions of Defines,
* Typedefs, Enumerations, and Functions, with detailed descriptions below.
* If you want to find a specific function, such as ubrk_next(), then click
* first on <a href="globals.html"> File Members</a>, then use your browser
* Find dialog to search for "ubrk_next()".</p>
*
*
* <h3>API References for Previous Releases</h3>
* <p>The API References for each release of ICU are also available as
* a zip file from the ICU
* <a href="http://icu-project.org/download/">download page</a>.</p>
*
* <hr>
*
* <h2>Architecture (User's Guide)</h2>
* <ul>
* <li><a href="http://icu-project.org/userguide/">Introduction</a></li>
* <li><a href="http://icu-project.org/userguide/i18n.html">Internationalization</a></li>
* <li><a href="http://icu-project.org/userguide/design.html">Locale Model</a></li>
* <li><a href="http://icu-project.org/userguide/design.html">Multithreading</a></li>
* <li><a href="http://icu-project.org/userguide/conversion.html">Conversion</a></li>
* <li><a href="http://icu-project.org/userguide/design.html">Error Handling</a></li>
* </ul>
*
* <hr>
*\htmlonly <h2><a NAME="Module">Module List</a></h2> \endhtmlonly
* <table border="1" cols="3" align="center">
* <tr>
* <td><strong>Module Name</strong></td>
* <td><strong>C</strong></td>
* <td><strong>C++</strong></td>
* </tr>
* <tr>
* <td>Basic Types and Constants</td>
* <td>utypes.h</td>
* <td>utypes.h</td>
* </tr>
* <tr>
* <td>Strings and Character Iteration</td>
* <td>ustring.h, utf.h</td>
* <td>UnicodeString, CharacterIterator</td>
* </tr>
* <tr>
* <td>Unicode Character<br>Properties and Names</td>
* <td>uchar.h</td>
* <td>uchar.h C API</td>
* </tr>
* <tr>
* <td>Codepage Conversion</td>
* <td>ucnv.h</td>
* <td>ucnv.h C API</td>
* </tr>
* <tr>
* <td>Unicode Text Compression</td>
* <td>ucnv.h <br> (encoding name "SCSU" or "BOCU-1")</td>
* <td>ucnv.h C API</td>
* </tr>
* <tr>
* <td>Locales </td>
* <td>uloc.h</a></td>
* <td>Locale</td>
* </tr>
* <tr>
* <td>Resource Bundles</td>
* <td>ures.h</td>
* <td>ResourceBundle</td>
* </tr>
* <tr>
* <td>Normalization</td>
* <td>unorm.h</td>
* <td>Normalizer</td>
* </tr>
* <tr>
* <td>Calendars</td>
* <td>ucal.h</td>
* <td>Calendar</td>
* </tr>
* <tr>
* <td>Date and Time Formatting</td>
* <td>udat.h</td>
* <td>DateFormat</td>
* </tr>
* <tr>
* <td>Message Formatting</td>
* <td>umsg.h</td>
* <td>MessageFormat</td>
* </tr>
* <tr>
* <td>Number Formatting</td>
* <td>unum.h</td>
* <td>NumberFormat</td>
* </tr>
* <tr>
* <td>Number Spellout <br> (Rule Based Number Formatting)</td>
* <td>unum.h <br> (use UNUM_SPELLOUT)</td>
* <td>RuleBasedNumberFormat</td>
* </tr>
* <tr>
* <td>Text Transformation <br> (Transliteration)</td>
* <td>utrans.h</td>
* <td>Transliterator</td>
* </tr>
* <tr>
* <td>Bidirectional Algorithm</td>
* <td>ubidi.h</td>
* <td>ubidi.h C API</td>
* </tr>
* <tr>
* <td>Arabic Shaping</td>
* <td>ushape.h</td>
* <td>ushape.h C API</td>
* </tr>
* <tr>
* <td>Collation</td>
* <td>ucol.h</td>
* <td>Collator</td>
* </tr>
* <tr>
* <td>String Searching</td>
* <td>usearch.h</td>
* <td>StringSearch</td>
* </tr>
* <tr>
* <td>Text Boundary Analysis <br> (Break Iteration)</td>
* <td>ubrk.h</td>
* <td>BreakIterator</td>
* </tr>
* <tr>
* <td>Unicode Set</td>
* <td>uset.h</td>
* <td>UnicodeSet</td>
* </tr>
* <tr>
* <td>Regular Expressions</td>
* <td>uregex.h</td>
* <td>RegexPattern, RegexMatcher</td>
* </tr>
* <tr>
* <td>StringPrep</td>
* <td>usprep.h</td>
* <td>usprep.h C API</td>
* </tr>
* <tr>
* <td>International Domain Names in Applications</td>
* <td>uidna.h</td>
* <td>uidna.h C API</td>
* </tr>
* <tr>
* <td>Universal Time Scale</td>
* <td>utmscale.h</td>
* <td>utmscale.h C API</td>
* </tr>
* <tr>
* <td>Basic Layout Engine Types and Constants</td>
* <td>(no C API)</td>
* <td>LETypes.h</td>
* </tr>
* <tr>
* <td>Complex Text Layout</td>
* <td>(no C API)</td>
* <td>LayoutEngine, ParagraphLayout</td>
* </tr>
* <tr>
* <td>ICU I/O</td>
* <td>ustdio.h</td>
* <td>ustream.h</td>
* </tr>
* </table>
* <i>This main page is generated from docmain.h</i>
*/
+721
View File
@@ -0,0 +1,721 @@
/*
********************************************************************************
* Copyright (C) 1997-2008, International Business Machines
* Corporation and others. All Rights Reserved.
********************************************************************************
*
* File DTFMTSYM.H
*
* Modification History:
*
* Date Name Description
* 02/19/97 aliu Converted from java.
* 07/21/98 stephen Added getZoneIndex()
* Changed to match C++ conventions
********************************************************************************
*/
#ifndef DTFMTSYM_H
#define DTFMTSYM_H
#include "unicode/utypes.h"
#if !UCONFIG_NO_FORMATTING
#include "unicode/calendar.h"
#include "unicode/uobject.h"
#include "unicode/locid.h"
#include "unicode/ures.h"
/**
* \file
* \brief C++ API: Symbols for formatting dates.
*/
U_NAMESPACE_BEGIN
/* forward declaration */
class SimpleDateFormat;
class Hashtable;
class ZoneStringFormat;
class SafeZoneStringFormatPtr;
/**
* DateFormatSymbols is a public class for encapsulating localizable date-time
* formatting data -- including timezone data. DateFormatSymbols is used by
* DateFormat and SimpleDateFormat.
* <P>
* Rather than first creating a DateFormatSymbols to get a date-time formatter
* by using a SimpleDateFormat constructor, clients are encouraged to create a
* date-time formatter using the getTimeInstance(), getDateInstance(), or
* getDateTimeInstance() method in DateFormat. Each of these methods can return a
* date/time formatter initialized with a default format pattern along with the
* date-time formatting data for a given or default locale. After a formatter is
* created, clients may modify the format pattern using the setPattern function
* as so desired. For more information on using these formatter factory
* functions, see DateFormat.
* <P>
* If clients decide to create a date-time formatter with a particular format
* pattern and locale, they can do so with new SimpleDateFormat(aPattern,
* new DateFormatSymbols(aLocale)). This will load the appropriate date-time
* formatting data from the locale.
* <P>
* DateFormatSymbols objects are clonable. When clients obtain a
* DateFormatSymbols object, they can feel free to modify the date-time
* formatting data as necessary. For instance, clients can
* replace the localized date-time format pattern characters with the ones that
* they feel easy to remember. Or they can change the representative cities
* originally picked by default to using their favorite ones.
* <P>
* DateFormatSymbols are not expected to be subclassed. Data for a calendar is
* loaded out of resource bundles. The 'type' parameter indicates the type of
* calendar, for example, "gregorian" or "japanese". If the type is not gregorian
* (or NULL, or an empty string) then the type is appended to the resource name,
* for example, 'Eras_japanese' instead of 'Eras'. If the resource 'Eras_japanese' did
* not exist (even in root), then this class will fall back to just 'Eras', that is,
* Gregorian data. Therefore, the calendar implementor MUST ensure that the root
* locale at least contains any resources that are to be particularized for the
* calendar type.
*/
class U_I18N_API DateFormatSymbols : public UObject {
public:
/**
* Construct a DateFormatSymbols object by loading format data from
* resources for the default locale, in the default calendar (Gregorian).
* <P>
* NOTE: This constructor will never fail; if it cannot get resource
* data for the default locale, it will return a last-resort object
* based on hard-coded strings.
*
* @param status Status code. Failure
* results if the resources for the default cannot be
* found or cannot be loaded
* @stable ICU 2.0
*/
DateFormatSymbols(UErrorCode& status);
/**
* Construct a DateFormatSymbols object by loading format data from
* resources for the given locale, in the default calendar (Gregorian).
*
* @param locale Locale to load format data from.
* @param status Status code. Failure
* results if the resources for the locale cannot be
* found or cannot be loaded
* @stable ICU 2.0
*/
DateFormatSymbols(const Locale& locale,
UErrorCode& status);
/**
* Construct a DateFormatSymbols object by loading format data from
* resources for the default locale, in the default calendar (Gregorian).
* <P>
* NOTE: This constructor will never fail; if it cannot get resource
* data for the default locale, it will return a last-resort object
* based on hard-coded strings.
*
* @param type Type of calendar (as returned by Calendar::getType).
* Will be used to access the correct set of strings.
* (NULL or empty string defaults to "gregorian".)
* @param status Status code. Failure
* results if the resources for the default cannot be
* found or cannot be loaded
* @internal
*/
DateFormatSymbols(const char *type, UErrorCode& status);
/**
* Construct a DateFormatSymbols object by loading format data from
* resources for the given locale, in the default calendar (Gregorian).
*
* @param locale Locale to load format data from.
* @param type Type of calendar (as returned by Calendar::getType).
* Will be used to access the correct set of strings.
* (NULL or empty string defaults to "gregorian".)
* @param status Status code. Failure
* results if the resources for the locale cannot be
* found or cannot be loaded
* @internal
*/
DateFormatSymbols(const Locale& locale,
const char *type,
UErrorCode& status);
/**
* Copy constructor.
* @stable ICU 2.0
*/
DateFormatSymbols(const DateFormatSymbols&);
/**
* Assignment operator.
* @stable ICU 2.0
*/
DateFormatSymbols& operator=(const DateFormatSymbols&);
/**
* Destructor. This is nonvirtual because this class is not designed to be
* subclassed.
* @stable ICU 2.0
*/
virtual ~DateFormatSymbols();
/**
* Return true if another object is semantically equal to this one.
*
* @param other the DateFormatSymbols object to be compared with.
* @return true if other is semantically equal to this.
* @stable ICU 2.0
*/
UBool operator==(const DateFormatSymbols& other) const;
/**
* Return true if another object is semantically unequal to this one.
*
* @param other the DateFormatSymbols object to be compared with.
* @return true if other is semantically unequal to this.
* @stable ICU 2.0
*/
UBool operator!=(const DateFormatSymbols& other) const { return !operator==(other); }
/**
* Gets abbreviated era strings. For example: "AD" and "BC".
*
* @param count Filled in with length of the array.
* @return the era strings.
* @stable ICU 2.0
*/
const UnicodeString* getEras(int32_t& count) const;
/**
* Sets abbreviated era strings. For example: "AD" and "BC".
* @param eras Array of era strings (DateFormatSymbols retains ownership.)
* @param count Filled in with length of the array.
* @stable ICU 2.0
*/
void setEras(const UnicodeString* eras, int32_t count);
/**
* Gets era name strings. For example: "Anno Domini" and "Before Christ".
*
* @param count Filled in with length of the array.
* @return the era name strings.
* @stable ICU 3.4
*/
const UnicodeString* getEraNames(int32_t& count) const;
/**
* Sets era name strings. For example: "Anno Domini" and "Before Christ".
* @param eraNames Array of era name strings (DateFormatSymbols retains ownership.)
* @param count Filled in with length of the array.
* @stable ICU 3.6
*/
void setEraNames(const UnicodeString* eraNames, int32_t count);
/**
* Gets narrow era strings. For example: A" and "D".
*
* @param count Filled in with length of the array.
* @return the narrow era strings.
* @draft ICU 4.2
*/
const UnicodeString* getNarrowEras(int32_t& count) const;
/**
* Sets narrow era strings. For example: "A" and "B".
* @param narrowEras Array of narrow era strings (DateFormatSymbols retains ownership.)
* @param count Filled in with length of the array.
* @draft ICU 4.2
*/
void setNarrowEras(const UnicodeString* narrowEras, int32_t count);
/**
* Gets month strings. For example: "January", "February", etc.
* @param count Filled in with length of the array.
* @return the month strings. (DateFormatSymbols retains ownership.)
* @stable ICU 2.0
*/
const UnicodeString* getMonths(int32_t& count) const;
/**
* Sets month strings. For example: "January", "February", etc.
*
* @param months the new month strings. (not adopted; caller retains ownership)
* @param count Filled in with length of the array.
* @stable ICU 2.0
*/
void setMonths(const UnicodeString* months, int32_t count);
/**
* Gets short month strings. For example: "Jan", "Feb", etc.
*
* @param count Filled in with length of the array.
* @return the short month strings. (DateFormatSymbols retains ownership.)
* @stable ICU 2.0
*/
const UnicodeString* getShortMonths(int32_t& count) const;
/**
* Sets short month strings. For example: "Jan", "Feb", etc.
* @param count Filled in with length of the array.
* @param shortMonths the new short month strings. (not adopted; caller retains ownership)
* @stable ICU 2.0
*/
void setShortMonths(const UnicodeString* shortMonths, int32_t count);
/**
* Selector for date formatting context
* @stable ICU 3.6
*/
enum DtContextType {
FORMAT,
STANDALONE,
DT_CONTEXT_COUNT
};
/**
* Selector for date formatting width
* @stable ICU 3.6
*/
enum DtWidthType {
ABBREVIATED,
WIDE,
NARROW,
DT_WIDTH_COUNT
};
/**
* Gets month strings by width and context. For example: "January", "February", etc.
* @param count Filled in with length of the array.
* @param context The formatting context, either FORMAT or STANDALONE
* @param width The width of returned strings, either WIDE, ABBREVIATED, or NARROW.
* @return the month strings. (DateFormatSymbols retains ownership.)
* @stable ICU 3.4
*/
const UnicodeString* getMonths(int32_t& count, DtContextType context, DtWidthType width) const;
/**
* Sets month strings by width and context. For example: "January", "February", etc.
*
* @param months The new month strings. (not adopted; caller retains ownership)
* @param count Filled in with length of the array.
* @param context The formatting context, either FORMAT or STANDALONE
* @param width The width of returned strings, either WIDE, ABBREVIATED, or NARROW.
* @stable ICU 3.6
*/
void setMonths(const UnicodeString* months, int32_t count, DtContextType context, DtWidthType width);
/**
* Gets weekday strings. For example: "Sunday", "Monday", etc.
* @param count Filled in with length of the array.
* @return the weekday strings. (DateFormatSymbols retains ownership.)
* @stable ICU 2.0
*/
const UnicodeString* getWeekdays(int32_t& count) const;
/**
* Sets weekday strings. For example: "Sunday", "Monday", etc.
* @param weekdays the new weekday strings. (not adopted; caller retains ownership)
* @param count Filled in with length of the array.
* @stable ICU 2.0
*/
void setWeekdays(const UnicodeString* weekdays, int32_t count);
/**
* Gets short weekday strings. For example: "Sun", "Mon", etc.
* @param count Filled in with length of the array.
* @return the short weekday strings. (DateFormatSymbols retains ownership.)
* @stable ICU 2.0
*/
const UnicodeString* getShortWeekdays(int32_t& count) const;
/**
* Sets short weekday strings. For example: "Sun", "Mon", etc.
* @param shortWeekdays the new short weekday strings. (not adopted; caller retains ownership)
* @param count Filled in with length of the array.
* @stable ICU 2.0
*/
void setShortWeekdays(const UnicodeString* shortWeekdays, int32_t count);
/**
* Gets weekday strings by width and context. For example: "Sunday", "Monday", etc.
* @param count Filled in with length of the array.
* @param context The formatting context, either FORMAT or STANDALONE
* @param width The width of returned strings, either WIDE, ABBREVIATED, or NARROW
* @return the month strings. (DateFormatSymbols retains ownership.)
* @stable ICU 3.4
*/
const UnicodeString* getWeekdays(int32_t& count, DtContextType context, DtWidthType width) const;
/**
* Sets weekday strings by width and context. For example: "Sunday", "Monday", etc.
* @param weekdays The new weekday strings. (not adopted; caller retains ownership)
* @param count Filled in with length of the array.
* @param context The formatting context, either FORMAT or STANDALONE
* @param width The width of returned strings, either WIDE, ABBREVIATED, or NARROW
* @stable ICU 3.6
*/
void setWeekdays(const UnicodeString* weekdays, int32_t count, DtContextType context, DtWidthType width);
/**
* Gets quarter strings by width and context. For example: "1st Quarter", "2nd Quarter", etc.
* @param count Filled in with length of the array.
* @param context The formatting context, either FORMAT or STANDALONE
* @param width The width of returned strings, either WIDE or ABBREVIATED. There
* are no NARROW quarters.
* @return the quarter strings. (DateFormatSymbols retains ownership.)
* @stable ICU 3.6
*/
const UnicodeString* getQuarters(int32_t& count, DtContextType context, DtWidthType width) const;
/**
* Sets quarter strings by width and context. For example: "1st Quarter", "2nd Quarter", etc.
*
* @param quarters The new quarter strings. (not adopted; caller retains ownership)
* @param count Filled in with length of the array.
* @param context The formatting context, either FORMAT or STANDALONE
* @param width The width of returned strings, either WIDE or ABBREVIATED. There
* are no NARROW quarters.
* @stable ICU 3.6
*/
void setQuarters(const UnicodeString* quarters, int32_t count, DtContextType context, DtWidthType width);
/**
* Gets AM/PM strings. For example: "AM" and "PM".
* @param count Filled in with length of the array.
* @return the weekday strings. (DateFormatSymbols retains ownership.)
* @stable ICU 2.0
*/
const UnicodeString* getAmPmStrings(int32_t& count) const;
/**
* Sets ampm strings. For example: "AM" and "PM".
* @param ampms the new ampm strings. (not adopted; caller retains ownership)
* @param count Filled in with length of the array.
* @stable ICU 2.0
*/
void setAmPmStrings(const UnicodeString* ampms, int32_t count);
/**
* Gets timezone strings. These strings are stored in a 2-dimensional array.
* @param rowCount Output param to receive number of rows.
* @param columnCount Output param to receive number of columns.
* @return The timezone strings as a 2-d array. (DateFormatSymbols retains ownership.)
* @deprecated ICU 3.6
*/
const UnicodeString** getZoneStrings(int32_t& rowCount, int32_t& columnCount) const;
/**
* Sets timezone strings. These strings are stored in a 2-dimensional array.
* @param strings The timezone strings as a 2-d array to be copied. (not adopted; caller retains ownership)
* @param rowCount The number of rows (count of first index).
* @param columnCount The number of columns (count of second index).
* @stable ICU 2.0
*/
void setZoneStrings(const UnicodeString* const* strings, int32_t rowCount, int32_t columnCount);
/**
* Get the non-localized date-time pattern characters.
* @return the non-localized date-time pattern characters
* @stable ICU 2.0
*/
static const UChar * U_EXPORT2 getPatternUChars(void);
/**
* Gets localized date-time pattern characters. For example: 'u', 't', etc.
* <p>
* Note: ICU no longer provides localized date-time pattern characters for a locale
* starting ICU 3.8. This method returns the non-localized date-time pattern
* characters unless user defined localized data is set by setLocalPatternChars.
* @param result Output param which will receive the localized date-time pattern characters.
* @return A reference to 'result'.
* @stable ICU 2.0
*/
UnicodeString& getLocalPatternChars(UnicodeString& result) const;
/**
* Sets localized date-time pattern characters. For example: 'u', 't', etc.
* @param newLocalPatternChars the new localized date-time
* pattern characters.
* @stable ICU 2.0
*/
void setLocalPatternChars(const UnicodeString& newLocalPatternChars);
/**
* 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;
/**
* ICU "poor man's RTTI", returns a UClassID for the actual class.
*
* @stable ICU 2.2
*/
virtual UClassID getDynamicClassID() const;
/**
* ICU "poor man's RTTI", returns a UClassID for this class.
*
* @stable ICU 2.2
*/
static UClassID U_EXPORT2 getStaticClassID();
private:
friend class SimpleDateFormat;
friend class DateFormatSymbolsSingleSetter; // see udat.cpp
/**
* Abbreviated era strings. For example: "AD" and "BC".
*/
UnicodeString* fEras;
int32_t fErasCount;
/**
* Era name strings. For example: "Anno Domini" and "Before Christ".
*/
UnicodeString* fEraNames;
int32_t fEraNamesCount;
/**
* Narrow era strings. For example: "A" and "B".
*/
UnicodeString* fNarrowEras;
int32_t fNarrowErasCount;
/**
* Month strings. For example: "January", "February", etc.
*/
UnicodeString* fMonths;
int32_t fMonthsCount;
/**
* Short month strings. For example: "Jan", "Feb", etc.
*/
UnicodeString* fShortMonths;
int32_t fShortMonthsCount;
/**
* Narrow month strings. For example: "J", "F", etc.
*/
UnicodeString* fNarrowMonths;
int32_t fNarrowMonthsCount;
/**
* Standalone Month strings. For example: "January", "February", etc.
*/
UnicodeString* fStandaloneMonths;
int32_t fStandaloneMonthsCount;
/**
* Standalone Short month strings. For example: "Jan", "Feb", etc.
*/
UnicodeString* fStandaloneShortMonths;
int32_t fStandaloneShortMonthsCount;
/**
* Standalone Narrow month strings. For example: "J", "F", etc.
*/
UnicodeString* fStandaloneNarrowMonths;
int32_t fStandaloneNarrowMonthsCount;
/**
* Weekday strings. For example: "Sunday", "Monday", etc.
*/
UnicodeString* fWeekdays;
int32_t fWeekdaysCount;
/**
* Short weekday strings. For example: "Sun", "Mon", etc.
*/
UnicodeString* fShortWeekdays;
int32_t fShortWeekdaysCount;
/**
* Narrow weekday strings. For example: "Sun", "Mon", etc.
*/
UnicodeString* fNarrowWeekdays;
int32_t fNarrowWeekdaysCount;
/**
* Standalone Weekday strings. For example: "Sunday", "Monday", etc.
*/
UnicodeString* fStandaloneWeekdays;
int32_t fStandaloneWeekdaysCount;
/**
* Standalone Short weekday strings. For example: "Sun", "Mon", etc.
*/
UnicodeString* fStandaloneShortWeekdays;
int32_t fStandaloneShortWeekdaysCount;
/**
* Standalone Narrow weekday strings. For example: "Sun", "Mon", etc.
*/
UnicodeString* fStandaloneNarrowWeekdays;
int32_t fStandaloneNarrowWeekdaysCount;
/**
* Ampm strings. For example: "AM" and "PM".
*/
UnicodeString* fAmPms;
int32_t fAmPmsCount;
/**
* Quarter strings. For example: "1st quarter", "2nd quarter", etc.
*/
UnicodeString *fQuarters;
int32_t fQuartersCount;
/**
* Short quarters. For example: "Q1", "Q2", etc.
*/
UnicodeString *fShortQuarters;
int32_t fShortQuartersCount;
/**
* Standalone quarter strings. For example: "1st quarter", "2nd quarter", etc.
*/
UnicodeString *fStandaloneQuarters;
int32_t fStandaloneQuartersCount;
/**
* Standalone short quarter strings. For example: "Q1", "Q2", etc.
*/
UnicodeString *fStandaloneShortQuarters;
int32_t fStandaloneShortQuartersCount;
/**
* The format data of all the timezones in this locale.
*/
UnicodeString **fZoneStrings; // Zone string array set by setZoneStrings
UnicodeString **fLocaleZoneStrings; // Zone string array created by the locale
int32_t fZoneStringsRowCount;
int32_t fZoneStringsColCount;
const ZoneStringFormat *fZoneStringFormat;
ZoneStringFormat *fZSFLocal; // Local ZoneStringFormat instance
SafeZoneStringFormatPtr *fZSFCachePtr; // Cached ZoneStringFormat
Locale fZSFLocale; // Locale used for getting ZoneStringFormat
/**
* Pattern string used for localized time zone GMT format. For example, "GMT{0}"
*/
UnicodeString fGmtFormat;
/**
* Pattern strings used for formatting zone offset in a localized time zone GMT string.
*/
UnicodeString *fGmtHourFormats;
int32_t fGmtHourFormatsCount;
enum GMTHourType {
GMT_NEGATIVE_HMS = 0,
GMT_NEGATIVE_HM,
GMT_POSITIVE_HMS,
GMT_POSITIVE_HM,
GMT_HOUR_COUNT
};
/**
* Localized date-time pattern characters. For example: use 'u' as 'y'.
*/
UnicodeString fLocalPatternChars;
private:
/** valid/actual locale information
* these are always ICU locales, so the length should not be a problem
*/
char validLocale[ULOC_FULLNAME_CAPACITY];
char actualLocale[ULOC_FULLNAME_CAPACITY];
DateFormatSymbols(); // default constructor not implemented
/**
* Called by the constructors to actually load data from the resources
*
* @param locale The locale to get symbols for.
* @param type Calendar Type (as from Calendar::getType())
* @param status Input/output parameter, set to success or
* failure code upon return.
* @param useLastResortData determine if use last resort data
*/
void initializeData(const Locale&, const char *type, UErrorCode& status, UBool useLastResortData = FALSE);
/**
* Copy or alias an array in another object, as appropriate.
*
* @param dstArray the copy destination array.
* @param dstCount fill in with the lenth of 'dstArray'.
* @param srcArray the source array to be copied.
* @param srcCount the length of items to be copied from the 'srcArray'.
*/
static void assignArray(UnicodeString*& dstArray,
int32_t& dstCount,
const UnicodeString* srcArray,
int32_t srcCount);
/**
* Return true if the given arrays' contents are equal, or if the arrays are
* identical (pointers are equal).
*
* @param array1 one array to be compared with.
* @param array2 another array to be compared with.
* @param count the length of items to be copied.
* @return true if the given arrays' contents are equal, or if the arrays are
* identical (pointers are equal).
*/
static UBool arrayCompare(const UnicodeString* array1,
const UnicodeString* array2,
int32_t count);
/**
* Create a copy, in fZoneStrings, of the given zone strings array. The
* member variables fZoneStringsRowCount and fZoneStringsColCount should be
* set already by the caller.
*/
void createZoneStrings(const UnicodeString *const * otherStrings);
/**
* Delete all the storage owned by this object.
*/
void dispose(void);
/**
* Copy all of the other's data to this.
* @param other the object to be copied.
*/
void copyData(const DateFormatSymbols& other);
/**
* Returns a ZoneStringFormat, used only by SimpleDateFormat for now.
*/
const ZoneStringFormat* getZoneStringFormat(void) const;
/**
* Create a ZoneStringFormat by locale if not yet availble
*/
void initZoneStringFormat(void);
/**
* Create zone strings array by locale if not yet available
*/
void initZoneStringsArray(void);
/**
* Delete just the zone strings.
*/
void disposeZoneStrings(void);
};
U_NAMESPACE_END
#endif /* #if !UCONFIG_NO_FORMATTING */
#endif // _DTFMTSYM
//eof
+158
View File
@@ -0,0 +1,158 @@
/*
*******************************************************************************
* Copyright (C) 2008-2009, International Business Machines Corporation and
* others. All Rights Reserved.
*******************************************************************************
*
* File DTINTRV.H
*
*******************************************************************************
*/
#ifndef __DTINTRV_H__
#define __DTINTRV_H__
#include "unicode/utypes.h"
#include "unicode/uobject.h"
/**
* \file
* \brief C++ API: Date Interval data type
*/
U_NAMESPACE_BEGIN
/**
* This class represents a date interval.
* It is a pair of UDate representing from UDate 1 to UDate 2.
* @stable ICU 4.0
**/
class U_COMMON_API DateInterval : public UObject {
public:
/**
* Construct a DateInterval given a from date and a to date.
* @param fromDate The from date in date interval.
* @param toDate The to date in date interval.
* @stable ICU 4.0
*/
DateInterval(UDate fromDate, UDate toDate);
/**
* destructor
* @stable ICU 4.0
*/
virtual ~DateInterval();
/**
* Get the from date.
* @return the from date in dateInterval.
* @stable ICU 4.0
*/
UDate getFromDate() const;
/**
* Get the to date.
* @return the to date in dateInterval.
* @stable ICU 4.0
*/
UDate getToDate() 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.0
*/
static UClassID U_EXPORT2 getStaticClassID(void);
/**
* 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.0
*/
virtual UClassID getDynamicClassID(void) const;
/**
* Copy constructor.
* @stable ICU 4.0
*/
DateInterval(const DateInterval& other);
/**
* Default assignment operator
* @stable ICU 4.0
*/
DateInterval& operator=(const DateInterval&);
/**
* Equality operator.
* @return TRUE if the two DateIntervals are the same
* @stable ICU 4.0
*/
virtual UBool operator==(const DateInterval& other) const;
/**
* Non-equality operator
* @return TRUE if the two DateIntervals are not the same
* @stable ICU 4.0
*/
UBool operator!=(const DateInterval& other) const;
/**
* clone this object.
* The caller owns the result and should delete it when done.
* @return a cloned DateInterval
* @stable ICU 4.0
*/
virtual DateInterval* clone() const;
private:
/**
* Default constructor, not implemented.
*/
DateInterval();
UDate fromDate;
UDate toDate;
} ;// end class DateInterval
inline UDate
DateInterval::getFromDate() const {
return fromDate;
}
inline UDate
DateInterval::getToDate() const {
return toDate;
}
inline UBool
DateInterval::operator!=(const DateInterval& other) const {
return ( !operator==(other) );
}
U_NAMESPACE_END
#endif
+972
View File
@@ -0,0 +1,972 @@
/********************************************************************************
* Copyright (C) 2008-2009, International Business Machines Corporation and others. All Rights Reserved.
*******************************************************************************
*
* File DTITVFMT.H
*
*******************************************************************************
*/
#ifndef __DTITVFMT_H__
#define __DTITVFMT_H__
#include "unicode/utypes.h"
/**
* \file
* \brief C++ API: Format and parse date interval in a language-independent manner.
*/
#if !UCONFIG_NO_FORMATTING
#include "unicode/ucal.h"
#include "unicode/smpdtfmt.h"
#include "unicode/dtintrv.h"
#include "unicode/dtitvinf.h"
#include "unicode/dtptngen.h"
U_NAMESPACE_BEGIN
/**
* DateIntervalFormat is a class for formatting and parsing date
* intervals in a language-independent manner.
* Date interval formatting is supported in Gregorian calendar only.
* And only formatting is supported. Parsing is not supported.
*
* <P>
* Date interval means from one date to another date,
* for example, from "Jan 11, 2008" to "Jan 18, 2008".
* We introduced class DateInterval to represent it.
* DateInterval is a pair of UDate, which is
* the standard milliseconds since 24:00 GMT, Jan 1, 1970.
*
* <P>
* DateIntervalFormat formats a DateInterval into
* text as compactly as possible.
* For example, the date interval format from "Jan 11, 2008" to "Jan 18,. 2008"
* is "Jan 11-18, 2008" for English.
* And it parses text into DateInterval,
* although initially, parsing is not supported.
*
* <P>
* There is no structural information in date time patterns.
* For any punctuations and string literals inside a date time pattern,
* we do not know whether it is just a separator, or a prefix, or a suffix.
* Without such information, so, it is difficult to generate a sub-pattern
* (or super-pattern) by algorithm.
* So, formatting a DateInterval is pattern-driven. It is very
* similar to formatting in SimpleDateFormat.
* We introduce class DateIntervalInfo to save date interval
* patterns, similar to date time pattern in SimpleDateFormat.
*
* <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>
* <li>
* hides the order of fields.
* </li>
* <li>
* might hide a field's pattern letter length.
* </li>
* </ol>
*
* 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.
*
* <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 > hour (in day) > 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 "Jan 10, 2007"
* and "Feb 20, 2008" is year.
*
* <P>
* For other calendar fields, the compact interval formatting is not
* supported. And the interval format will be fall back to fall-back
* patterns, which is mostly "{date0} - {date1}".
*
* <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 "yMMMd",
* in en_US, if the largest different calendar field between date1 and date2
* is "year", the date interval pattern is "MMM d, yyyy - MMM d, yyyy",
* such as "Jan 10, 2007 - Jan 10, 2008".
* If the largest different calendar field between date1 and date2 is "month",
* the date interval pattern is "MMM d - MMM d, yyyy",
* such as "Jan 10 - Feb 10, 2007".
* If the largest different calendar field between date1 and date2 is "day",
* the date interval pattern is ""MMM d-d, yyyy", such as "Jan 10-20, 2007".
*
* 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>
* If a skeleton is not found in a locale's DateIntervalInfo, which means
* the interval patterns for the skeleton is not defined in resource file,
* the interval pattern will falls back to the interval "fallback" pattern
* defined in resource file.
* If the interval "fallback" pattern is not defined, the default fall-back
* is "{date0} - {data1}".
*
* <P>
* For the combination of date and time,
* The rule to generate interval patterns are:
* <ol>
* <li>
* when the year, month, or day differs, falls back to fall-back
* interval pattern, which mostly is the concatenate the two original
* expressions with a separator between,
* For example, interval pattern from "Jan 10, 2007 10:10 am"
* to "Jan 11, 2007 10:10am" is
* "Jan 10, 2007 10:10 am - Jan 11, 2007 10:10am"
* </li>
* <li>
* otherwise, present the date followed by the range expression
* for the time.
* For example, interval pattern from "Jan 10, 2007 10:10 am"
* to "Jan 10, 2007 11:10am" is "Jan 10, 2007 10:10 am - 11:10am"
* </li>
* </ol>
*
*
* <P>
* If two dates are the same, the interval pattern is the single date pattern.
* For example, interval pattern from "Jan 10, 2007" to "Jan 10, 2007" is
* "Jan 10, 2007".
*
* Or if the presenting fields between 2 dates have the exact same values,
* the interval pattern is the single date pattern.
* For example, if user only requests year and month,
* the interval pattern from "Jan 10, 2007" to "Jan 20, 2007" is "Jan 2007".
*
* <P>
* DateIntervalFormat needs the following information for correct
* formatting: time zone, calendar type, pattern, date format symbols,
* and date interval patterns.
* It can be instantiated in 2 ways:
* <ol>
* <li>
* create an instance using default or given locale plus given skeleton.
* Users are encouraged to created date interval formatter this way and
* to use the pre-defined skeleton macros, such as
* UDAT_YEAR_NUM_MONTH, which consists the calendar fields and
* the format style.
* </li>
* <li>
* create an instance using default or given locale plus given skeleton
* plus a given DateIntervalInfo.
* This factory method is for powerful users who want to provide their own
* interval patterns.
* Locale provides the timezone, calendar, and format symbols information.
* Local plus skeleton provides full pattern information.
* DateIntervalInfo provides the date interval patterns.
* </li>
* </ol>
*
* <P>
* For the calendar field pattern letter, such as G, y, M, d, a, h, H, m, s etc.
* DateIntervalFormat uses the same syntax as that of
* DateTime format.
*
* <P>
* Code Sample: general usage
* <pre>
* \code
* // the date interval object which the DateIntervalFormat formats on
* // and parses into
* DateInterval* dtInterval = new DateInterval(1000*3600*24, 1000*3600*24*2);
* UErrorCode status = U_ZERO_ERROR;
* DateIntervalFormat* dtIntervalFmt = DateIntervalFormat::createInstance(
* UDAT_YEAR_MONTH_DAY,
* Locale("en", "GB", ""), status);
* UnicodeUnicodeString dateIntervalString;
* FieldPosition pos = 0;
* // formatting
* dtIntervalFmt->format(dtInterval, dateIntervalUnicodeString, pos, status);
* delete dtIntervalFmt;
* \endcode
* </pre>
*/
class U_I18N_API DateIntervalFormat : public Format {
public:
/**
* Construct a DateIntervalFormat from skeleton and the default locale.
*
* This is a convenient override of
* createInstance(const UnicodeString& skeleton, const Locale& locale,
* UErrorCode&)
* with the value of locale as default locale.
*
* @param skeleton the skeleton on which interval format based.
* @param status output param set to success/failure code on exit
* @return a date time interval formatter which the caller owns.
* @stable ICU 4.0
*/
static DateIntervalFormat* U_EXPORT2 createInstance(
const UnicodeString& skeleton,
UErrorCode& status);
/**
* Construct a DateIntervalFormat from skeleton and a given locale.
* <P>
* In this factory method,
* the date interval pattern information is load from resource files.
* Users are encouraged to created date interval formatter this way and
* to use the pre-defined skeleton macros.
*
* <P>
* There are pre-defined skeletons (defined in udate.h) having predefined
* interval patterns in resource files.
* Users are encouraged to use those macros.
* For example:
* DateIntervalFormat::createInstance(UDAT_MONTH_DAY, status)
*
* The given Locale provides the interval patterns.
* For example, for en_GB, if skeleton is UDAT_YEAR_ABBR_MONTH_WEEKDAY_DAY,
* which is "yMMMEEEd",
* the interval patterns defined in resource file to above skeleton are:
* "EEE, d MMM, yyyy - EEE, d MMM, yyyy" for year differs,
* "EEE, d MMM - EEE, d MMM, yyyy" for month differs,
* "EEE, d - EEE, d MMM, yyyy" for day differs,
* @param skeleton the skeleton on which interval format based.
* @param locale the given locale
* @param status output param set to success/failure code on exit
* @return a date time interval formatter which the caller owns.
* @stable ICU 4.0
*/
static DateIntervalFormat* U_EXPORT2 createInstance(
const UnicodeString& skeleton,
const Locale& locale,
UErrorCode& status);
/**
* Construct a DateIntervalFormat from skeleton
* DateIntervalInfo, and default locale.
*
* This is a convenient override of
* createInstance(const UnicodeString& skeleton, const Locale& locale,
* const DateIntervalInfo& dtitvinf, UErrorCode&)
* with the locale value as default locale.
*
* @param skeleton the skeleton on which interval format based.
* @param dtitvinf the DateIntervalInfo object.
* @param status output param set to success/failure code on exit
* @return a date time interval formatter which the caller owns.
* @stable ICU 4.0
*/
static DateIntervalFormat* U_EXPORT2 createInstance(
const UnicodeString& skeleton,
const DateIntervalInfo& dtitvinf,
UErrorCode& status);
/**
* Construct a DateIntervalFormat from skeleton
* a DateIntervalInfo, and the given locale.
*
* <P>
* In this factory method, user provides its own date interval pattern
* information, instead of using those pre-defined data in resource file.
* This factory method is for powerful users who want to provide their own
* interval patterns.
* <P>
* There are pre-defined skeletons (defined in udate.h) having predefined
* interval patterns in resource files.
* Users are encouraged to use those macros.
* For example:
* DateIntervalFormat::createInstance(UDAT_MONTH_DAY, status)
*
* The DateIntervalInfo provides the interval patterns.
* and the DateIntervalInfo ownership remains to the caller.
*
* User are encouraged to set default interval pattern in DateIntervalInfo
* as well, if they want to set other interval patterns ( instead of
* reading the interval patterns from resource files).
* When the corresponding interval pattern for a largest calendar different
* field is not found ( if user not set it ), interval format fallback to
* the default interval pattern.
* If user does not provide default interval pattern, it fallback to
* "{date0} - {date1}"
*
* @param skeleton the skeleton on which interval format based.
* @param locale the given locale
* @param dtitvinf the DateIntervalInfo object.
* @param status output param set to success/failure code on exit
* @return a date time interval formatter which the caller owns.
* @stable ICU 4.0
*/
static DateIntervalFormat* U_EXPORT2 createInstance(
const UnicodeString& skeleton,
const Locale& locale,
const DateIntervalInfo& dtitvinf,
UErrorCode& status);
/**
* Destructor.
* @stable ICU 4.0
*/
virtual ~DateIntervalFormat();
/**
* Clone this Format object polymorphically. The caller owns the result and
* should delete it when done.
* @return A copy of the object.
* @stable ICU 4.0
*/
virtual Format* clone(void) const;
/**
* 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 true if the given Format objects are semantically equal.
* @stable ICU 4.0
*/
virtual UBool operator==(const Format& other) const;
/**
* Return true if the given Format objects are not semantically equal.
* Objects of different subclasses are considered unequal.
* @param other the object to be compared with.
* @return true if the given Format objects are not semantically equal.
* @stable ICU 4.0
*/
UBool operator!=(const Format& other) const;
/**
* Format an object to produce a string. This method handles Formattable
* objects with a DateInterval type.
* If a the Formattable object type is not a DateInterval,
* then it returns a failing UErrorCode.
*
* @param obj The object to format.
* Must be a DateInterval.
* @param appendTo Output parameter to receive result.
* Result is appended to existing contents.
* @param fieldPosition 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
*/
virtual UnicodeString& format(const Formattable& obj,
UnicodeString& appendTo,
FieldPosition& fieldPosition,
UErrorCode& status) const ;
/**
* Format a DateInterval to produce a string.
*
* @param dtInterval DateInterval to be formatted.
* @param appendTo Output parameter to receive result.
* Result is appended to existing contents.
* @param fieldPosition 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 DateInterval* dtInterval,
UnicodeString& appendTo,
FieldPosition& fieldPosition,
UErrorCode& status) const ;
/**
* Format 2 Calendars to produce a string.
*
* Note: "fromCalendar" and "toCalendar" are not const,
* since calendar is not const in SimpleDateFormat::format(Calendar&),
*
* @param fromCalendar calendar set to the from date in date interval
* to be formatted into date interval string
* @param toCalendar calendar set to the to date in date interval
* to be formatted into date interval string
* @param appendTo Output parameter to receive result.
* Result is appended to existing contents.
* @param fieldPosition On input: an alignment field, if desired.
* On output: the offsets of the alignment field.
* @param status Output param filled with success/failure status.
* Caller needs to make sure it is SUCCESS
* at the function entrance
* @return Reference to 'appendTo' parameter.
* @stable ICU 4.0
*/
UnicodeString& format(Calendar& fromCalendar,
Calendar& toCalendar,
UnicodeString& appendTo,
FieldPosition& fieldPosition,
UErrorCode& status) const ;
/**
* Date interval parsing is not supported. Please do not use.
* <P>
* This method should handle parsing of
* date time interval strings into Formattable objects with
* DateInterval type, which is a pair of UDate.
* <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. Since no parsing
* is supported, upon return this param is unchanged.
* @return A newly created Formattable* object, or NULL
* on failure. The caller owns this and should
* delete it when done.
* @internal ICU 4.0
*/
virtual void parseObject(const UnicodeString& source,
Formattable& result,
ParsePosition& parse_pos) const;
/**
* Gets the date time interval patterns.
* @return the date time interval patterns associated with
* this date interval formatter.
* @stable ICU 4.0
*/
const DateIntervalInfo* getDateIntervalInfo(void) const;
/**
* Set the date time interval patterns.
* @param newIntervalPatterns the given interval patterns to copy.
* @param status output param set to success/failure code on exit
* @stable ICU 4.0
*/
void setDateIntervalInfo(const DateIntervalInfo& newIntervalPatterns,
UErrorCode& status);
/**
* Gets the date formatter
* @return the date formatter associated with this date interval formatter.
* @stable ICU 4.0
*/
const DateFormat* getDateFormat(void) 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.0
*/
static UClassID U_EXPORT2 getStaticClassID(void);
/**
* 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.0
*/
virtual UClassID getDynamicClassID(void) const;
protected:
/**
* Copy constructor.
* @stable ICU 4.0
*/
DateIntervalFormat(const DateIntervalFormat&);
/**
* Assignment operator.
* @stable ICU 4.0
*/
DateIntervalFormat& operator=(const DateIntervalFormat&);
private:
/*
* This is for ICU internal use only. Please do not use.
* Save the interval pattern information.
* Interval pattern consists of 2 single date patterns and the separator.
* For example, interval pattern "MMM d - MMM d, yyyy" consists
* a single date pattern "MMM d", another single date pattern "MMM d, yyyy",
* and a separator "-".
* The pattern is divided into 2 parts. For above example,
* the first part is "MMM d - ", and the second part is "MMM d, yyyy".
* Also, the first date appears in an interval pattern could be
* the earlier date or the later date.
* And such information is saved in the interval pattern as well.
* @internal ICU 4.0
*/
struct PatternInfo {
UnicodeString firstPart;
UnicodeString secondPart;
/**
* Whether the first date in interval pattern is later date or not.
* Fallback format set the default ordering.
* And for a particular interval pattern, the order can be
* overriden by prefixing the interval pattern with "latestFirst:" or
* "earliestFirst:"
* For example, given 2 date, Jan 10, 2007 to Feb 10, 2007.
* if the fallback format is "{0} - {1}",
* and the pattern is "d MMM - d MMM yyyy", the interval format is
* "10 Jan - 10 Feb, 2007".
* If the pattern is "latestFirst:d MMM - d MMM yyyy",
* the interval format is "10 Feb - 10 Jan, 2007"
*/
UBool laterDateFirst;
};
/**
* default constructor
* @internal ICU 4.0
*/
DateIntervalFormat();
/**
* Construct a DateIntervalFormat from DateFormat,
* a DateIntervalInfo, and skeleton.
* DateFormat provides the timezone, calendar,
* full pattern, and date format symbols information.
* It should be a SimpleDateFormat object which
* has a pattern in it.
* the DateIntervalInfo provides the interval patterns.
*
* Note: the DateIntervalFormat takes ownership of both
* DateFormat and DateIntervalInfo objects.
* Caller should not delete them.
*
* @param locale the locale of this date interval formatter.
* @param dtitvinf the DateIntervalInfo object to be adopted.
* @param skeleton the skeleton of the date formatter
* @param status output param set to success/failure code on exit
* @internal ICU 4.0
*/
DateIntervalFormat(const Locale& locale, DateIntervalInfo* dtItvInfo,
const UnicodeString* skeleton, UErrorCode& status);
/**
* Construct a DateIntervalFormat from DateFormat
* and a DateIntervalInfo.
*
* It is a wrapper of the constructor.
*
* @param locale the locale of this date interval formatter.
* @param dtitvinf the DateIntervalInfo object to be adopted.
* @param skeleton the skeleton of this formatter.
* @param status Output param set to success/failure code.
* @return a date time interval formatter which the caller owns.
* @internal ICU 4.0
*/
static DateIntervalFormat* U_EXPORT2 create(const Locale& locale,
DateIntervalInfo* dtitvinf,
const UnicodeString* skeleton,
UErrorCode& status);
/**
* Create a simple date/time formatter from skeleton, given locale,
* and date time pattern generator.
*
* @param skeleton the skeleton on which date format based.
* @param locale the given locale.
* @param dtpng the date time pattern generator.
* @param status Output param to be set to success/failure code.
* If it is failure, the returned date formatter will
* be NULL.
* @return a simple date formatter which the caller owns.
* @internal ICU 4.0
*/
static SimpleDateFormat* U_EXPORT2 createSDFPatternInstance(
const UnicodeString& skeleton,
const Locale& locale,
DateTimePatternGenerator* dtpng,
UErrorCode& status);
/**
* Below are for generating interval patterns local to the formatter
*/
/**
* Format 2 Calendars using fall-back interval pattern
*
* The full pattern used in this fall-back format is the
* full pattern of the date formatter.
*
* @param fromCalendar calendar set to the from date in date interval
* to be formatted into date interval string
* @param toCalendar calendar set to the to date in date interval
* to be formatted into date interval string
* @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
* @return Reference to 'appendTo' parameter.
* @internal ICU 4.0
*/
UnicodeString& fallbackFormat(Calendar& fromCalendar,
Calendar& toCalendar,
UnicodeString& appendTo,
FieldPosition& pos,
UErrorCode& status) const;
/**
* Initialize interval patterns locale to this formatter
*
* This code is a bit complicated since
* 1. the interval patterns saved in resource bundle files are interval
* patterns based on date or time only.
* It does not have interval patterns based on both date and time.
* Interval patterns on both date and time are algorithm generated.
*
* For example, it has interval patterns on skeleton "dMy" and "hm",
* but it does not have interval patterns on skeleton "dMyhm".
*
* The rule to generate interval patterns for both date and time skeleton are
* 1) when the year, month, or day differs, concatenate the two original
* expressions with a separator between,
* For example, interval pattern from "Jan 10, 2007 10:10 am"
* to "Jan 11, 2007 10:10am" is
* "Jan 10, 2007 10:10 am - Jan 11, 2007 10:10am"
*
* 2) otherwise, present the date followed by the range expression
* for the time.
* For example, interval pattern from "Jan 10, 2007 10:10 am"
* to "Jan 10, 2007 11:10am" is
* "Jan 10, 2007 10:10 am - 11:10am"
*
* 2. even a pattern does not request a certain calendar field,
* the interval pattern needs to include such field if such fields are
* different between 2 dates.
* For example, a pattern/skeleton is "hm", but the interval pattern
* includes year, month, and date when year, month, and date differs.
*
*
* @param status output param set to success/failure code on exit
* @internal ICU 4.0
*/
void initializePattern(UErrorCode& status);
/**
* Set fall back interval pattern given a calendar field,
* a skeleton, and a date time pattern generator.
* @param field the largest different calendar field
* @param skeleton a skeleton
* @param status output param set to success/failure code on exit
* @internal ICU 4.0
*/
void setFallbackPattern(UCalendarDateFields field,
const UnicodeString& skeleton,
UErrorCode& status);
/**
* get separated date and time skeleton from a combined skeleton.
*
* The difference between date skeleton and normalizedDateSkeleton are:
* 1. both 'y' and 'd' are appeared only once in normalizeDateSkeleton
* 2. 'E' and 'EE' are normalized into 'EEE'
* 3. 'MM' is normalized into 'M'
*
** the difference between time skeleton and normalizedTimeSkeleton are:
* 1. both 'H' and 'h' are normalized as 'h' in normalized time skeleton,
* 2. 'a' is omitted in normalized time skeleton.
* 3. there is only one appearance for 'h', 'm','v', 'z' in normalized time
* skeleton
*
*
* @param skeleton given combined skeleton.
* @param date Output parameter for date only skeleton.
* @param normalizedDate Output parameter for normalized date only
*
* @param time Output parameter for time only skeleton.
* @param normalizedTime Output parameter for normalized time only
* skeleton.
*
* @internal ICU 4.0
*/
static void U_EXPORT2 getDateTimeSkeleton(const UnicodeString& skeleton,
UnicodeString& date,
UnicodeString& normalizedDate,
UnicodeString& time,
UnicodeString& normalizedTime);
/**
* Generate date or time interval pattern from resource,
* and set them into the interval pattern locale to this formatter.
*
* It needs to handle the following:
* 1. need to adjust field width.
* For example, the interval patterns saved in DateIntervalInfo
* includes "dMMMy", but not "dMMMMy".
* Need to get interval patterns for dMMMMy from dMMMy.
* Another example, the interval patterns saved in DateIntervalInfo
* includes "hmv", but not "hmz".
* Need to get interval patterns for "hmz' from 'hmv'
*
* 2. there might be no pattern for 'y' differ for skeleton "Md",
* in order to get interval patterns for 'y' differ,
* need to look for it from skeleton 'yMd'
*
* @param dateSkeleton normalized date skeleton
* @param timeSkeleton normalized time skeleton
* @return whether the resource is found for the skeleton.
* TRUE if interval pattern found for the skeleton,
* FALSE otherwise.
* @internal ICU 4.0
*/
UBool setSeparateDateTimePtn(const UnicodeString& dateSkeleton,
const UnicodeString& timeSkeleton);
/**
* Generate interval pattern from existing resource
*
* It not only save the interval patterns,
* but also return the extended skeleton and its best match skeleton.
*
* @param field largest different calendar field
* @param skeleton skeleton
* @param bestSkeleton the best match skeleton which has interval pattern
* defined in resource
* @param differenceInfo the difference between skeleton and best skeleton
* 0 means the best matched skeleton is the same as input skeleton
* 1 means the fields are the same, but field width are different
* 2 means the only difference between fields are v/z,
* -1 means there are other fields difference
*
* @param extendedSkeleton extended skeleton
* @param extendedBestSkeleton extended best match skeleton
* @return whether the interval pattern is found
* through extending skeleton or not.
* TRUE if interval pattern is found by
* extending skeleton, FALSE otherwise.
* @internal ICU 4.0
*/
UBool setIntervalPattern(UCalendarDateFields field,
const UnicodeString* skeleton,
const UnicodeString* bestSkeleton,
int8_t differenceInfo,
UnicodeString* extendedSkeleton = NULL,
UnicodeString* extendedBestSkeleton = NULL);
/**
* Adjust field width in best match interval pattern to match
* the field width in input skeleton.
*
* TODO (xji) make a general solution
* The adjusting rule can be:
* 1. always adjust
* 2. never adjust
* 3. default adjust, which means adjust according to the following rules
* 3.1 always adjust string, such as MMM and MMMM
* 3.2 never adjust between string and numeric, such as MM and MMM
* 3.3 always adjust year
* 3.4 do not adjust 'd', 'h', or 'm' if h presents
* 3.5 do not adjust 'M' if it is numeric(?)
*
* Since date interval format is well-formed format,
* date and time skeletons are normalized previously,
* till this stage, the adjust here is only "adjust strings, such as MMM
* and MMMM, EEE and EEEE.
*
* @param inputSkeleton the input skeleton
* @param bestMatchSkeleton the best match skeleton
* @param bestMatchIntervalpattern the best match interval pattern
* @param differenceInfo the difference between 2 skeletons
* 1 means only field width differs
* 2 means v/z exchange
* @param adjustedIntervalPattern adjusted interval pattern
* @internal ICU 4.0
*/
static void U_EXPORT2 adjustFieldWidth(
const UnicodeString& inputSkeleton,
const UnicodeString& bestMatchSkeleton,
const UnicodeString& bestMatchIntervalPattern,
int8_t differenceInfo,
UnicodeString& adjustedIntervalPattern);
/**
* Concat a single date pattern with a time interval pattern,
* set it into the intervalPatterns, while field is time field.
* This is used to handle time interval patterns on skeleton with
* both time and date. Present the date followed by
* the range expression for the time.
* @param format date and time format
* @param formatLen format string length
* @param datePattern date pattern
* @param field time calendar field: AM_PM, HOUR, MINUTE
* @param status output param set to success/failure code on exit
* @internal ICU 4.0
*/
void concatSingleDate2TimeInterval(const UChar* format,
int32_t formatLen,
const UnicodeString& datePattern,
UCalendarDateFields field,
UErrorCode& status);
/**
* check whether a calendar field present in a skeleton.
* @param field calendar field need to check
* @param skeleton given skeleton on which to check the calendar field
* @return true if field present in a skeleton.
* @internal ICU 4.0
*/
static UBool U_EXPORT2 fieldExistsInSkeleton(UCalendarDateFields field,
const UnicodeString& skeleton);
/**
* Split interval patterns into 2 part.
* @param intervalPattern interval pattern
* @return the index in interval pattern which split the pattern into 2 part
* @internal ICU 4.0
*/
static int32_t U_EXPORT2 splitPatternInto2Part(const UnicodeString& intervalPattern);
/**
* Break interval patterns as 2 part and save them into pattern info.
* @param field calendar field
* @param intervalPattern interval pattern
* @internal ICU 4.0
*/
void setIntervalPattern(UCalendarDateFields field,
const UnicodeString& intervalPattern);
/**
* Break interval patterns as 2 part and save them into pattern info.
* @param field calendar field
* @param intervalPattern interval pattern
* @param laterDateFirst whether later date appear first in interval pattern
* @internal ICU 4.0
*/
void setIntervalPattern(UCalendarDateFields field,
const UnicodeString& intervalPattern,
UBool laterDateFirst);
/**
* Set pattern information.
*
* @param field calendar field
* @param firstPart the first part in interval pattern
* @param secondPart the second part in interval pattern
* @param laterDateFirst whether the first date in intervalPattern
* is earlier date or later date
* @internal ICU 4.0
*/
void setPatternInfo(UCalendarDateFields field,
const UnicodeString* firstPart,
const UnicodeString* secondpart,
UBool laterDateFirst);
// from calendar field to pattern letter
static const UChar fgCalendarFieldToPatternLetter[];
/**
* The interval patterns for this locale.
*/
DateIntervalInfo* fInfo;
/**
* The DateFormat object used to format single pattern
*/
SimpleDateFormat* fDateFormat;
/**
* The 2 calendars with the from and to date.
* could re-use the calendar in fDateFormat,
* but keeping 2 calendars make it clear and clean.
*/
Calendar* fFromCalendar;
Calendar* fToCalendar;
/**
* Date time pattern generator
*/
DateTimePatternGenerator* fDtpng;
/**
* Following are interval information relavent (locale) to this formatter.
*/
UnicodeString fSkeleton;
PatternInfo fIntervalPatterns[DateIntervalInfo::kIPI_MAX_INDEX];
};
inline UBool
DateIntervalFormat::operator!=(const Format& other) const {
return !operator==(other);
}
U_NAMESPACE_END
#endif /* #if !UCONFIG_NO_FORMATTING */
#endif // _DTITVFMT_H__
//eof
+528
View File
@@ -0,0 +1,528 @@
/*
*******************************************************************************
* Copyright (C) 2008-2009, International Business Machines Corporation and
* others. All Rights Reserved.
*******************************************************************************
*
* File DTITVINF.H
*
*******************************************************************************
*/
#ifndef __DTITVINF_H__
#define __DTITVINF_H__
#include "unicode/utypes.h"
/**
* \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"
//#include "dtitv_impl.h"
/**
* @internal ICU 4.0
*/
union UHashTok;
U_NAMESPACE_BEGIN
U_CDECL_BEGIN
/**
* @internal ICU 4.0
*/
UBool U_CALLCONV dtitvinfHashTableValueComparator(UHashTok val1, UHashTok val2) ;
U_CDECL_END
/**
* 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 manupulating 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 "Jan 10, 2007"
* and "Feb 20, 2008" 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 "yMMMd",
* in en_US, if the largest different calendar field between date1 and date2
* is "year", the date interval pattern is "MMM d, yyyy - MMM d, yyyy",
* such as "Jan 10, 2007 - Jan 10, 2008".
* If the largest different calendar field between date1 and date2 is "month",
* the date interval pattern is "MMM d - MMM d, yyyy",
* such as "Jan 10 - Feb 10, 2007".
* If the largest different calendar field between date1 and date2 is "day",
* the date interval pattern is ""MMM d-d, yyyy", such as "Jan 10-20, 2007".
*
* 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 "{0} - {1}", it means
* the first date in the interval pattern for this locale is earlier date.
* If the fallback format is "{1} - {0}", it means the first date is the
* later date.
* For a particular interval pattern, the default order can be overriden
* by prefixing "latestFirst:" or "earliestFirst:" to the interval pattern.
* For example, if the fallback format is "{0}-{1}",
* but for skeleton "yMMMd", the interval pattern when day is different is
* "latestFirst:d-d MMM yy", it means by default, the first date in interval
* pattern is the earlier date. But for skeleton "yMMMd", when day is different,
* the first date in "d-d MMM yy" 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, and MINUTE.
* 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.
* To ICU 4.0, date interval patterns are only supported in Gregorian calendar.
* @stable ICU 4.0
**/
class U_I18N_API DateIntervalInfo : 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 Gregorian
* calendar data 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(void) 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 UBool 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
*/
UBool 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, and MINUTE.
* 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;
/**
* 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;
friend UBool U_CALLCONV dtitvinfHashTableValueComparator(UHashTok val1, UHashTok val2) ;
/**
* Following is for saving the interval patterns.
* We only support interval patterns on
* ERA, YEAR, MONTH, DAY, AM_PM, HOUR, and MINUTE
*/
enum IntervalPatternIndex
{
kIPI_ERA,
kIPI_YEAR,
kIPI_MONTH,
kIPI_DATE,
kIPI_AM_PM,
kIPI_HOUR,
kIPI_MINUTE,
kIPI_MAX_INDEX
};
/**
* Initialize the DateIntervalInfo from locale
* @param locale the given locale.
* @param status output param set to success/failure code on exit
* @internal ICU 4.0
*/
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
* @internal ICU 4.0
*/
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 funtionality 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
* @internal ICU 4.0
*/
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
* @internal ICU 4.0
*/
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.
* @internal ICU 4.0
*/
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, and MINUTE,
* 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
* @internal ICU 4.0
*/
static IntervalPatternIndex U_EXPORT2 calendarFieldToIntervalIndex(
UCalendarDateFields field,
UErrorCode& status);
/**
* delete hash table (of type fIntervalPatterns).
*
* @param hTable hash table to be deleted
* @internal ICU 4.0
*/
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
* @internal ICU 4.0
*/
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
* @internal ICU 4.0
*/
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 UBool
DateIntervalInfo::operator!=(const DateIntervalInfo& other) const {
return !operator==(other);
}
U_NAMESPACE_END
#endif
#endif
+423
View File
@@ -0,0 +1,423 @@
/*
*******************************************************************************
* Copyright (C) 2007-2009, International Business Machines Corporation and
* others. All Rights Reserved.
*******************************************************************************
*
* File DTPTNGEN.H
*
*******************************************************************************
*/
#ifndef __DTPTNGEN_H__
#define __DTPTNGEN_H__
#include "unicode/datefmt.h"
#include "unicode/locid.h"
#include "unicode/udat.h"
#include "unicode/udatpg.h"
U_NAMESPACE_BEGIN
/**
* \file
* \brief C++ API: Date/Time Pattern Generator
*/
class Hashtable;
class FormatParser;
class DateTimeMatcher;
class DistanceInfo;
class PatternMap;
class PtnSkeleton;
/**
* 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);
/**
* 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
*/
UBool 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
*/
UBool 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 3.8
*/
UnicodeString getSkeleton(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).
*
* @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 "Md"
* @stable ICU 3.8
*/
UnicodeString getBaseSkeleton(const UnicodeString& pattern, UErrorCode& 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 overriden. 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.
*
* @param field such as UDATPG_ERA_FIELD.
* @return name for field
* @stable ICU 3.8
*/
const UnicodeString& getAppendItemName(UDateTimePatternField field) const;
/**
* The date time format is a message format pattern used to compose date and
* time patterns. The default value is "{0} {1}", where {0} will be replaced
* by the date pattern and {1} will be replaced by the time pattern.
* <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 "{0} {1}". 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".
*
* @param dateTimeFormat
* message format pattern, here {0} will be replaced by the date
* pattern and {1} will be replaced by the time pattern.
* @stable ICU 3.8
*/
void setDateTimeFormat(const UnicodeString& dateTimeFormat);
/**
* Getter corresponding to setDateTimeFormat.
* @return DateTimeFormat.
* @stable ICU 3.8
*/
const UnicodeString& getDateTimeFormat() const;
/**
* 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);
/**
* 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);
/**
* 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;
/**
* 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);
/**
* 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;
/**
* ICU "poor man's RTTI", returns a UClassID for the actual class.
*
* @stable ICU 3.8
*/
virtual UClassID getDynamicClassID() const;
/**
* ICU "poor man's RTTI", returns a UClassID for this class.
*
* @stable ICU 3.8
*/
static UClassID U_EXPORT2 getStaticClassID(void);
private:
/**
* Constructor.
* @stable ICU 3.8
*/
DateTimePatternGenerator(UErrorCode & status);
/**
* Constructor.
* @stable ICU 3.8
*/
DateTimePatternGenerator(const Locale& locale, UErrorCode & status);
/**
* Copy constructor.
* @param other DateTimePatternGenerator to copy
* @stable ICU 3.8
*/
DateTimePatternGenerator(const DateTimePatternGenerator& other);
/**
* Default assignment operator.
* @param other DateTimePatternGenerator to copy
* @stable ICU 3.8
*/
DateTimePatternGenerator& operator=(const DateTimePatternGenerator& other);
Locale pLocale; // pattern locale
FormatParser *fp;
DateTimeMatcher* dtMatcher;
DistanceInfo *distanceInfo;
PatternMap *patternMap;
UnicodeString appendItemFormats[UDATPG_FIELD_COUNT];
UnicodeString appendItemNames[UDATPG_FIELD_COUNT];
UnicodeString dateTimeFormat;
UnicodeString decimal;
DateTimeMatcher *skipMatcher;
Hashtable *fAvailableFormatKeyHash;
UnicodeString hackPattern;
UnicodeString emptyString;
UChar fDefaultHourFormatChar;
void initData(const Locale &locale, UErrorCode &status);
void addCanonicalItems();
void addICUPatterns(const Locale& locale, UErrorCode& status);
void hackTimes(const UnicodeString& hackPattern, 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;
UDateTimePatternField getAppendNameNumber(const char* field) const;
void getAppendName(UDateTimePatternField field, UnicodeString& value);
int32_t getCanonicalIndex(const UnicodeString& field);
const UnicodeString* getBestRaw(DateTimeMatcher& source, int32_t includeMask, DistanceInfo* missingFields, const PtnSkeleton** specifiedSkeletonPtr = 0);
UnicodeString adjustFieldTypes(const UnicodeString& pattern, const PtnSkeleton* specifiedSkeleton, UBool fixFractionalSeconds);
UnicodeString getBestAppending(int32_t missingFields);
int32_t getTopBitNumber(int32_t foundMask);
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;
} ;// end class DateTimePatternGenerator
U_NAMESPACE_END
#endif
+250
View File
@@ -0,0 +1,250 @@
/*
*******************************************************************************
* Copyright (C) 2007-2008, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
*/
#ifndef DTRULE_H
#define DTRULE_H
#include "unicode/utypes.h"
/**
* \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 occurence of the day of week,
for example, 2nd Sunday in March. */
DOW_GEQ_DOM, /**< The first occurence 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 occurence 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 oridinal
* 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(void) 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
*/
UBool 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
*/
UBool 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(void) 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(void) const;
/**
* Gets the rule month.
* @return The rule month.
* @stable ICU 3.8
*/
int32_t getRuleMonth(void) 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(void) 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(void) const;
/**
* Gets the ordinal number of the occurence 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(void) 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(void) 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(void);
/**
* 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(void) const;
};
U_NAMESPACE_END
#endif /* #if !UCONFIG_NO_FORMATTING */
#endif // DTRULE_H
//eof
+128
View File
@@ -0,0 +1,128 @@
/*
*******************************************************************************
*
* Copyright (C) 2009, International Business Machines
* Corporation and others. All Rights Reserved.
*
*******************************************************************************
* file name: errorcode.h
* encoding: US-ASCII
* tab size: 8 (not used)
* indentation:4
*
* created on: 2009mar10
* created by: Markus W. Scherer
*/
#ifndef __ERRORCODE_H__
#define __ERRORCODE_H__
/**
* \file
* \brief C++ API: ErrorCode class intended to make it easier to use
* ICU C and C++ APIs from C++ user code.
*/
#include "unicode/utypes.h"
#include "unicode/uobject.h"
U_NAMESPACE_BEGIN
/**
* Wrapper class for UErrorCode, with conversion operators for direct use
* in ICU C and C++ APIs.
* Intended to be used as a base class, where a subclass overrides
* the handleFailure() function so that it throws an exception,
* does an assert(), logs an error, etc.
* This is not an abstract base class. This class can be used and instantiated
* by itself, although it will be more useful when subclassed.
*
* Features:
* - The constructor initializes the internal UErrorCode to U_ZERO_ERROR,
* removing one common source of errors.
* - Same use in C APIs taking a UErrorCode * (pointer)
* and C++ taking UErrorCode & (reference) via conversion operators.
* - Possible automatic checking for success when it goes out of scope.
*
* Note: For automatic checking for success in the destructor, a subclass
* must implement such logic in its own destructor because the base class
* destructor cannot call a subclass function (like handleFailure()).
* The ErrorCode base class destructor does nothing.
*
* Note also: While it is possible for a destructor to throw an exception,
* it is generally unsafe to do so. This means that in a subclass the destructor
* and the handleFailure() function may need to take different actions.
*
* Sample code:
* \code
* class IcuErrorCode: public icu::ErrorCode {
* public:
* virtual ~IcuErrorCode() {
* // Safe because our handleFailure() does not throw exceptions.
* if(isFailure()) { handleFailure(); }
* }
* protected:
* virtual handleFailure() {
* log_failure(u_errorName(errorCode));
* exit(errorCode);
* }
* };
* IcuErrorCode error_code;
* UConverter *cnv = ucnv_open("Shift-JIS", error_code);
* length = ucnv_fromUChars(dest, capacity, src, length, error_code);
* ucnv_close(cnv);
* // IcuErrorCode destructor checks for success.
* \endcode
*
* @draft ICU 4.2
*/
class U_COMMON_API ErrorCode: public UMemory {
public:
/**
* Default constructor. Initializes its UErrorCode to U_ZERO_ERROR.
* @draft ICU 4.2
*/
ErrorCode() : errorCode(U_ZERO_ERROR) {}
/** Destructor, does nothing. See class documentation for details. @draft ICU 4.2 */
virtual ~ErrorCode() {}
/** Conversion operator, returns a reference. @draft ICU 4.2 */
operator UErrorCode & () { return errorCode; }
/** Conversion operator, returns a pointer. @draft ICU 4.2 */
operator UErrorCode * () { return &errorCode; }
/** Tests for U_SUCCESS(). @draft ICU 4.2 */
UBool isSuccess() const { return U_SUCCESS(errorCode); }
/** Tests for U_FAILURE(). @draft ICU 4.2 */
UBool isFailure() const { return U_FAILURE(errorCode); }
/** Returns the UErrorCode value. @draft ICU 4.2 */
UErrorCode get() const { return errorCode; }
/** Sets the UErrorCode value. @draft ICU 4.2 */
void set(UErrorCode value) { errorCode=value; }
/** Returns the UErrorCode value and resets it to U_ZERO_ERROR. @draft ICU 4.2 */
UErrorCode reset();
/**
* Checks for a failure code:
* \code
* if(isFailure()) { handleFailure(); }
* \endcode
* @draft ICU 4.2
*/
void check() const;
protected:
/**
* Internal UErrorCode, accessible to subclasses.
* @draft ICU 4.2
*/
UErrorCode errorCode;
/**
* Called by check() if isFailure() is true.
* A subclass should override this function to deal with a failure code:
* Throw an exception, log an error, terminate the program, or similar.
* @draft ICU 4.2
*/
virtual void handleFailure() const {}
};
U_NAMESPACE_END
#endif // __ERRORCODE_H__
+291
View File
@@ -0,0 +1,291 @@
/*
********************************************************************************
* 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"
/**
* \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 suitable for 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. Do not subclass.
*/
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
*/
UBool 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
*/
UBool operator!=(const FieldPosition& that) const;
/**
* Clone this object.
* Clones can be used concurrently in multiple threads.
* If an error occurs, then NULL 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(void) 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(void) 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(void) 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;
/**
* 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 UBool
FieldPosition::operator==(const FieldPosition& copy) const
{
return (fField == copy.fField &&
fEndIndex == copy.fEndIndex &&
fBeginIndex == copy.fBeginIndex);
}
inline UBool
FieldPosition::operator!=(const FieldPosition& copy) const
{
return !operator==(copy);
}
U_NAMESPACE_END
#endif /* #if !UCONFIG_NO_FORMATTING */
#endif // _FIELDPOS
//eof
+591
View File
@@ -0,0 +1,591 @@
/*
********************************************************************************
* Copyright (C) 1997-2006, 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"
#include "unicode/unistr.h"
/**
* \file
* \brief C++ API: Formattable is a thin wrapper for primitive numeric types.
*/
#if !UCONFIG_NO_FORMATTING
U_NAMESPACE_BEGIN
/**
* 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.
*/
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 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
*/
UBool 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
*/
UBool 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 NULL 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(void) 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(void) const { return fValue.fDouble; }
/**
* Gets the double value of this object. If this object is of type
* long or int64 then a casting conversion is peformed, 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(void) const { return (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 casting conversion is peformed, 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(void) const { return fValue.fInt64; }
/**
* Gets the int64 value of this object. If this object is of type
* kDouble 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
* peformed, 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(void) 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(void);
/**
* 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 NULL.
* @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 NULL if this object does not contain a UObject.
* @return a UObject pointer, or NULL
* @stable ICU 3.0
*/
const UObject* getObject() const;
/**
* 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);
/**
* ICU "poor man's RTTI", returns a UClassID for the actual class.
*
* @stable ICU 2.2
*/
virtual UClassID getDynamicClassID() const;
/**
* ICU "poor man's RTTI", returns a UClassID for this class.
*
* @stable ICU 2.2
*/
static UClassID U_EXPORT2 getStaticClassID();
/**
* 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;
private:
/**
* Cleans up the memory for unwanted values. For example, the adopted
* string or array objects.
*/
void dispose(void);
UnicodeString* getBogus() const;
union {
UObject* fObject;
UnicodeString* fString;
double fDouble;
int64_t fInt64;
UDate fDate;
struct {
Formattable* fArray;
int32_t fCount;
} fArrayAndCount;
} fValue;
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(void) const {
return *fValue.fString;
}
inline UnicodeString& Formattable::getString(void) {
return *fValue.fString;
}
inline int32_t Formattable::getLong(UErrorCode* status) const {
return getLong(*status);
}
U_NAMESPACE_END
#endif /* #if !UCONFIG_NO_FORMATTING */
#endif //_FMTABLE
//eof
+296
View File
@@ -0,0 +1,296 @@
/*
********************************************************************************
* Copyright (C) 1997-2006, 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"
/**
* \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/parsepos.h"
#include "unicode/parseerr.h"
#include "unicode/locid.h"
U_NAMESPACE_BEGIN
/**
* 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
* retured 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 UBool 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
*/
UBool 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;
/**
* 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;
/**
* Returns a unique class ID POLYMORPHICALLY. Pure virtual method.
* 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.
* Concrete subclasses of Format must implement getDynamicClassID()
*
* @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 = 0;
/** 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;
/** 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;
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 occured
* @param parseError The UParseError object to fill in
* @stable ICU 2.4
*/
static void syntaxError(const UnicodeString& pattern,
int32_t pos,
UParseError& parseError);
private:
char actualLocale[ULOC_FULLNAME_CAPACITY];
char validLocale[ULOC_FULLNAME_CAPACITY];
};
U_NAMESPACE_END
#endif /* #if !UCONFIG_NO_FORMATTING */
#endif // _FORMAT
//eof
+823
View File
@@ -0,0 +1,823 @@
/*
* Copyright (C) 1997-2009, 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 !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);
* // if no ids were returned, something is wrong. get out.
* if (ids == 0 || ids->count(success) == 0) {
* return;
* }
*
* // begin output
* cout << "Current Time" << endl;
*
* // create a Pacific Standard Time time zone
* SimpleTimeZone* pdt = new SimpleTimeZone(-8 * 60 * 60 * 1000, ids->unext(NULL, 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 occured. 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 Calendar* clone(void) const;
/**
* 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(void) 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;
/**
* (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);
/**
* (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);
/**
* 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;
/**
* 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;
/**
* 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.
* @return the maximum value that this field could have, given the current date.
* @deprecated ICU 2.6. Use getActualMaximum(UCalendarDateFields field) instead.
*/
int32_t getActualMaximum(EDateFields field) const;
/**
* 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;
/**
* (Overrides Calendar) Return true if the current date for this Calendar is in
* Daylight Savings Time. Recognizes DST_OFFSET, if it is set.
*
* @param status Fill-in parameter which receives the status of this operation.
* @return True if the current date for this Calendar is in Daylight Savings Time,
* false, otherwise.
* @stable ICU 2.0
*/
virtual UBool inDaylightTime(UErrorCode& status) const;
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(void) const;
/**
* 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(void);
/**
* Get the calendar type, "gregorian", for use in DateFormatSymbols.
*
* @return calendar type
* @internal
*/
virtual const char * getType() const;
protected:
/**
* (Overrides Calendar) Converts GMT as milliseconds to time field values.
* @param status Fill-in parameter which receives the status of this operation.
* @stable ICU 2.0
*/
private:
GregorianCalendar(); // 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
* @return the Julian day number of the day before the first
* day of the given month and year
* @internal
*/
virtual int32_t handleComputeMonthStart(int32_t eyear, int32_t month,
UBool useMonth) const;
/**
* 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
* @return julian day specified by calendar fields.
* @internal
*/
virtual int32_t handleComputeJulianDay(UCalendarDateFields bestField) ;
/**
* 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) const;
/**
* 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) const;
/**
* return the length of the given month.
* @param month the given month.
* @return the length of the given month.
* @internal
*/
virtual int32_t monthLength(int32_t month) 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;
/**
* return the length of the given year.
* @param year the given year.
* @return the length of the given year.
* @internal
*/
int32_t yearLength(int32_t year) const;
/**
* return the length of the year field.
* @return the length of the year field
* @internal
*/
int32_t yearLength(void) const;
/**
* After adjustments such as add(MONTH), add(YEAR), we don't want the
* month to jump around. E.g., we don't want Jan 31 + 1 month to go to Mar
* 3, we want it to go to Feb 28. Adjustments which might run into this
* problem call this method to retain the proper month.
* @internal
*/
void pinDayOfMonth(void);
/**
* 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;
/**
* 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.
* @return the extended year
* @internal
*/
virtual int32_t handleGetExtendedYear();
/**
* 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);
/**
* 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);
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(void) 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.
* @internal
*/
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;
/**
* The year of the gregorianCutover, with 0 representing
* 1 BC, -1 representing 2 BC, etc.
*/
int32_t fGregorianCutoverJulianDay;// = 2299161;
/**
* 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
/**
* @internal
* @return TRUE if this calendar has the notion of a default century
*/
virtual UBool haveDefaultCentury() const;
/**
* @internal
* @return the start of the default century
*/
virtual UDate defaultCenturyStart() const;
/**
* @internal
* @return the beginning year of the default century
*/
virtual int32_t defaultCenturyStartYear() const;
private:
/**
* The system maintains a static default century start date. This is initialized
* the first time it is used. Before then, it is set to SYSTEM_DEFAULT_CENTURY to
* indicate an uninitialized state. Once the system default century date and year
* are set, they do not change.
*/
static UDate fgSystemDefaultCenturyStart;
/**
* See documentation for systemDefaultCenturyStart.
*/
static int32_t fgSystemDefaultCenturyStartYear;
/**
* Default value that indicates the defaultCenturyStartYear is unitialized
*/
static const int32_t fgSystemDefaultCenturyYear;
/**
* Default value that indicates the UDate of the beginning of the system default century
*/
static const UDate fgSystemDefaultCentury;
/**
* Returns the beginning date of the 100-year window that dates with 2-digit years
* are considered to fall within.
* @return the beginning date of the 100-year window that dates with 2-digit years
* are considered to fall within.
*/
UDate internalGetDefaultCenturyStart(void) const;
/**
* Returns the first year of the 100-year window that dates with 2-digit years
* are considered to fall within.
* @return the first year of the 100-year window that dates with 2-digit years
* are considered to fall within.
*/
int32_t internalGetDefaultCenturyStartYear(void) const;
/**
* Initializes the 100-year window that dates with 2-digit years are considered
* to fall within so that its start date is 80 years before the current time.
*/
static void initializeSystemDefaultCentury(void);
};
U_NAMESPACE_END
#endif /* #if !UCONFIG_NO_FORMATTING */
#endif // _GREGOCAL
//eof
+765
View File
@@ -0,0 +1,765 @@
/*
******************************************************************************
*
* Copyright (C) 1996-2006, International Business Machines
* Corporation and others. All Rights Reserved.
*
******************************************************************************
*
* File locid.h
*
* Created by: Helena Shih
*
* Modification History:
*
* Date Name Description
* 02/11/97 aliu Changed gLocPath to fgLocPath and added methods to
* get and set it.
* 04/02/97 aliu Made operator!= inline; fixed return value of getName().
* 04/15/97 aliu Cleanup for AIX/Win32.
* 04/24/97 aliu Numerous changes per code review.
* 08/18/98 stephen Added tokenizeString(),changed getDisplayName()
* 09/08/98 stephen Moved definition of kEmptyString for Mac Port
* 11/09/99 weiv Added const char * getName() const;
* 04/12/00 srl removing unicodestring api's and cached hash code
* 08/10/01 grhoten Change the static Locales to accessor functions
******************************************************************************
*/
#ifndef LOCID_H
#define LOCID_H
#include "unicode/utypes.h"
#include "unicode/uobject.h"
#include "unicode/unistr.h"
#include "unicode/putil.h"
#include "unicode/uloc.h"
#include "unicode/strenum.h"
/**
* \file
* \brief C++ API: Locale ID object.
*/
/**
* A <code>Locale</code> object represents a specific geographical, political,
* or cultural region. An operation that requires a <code>Locale</code> to perform
* its task is called <em>locale-sensitive</em> and uses the <code>Locale</code>
* to tailor information for the user. For example, displaying a number
* is a locale-sensitive operation--the number should be formatted
* according to the customs/conventions of the user's native country,
* region, or culture.
*
* The Locale class is not suitable for subclassing.
*
* <P>
* You can create a <code>Locale</code> object using the constructor in
* this class:
* \htmlonly<blockquote>\endhtmlonly
* <pre>
* Locale( const char* language,
* const char* country,
* const char* variant);
* </pre>
* \htmlonly</blockquote>\endhtmlonly
* The first argument to the constructors is a valid <STRONG>ISO
* Language Code.</STRONG> These codes are the lower-case two-letter
* codes as defined by ISO-639.
* You can find a full list of these codes at:
* <BR><a href ="http://www.loc.gov/standards/iso639-2/">
* http://www.loc.gov/standards/iso639-2/</a>
*
* <P>
* The second argument to the constructors is a valid <STRONG>ISO Country
* Code.</STRONG> These codes are the upper-case two-letter codes
* as defined by ISO-3166.
* You can find a full list of these codes at a number of sites, such as:
* <BR><a href="http://www.iso.org/iso/en/prods-services/iso3166ma/index.html">
* http://www.iso.org/iso/en/prods-services/iso3166ma/index.html</a>
*
* <P>
* The third constructor requires a third argument--the <STRONG>Variant.</STRONG>
* The Variant codes are vendor and browser-specific.
* For example, use REVISED for a langauge's revised script orthography, and POSIX for POSIX.
* Where there are two variants, separate them with an underscore, and
* put the most important one first. For
* example, a Traditional Spanish collation might be referenced, with
* "ES", "ES", "Traditional_POSIX".
*
* <P>
* Because a <code>Locale</code> object is just an identifier for a region,
* no validity check is performed when you construct a <code>Locale</code>.
* If you want to see whether particular resources are available for the
* <code>Locale</code> you construct, you must query those resources. For
* example, ask the <code>NumberFormat</code> for the locales it supports
* using its <code>getAvailableLocales</code> method.
* <BR><STRONG>Note:</STRONG> When you ask for a resource for a particular
* locale, you get back the best available match, not necessarily
* precisely what you asked for. For more information, look at
* <code>ResourceBundle</code>.
*
* <P>
* The <code>Locale</code> class provides a number of convenient constants
* that you can use to create <code>Locale</code> objects for commonly used
* locales. For example, the following refers to a <code>Locale</code> object
* for the United States:
* \htmlonly<blockquote>\endhtmlonly
* <pre>
* Locale::getUS()
* </pre>
* \htmlonly</blockquote>\endhtmlonly
*
* <P>
* Once you've created a <code>Locale</code> you can query it for information about
* itself. Use <code>getCountry</code> to get the ISO Country Code and
* <code>getLanguage</code> to get the ISO Language Code. You can
* use <code>getDisplayCountry</code> to get the
* name of the country suitable for displaying to the user. Similarly,
* you can use <code>getDisplayLanguage</code> to get the name of
* the language suitable for displaying to the user. Interestingly,
* the <code>getDisplayXXX</code> methods are themselves locale-sensitive
* and have two versions: one that uses the default locale and one
* that takes a locale as an argument and displays the name or country in
* a language appropriate to that locale.
*
* <P>
* ICU provides a number of classes that perform locale-sensitive
* operations. For example, the <code>NumberFormat</code> class formats
* numbers, currency, or percentages in a locale-sensitive manner. Classes
* such as <code>NumberFormat</code> have a number of convenience methods
* for creating a default object of that type. For example, the
* <code>NumberFormat</code> class provides these three convenience methods
* for creating a default <code>NumberFormat</code> object:
* \htmlonly<blockquote>\endhtmlonly
* <pre>
* UErrorCode success = U_ZERO_ERROR;
* Locale myLocale;
* NumberFormat *nf;
*
* nf = NumberFormat::createInstance( success ); delete nf;
* nf = NumberFormat::createCurrencyInstance( success ); delete nf;
* nf = NumberFormat::createPercentInstance( success ); delete nf;
* </pre>
* \htmlonly</blockquote>\endhtmlonly
* Each of these methods has two variants; one with an explicit locale
* and one without; the latter using the default locale.
* \htmlonly<blockquote>\endhtmlonly
* <pre>
* nf = NumberFormat::createInstance( myLocale, success ); delete nf;
* nf = NumberFormat::createCurrencyInstance( myLocale, success ); delete nf;
* nf = NumberFormat::createPercentInstance( myLocale, success ); delete nf;
* </pre>
* \htmlonly</blockquote>\endhtmlonly
* A <code>Locale</code> is the mechanism for identifying the kind of object
* (<code>NumberFormat</code>) that you would like to get. The locale is
* <STRONG>just</STRONG> a mechanism for identifying objects,
* <STRONG>not</STRONG> a container for the objects themselves.
*
* <P>
* Each class that performs locale-sensitive operations allows you
* to get all the available objects of that type. You can sift
* through these objects by language, country, or variant,
* and use the display names to present a menu to the user.
* For example, you can create a menu of all the collation objects
* suitable for a given language. Such classes implement these
* three class methods:
* \htmlonly<blockquote>\endhtmlonly
* <pre>
* static Locale* getAvailableLocales(int32_t& numLocales)
* static UnicodeString& getDisplayName(const Locale& objectLocale,
* const Locale& displayLocale,
* UnicodeString& displayName)
* static UnicodeString& getDisplayName(const Locale& objectLocale,
* UnicodeString& displayName)
* </pre>
* \htmlonly</blockquote>\endhtmlonly
*
* @stable ICU 2.0
* @see ResourceBundle
*/
U_NAMESPACE_BEGIN
class U_COMMON_API Locale : public UObject {
public:
/** Useful constant for this language. @stable ICU 2.0 */
static const Locale &U_EXPORT2 getEnglish(void);
/** Useful constant for this language. @stable ICU 2.0 */
static const Locale &U_EXPORT2 getFrench(void);
/** Useful constant for this language. @stable ICU 2.0 */
static const Locale &U_EXPORT2 getGerman(void);
/** Useful constant for this language. @stable ICU 2.0 */
static const Locale &U_EXPORT2 getItalian(void);
/** Useful constant for this language. @stable ICU 2.0 */
static const Locale &U_EXPORT2 getJapanese(void);
/** Useful constant for this language. @stable ICU 2.0 */
static const Locale &U_EXPORT2 getKorean(void);
/** Useful constant for this language. @stable ICU 2.0 */
static const Locale &U_EXPORT2 getChinese(void);
/** Useful constant for this language. @stable ICU 2.0 */
static const Locale &U_EXPORT2 getSimplifiedChinese(void);
/** Useful constant for this language. @stable ICU 2.0 */
static const Locale &U_EXPORT2 getTraditionalChinese(void);
/** Useful constant for this country/region. @stable ICU 2.0 */
static const Locale &U_EXPORT2 getFrance(void);
/** Useful constant for this country/region. @stable ICU 2.0 */
static const Locale &U_EXPORT2 getGermany(void);
/** Useful constant for this country/region. @stable ICU 2.0 */
static const Locale &U_EXPORT2 getItaly(void);
/** Useful constant for this country/region. @stable ICU 2.0 */
static const Locale &U_EXPORT2 getJapan(void);
/** Useful constant for this country/region. @stable ICU 2.0 */
static const Locale &U_EXPORT2 getKorea(void);
/** Useful constant for this country/region. @stable ICU 2.0 */
static const Locale &U_EXPORT2 getChina(void);
/** Useful constant for this country/region. @stable ICU 2.0 */
static const Locale &U_EXPORT2 getPRC(void);
/** Useful constant for this country/region. @stable ICU 2.0 */
static const Locale &U_EXPORT2 getTaiwan(void);
/** Useful constant for this country/region. @stable ICU 2.0 */
static const Locale &U_EXPORT2 getUK(void);
/** Useful constant for this country/region. @stable ICU 2.0 */
static const Locale &U_EXPORT2 getUS(void);
/** Useful constant for this country/region. @stable ICU 2.0 */
static const Locale &U_EXPORT2 getCanada(void);
/** Useful constant for this country/region. @stable ICU 2.0 */
static const Locale &U_EXPORT2 getCanadaFrench(void);
/**
* Construct a default locale object, a Locale for the default locale ID.
*
* @see getDefault
* @see uloc_getDefault
* @stable ICU 2.0
*/
Locale();
/**
* Construct a locale from language, country, variant.
* If an error occurs, then the constructed object will be "bogus"
* (isBogus() will return TRUE).
*
* @param language Lowercase two-letter or three-letter ISO-639 code.
* This parameter can instead be an ICU style C locale (e.g. "en_US"),
* but the other parameters must not be used.
* This parameter can be NULL; if so,
* the locale is initialized to match the current default locale.
* (This is the same as using the default constructor.)
* Please note: The Java Locale class does NOT accept the form
* 'new Locale("en_US")' but only 'new Locale("en","US")'
*
* @param country Uppercase two-letter ISO-3166 code. (optional)
* @param variant Uppercase vendor and browser specific code. See class
* description. (optional)
* @param keywordsAndValues A string consisting of keyword/values pairs, such as
* "collation=phonebook;currency=euro"
*
* @see getDefault
* @see uloc_getDefault
* @stable ICU 2.0
*/
Locale( const char * language,
const char * country = 0,
const char * variant = 0,
const char * keywordsAndValues = 0);
/**
* Initializes a Locale object from another Locale object.
*
* @param other The Locale object being copied in.
* @stable ICU 2.0
*/
Locale(const Locale& other);
/**
* Destructor
* @stable ICU 2.0
*/
virtual ~Locale() ;
/**
* Replaces the entire contents of *this with the specified value.
*
* @param other The Locale object being copied in.
* @return *this
* @stable ICU 2.0
*/
Locale& operator=(const Locale& other);
/**
* Checks if two locale keys are the same.
*
* @param other The locale key object to be compared with this.
* @return True if the two locale keys are the same, false otherwise.
* @stable ICU 2.0
*/
UBool operator==(const Locale& other) const;
/**
* Checks if two locale keys are not the same.
*
* @param other The locale key object to be compared with this.
* @return True if the two locale keys are not the same, false
* otherwise.
* @stable ICU 2.0
*/
UBool operator!=(const Locale& other) const;
/**
* Clone this object.
* Clones can be used concurrently in multiple threads.
* If an error occurs, then NULL is returned.
* The caller must delete the clone.
*
* @return a clone of this object
*
* @see getDynamicClassID
* @stable ICU 2.8
*/
Locale *clone() const;
/**
* Common methods of getting the current default Locale. Used for the
* presentation: menus, dialogs, etc. Generally set once when your applet or
* application is initialized, then never reset. (If you do reset the
* default locale, you probably want to reload your GUI, so that the change
* is reflected in your interface.)
*
* More advanced programs will allow users to use different locales for
* different fields, e.g. in a spreadsheet.
*
* Note that the initial setting will match the host system.
* @return a reference to the Locale object for the default locale ID
* @system
* @stable ICU 2.0
*/
static const Locale& U_EXPORT2 getDefault(void);
/**
* Sets the default. Normally set once at the beginning of a process,
* then never reset.
* setDefault() only changes ICU's default locale ID, <strong>not</strong>
* the default locale ID of the runtime environment.
*
* @param newLocale Locale to set to. If NULL, set to the value obtained
* from the runtime environement.
* @param success The error code.
* @system
* @stable ICU 2.0
*/
static void U_EXPORT2 setDefault(const Locale& newLocale,
UErrorCode& success);
/**
* Creates a locale which has had minimal canonicalization
* as per uloc_getName().
* @param name The name to create from. If name is null,
* the default Locale is used.
* @return new locale object
* @stable ICU 2.0
* @see uloc_getName
*/
static Locale U_EXPORT2 createFromName(const char *name);
/**
* Creates a locale from the given string after canonicalizing
* the string by calling uloc_canonicalize().
* @param name the locale ID to create from. Must not be NULL.
* @return a new locale object corresponding to the given name
* @stable ICU 3.0
* @see uloc_canonicalize
*/
static Locale U_EXPORT2 createCanonical(const char* name);
/**
* Returns the locale's ISO-639 language code.
* @return An alias to the code
* @stable ICU 2.0
*/
inline const char * getLanguage( ) const;
/**
* Returns the locale's ISO-15924 abbreviation script code.
* @return An alias to the code
* @see uscript_getShortName
* @see uscript_getCode
* @stable ICU 2.8
*/
inline const char * getScript( ) const;
/**
* Returns the locale's ISO-3166 country code.
* @return An alias to the code
* @stable ICU 2.0
*/
inline const char * getCountry( ) const;
/**
* Returns the locale's variant code.
* @return An alias to the code
* @stable ICU 2.0
*/
inline const char * getVariant( ) const;
/**
* Returns the programmatic name of the entire locale, with the language,
* country and variant separated by underbars. If a field is missing, up
* to two leading underbars will occur. Example: "en", "de_DE", "en_US_WIN",
* "de__POSIX", "fr__MAC", "__MAC", "_MT", "_FR_EURO"
* @return A pointer to "name".
* @stable ICU 2.0
*/
inline const char * getName() const;
/**
* Returns the programmatic name of the entire locale as getName would return,
* but without keywords.
* @return A pointer to "name".
* @see getName
* @stable ICU 2.8
*/
const char * getBaseName() const;
/**
* Gets the list of keywords for the specified locale.
*
* @return pointer to StringEnumeration class. Client must dispose of it by calling delete.
* @param status Returns any error information while performing this operation.
* @stable ICU 2.8
*/
StringEnumeration * createKeywords(UErrorCode &status) const;
/**
* Get the value for a keyword.
*
* @param keywordName name of the keyword for which we want the value. Case insensitive.
* @param status Returns any error information while performing this operation.
* @param buffer The buffer to receive the keyword value.
* @param bufferCapacity The capacity of receiving buffer
* @return the length of keyword value
*
* @stable ICU 2.8
*/
int32_t getKeywordValue(const char* keywordName, char *buffer, int32_t bufferCapacity, UErrorCode &status) const;
/**
* returns the locale's three-letter language code, as specified
* in ISO draft standard ISO-639-2.
* @return An alias to the code, or NULL
* @stable ICU 2.0
*/
const char * getISO3Language() const;
/**
* Fills in "name" with the locale's three-letter ISO-3166 country code.
* @return An alias to the code, or NULL
* @stable ICU 2.0
*/
const char * getISO3Country() const;
/**
* Returns the Windows LCID value corresponding to this locale.
* This value is stored in the resource data for the locale as a one-to-four-digit
* hexadecimal number. If the resource is missing, in the wrong format, or
* there is no Windows LCID value that corresponds to this locale, returns 0.
* @stable ICU 2.0
*/
uint32_t getLCID(void) const;
/**
* Fills in "dispLang" with the name of this locale's language in a format suitable for
* user display in the default locale. For example, if the locale's language code is
* "fr" and the default locale's language code is "en", this function would set
* dispLang to "French".
* @param dispLang Receives the language's display name.
* @return A reference to "dispLang".
* @stable ICU 2.0
*/
UnicodeString& getDisplayLanguage(UnicodeString& dispLang) const;
/**
* Fills in "dispLang" with the name of this locale's language in a format suitable for
* user display in the locale specified by "displayLocale". For example, if the locale's
* language code is "en" and displayLocale's language code is "fr", this function would set
* dispLang to "Anglais".
* @param displayLocale Specifies the locale to be used to display the name. In other words,
* if the locale's language code is "en", passing Locale::getFrench() for
* displayLocale would result in "Anglais", while passing Locale::getGerman()
* for displayLocale would result in "Englisch".
* @param dispLang Receives the language's display name.
* @return A reference to "dispLang".
* @stable ICU 2.0
*/
UnicodeString& getDisplayLanguage( const Locale& displayLocale,
UnicodeString& dispLang) const;
/**
* Fills in "dispScript" with the name of this locale's script in a format suitable
* for user display in the default locale. For example, if the locale's script code
* is "LATN" and the default locale's language code is "en", this function would set
* dispScript to "Latin".
* @param dispScript Receives the scripts's display name.
* @return A reference to "dispScript".
* @stable ICU 2.8
*/
UnicodeString& getDisplayScript( UnicodeString& dispScript) const;
/**
* Fills in "dispScript" with the name of this locale's country in a format suitable
* for user display in the locale specified by "displayLocale". For example, if the locale's
* script code is "LATN" and displayLocale's language code is "en", this function would set
* dispScript to "Latin".
* @param displayLocale Specifies the locale to be used to display the name. In other
* words, if the locale's script code is "LATN", passing
* Locale::getFrench() for displayLocale would result in "", while
* passing Locale::getGerman() for displayLocale would result in
* "".
* @param dispScript Receives the scripts's display name.
* @return A reference to "dispScript".
* @stable ICU 2.8
*/
UnicodeString& getDisplayScript( const Locale& displayLocale,
UnicodeString& dispScript) const;
/**
* Fills in "dispCountry" with the name of this locale's country in a format suitable
* for user display in the default locale. For example, if the locale's country code
* is "FR" and the default locale's language code is "en", this function would set
* dispCountry to "France".
* @param dispCountry Receives the country's display name.
* @return A reference to "dispCountry".
* @stable ICU 2.0
*/
UnicodeString& getDisplayCountry( UnicodeString& dispCountry) const;
/**
* Fills in "dispCountry" with the name of this locale's country in a format suitable
* for user display in the locale specified by "displayLocale". For example, if the locale's
* country code is "US" and displayLocale's language code is "fr", this function would set
* dispCountry to "&Eacute;tats-Unis".
* @param displayLocale Specifies the locale to be used to display the name. In other
* words, if the locale's country code is "US", passing
* Locale::getFrench() for displayLocale would result in "&Eacute;tats-Unis", while
* passing Locale::getGerman() for displayLocale would result in
* "Vereinigte Staaten".
* @param dispCountry Receives the country's display name.
* @return A reference to "dispCountry".
* @stable ICU 2.0
*/
UnicodeString& getDisplayCountry( const Locale& displayLocale,
UnicodeString& dispCountry) const;
/**
* Fills in "dispVar" with the name of this locale's variant code in a format suitable
* for user display in the default locale.
* @param dispVar Receives the variant's name.
* @return A reference to "dispVar".
* @stable ICU 2.0
*/
UnicodeString& getDisplayVariant( UnicodeString& dispVar) const;
/**
* Fills in "dispVar" with the name of this locale's variant code in a format
* suitable for user display in the locale specified by "displayLocale".
* @param displayLocale Specifies the locale to be used to display the name.
* @param dispVar Receives the variant's display name.
* @return A reference to "dispVar".
* @stable ICU 2.0
*/
UnicodeString& getDisplayVariant( const Locale& displayLocale,
UnicodeString& dispVar) const;
/**
* Fills in "name" with the name of this locale in a format suitable for user display
* in the default locale. This function uses getDisplayLanguage(), getDisplayCountry(),
* and getDisplayVariant() to do its work, and outputs the display name in the format
* "language (country[,variant])". For example, if the default locale is en_US, then
* fr_FR's display name would be "French (France)", and es_MX_Traditional's display name
* would be "Spanish (Mexico,Traditional)".
* @param name Receives the locale's display name.
* @return A reference to "name".
* @stable ICU 2.0
*/
UnicodeString& getDisplayName( UnicodeString& name) const;
/**
* Fills in "name" with the name of this locale in a format suitable for user display
* in the locale specfied by "displayLocale". This function uses getDisplayLanguage(),
* getDisplayCountry(), and getDisplayVariant() to do its work, and outputs the display
* name in the format "language (country[,variant])". For example, if displayLocale is
* fr_FR, then en_US's display name would be "Anglais (&Eacute;tats-Unis)", and no_NO_NY's
* display name would be "norv&eacute;gien (Norv&egrave;ge,NY)".
* @param displayLocale Specifies the locale to be used to display the name.
* @param name Receives the locale's display name.
* @return A reference to "name".
* @stable ICU 2.0
*/
UnicodeString& getDisplayName( const Locale& displayLocale,
UnicodeString& name) const;
/**
* Generates a hash code for the locale.
* @stable ICU 2.0
*/
int32_t hashCode(void) const;
/**
* Sets the locale to bogus
* A bogus locale represents a non-existing locale associated
* with services that can be instantiated from non-locale data
* in addition to locale (for example, collation can be
* instantiated from a locale and from a rule set).
* @stable ICU 2.1
*/
void setToBogus();
/**
* Gets the bogus state. Locale object can be bogus if it doesn't exist
* @return FALSE if it is a real locale, TRUE if it is a bogus locale
* @stable ICU 2.1
*/
UBool isBogus(void) const;
/**
* Returns a list of all installed locales.
* @param count Receives the number of locales in the list.
* @return A pointer to an array of Locale objects. This array is the list
* of all locales with installed resource files. The called does NOT
* get ownership of this list, and must NOT delete it.
* @stable ICU 2.0
*/
static const Locale* U_EXPORT2 getAvailableLocales(int32_t& count);
/**
* Gets a list of all available 2-letter country codes defined in ISO 639. This is a
* pointer to an array of pointers to arrays of char. All of these pointers are
* owned by ICU-- do not delete them, and do not write through them. The array is
* terminated with a null pointer.
* @return a list of all available country codes
* @stable ICU 2.0
*/
static const char* const* U_EXPORT2 getISOCountries();
/**
* Gets a list of all available language codes defined in ISO 639. This is a pointer
* to an array of pointers to arrays of char. All of these pointers are owned
* by ICU-- do not delete them, and do not write through them. The array is
* terminated with a null pointer.
* @return a list of all available language codes
* @stable ICU 2.0
*/
static const char* const* U_EXPORT2 getISOLanguages();
/**
* ICU "poor man's RTTI", returns a UClassID for this class.
*
* @stable ICU 2.2
*/
static UClassID U_EXPORT2 getStaticClassID();
/**
* ICU "poor man's RTTI", returns a UClassID for the actual class.
*
* @stable ICU 2.2
*/
virtual UClassID getDynamicClassID() const;
protected: /* only protected for testing purposes. DO NOT USE. */
/**
* Set this from a single POSIX style locale string.
* @internal
*/
void setFromPOSIXID(const char *posixID);
private:
/**
* Initialize the locale object with a new name.
* Was deprecated - used in implementation - moved internal
*
* @param cLocaleID The new locale name.
*/
Locale& init(const char* cLocaleID, UBool canonicalize);
/*
* Internal constructor to allow construction of a locale object with
* NO side effects. (Default constructor tries to get
* the default locale.)
*/
enum ELocaleType {
eBOGUS
};
Locale(ELocaleType);
/**
* Initialize the locale cache for commonly used locales
*/
static Locale *getLocaleCache(void);
char language[ULOC_LANG_CAPACITY];
char script[ULOC_SCRIPT_CAPACITY];
char country[ULOC_COUNTRY_CAPACITY];
int32_t variantBegin;
char* fullName;
char fullNameBuffer[ULOC_FULLNAME_CAPACITY];
// name without keywords
char* baseName;
char baseNameBuffer[ULOC_FULLNAME_CAPACITY];
UBool fIsBogus;
static const Locale &getLocale(int locid);
/**
* A friend to allow the default locale to be set by either the C or C++ API.
* @internal
*/
friend void locale_set_default_internal(const char *);
};
inline UBool
Locale::operator!=(const Locale& other) const
{
return !operator==(other);
}
inline const char *
Locale::getCountry() const
{
return country;
}
inline const char *
Locale::getLanguage() const
{
return language;
}
inline const char *
Locale::getScript() const
{
return script;
}
inline const char *
Locale::getVariant() const
{
return &fullName[variantBegin];
}
inline const char *
Locale::getName() const
{
return fullName;
}
inline UBool
Locale::isBogus(void) const {
return fIsBogus;
}
U_NAMESPACE_END
#endif
+77
View File
@@ -0,0 +1,77 @@
/*
**********************************************************************
* Copyright (c) 2004-2006, 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 !UCONFIG_NO_FORMATTING
#include "unicode/format.h"
/**
* \file
* \brief C++ API: Formatter for measure objects.
*/
U_NAMESPACE_BEGIN
/**
*
* A formatter for measure objects. This is an abstract base class.
*
* <p>To format or parse a measure object, first create a formatter
* object using a MeasureFormat factory method. Then use that
* object's format and parse methods.
*
* <p>This is an abstract class.
*
* @see Format
* @author Alan Liu
* @stable ICU 3.0
*/
class U_I18N_API MeasureFormat : public Format {
public:
/**
* Return a formatter for CurrencyAmount objects in the given
* locale.
* @param locale desired locale
* @param ec input-output error code
* @return a formatter object, or NULL 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.
* @param ec input-output error code
* @return a formatter object, or NULL upon error
* @stable ICU 3.0
*/
static MeasureFormat* U_EXPORT2 createCurrencyFormat(UErrorCode& ec);
protected:
/**
* Default constructor.
* @stable ICU 3.0
*/
MeasureFormat();
};
U_NAMESPACE_END
#endif // #if !UCONFIG_NO_FORMATTING
#endif // #ifndef MEASUREFORMAT_H
+71
View File
@@ -0,0 +1,71 @@
/*
**********************************************************************
* 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 __MEASUREUNIT_H__
#define __MEASUREUNIT_H__
#include "unicode/utypes.h"
#if !UCONFIG_NO_FORMATTING
#include "unicode/fmtable.h"
/**
* \file
* \brief C++ API: A unit for measuring a quantity.
*/
U_NAMESPACE_BEGIN
/**
* A unit such as length, mass, volume, currency, etc. A unit is
* coupled with a numeric amount to produce a Measure.
*
* <p>This is an abstract class.
*
* @author Alan Liu
* @stable ICU 3.0
*/
class U_I18N_API MeasureUnit: public UObject {
public:
/**
* Return a polymorphic clone of this object. The result will
* have the same class as returned by getDynamicClassID().
* @stable ICU 3.0
*/
virtual UObject* clone() const = 0;
/**
* Destructor
* @stable ICU 3.0
*/
virtual ~MeasureUnit();
/**
* Equality operator. Return true if this object is equal
* to the given object.
* @stable ICU 3.0
*/
virtual UBool operator==(const UObject& other) const = 0;
protected:
/**
* Default constructor.
* @stable ICU 3.0
*/
MeasureUnit();
};
U_NAMESPACE_END
// NOTE: There is no measunit.cpp. For implementation, see measure.cpp. [alan]
#endif // !UCONFIG_NO_FORMATTING
#endif // __MEASUREUNIT_H__
+137
View File
@@ -0,0 +1,137 @@
/*
**********************************************************************
* 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 __MEASURE_H__
#define __MEASURE_H__
#include "unicode/utypes.h"
/**
* \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. This is an abstract class.
* Subclasses specify a concrete Unit type.
*
* <p>Measure objects are parsed and formatted by subclasses of
* MeasureFormat.
*
* <p>Measure objects are immutable.
*
* <p>This is an abstract class.
*
* @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 NULL
* @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 UObject* clone() const = 0;
/**
* Destructor
* @stable ICU 3.0
*/
virtual ~Measure();
/**
* Equality operator. Return true if this object is equal
* to the given object.
* @stable ICU 3.0
*/
UBool operator==(const UObject& other) const;
/**
* 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;
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 // __MEASURE_H__
+953
View File
@@ -0,0 +1,953 @@
/*
* Copyright (C) 2007-2009, International Business Machines Corporation and others. All Rights Reserved.
********************************************************************************
*
* File MSGFMT.H
*
* Modification History:
*
* Date Name Description
* 02/19/97 aliu Converted from java.
* 03/20/97 helena Finished first cut of implementation.
* 07/22/98 stephen Removed operator!= (defined in Format)
* 08/19/2002 srl Removing Javaisms
********************************************************************************
*/
#ifndef MSGFMT_H
#define MSGFMT_H
#include "unicode/utypes.h"
/**
* \file
* \brief C++ API: Formats messages in a language-neutral way.
*/
#if !UCONFIG_NO_FORMATTING
#include "unicode/format.h"
#include "unicode/locid.h"
#include "unicode/parseerr.h"
#include "unicode/uchar.h"
U_NAMESPACE_BEGIN
class NumberFormat;
class DateFormat;
/**
*
* A MessageFormat produces concatenated messages in a
* language-neutral way. It should be used for all string
* concatenations that are visible to end users.
* <P>
* A MessageFormat contains an array of <EM>subformats</EM> arranged
* within a <EM>template string</EM>. Together, the subformats and
* template string determine how the MessageFormat will operate during
* formatting and parsing.
* <P>
* Typically, both the subformats and the template string are
* specified at once in a <EM>pattern</EM>. By using different
* patterns for different locales, messages may be localized.
* <P>
* During formatting, the MessageFormat takes an array of arguments
* and produces a user-readable string. Each argument is a
* Formattable object; they may be passed in in an array, or as a
* single Formattable object which itself contains an array. Each
* argument is matched up with its corresponding subformat, which then
* formats it into a string. The resultant strings are then assembled
* within the string template of the MessageFormat to produce the
* final output string.
* <p>
* <strong>Note:</strong>
* In ICU 4.0 MessageFormat supports named arguments. If a named argument
* is used, all arguments must be named. Names start with a character in
* <code>UCHAR_ID_START</code> and continue with characters in
* <code>UCHARID_CONTINUE</code>, in particular they do not start with a digit.
* If named arguments are used, {@link #usesNamedArguments()} will return true.
* <p>
* The other new methods supporting named arguments are
* {@link #getFormatNames(UErrorCode& status)},
* {@link #getFormat(const UnicodeString& formatName, UErrorCode& status)}
* {@link #setFormat(const UnicodeString& formatName, const Format& format, UErrorCode& status)},
* {@link #adoptFormat(const UnicodeString& formatName, Format* formatToAdopt, UErrorCode& status)},
* {@link #format(const Formattable* arguments, const UnicodeString *argumentNames, int32_t cnt, UnicodeString& appendTo, FieldPosition& status, int32_t recursionProtection, UErrorCode& success)},
* {@link #format(const UnicodeString* argumentNames, const Formattable* arguments, int32_t count, UnicodeString& appendTo,UErrorCode& status)}.
* These methods are all compatible with patterns that do not used named arguments--
* in these cases the keys in the input or output use <code>UnicodeString</code>s
* that name the argument indices, e.g. "0", "1", "2"... etc.
* <p>
* When named arguments are used, certain methods on MessageFormat that take or
* return arrays do not perform any action, since it is not possible to
* identify positions in an array using a name. UErrorCode is set to
* U_ARGUMENT_TYPE_MISMATCH if there is a status/success field in the method.
* These methods are
* {@link #adoptFormats(Format** formatsToAdopt, int32_t count)},
* {@link #setFormats(const Format** newFormats,int32_t count)},
* {@link #adoptFormat(int32_t n, Format *newFormat)},
* {@link #getFormats(int32_t& count)},
* {@link #format(const Formattable* source,int32_t cnt,UnicodeString& appendTo, FieldPosition& ignore, UErrorCode& success)},
* {@link #format(const UnicodeString& pattern,const Formattable* arguments,int32_t cnt,UnicodeString& appendTo,UErrorCode& success)},
* {@link #format(const Formattable& source, UnicodeString& appendTo,FieldPosition& ignore, UErrorCode& success)},
* {@link #format(const Formattable* arguments, int32_t cnt, UnicodeString& appendTo, FieldPosition& status, int32_t recursionProtection,UErrorCode& success)},
* {@link #parse(const UnicodeString& source, ParsePosition& pos,int32_t& count)},
* {@link #parse(const UnicodeString& source, int32_t& cnt, UErrorCode& status)}
* <p>
*
* <P>
* During parsing, an input string is matched against the string
* template of the MessageFormat to produce an array of Formattable
* objects. Plain text of the template string is matched directly
* against intput text. At each position in the template string where
* a subformat is located, the subformat is called to parse the
* corresponding segment of input text to produce an output argument.
* In this way, an array of arguments is created which together
* constitute the parse result.
* <P>
* Parsing may fail or produce unexpected results in a number of
* circumstances.
* <UL>
* <LI>If one of the arguments does not occur in the pattern, it
* will be returned as a default Formattable.
* <LI>If the format of an argument is loses information, such as with
* a choice format where a large number formats to "many", then the
* parse may not correspond to the originally formatted argument.
* <LI>MessageFormat does not handle ChoiceFormat recursion during
* parsing; such parses will fail.
* <LI>Parsing will not always find a match (or the correct match) if
* some part of the parse is ambiguous. For example, if the pattern
* "{1},{2}" is used with the string arguments {"a,b", "c"}, it will
* format as "a,b,c". When the result is parsed, it will return {"a",
* "b,c"}.
* <LI>If a single argument is formatted more than once in the string,
* then the rightmost subformat in the pattern string will produce the
* parse result; prior subformats with the same argument index will
* have no effect.
* </UL>
* Here are some examples of usage:
* <P>
* Example 1:
* <pre>
* \code
* UErrorCode success = U_ZERO_ERROR;
* GregorianCalendar cal(success);
* Formattable arguments[] = {
* 7L,
* Formattable( (Date) cal.getTime(success), Formattable::kIsDate),
* "a disturbance in the Force"
* };
*
* UnicodeString result;
* MessageFormat::format(
* "At {1,time} on {1,date}, there was {2} on planet {0,number}.",
* arguments, 3, result, success );
*
* cout << "result: " << result << endl;
* //<output>: At 4:34:20 PM on 23-Mar-98, there was a disturbance
* // in the 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
* success = U_ZERO_ERROR;
* Formattable testArgs[] = {3L, "MyDisk"};
*
* MessageFormat form(
* "The disk \"{1}\" contains {0} file(s).", success );
*
* UnicodeString string;
* FieldPosition fpos = 0;
* cout << "format: " << form.format(testArgs, 2, string, fpos, success ) << endl;
*
* // output, with different testArgs:
* // output: The disk "MyDisk" contains 0 file(s).
* // output: The disk "MyDisk" contains 1 file(s).
* // output: The disk "MyDisk" contains 1,273 file(s).
* \endcode
* </pre>
*
* The pattern is of the following form. Legend:
* <pre>
* \code
* {optional item}
* (group that may be repeated)*
* \endcode
* </pre>
* Do not confuse optional items with items inside quotes braces, such
* as this: "{". Quoted braces are literals.
* <pre>
* \code
* messageFormatPattern := string ( "{" messageFormatElement "}" string )*
*
* messageFormatElement := argumentIndex | argumentName { "," elementFormat }
*
* elementFormat := "time" { "," datetimeStyle }
* | "date" { "," datetimeStyle }
* | "number" { "," numberStyle }
* | "choice" "," choiceStyle
*
* datetimeStyle := "short"
* | "medium"
* | "long"
* | "full"
* | dateFormatPattern
*
* numberStyle := "currency"
* | "percent"
* | "integer"
* | numberFormatPattern
*
* choiceStyle := choiceFormatPattern
*
* pluralStyle := pluralFormatPattern
* \endcode
* </pre>
* If there is no elementFormat, then the argument must be a string,
* which is substituted. If there is no dateTimeStyle or numberStyle,
* then the default format is used (e.g. NumberFormat::createInstance(),
* DateFormat::createTimeInstance(DateFormat::kDefault, ...) or DateFormat::createDateInstance(DateFormat::kDefault, ...). For
* a ChoiceFormat, the pattern must always be specified, since there
* is no default.
* <P>
* In strings, single quotes can be used to quote syntax characters.
* A literal single quote is represented by '', both within and outside
* of single-quoted segments. Inside a
* messageFormatElement, quotes are <EM>not</EM> removed. For example,
* {1,number,$'#',##} will produce a number format with the pound-sign
* quoted, with a result such as: "$#31,45".
* <P>
* If a pattern is used, then unquoted braces in the pattern, if any,
* must match: that is, "ab {0} de" and "ab '}' de" are ok, but "ab
* {0'}' de" and "ab } de" are not.
* <p>
* <dl><dt><b>Warning:</b><dd>The rules for using quotes within message
* format patterns unfortunately have shown to be somewhat confusing.
* In particular, it isn't always obvious to localizers whether single
* quotes need to be doubled or not. Make sure to inform localizers about
* the rules, and tell them (for example, by using comments in resource
* bundle source files) which strings will be processed by MessageFormat.
* Note that localizers may need to use single quotes in translated
* strings where the original version doesn't have them.
* <br>Note also that the simplest way to avoid the problem is to
* use the real apostrophe (single quote) character U+2019 (') for
* human-readable text, and to use the ASCII apostrophe (U+0027 ' )
* only in program syntax, like quoting in MessageFormat.
* See the annotations for U+0027 Apostrophe in The Unicode Standard.</p>
* </dl>
* <P>
* The argumentIndex is a non-negative integer, which corresponds to the
* index of the arguments presented in an array to be formatted. The
* first argument has argumentIndex 0.
* <P>
* It is acceptable to have unused arguments in the array. With missing
* arguments or arguments that are not of the right class for the
* specified format, a failing UErrorCode result is set.
* <P>
* For more sophisticated patterns, you can use a ChoiceFormat to get
* output:
* <pre>
* \code
* UErrorCode success = U_ZERO_ERROR;
* MessageFormat* form("The disk \"{1}\" contains {0}.", success);
* double filelimits[] = {0,1,2};
* UnicodeString filepart[] = {"no files","one file","{0,number} files"};
* ChoiceFormat* fileform = new ChoiceFormat(filelimits, filepart, 3);
* form.setFormat(1, *fileform); // NOT zero, see below
*
* Formattable testArgs[] = {1273L, "MyDisk"};
*
* UnicodeString string;
* FieldPosition fpos = 0;
* cout << form.format(testArgs, 2, string, fpos, success) << endl;
*
* // output, with different testArgs
* // output: The disk "MyDisk" contains no files.
* // output: The disk "MyDisk" contains one file.
* // output: The disk "MyDisk" contains 1,273 files.
* \endcode
* </pre>
* You can either do this programmatically, as in the above example,
* or by using a pattern (see ChoiceFormat for more information) as in:
* <pre>
* \code
* form.applyPattern(
* "There {0,choice,0#are no files|1#is one file|1<are {0,number,integer} files}.");
* \endcode
* </pre>
* <P>
* <EM>Note:</EM> As we see above, the string produced by a ChoiceFormat in
* MessageFormat is treated specially; occurences of '{' are used to
* indicated subformats, and cause recursion. If you create both a
* MessageFormat and ChoiceFormat programmatically (instead of using
* the string patterns), then be careful not to produce a format that
* recurses on itself, which will cause an infinite loop.
* <P>
* <EM>Note:</EM> Subformats are numbered by their order in the pattern.
* This is <EM>not</EM> the same as the argumentIndex.
* <pre>
* \code
* For example: with "abc{2}def{3}ghi{0}...",
*
* format0 affects the first variable {2}
* format1 affects the second variable {3}
* format2 affects the second variable {0}
* \endcode
* </pre>
*
* <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 MessageFormat : public Format {
public:
/**
* Enum type for kMaxFormat.
* @obsolete ICU 3.0. The 10-argument limit was removed as of ICU 2.6,
* rendering this enum type obsolete.
*/
enum EFormatNumber {
/**
* The maximum number of arguments.
* @obsolete ICU 3.0. The 10-argument limit was removed as of ICU 2.6,
* rendering this constant obsolete.
*/
kMaxFormat = 10
};
/**
* Constructs a new MessageFormat using the given pattern and the
* default locale.
*
* @param pattern Pattern used to construct object.
* @param status Input/output error code. If the
* pattern cannot be parsed, set to failure code.
* @stable ICU 2.0
*/
MessageFormat(const UnicodeString& pattern,
UErrorCode &status);
/**
* Constructs a new MessageFormat using the given pattern and locale.
* @param pattern Pattern used to construct object.
* @param newLocale The locale to use for formatting dates and numbers.
* @param status Input/output error code. If the
* pattern cannot be parsed, set to failure code.
* @stable ICU 2.0
*/
MessageFormat(const UnicodeString& pattern,
const Locale& newLocale,
UErrorCode& status);
/**
* Constructs a new MessageFormat using the given pattern and locale.
* @param pattern Pattern used to construct object.
* @param newLocale The locale to use for formatting dates and numbers.
* @param parseError Struct to recieve information on position
* of error within the pattern.
* @param status Input/output error code. If the
* pattern cannot be parsed, set to failure code.
* @stable ICU 2.0
*/
MessageFormat(const UnicodeString& pattern,
const Locale& newLocale,
UParseError& parseError,
UErrorCode& status);
/**
* Constructs a new MessageFormat from an existing one.
* @stable ICU 2.0
*/
MessageFormat(const MessageFormat&);
/**
* Assignment operator.
* @stable ICU 2.0
*/
const MessageFormat& operator=(const MessageFormat&);
/**
* Destructor.
* @stable ICU 2.0
*/
virtual ~MessageFormat();
/**
* Clones this Format object polymorphically. The caller owns the
* result and should delete it when done.
* @stable ICU 2.0
*/
virtual Format* clone(void) const;
/**
* Returns 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 true if the given Format objects are semantically equal.
* @stable ICU 2.0
*/
virtual UBool operator==(const Format& other) const;
/**
* Sets the locale. This locale is used for fetching default number or date
* format information.
* @param theLocale the new locale value to be set.
* @stable ICU 2.0
*/
virtual void setLocale(const Locale& theLocale);
/**
* Gets the locale. This locale is used for fetching default number or date
* format information.
* @return the locale of the object.
* @stable ICU 2.0
*/
virtual const Locale& getLocale(void) const;
/**
* Applies the given pattern string to this message format.
*
* @param pattern The pattern to be applied.
* @param status Input/output error code. If the
* pattern cannot be parsed, set to failure code.
* @stable ICU 2.0
*/
virtual void applyPattern(const UnicodeString& pattern,
UErrorCode& status);
/**
* Applies the given pattern string to this message format.
*
* @param pattern The pattern to be applied.
* @param parseError Struct to recieve information on position
* of error within pattern.
* @param status Input/output error code. If the
* pattern cannot be parsed, set to failure code.
* @stable ICU 2.0
*/
virtual void applyPattern(const UnicodeString& pattern,
UParseError& parseError,
UErrorCode& status);
/**
* Returns a pattern that can be used to recreate this object.
*
* @param appendTo Output parameter to receive the pattern.
* Result is appended to existing contents.
* @return Reference to 'appendTo' parameter.
* @stable ICU 2.0
*/
virtual UnicodeString& toPattern(UnicodeString& appendTo) const;
/**
* Sets subformats.
* See the class description about format numbering.
* The caller should not delete the Format objects after this call.
* <EM>The array formatsToAdopt is not itself adopted.</EM> Its
* ownership is retained by the caller. If the call fails because
* memory cannot be allocated, then the formats will be deleted
* by this method, and this object will remain unchanged.
*
* @stable ICU 2.0
* @param formatsToAdopt the format to be adopted.
* @param count the size of the array.
*/
virtual void adoptFormats(Format** formatsToAdopt, int32_t count);
/**
* Sets subformats.
* See the class description about format numbering.
* Each item in the array is cloned into the internal array.
* If the call fails because memory cannot be allocated, then this
* object will remain unchanged.
*
* @stable ICU 2.0
* @param newFormats the new format to be set.
* @param cnt the size of the array.
*/
virtual void setFormats(const Format** newFormats, int32_t cnt);
/**
* Sets one subformat.
* See the class description about format numbering.
* The caller should not delete the Format object after this call.
* If the number is over the number of formats already set,
* the item will be deleted and ignored.
* @stable ICU 2.0
* @param formatNumber index of the subformat.
* @param formatToAdopt the format to be adopted.
*/
virtual void adoptFormat(int32_t formatNumber, Format* formatToAdopt);
/**
* Sets one subformat.
* See the class description about format numbering.
* If the number is over the number of formats already set,
* the item will be ignored.
* @param formatNumber index of the subformat.
* @param format the format to be set.
* @stable ICU 2.0
*/
virtual void setFormat(int32_t formatNumber, const Format& format);
/**
* Gets format names. This function returns formatNames in StringEnumerations
* which can be used with getFormat() and setFormat() to export formattable
* array from current MessageFormat to another. It is caller's resposibility
* to delete the returned formatNames.
* @param status output param set to success/failure code.
* @stable ICU 4.0
*/
virtual StringEnumeration* getFormatNames(UErrorCode& status);
/**
* Gets subformat pointer for given format name.
* This function supports both named and numbered
* arguments-- if numbered, the formatName is the
* corresponding UnicodeStrings (e.g. "0", "1", "2"...).
* The returned Format object should not be deleted by the caller,
* nor should the ponter of other object . The pointer and its
* contents remain valid only until the next call to any method
* of this class is made with this object.
* @param formatName the name or number specifying a format
* @param status output param set to success/failure code.
* @stable ICU 4.0
*/
virtual Format* getFormat(const UnicodeString& formatName, UErrorCode& status);
/**
* Sets one subformat for given format name.
* See the class description about format name.
* This function supports both named and numbered
* arguments-- if numbered, the formatName is the
* corresponding UnicodeStrings (e.g. "0", "1", "2"...).
* If there is no matched formatName or wrong type,
* the item will be ignored.
* @param formatName Name of the subformat.
* @param format the format to be set.
* @param status output param set to success/failure code.
* @stable ICU 4.0
*/
virtual void setFormat(const UnicodeString& formatName, const Format& format, UErrorCode& status);
/**
* Sets one subformat for given format name.
* See the class description about format name.
* This function supports both named and numbered
* arguments-- if numbered, the formatName is the
* corresponding UnicodeStrings (e.g. "0", "1", "2"...).
* If there is no matched formatName or wrong type,
* the item will be ignored.
* The caller should not delete the Format object after this call.
* @param formatName Name of the subformat.
* @param formatToAdopt Format to be adopted.
* @param status output param set to success/failure code.
* @stable ICU 4.0
*/
virtual void adoptFormat(const UnicodeString& formatName, Format* formatToAdopt, UErrorCode& status);
/**
* Gets an array of subformats of this object. The returned array
* should not be deleted by the caller, nor should the pointers
* within the array. The array and its contents remain valid only
* until the next call to any method of this class is made with
* this object. See the class description about format numbering.
* @param count output parameter to receive the size of the array
* @return an array of count Format* objects, or NULL if out of
* memory. Any or all of the array elements may be NULL.
* @stable ICU 2.0
*/
virtual const Format** getFormats(int32_t& count) const;
/**
* Formats the given array of arguments into a user-readable string.
* Does not take ownership of the Formattable* array or its contents.
*
* @param source An array of objects to be formatted.
* @param count The number of elements of 'source'.
* @param appendTo Output parameter to receive result.
* Result is appended to existing contents.
* @param ignore Not used; inherited from base class API.
* @param status Input/output error code. If the
* pattern cannot be parsed, set to failure code.
* @return Reference to 'appendTo' parameter.
* @stable ICU 2.0
*/
UnicodeString& format( const Formattable* source,
int32_t count,
UnicodeString& appendTo,
FieldPosition& ignore,
UErrorCode& status) const;
/**
* Formats the given array of arguments into a user-readable string
* using the given pattern.
*
* @param pattern The pattern.
* @param arguments An array of objects to be formatted.
* @param count The number of elements of 'source'.
* @param appendTo Output parameter to receive result.
* Result is appended to existing contents.
* @param status Input/output error code. If the
* pattern cannot be parsed, set to failure code.
* @return Reference to 'appendTo' parameter.
* @stable ICU 2.0
*/
static UnicodeString& format(const UnicodeString& pattern,
const Formattable* arguments,
int32_t count,
UnicodeString& appendTo,
UErrorCode& status);
/**
* Formats the given array of arguments into a user-readable
* string. The array must be stored within a single Formattable
* object of type kArray. If the Formattable object type is not of
* type kArray, then returns a failing UErrorCode.
*
* @param obj A Formattable of type kArray containing
* arguments 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.
* @param status Input/output error code. If the
* pattern cannot be parsed, set to failure code.
* @return Reference to 'appendTo' parameter.
* @stable ICU 2.0
*/
virtual UnicodeString& format(const Formattable& obj,
UnicodeString& appendTo,
FieldPosition& pos,
UErrorCode& status) const;
/**
* Formats the given array of arguments into a user-readable
* string. The array must be stored within a single Formattable
* object of type kArray. If the Formattable object type is not of
* type kArray, then returns a failing UErrorCode.
*
* @param obj The object to format
* @param appendTo Output parameter to receive result.
* Result is appended to existing contents.
* @param status Input/output error code. If the
* pattern cannot be parsed, set to failure code.
* @return Reference to 'appendTo' parameter.
* @stable ICU 2.0
*/
UnicodeString& format(const Formattable& obj,
UnicodeString& appendTo,
UErrorCode& status) const;
/**
* Formats the given array of arguments into a user-defined argument name
* array. This function supports both named and numbered
* arguments-- if numbered, the formatName is the
* corresponding UnicodeStrings (e.g. "0", "1", "2"...).
*
* @param argumentNames argument name array
* @param arguments An array of objects to be formatted.
* @param count The number of elements of 'argumentNames' and
* arguments. The number of argumentNames and arguments
* must be the same.
* @param appendTo Output parameter to receive result.
* Result is appended to existing contents.
* @param status Input/output error code. If the
* pattern cannot be parsed, set to failure code.
* @return Reference to 'appendTo' parameter.
* @stable ICU 4.0
*/
UnicodeString& format(const UnicodeString* argumentNames,
const Formattable* arguments,
int32_t count,
UnicodeString& appendTo,
UErrorCode& status) const;
/**
* Parses the given string into an array of output arguments.
*
* @param source String to be parsed.
* @param pos On input, starting position for parse. On output,
* final position after parse. Unchanged if parse
* fails.
* @param count Output parameter to receive the number of arguments
* parsed.
* @return an array of parsed arguments. The caller owns both
* the array and its contents.
* @stable ICU 2.0
*/
virtual Formattable* parse( const UnicodeString& source,
ParsePosition& pos,
int32_t& count) const;
/**
* Parses the given string into an array of output arguments.
*
* @param source String to be parsed.
* @param count Output param to receive size of returned array.
* @param status Input/output error code. If the
* pattern cannot be parsed, set to failure code.
* If the MessageFormat is named argument, the status is
* set to U_ARGUMENT_TYPE_MISMATCH.
* @return an array of parsed arguments. The caller owns both
* the array and its contents. Return NULL if status is not U_ZERO_ERROR.
*
* @stable ICU 2.0
*/
virtual Formattable* parse( const UnicodeString& source,
int32_t& count,
UErrorCode& status) const;
/**
* Parses the given string into an array of output arguments
* stored within a single Formattable of type kArray.
*
* @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 pos On input, starting position for parse. On output,
* final position after parse. Unchanged if parse
* fails.
* @stable ICU 2.0
*/
virtual void parseObject(const UnicodeString& source,
Formattable& result,
ParsePosition& pos) const;
/**
* 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 status Input/output error code. If the pattern
* cannot be parsed, the failure code is set.
* @return the standard equivalent of the original pattern
* @stable ICU 3.4
*/
static UnicodeString autoQuoteApostrophe(const UnicodeString& pattern,
UErrorCode& status);
/**
* Returns true if this MessageFormat uses named arguments,
* and false otherwise. See class description.
*
* @return true if named arguments are used.
* @stable ICU 4.0
*/
UBool usesNamedArguments() const;
/**
* This API is for ICU internal use only.
* Please do not use it.
*
* Returns argument types count in the parsed pattern.
* Used to distinguish pattern "{0} d" and "d".
*
* @return The number of formattable types in the pattern
* @internal
*/
int32_t getArgTypeCount() const;
/**
* 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(void) 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() ==
* . Derived::getStaticClassID()) ...
* </pre>
* @return The class ID for all objects of this class.
* @stable ICU 2.0
*/
static UClassID U_EXPORT2 getStaticClassID(void);
private:
Locale fLocale;
UnicodeString fPattern;
Format** formatAliases; // see getFormats
int32_t formatAliasesCapacity;
UProperty idStart;
UProperty idContinue;
MessageFormat(); // default constructor not implemented
/*
* A structure representing one subformat of this MessageFormat.
* Each subformat has a Format object, an offset into the plain
* pattern text fPattern, and an argument number. The argument
* number corresponds to the array of arguments to be formatted.
* @internal
*/
class Subformat;
/**
* A MessageFormat contains an array of subformats. This array
* needs to grow dynamically if the MessageFormat is modified.
*/
Subformat* subformats;
int32_t subformatCount;
int32_t subformatCapacity;
/**
* A MessageFormat formats an array of arguments. Each argument
* has an expected type, based on the pattern. For example, if
* the pattern contains the subformat "{3,number,integer}", then
* we expect argument 3 to have type Formattable::kLong. This
* array needs to grow dynamically if the MessageFormat is
* modified.
*/
Formattable::Type* argTypes;
int32_t argTypeCount;
int32_t argTypeCapacity;
/**
* Is true iff all argument names are non-negative numbers.
*
*/
UBool isArgNumeric;
// Variable-size array management
UBool allocateSubformats(int32_t capacity);
UBool allocateArgTypes(int32_t capacity);
/**
* Default Format objects used when no format is specified and a
* numeric or date argument is formatted. These are volatile
* cache objects maintained only for performance. They do not
* participate in operator=(), copy constructor(), nor
* operator==().
*/
NumberFormat* defaultNumberFormat;
DateFormat* defaultDateFormat;
/**
* Method to retrieve default formats (or NULL on failure).
* These are semantically const, but may modify *this.
*/
const NumberFormat* getDefaultNumberFormat(UErrorCode&) const;
const DateFormat* getDefaultDateFormat(UErrorCode&) const;
/**
* Finds the word s, in the keyword list and returns the located index.
* @param s the keyword to be searched for.
* @param list the list of keywords to be searched with.
* @return the index of the list which matches the keyword s.
*/
static int32_t findKeyword( const UnicodeString& s,
const UChar * const *list);
/**
* Formats the array of arguments and copies the result into the
* result buffer, updates the field position.
*
* @param arguments The formattable objects array.
* @param cnt The array count.
* @param appendTo Output parameter to receive result.
* Result is appended to existing contents.
* @param status Field position status.
* @param recursionProtection
* Initially zero. Bits 0..9 are used to indicate
* that a parameter has already been seen, to
* avoid recursion. Currently unused.
* @param success The error code status.
* @return Reference to 'appendTo' parameter.
*/
UnicodeString& format( const Formattable* arguments,
int32_t cnt,
UnicodeString& appendTo,
FieldPosition& status,
int32_t recursionProtection,
UErrorCode& success) const;
UnicodeString& format( const Formattable* arguments,
const UnicodeString *argumentNames,
int32_t cnt,
UnicodeString& appendTo,
FieldPosition& status,
int32_t recursionProtection,
UErrorCode& success) const;
void makeFormat(int32_t offsetNumber,
UnicodeString* segments,
UParseError& parseError,
UErrorCode& success);
/**
* Convenience method that ought to be in NumberFormat
*/
NumberFormat* createIntegerFormat(const Locale& locale, UErrorCode& status) const;
/**
* Checks the range of the source text to quote the special
* characters, { and ' and copy to target buffer.
* @param source
* @param start the text offset to start the process of in the source string
* @param end the text offset to end the process of in the source string
* @param appendTo Output parameter to receive result.
* Result is appended to existing contents.
*/
static void copyAndFixQuotes(const UnicodeString& appendTo, int32_t start, int32_t end, UnicodeString& target);
/**
* Returns array of argument types in the parsed pattern
* for use in C API. Only for the use of umsg_vformat(). Not
* for public consumption.
* @param listCount Output parameter to receive the size of array
* @return The array of formattable types in the pattern
* @internal
*/
const Formattable::Type* getArgTypeList(int32_t& listCount) const {
listCount = argTypeCount;
return argTypes;
}
/**
* Returns FALSE if the argument name is not legal.
* @param argName argument name.
* @return TRUE if the argument name is legal, otherwise return FALSE.
*/
UBool isLegalArgName(const UnicodeString& argName) const;
friend class MessageFormatAdapter; // getFormatTypeList() access
};
inline UnicodeString&
MessageFormat::format(const Formattable& obj,
UnicodeString& appendTo,
UErrorCode& status) const {
return Format::format(obj, appendTo, status);
}
U_NAMESPACE_END
#endif /* #if !UCONFIG_NO_FORMATTING */
#endif // _MSGFMT
//eof
+823
View File
@@ -0,0 +1,823 @@
/*
********************************************************************
* COPYRIGHT:
* Copyright (c) 1996-2006, International Business Machines Corporation and
* others. All Rights Reserved.
********************************************************************
*/
#ifndef NORMLZR_H
#define NORMLZR_H
#include "unicode/utypes.h"
/**
* \file
* \brief C++ API: Unicode Normalization
*/
#if !UCONFIG_NO_NORMALIZATION
#include "unicode/uobject.h"
#include "unicode/unistr.h"
#include "unicode/chariter.h"
#include "unicode/unorm.h"
struct UCharIterator;
typedef struct UCharIterator UCharIterator; /**< C typedef for struct UCharIterator. @stable ICU 2.1 */
U_NAMESPACE_BEGIN
/**
* The Normalizer class supports the standard normalization forms described in
* <a href="http://www.unicode.org/unicode/reports/tr15/" target="unicode">
* Unicode Standard Annex #15: Unicode Normalization Forms</a>.
*
* The Normalizer class consists of two parts:
* - static functions that normalize strings or test if strings are normalized
* - a Normalizer object is an iterator that takes any kind of text and
* provides iteration over its normalized form
*
* The Normalizer class is not suitable for subclassing.
*
* The static functions are basically wrappers around the C implementation,
* using UnicodeString instead of UChar*.
* For basic information about normalization forms and details about the C API
* please see the documentation in unorm.h.
*
* The iterator API with the Normalizer constructors and the non-static functions
* uses a CharacterIterator as input. It is possible to pass a string which
* is then internally wrapped in a CharacterIterator.
* The input text is not normalized all at once, but incrementally where needed
* (providing efficient random access).
* This allows to pass in a large text but spend only a small amount of time
* normalizing a small part of that text.
* However, if the entire text is normalized, then the iterator will be
* slower than normalizing the entire text at once and iterating over the result.
* A possible use of the Normalizer iterator is also to report an index into the
* original text that is close to where the normalized characters come from.
*
* <em>Important:</em> The iterator API was cleaned up significantly for ICU 2.0.
* The earlier implementation reported the getIndex() inconsistently,
* and previous() could not be used after setIndex(), next(), first(), and current().
*
* Normalizer allows to start normalizing from anywhere in the input text by
* calling setIndexOnly(), first(), or last().
* Without calling any of these, the iterator will start at the beginning of the text.
*
* At any time, next() returns the next normalized code point (UChar32),
* with post-increment semantics (like CharacterIterator::next32PostInc()).
* previous() returns the previous normalized code point (UChar32),
* with pre-decrement semantics (like CharacterIterator::previous32()).
*
* current() returns the current code point
* (respectively the one at the newly set index) without moving
* the getIndex(). Note that if the text at the current position
* needs to be normalized, then these functions will do that.
* (This is why current() is not const.)
* It is more efficient to call setIndexOnly() instead, which does not
* normalize.
*
* getIndex() always refers to the position in the input text where the normalized
* code points are returned from. It does not always change with each returned
* code point.
* The code point that is returned from any of the functions
* corresponds to text at or after getIndex(), according to the
* function's iteration semantics (post-increment or pre-decrement).
*
* next() returns a code point from at or after the getIndex()
* from before the next() call. After the next() call, the getIndex()
* might have moved to where the next code point will be returned from
* (from a next() or current() call).
* This is semantically equivalent to array access with array[index++]
* (post-increment semantics).
*
* previous() returns a code point from at or after the getIndex()
* from after the previous() call.
* This is semantically equivalent to array access with array[--index]
* (pre-decrement semantics).
*
* Internally, the Normalizer iterator normalizes a small piece of text
* starting at the getIndex() and ending at a following "safe" index.
* The normalized results is stored in an internal string buffer, and
* the code points are iterated from there.
* With multiple iteration calls, this is repeated until the next piece
* of text needs to be normalized, and the getIndex() needs to be moved.
*
* The following "safe" index, the internal buffer, and the secondary
* iteration index into that buffer are not exposed on the API.
* This also means that it is currently not practical to return to
* a particular, arbitrary position in the text because one would need to
* know, and be able to set, in addition to the getIndex(), at least also the
* current index into the internal buffer.
* It is currently only possible to observe when getIndex() changes
* (with careful consideration of the iteration semantics),
* at which time the internal index will be 0.
* For example, if getIndex() is different after next() than before it,
* then the internal index is 0 and one can return to this getIndex()
* later with setIndexOnly().
*
* @author Laura Werner, Mark Davis, Markus Scherer
* @stable ICU 2.0
*/
class U_COMMON_API Normalizer : public UObject {
public:
/**
* If DONE is returned from an iteration function that returns a code point,
* then there are no more normalization results available.
* @stable ICU 2.0
*/
enum {
DONE=0xffff
};
// Constructors
/**
* Creates a new <code>Normalizer</code> object for iterating over the
* normalized form of a given string.
* <p>
* @param str The string to be normalized. The normalization
* will start at the beginning of the string.
*
* @param mode The normalization mode.
* @stable ICU 2.0
*/
Normalizer(const UnicodeString& str, UNormalizationMode mode);
/**
* Creates a new <code>Normalizer</code> object for iterating over the
* normalized form of a given string.
* <p>
* @param str The string to be normalized. The normalization
* will start at the beginning of the string.
*
* @param length Length of the string, or -1 if NUL-terminated.
* @param mode The normalization mode.
* @stable ICU 2.0
*/
Normalizer(const UChar* str, int32_t length, UNormalizationMode mode);
/**
* Creates a new <code>Normalizer</code> object for iterating over the
* normalized form of the given text.
* <p>
* @param iter The input text to be normalized. The normalization
* will start at the beginning of the string.
*
* @param mode The normalization mode.
* @stable ICU 2.0
*/
Normalizer(const CharacterIterator& iter, UNormalizationMode mode);
/**
* Copy constructor.
* @param copy The object to be copied.
* @stable ICU 2.0
*/
Normalizer(const Normalizer& copy);
/**
* Destructor
* @stable ICU 2.0
*/
virtual ~Normalizer();
//-------------------------------------------------------------------------
// Static utility methods
//-------------------------------------------------------------------------
/**
* Normalizes a <code>UnicodeString</code> according to the specified normalization mode.
* This is a wrapper for unorm_normalize(), using UnicodeString's.
*
* The <code>options</code> parameter specifies which optional
* <code>Normalizer</code> features are to be enabled for this operation.
*
* @param source the input string to be normalized.
* @param mode the normalization mode
* @param options the optional features to be enabled (0 for no options)
* @param result The normalized string (on output).
* @param status The error code.
* @stable ICU 2.0
*/
static void U_EXPORT2 normalize(const UnicodeString& source,
UNormalizationMode mode, int32_t options,
UnicodeString& result,
UErrorCode &status);
/**
* Compose a <code>UnicodeString</code>.
* This is equivalent to normalize() with mode UNORM_NFC or UNORM_NFKC.
* This is a wrapper for unorm_normalize(), using UnicodeString's.
*
* The <code>options</code> parameter specifies which optional
* <code>Normalizer</code> features are to be enabled for this operation.
*
* @param source the string to be composed.
* @param compat Perform compatibility decomposition before composition.
* If this argument is <code>FALSE</code>, only canonical
* decomposition will be performed.
* @param options the optional features to be enabled (0 for no options)
* @param result The composed string (on output).
* @param status The error code.
* @stable ICU 2.0
*/
static void U_EXPORT2 compose(const UnicodeString& source,
UBool compat, int32_t options,
UnicodeString& result,
UErrorCode &status);
/**
* Static method to decompose a <code>UnicodeString</code>.
* This is equivalent to normalize() with mode UNORM_NFD or UNORM_NFKD.
* This is a wrapper for unorm_normalize(), using UnicodeString's.
*
* The <code>options</code> parameter specifies which optional
* <code>Normalizer</code> features are to be enabled for this operation.
*
* @param source the string to be decomposed.
* @param compat Perform compatibility decomposition.
* If this argument is <code>FALSE</code>, only canonical
* decomposition will be performed.
* @param options the optional features to be enabled (0 for no options)
* @param result The decomposed string (on output).
* @param status The error code.
* @stable ICU 2.0
*/
static void U_EXPORT2 decompose(const UnicodeString& source,
UBool compat, int32_t options,
UnicodeString& result,
UErrorCode &status);
/**
* Performing quick check on a string, to quickly determine if the string is
* in a particular normalization format.
* This is a wrapper for unorm_quickCheck(), using a UnicodeString.
*
* Three types of result can be returned UNORM_YES, UNORM_NO or
* UNORM_MAYBE. Result UNORM_YES indicates that the argument
* string is in the desired normalized format, UNORM_NO determines that
* argument string is not in the desired normalized format. A
* UNORM_MAYBE result indicates that a more thorough check is required,
* the user may have to put the string in its normalized form and compare the
* results.
* @param source string for determining if it is in a normalized format
* @param mode normalization format
* @param status A reference to a UErrorCode to receive any errors
* @return UNORM_YES, UNORM_NO or UNORM_MAYBE
*
* @see isNormalized
* @stable ICU 2.0
*/
static inline UNormalizationCheckResult
quickCheck(const UnicodeString &source, UNormalizationMode mode, UErrorCode &status);
/**
* Performing quick check on a string; same as the other version of quickCheck
* but takes an extra options parameter like most normalization functions.
*
* @param source string for determining if it is in a normalized format
* @param mode normalization format
* @param options the optional features to be enabled (0 for no options)
* @param status A reference to a UErrorCode to receive any errors
* @return UNORM_YES, UNORM_NO or UNORM_MAYBE
*
* @see isNormalized
* @stable ICU 2.6
*/
static inline UNormalizationCheckResult
quickCheck(const UnicodeString &source, UNormalizationMode mode, int32_t options, UErrorCode &status);
/**
* Test if a string is in a given normalization form.
* This is semantically equivalent to source.equals(normalize(source, mode)) .
*
* Unlike unorm_quickCheck(), this function returns a definitive result,
* never a "maybe".
* For NFD, NFKD, and FCD, both functions work exactly the same.
* For NFC and NFKC where quickCheck may return "maybe", this function will
* perform further tests to arrive at a TRUE/FALSE result.
*
* @param src String that is to be tested if it is in a normalization format.
* @param mode Which normalization form to test for.
* @param errorCode ICU error code in/out parameter.
* Must fulfill U_SUCCESS before the function call.
* @return Boolean value indicating whether the source string is in the
* "mode" normalization form.
*
* @see quickCheck
* @stable ICU 2.2
*/
static inline UBool
isNormalized(const UnicodeString &src, UNormalizationMode mode, UErrorCode &errorCode);
/**
* Test if a string is in a given normalization form; same as the other version of isNormalized
* but takes an extra options parameter like most normalization functions.
*
* @param src String that is to be tested if it is in a normalization format.
* @param mode Which normalization form to test for.
* @param options the optional features to be enabled (0 for no options)
* @param errorCode ICU error code in/out parameter.
* Must fulfill U_SUCCESS before the function call.
* @return Boolean value indicating whether the source string is in the
* "mode" normalization form.
*
* @see quickCheck
* @stable ICU 2.6
*/
static inline UBool
isNormalized(const UnicodeString &src, UNormalizationMode mode, int32_t options, UErrorCode &errorCode);
/**
* Concatenate normalized strings, making sure that the result is normalized as well.
*
* If both the left and the right strings are in
* the normalization form according to "mode/options",
* then the result will be
*
* \code
* dest=normalize(left+right, mode, options)
* \endcode
*
* For details see unorm_concatenate in unorm.h.
*
* @param left Left source string.
* @param right Right source string.
* @param result The output string.
* @param mode The normalization mode.
* @param options A bit set of normalization options.
* @param errorCode ICU error code in/out parameter.
* Must fulfill U_SUCCESS before the function call.
* @return result
*
* @see unorm_concatenate
* @see normalize
* @see unorm_next
* @see unorm_previous
*
* @stable ICU 2.1
*/
static UnicodeString &
U_EXPORT2 concatenate(UnicodeString &left, UnicodeString &right,
UnicodeString &result,
UNormalizationMode mode, int32_t options,
UErrorCode &errorCode);
/**
* Compare two strings for canonical equivalence.
* Further options include case-insensitive comparison and
* code point order (as opposed to code unit order).
*
* Canonical equivalence between two strings is defined as their normalized
* forms (NFD or NFC) being identical.
* This function compares strings incrementally instead of normalizing
* (and optionally case-folding) both strings entirely,
* improving performance significantly.
*
* Bulk normalization is only necessary if the strings do not fulfill the FCD
* conditions. Only in this case, and only if the strings are relatively long,
* is memory allocated temporarily.
* For FCD strings and short non-FCD strings there is no memory allocation.
*
* Semantically, this is equivalent to
* strcmp[CodePointOrder](NFD(foldCase(s1)), NFD(foldCase(s2)))
* where code point order and foldCase are all optional.
*
* UAX 21 2.5 Caseless Matching specifies that for a canonical caseless match
* the case folding must be performed first, then the normalization.
*
* @param s1 First source string.
* @param s2 Second source string.
*
* @param options A bit set of options:
* - U_FOLD_CASE_DEFAULT or 0 is used for default options:
* Case-sensitive comparison in code unit order, and the input strings
* are quick-checked for FCD.
*
* - UNORM_INPUT_IS_FCD
* Set if the caller knows that both s1 and s2 fulfill the FCD conditions.
* If not set, the function will quickCheck for FCD
* and normalize if necessary.
*
* - U_COMPARE_CODE_POINT_ORDER
* Set to choose code point order instead of code unit order
* (see u_strCompare for details).
*
* - U_COMPARE_IGNORE_CASE
* Set to compare strings case-insensitively using case folding,
* instead of case-sensitively.
* If set, then the following case folding options are used.
*
* - Options as used with case-insensitive comparisons, currently:
*
* - U_FOLD_CASE_EXCLUDE_SPECIAL_I
* (see u_strCaseCompare for details)
*
* - regular normalization options shifted left by UNORM_COMPARE_NORM_OPTIONS_SHIFT
*
* @param errorCode ICU error code in/out parameter.
* Must fulfill U_SUCCESS before the function call.
* @return <0 or 0 or >0 as usual for string comparisons
*
* @see unorm_compare
* @see normalize
* @see UNORM_FCD
* @see u_strCompare
* @see u_strCaseCompare
*
* @stable ICU 2.2
*/
static inline int32_t
compare(const UnicodeString &s1, const UnicodeString &s2,
uint32_t options,
UErrorCode &errorCode);
//-------------------------------------------------------------------------
// Iteration API
//-------------------------------------------------------------------------
/**
* Return the current character in the normalized text.
* current() may need to normalize some text at getIndex().
* The getIndex() is not changed.
*
* @return the current normalized code point
* @stable ICU 2.0
*/
UChar32 current(void);
/**
* Return the first character in the normalized text.
* This is equivalent to setIndexOnly(startIndex()) followed by next().
* (Post-increment semantics.)
*
* @return the first normalized code point
* @stable ICU 2.0
*/
UChar32 first(void);
/**
* Return the last character in the normalized text.
* This is equivalent to setIndexOnly(endIndex()) followed by previous().
* (Pre-decrement semantics.)
*
* @return the last normalized code point
* @stable ICU 2.0
*/
UChar32 last(void);
/**
* Return the next character in the normalized text.
* (Post-increment semantics.)
* If the end of the text has already been reached, DONE is returned.
* The DONE value could be confused with a U+FFFF non-character code point
* in the text. If this is possible, you can test getIndex()<endIndex()
* before calling next(), or (getIndex()<endIndex() || last()!=DONE)
* after calling next(). (Calling last() will change the iterator state!)
*
* The C API unorm_next() is more efficient and does not have this ambiguity.
*
* @return the next normalized code point
* @stable ICU 2.0
*/
UChar32 next(void);
/**
* Return the previous character in the normalized text and decrement.
* (Pre-decrement semantics.)
* If the beginning of the text has already been reached, DONE is returned.
* The DONE value could be confused with a U+FFFF non-character code point
* in the text. If this is possible, you can test
* (getIndex()>startIndex() || first()!=DONE). (Calling first() will change
* the iterator state!)
*
* The C API unorm_previous() is more efficient and does not have this ambiguity.
*
* @return the previous normalized code point
* @stable ICU 2.0
*/
UChar32 previous(void);
/**
* Set the iteration position in the input text that is being normalized,
* without any immediate normalization.
* After setIndexOnly(), getIndex() will return the same index that is
* specified here.
*
* @param index the desired index in the input text.
* @stable ICU 2.0
*/
void setIndexOnly(int32_t index);
/**
* Reset the index to the beginning of the text.
* This is equivalent to setIndexOnly(startIndex)).
* @stable ICU 2.0
*/
void reset(void);
/**
* Retrieve the current iteration position in the input text that is
* being normalized.
*
* A following call to next() will return a normalized code point from
* the input text at or after this index.
*
* After a call to previous(), getIndex() will point at or before the
* position in the input text where the normalized code point
* was returned from with previous().
*
* @return the current index in the input text
* @stable ICU 2.0
*/
int32_t getIndex(void) const;
/**
* Retrieve the index of the start of the input text. This is the begin index
* of the <code>CharacterIterator</code> or the start (i.e. index 0) of the string
* over which this <code>Normalizer</code> is iterating.
*
* @return the smallest index in the input text where the Normalizer operates
* @stable ICU 2.0
*/
int32_t startIndex(void) const;
/**
* Retrieve the index of the end of the input text. This is the end index
* of the <code>CharacterIterator</code> or the length of the string
* over which this <code>Normalizer</code> is iterating.
* This end index is exclusive, i.e., the Normalizer operates only on characters
* before this index.
*
* @return the first index in the input text where the Normalizer does not operate
* @stable ICU 2.0
*/
int32_t endIndex(void) const;
/**
* Returns TRUE when both iterators refer to the same character in the same
* input text.
*
* @param that a Normalizer object to compare this one to
* @return comparison result
* @stable ICU 2.0
*/
UBool operator==(const Normalizer& that) const;
/**
* Returns FALSE when both iterators refer to the same character in the same
* input text.
*
* @param that a Normalizer object to compare this one to
* @return comparison result
* @stable ICU 2.0
*/
inline UBool operator!=(const Normalizer& that) const;
/**
* Returns a pointer to a new Normalizer that is a clone of this one.
* The caller is responsible for deleting the new clone.
* @return a pointer to a new Normalizer
* @stable ICU 2.0
*/
Normalizer* clone(void) const;
/**
* Generates a hash code for this iterator.
*
* @return the hash code
* @stable ICU 2.0
*/
int32_t hashCode(void) const;
//-------------------------------------------------------------------------
// Property access methods
//-------------------------------------------------------------------------
/**
* Set the normalization mode for this object.
* <p>
* <b>Note:</b>If the normalization mode is changed while iterating
* over a string, calls to {@link #next() } and {@link #previous() } may
* return previously buffers characters in the old normalization mode
* until the iteration is able to re-sync at the next base character.
* It is safest to call {@link #setIndexOnly }, {@link #reset() },
* {@link #setText }, {@link #first() },
* {@link #last() }, etc. after calling <code>setMode</code>.
* <p>
* @param newMode the new mode for this <code>Normalizer</code>.
* @see #getUMode
* @stable ICU 2.0
*/
void setMode(UNormalizationMode newMode);
/**
* Return the normalization mode for this object.
*
* This is an unusual name because there used to be a getMode() that
* returned a different type.
*
* @return the mode for this <code>Normalizer</code>
* @see #setMode
* @stable ICU 2.0
*/
UNormalizationMode getUMode(void) const;
/**
* Set options that affect this <code>Normalizer</code>'s operation.
* Options do not change the basic composition or decomposition operation
* that is being performed, but they control whether
* certain optional portions of the operation are done.
* Currently the only available option is obsolete.
*
* It is possible to specify multiple options that are all turned on or off.
*
* @param option the option(s) whose value is/are to be set.
* @param value the new setting for the option. Use <code>TRUE</code> to
* turn the option(s) on and <code>FALSE</code> to turn it/them off.
*
* @see #getOption
* @stable ICU 2.0
*/
void setOption(int32_t option,
UBool value);
/**
* Determine whether an option is turned on or off.
* If multiple options are specified, then the result is TRUE if any
* of them are set.
* <p>
* @param option the option(s) that are to be checked
* @return TRUE if any of the option(s) are set
* @see #setOption
* @stable ICU 2.0
*/
UBool getOption(int32_t option) const;
/**
* Set the input text over which this <code>Normalizer</code> will iterate.
* The iteration position is set to the beginning.
*
* @param newText a string that replaces the current input text
* @param status a UErrorCode
* @stable ICU 2.0
*/
void setText(const UnicodeString& newText,
UErrorCode &status);
/**
* Set the input text over which this <code>Normalizer</code> will iterate.
* The iteration position is set to the beginning.
*
* @param newText a CharacterIterator object that replaces the current input text
* @param status a UErrorCode
* @stable ICU 2.0
*/
void setText(const CharacterIterator& newText,
UErrorCode &status);
/**
* Set the input text over which this <code>Normalizer</code> will iterate.
* The iteration position is set to the beginning.
*
* @param newText a string that replaces the current input text
* @param length the length of the string, or -1 if NUL-terminated
* @param status a UErrorCode
* @stable ICU 2.0
*/
void setText(const UChar* newText,
int32_t length,
UErrorCode &status);
/**
* Copies the input text into the UnicodeString argument.
*
* @param result Receives a copy of the text under iteration.
* @stable ICU 2.0
*/
void getText(UnicodeString& result);
/**
* ICU "poor man's RTTI", returns a UClassID for this class.
* @returns a UClassID for this class.
* @stable ICU 2.2
*/
static UClassID U_EXPORT2 getStaticClassID();
/**
* ICU "poor man's RTTI", returns a UClassID for the actual class.
* @return a UClassID for the actual class.
* @stable ICU 2.2
*/
virtual UClassID getDynamicClassID() const;
private:
//-------------------------------------------------------------------------
// Private functions
//-------------------------------------------------------------------------
Normalizer(); // default constructor not implemented
Normalizer &operator=(const Normalizer &that); // assignment operator not implemented
// Private utility methods for iteration
// For documentation, see the source code
UBool nextNormalize();
UBool previousNormalize();
void init(CharacterIterator *iter);
void clearBuffer(void);
//-------------------------------------------------------------------------
// Private data
//-------------------------------------------------------------------------
UNormalizationMode fUMode;
int32_t fOptions;
// The input text and our position in it
UCharIterator *text;
// The normalization buffer is the result of normalization
// of the source in [currentIndex..nextIndex[ .
int32_t currentIndex, nextIndex;
// A buffer for holding intermediate results
UnicodeString buffer;
int32_t bufferPos;
};
//-------------------------------------------------------------------------
// Inline implementations
//-------------------------------------------------------------------------
inline UBool
Normalizer::operator!= (const Normalizer& other) const
{ return ! operator==(other); }
inline UNormalizationCheckResult
Normalizer::quickCheck(const UnicodeString& source,
UNormalizationMode mode,
UErrorCode &status) {
if(U_FAILURE(status)) {
return UNORM_MAYBE;
}
return unorm_quickCheck(source.getBuffer(), source.length(),
mode, &status);
}
inline UNormalizationCheckResult
Normalizer::quickCheck(const UnicodeString& source,
UNormalizationMode mode, int32_t options,
UErrorCode &status) {
if(U_FAILURE(status)) {
return UNORM_MAYBE;
}
return unorm_quickCheckWithOptions(source.getBuffer(), source.length(),
mode, options, &status);
}
inline UBool
Normalizer::isNormalized(const UnicodeString& source,
UNormalizationMode mode,
UErrorCode &status) {
if(U_FAILURE(status)) {
return FALSE;
}
return unorm_isNormalized(source.getBuffer(), source.length(),
mode, &status);
}
inline UBool
Normalizer::isNormalized(const UnicodeString& source,
UNormalizationMode mode, int32_t options,
UErrorCode &status) {
if(U_FAILURE(status)) {
return FALSE;
}
return unorm_isNormalizedWithOptions(source.getBuffer(), source.length(),
mode, options, &status);
}
inline int32_t
Normalizer::compare(const UnicodeString &s1, const UnicodeString &s2,
uint32_t options,
UErrorCode &errorCode) {
// all argument checking is done in unorm_compare
return unorm_compare(s1.getBuffer(), s1.length(),
s2.getBuffer(), s2.length(),
options,
&errorCode);
}
U_NAMESPACE_END
#endif /* #if !UCONFIG_NO_NORMALIZATION */
#endif // NORMLZR_H
+892
View File
@@ -0,0 +1,892 @@
/*
********************************************************************************
* Copyright (C) 1997-2009, International Business Machines Corporation and others.
* All Rights Reserved.
********************************************************************************
*
* File NUMFMT.H
*
* Modification History:
*
* Date Name Description
* 02/19/97 aliu Converted from java.
* 03/18/97 clhuang Updated per C++ implementation.
* 04/17/97 aliu Changed DigitCount to int per code review.
* 07/20/98 stephen JDK 1.2 sync up. Added scientific support.
* Changed naming conventions to match C++ guidelines
* Derecated Java style constants (eg, INTEGER_FIELD)
********************************************************************************
*/
#ifndef NUMFMT_H
#define NUMFMT_H
#include "unicode/utypes.h"
/**
* \file
* \brief C++ API: Abstract base class for all number formats.
*/
#if !UCONFIG_NO_FORMATTING
#include "unicode/unistr.h"
#include "unicode/format.h"
#include "unicode/unum.h" // UNumberFormatStyle
#include "unicode/locid.h"
U_NAMESPACE_BEGIN
#if !UCONFIG_NO_SERVICE
class NumberFormatFactory;
class StringEnumeration;
#endif
/**
*
* Abstract base class for all number formats. Provides interface for
* formatting and parsing a number. Also provides methods for
* determining which locales have number formats, and what their names
* are.
* <P>
* NumberFormat helps you to format and parse numbers for any locale.
* Your code can be completely independent of the locale conventions
* for decimal points, thousands-separators, or even the particular
* decimal digits used, or whether the number format is even decimal.
* <P>
* To format a number for the current Locale, use one of the static
* factory methods:
* <pre>
* \code
* double myNumber = 7.0;
* UnicodeString myString;
* UErrorCode success = U_ZERO_ERROR;
* NumberFormat* nf = NumberFormat::createInstance(success)
* nf->format(myNumber, myString);
* cout << " Example 1: " << myString << endl;
* \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
* UnicodeString myString;
* UErrorCode success = U_ZERO_ERROR;
* nf = NumberFormat::createInstance( success );
* int32_t a[] = { 123, 3333, -1234567 };
* const int32_t a_len = sizeof(a) / sizeof(a[0]);
* myString.remove();
* for (int32_t i = 0; i < a_len; i++) {
* nf->format(a[i], myString);
* myString += " ; ";
* }
* cout << " Example 2: " << myString << endl;
* \endcode
* </pre>
* To format a number for a different Locale, specify it in the
* call to createInstance().
* <pre>
* \code
* nf = NumberFormat::createInstance( Locale::FRENCH, success );
* \endcode
* </pre>
* You can use a NumberFormat to parse also.
* <pre>
* \code
* UErrorCode success;
* Formattable result(-999); // initialized with error code
* nf->parse(myString, result, success);
* \endcode
* </pre>
* Use createInstance to get the normal number format for that country.
* There are other static factory methods available. Use getCurrency
* to get the currency number format for that country. Use getPercent
* to get a format for displaying percentages. With this format, a
* fraction from 0.53 is displayed as 53%.
* <P>
* Starting from ICU 4.2, you can use createInstance() by passing in a 'style'
* as parameter to get the correct instance.
* For example,
* use createInstance(...kNumberStyle...) to get the normal number format,
* createInstance(...kPercentStyle...) to get a format for displaying
* percentage,
* createInstance(...kScientificStyle...) to get a format for displaying
* scientific number,
* createInstance(...kCurrencyStyle...) to get the currency number format,
* in which the currency is represented by its symbol, for example, "$3.00".
* createInstance(...kIsoCurrencyStyle...) to get the currency number format,
* in which the currency is represented by its ISO code, for example "USD3.00".
* createInstance(...kPluralCurrencyStyle...) to get the currency number format,
* in which the currency is represented by its full name in plural format,
* for example, "3.00 US dollars" or "1.00 US dollar".
* <P>
* You can also control the display of numbers with such methods as
* getMinimumFractionDigits. If you want even more control over the
* format or parsing, or want to give your users more control, you can
* try casting the NumberFormat you get from the factory methods to a
* DecimalNumberFormat. This will work for the vast majority of
* countries; just remember to put it in a try block in case you
* encounter an unusual one.
* <P>
* You can also use forms of the parse and format methods with
* ParsePosition and FieldPosition to allow you to:
* <ul type=round>
* <li>(a) progressively parse through pieces of a string.
* <li>(b) align the decimal point and other areas.
* </ul>
* For example, you can align numbers in two ways.
* <P>
* If you are using a monospaced font with spacing for alignment, you
* can pass the FieldPosition in your format call, with field =
* INTEGER_FIELD. On output, getEndIndex will be set to the offset
* between the last character of the integer and the decimal. Add
* (desiredSpaceCount - getEndIndex) spaces at the front of the
* string.
* <P>
* If you are using proportional fonts, instead of padding with
* spaces, measure the width of the string in pixels from the start to
* getEndIndex. Then move the pen by (desiredPixelWidth -
* widthToAlignmentPoint) before drawing the text. It also works
* where there is no decimal, but possibly additional characters at
* the end, e.g. with parentheses in negative numbers: "(12)" for -12.
* <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.
*
* @stable ICU 2.0
*/
class U_I18N_API NumberFormat : public Format {
public:
/**
* Constants for various number format styles.
* kNumberStyle specifies a normal number style of format.
* kCurrencyStyle specifies a currency format using currency symbol name,
* such as in "$1.00".
* kPercentStyle specifies a style of format to display percent.
* kScientificStyle specifies a style of format to display scientific number.
* kISOCurrencyStyle specifies a currency format using ISO currency code,
* such as in "USD1.00".
* kPluralCurrencyStyle specifies a currency format using currency plural
* names, such as in "1.00 US dollar" and "3.00 US dollars".
* @draft ICU 4.2
*/
enum EStyles {
kNumberStyle,
kCurrencyStyle,
kPercentStyle,
kScientificStyle,
kIsoCurrencyStyle,
kPluralCurrencyStyle,
kStyleCount // ALWAYS LAST ENUM: number of styles
};
/**
* Alignment Field constants used to construct a FieldPosition object.
* Signifies that the position of the integer part or fraction part of
* a formatted number should be returned.
*
* @see FieldPosition
* @stable ICU 2.0
*/
enum EAlignmentFields {
kIntegerField,
kFractionField,
/**
* These constants are provided for backwards compatibility only.
* Please use the C++ style constants defined above.
* @stable ICU 2.0
*/
INTEGER_FIELD = kIntegerField,
FRACTION_FIELD = kFractionField
};
/**
* Destructor.
* @stable ICU 2.0
*/
virtual ~NumberFormat();
/**
* Return true if the given Format objects are semantically equal.
* Objects of different subclasses are considered unequal.
* @return true if the given Format objects are semantically equal.
* @stable ICU 2.0
*/
virtual UBool operator==(const Format& other) const;
/**
* Format an object to produce a string. This method handles
* Formattable objects with numeric types. If the Formattable
* object type is not a numeric type, 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;
/**
* Parse a string to produce an object. This methods handles
* parsing of numeric strings into Formattable objects with numeric
* 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
* indicates the position after the successfully parsed text. If
* an error occurs, parse_pos.index is unchanged.
* <P>
* When parsing, leading whitespace is discarded (with 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.
* @return A newly created Formattable* object, or NULL
* on failure. The caller owns this and should
* delete it when done.
* @stable ICU 2.0
*/
virtual void parseObject(const UnicodeString& source,
Formattable& result,
ParsePosition& parse_pos) const;
/**
* Format a double number. These methods call the NumberFormat
* pure virtual format() methods with the default FieldPosition.
*
* @param number The value to be formatted.
* @param appendTo Output parameter to receive result.
* Result is appended to existing contents.
* @return Reference to 'appendTo' parameter.
* @stable ICU 2.0
*/
UnicodeString& format( double number,
UnicodeString& appendTo) const;
/**
* Format a long number. These methods call the NumberFormat
* pure virtual format() methods with the default FieldPosition.
*
* @param number The value to be formatted.
* @param appendTo Output parameter to receive result.
* Result is appended to existing contents.
* @return Reference to 'appendTo' parameter.
* @stable ICU 2.0
*/
UnicodeString& format( int32_t number,
UnicodeString& appendTo) const;
/**
* Format an int64 number. These methods call the NumberFormat
* pure virtual format() methods with the default FieldPosition.
*
* @param number The value to be formatted.
* @param appendTo Output parameter to receive result.
* Result is appended to existing contents.
* @return Reference to 'appendTo' parameter.
* @stable ICU 2.8
*/
UnicodeString& format( int64_t number,
UnicodeString& appendTo) const;
/**
* Format a double number. Concrete subclasses must implement
* these pure virtual methods.
*
* @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.
* @stable ICU 2.0
*/
virtual UnicodeString& format(double number,
UnicodeString& appendTo,
FieldPosition& pos) const = 0;
/**
* Format a long number. Concrete subclasses must implement
* these pure virtual methods.
*
* @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.
* @stable ICU 2.0
*/
virtual UnicodeString& format(int32_t number,
UnicodeString& appendTo,
FieldPosition& pos) const = 0;
/**
* Format an int64 number. (Not abstract to retain compatibility
* with earlier releases, however subclasses should override this
* method as it just delegates to format(int32_t number...);
*
* @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.
* @stable ICU 2.8
*/
virtual UnicodeString& format(int64_t number,
UnicodeString& appendTo,
FieldPosition& pos) const;
/**
* Redeclared Format method.
* @param obj The object to be formatted.
* @param appendTo Output parameter to receive result.
* Result is appended to existing contents.
* @param status Output parameter set to a failure error code
* when a failure occurs.
* @return Reference to 'appendTo' parameter.
* @stable ICU 2.0
*/
UnicodeString& format(const Formattable& obj,
UnicodeString& appendTo,
UErrorCode& status) const;
/**
* Return a long if possible (e.g. within range LONG_MAX,
* LONG_MAX], and with no decimals), otherwise a double. If
* IntegerOnly is set, will stop at a decimal point (or equivalent;
* e.g. for rational numbers "1 2/3", will stop after the 1).
* <P>
* If no object can be parsed, index is unchanged, and NULL is
* returned.
* <P>
* This is a pure virtual which concrete subclasses must implement.
*
* @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.
* @return A Formattable object of numeric type. The caller
* owns this an must delete it. NULL on failure.
* @stable ICU 2.0
*/
virtual void parse(const UnicodeString& text,
Formattable& result,
ParsePosition& parsePosition) const = 0;
/**
* Parse a string as a numeric value, and return a Formattable
* numeric object. This method parses integers only if IntegerOnly
* is set.
*
* @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 status Output parameter set to a failure error code
* when a failure occurs.
* @return A Formattable object of numeric type. The caller
* owns this an must delete it. NULL on failure.
* @see NumberFormat::isParseIntegerOnly
* @stable ICU 2.0
*/
virtual void parse( const UnicodeString& text,
Formattable& result,
UErrorCode& status) const;
/**
* 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.
*
* @param text the string to parse
* @param result output parameter to receive result. This will have
* its currency set to the parsed ISO currency code.
* @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 a reference to result
* @internal
*/
virtual Formattable& parseCurrency(const UnicodeString& text,
Formattable& result,
ParsePosition& pos) const;
/**
* Return true if this format will parse numbers as integers
* only. For example in the English locale, with ParseIntegerOnly
* true, the string "1234." would be parsed as the integer value
* 1234 and parsing would stop at the "." character. Of course,
* the exact format accepted by the parse operation is locale
* dependant and determined by sub-classes of NumberFormat.
* @return true if this format will parse numbers as integers
* only.
* @stable ICU 2.0
*/
UBool isParseIntegerOnly(void) const;
/**
* Sets whether or not numbers should be parsed as integers only.
* @param value set True, this format will parse numbers as integers
* only.
* @see isParseIntegerOnly
* @stable ICU 2.0
*/
virtual void setParseIntegerOnly(UBool value);
/**
* Returns the default number format for the current default
* locale. The default format is one of the styles provided by
* the other factory methods: getNumberInstance,
* getCurrencyInstance or getPercentInstance. Exactly which one
* is locale dependant.
* @stable ICU 2.0
*/
static NumberFormat* U_EXPORT2 createInstance(UErrorCode&);
/**
* Returns the default number format for the specified locale.
* The default format is one of the styles provided by the other
* factory methods: getNumberInstance, getCurrencyInstance or
* getPercentInstance. Exactly which one is locale dependant.
* @param inLocale the given locale.
* @stable ICU 2.0
*/
static NumberFormat* U_EXPORT2 createInstance(const Locale& inLocale,
UErrorCode&);
/**
* Creates the specified decimal format style of the desired locale.
* @param desiredLocale the given locale.
* @param choice the given style.
* @param success Output param filled with success/failure status.
* @return A new NumberFormat instance.
* @draft ICU 4.2
*/
static NumberFormat* U_EXPORT2 createInstance(const Locale& desiredLocale, EStyles choice, UErrorCode& success);
/**
* Returns a currency format for the current default locale.
* @stable ICU 2.0
*/
static NumberFormat* U_EXPORT2 createCurrencyInstance(UErrorCode&);
/**
* Returns a currency format for the specified locale.
* @param inLocale the given locale.
* @stable ICU 2.0
*/
static NumberFormat* U_EXPORT2 createCurrencyInstance(const Locale& inLocale,
UErrorCode&);
/**
* Returns a percentage format for the current default locale.
* @stable ICU 2.0
*/
static NumberFormat* U_EXPORT2 createPercentInstance(UErrorCode&);
/**
* Returns a percentage format for the specified locale.
* @param inLocale the given locale.
* @stable ICU 2.0
*/
static NumberFormat* U_EXPORT2 createPercentInstance(const Locale& inLocale,
UErrorCode&);
/**
* Returns a scientific format for the current default locale.
* @stable ICU 2.0
*/
static NumberFormat* U_EXPORT2 createScientificInstance(UErrorCode&);
/**
* Returns a scientific format for the specified locale.
* @param inLocale the given locale.
* @stable ICU 2.0
*/
static NumberFormat* U_EXPORT2 createScientificInstance(const Locale& inLocale,
UErrorCode&);
/**
* Get the set of Locales for which NumberFormats are installed.
* @param count Output param to receive the size of the locales
* @stable ICU 2.0
*/
static const Locale* U_EXPORT2 getAvailableLocales(int32_t& count);
#if !UCONFIG_NO_SERVICE
/**
* Register a new NumberFormatFactory. The factory will be adopted.
* @param toAdopt the NumberFormatFactory instance to be adopted
* @param status the in/out status code, no special meanings are assigned
* @return a registry key that can be used to unregister this factory
* @stable ICU 2.6
*/
static URegistryKey U_EXPORT2 registerFactory(NumberFormatFactory* toAdopt, UErrorCode& status);
/**
* Unregister a previously-registered NumberFormatFactory using the key returned from the
* register call. Key becomes invalid after a successful call and should not be used again.
* The NumberFormatFactory corresponding to the key will be deleted.
* @param key the registry key returned by a previous call to registerFactory
* @param status the in/out status code, no special meanings are assigned
* @return TRUE if the factory for the key was successfully unregistered
* @stable ICU 2.6
*/
static UBool U_EXPORT2 unregister(URegistryKey key, UErrorCode& status);
/**
* Return a StringEnumeration over the locales available at the time of the call,
* including registered locales.
* @return a StringEnumeration over the locales available at the time of the call
* @stable ICU 2.6
*/
static StringEnumeration* U_EXPORT2 getAvailableLocales(void);
#endif /* UCONFIG_NO_SERVICE */
/**
* Returns true if grouping is used in this format. For example,
* in the English locale, with grouping on, the number 1234567
* might be formatted as "1,234,567". The grouping separator as
* well as the size of each group is locale dependant and is
* determined by sub-classes of NumberFormat.
* @see setGroupingUsed
* @stable ICU 2.0
*/
UBool isGroupingUsed(void) const;
/**
* Set whether or not grouping will be used in this format.
* @param newValue True, grouping will be used in this format.
* @see getGroupingUsed
* @stable ICU 2.0
*/
virtual void setGroupingUsed(UBool newValue);
/**
* Returns the maximum number of digits allowed in the integer portion of a
* number.
* @return the maximum number of digits allowed in the integer portion of a
* number.
* @see setMaximumIntegerDigits
* @stable ICU 2.0
*/
int32_t getMaximumIntegerDigits(void) const;
/**
* Sets the maximum number of digits allowed in the integer portion of a
* number. maximumIntegerDigits must be >= minimumIntegerDigits. If the
* new value for maximumIntegerDigits is less than the current value
* of minimumIntegerDigits, then minimumIntegerDigits will also be set to
* the new value.
*
* @param newValue the new value for the maximum number of digits
* allowed in the integer portion of a number.
* @see getMaximumIntegerDigits
* @stable ICU 2.0
*/
virtual void setMaximumIntegerDigits(int32_t newValue);
/**
* Returns the minimum number of digits allowed in the integer portion of a
* number.
* @return the minimum number of digits allowed in the integer portion of a
* number.
* @see setMinimumIntegerDigits
* @stable ICU 2.0
*/
int32_t getMinimumIntegerDigits(void) const;
/**
* Sets the minimum number of digits allowed in the integer portion of a
* number. minimumIntegerDigits must be &lt;= maximumIntegerDigits. If the
* new value for minimumIntegerDigits exceeds the current value
* of maximumIntegerDigits, then maximumIntegerDigits will also be set to
* the new value.
* @param newValue the new value to be set.
* @see getMinimumIntegerDigits
* @stable ICU 2.0
*/
virtual void setMinimumIntegerDigits(int32_t newValue);
/**
* Returns the maximum number of digits allowed in the fraction portion of a
* number.
* @return the maximum number of digits allowed in the fraction portion of a
* number.
* @see setMaximumFractionDigits
* @stable ICU 2.0
*/
int32_t getMaximumFractionDigits(void) const;
/**
* Sets the maximum number of digits allowed in the fraction portion of a
* number. maximumFractionDigits must be >= minimumFractionDigits. If the
* new value for maximumFractionDigits is less than the current value
* of minimumFractionDigits, then minimumFractionDigits will also be set to
* the new value.
* @param newValue the new value to be set.
* @see getMaximumFractionDigits
* @stable ICU 2.0
*/
virtual void setMaximumFractionDigits(int32_t newValue);
/**
* Returns the minimum number of digits allowed in the fraction portion of a
* number.
* @return the minimum number of digits allowed in the fraction portion of a
* number.
* @see setMinimumFractionDigits
* @stable ICU 2.0
*/
int32_t getMinimumFractionDigits(void) const;
/**
* Sets the minimum number of digits allowed in the fraction portion of a
* number. minimumFractionDigits must be &lt;= maximumFractionDigits. If the
* new value for minimumFractionDigits exceeds the current value
* of maximumFractionDigits, then maximumIntegerDigits will also be set to
* the new value
* @param newValue the new value to be set.
* @see getMinimumFractionDigits
* @stable ICU 2.0
*/
virtual void setMinimumFractionDigits(int32_t newValue);
/**
* Sets the currency used to display currency
* amounts. This takes effect immediately, if this format is a
* currency format. If this format is not a currency format, then
* the currency is used if and when this object becomes a
* currency format.
* @param theCurrency a 3-letter ISO code indicating new currency
* to use. It need not be null-terminated. May be the empty
* string or NULL to indicate no currency.
* @param ec input-output error code
* @stable ICU 3.0
*/
virtual void setCurrency(const UChar* theCurrency, UErrorCode& ec);
/**
* Gets the currency used to display currency
* amounts. This may be an empty string for some subclasses.
* @return a 3-letter null-terminated ISO code indicating
* the currency in use, or a pointer to the empty string.
* @stable ICU 2.6
*/
const UChar* getCurrency() const;
public:
/**
* Return the class ID for this class. This is useful for
* comparing to a return value from getDynamicClassID(). Note that,
* because NumberFormat is an abstract base class, no fully constructed object
* will have the class ID returned by NumberFormat::getStaticClassID().
* @return The class ID for all objects of this class.
* @stable ICU 2.0
*/
static UClassID U_EXPORT2 getStaticClassID(void);
/**
* 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.
* <P>
* @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(void) const = 0;
protected:
/**
* Default constructor for subclass use only.
* @stable ICU 2.0
*/
NumberFormat();
/**
* Copy constructor.
* @stable ICU 2.0
*/
NumberFormat(const NumberFormat&);
/**
* Assignment operator.
* @stable ICU 2.0
*/
NumberFormat& operator=(const NumberFormat&);
/**
* Returns the currency in effect for this formatter. Subclasses
* should override this method as needed. Unlike getCurrency(),
* this method should never return "".
* @result output parameter for null-terminated result, which must
* have a capacity of at least 4
* @internal
*/
virtual void getEffectiveCurrency(UChar* result, UErrorCode& ec) const;
private:
/**
* Creates the specified decimal format style of the desired locale.
* @param desiredLocale the given locale.
* @param choice the given style.
* @param success Output param filled with success/failure status.
* @return A new NumberFormat instance.
*/
static NumberFormat* makeInstance(const Locale& desiredLocale, EStyles choice, UErrorCode& success);
UBool fGroupingUsed;
int32_t fMaxIntegerDigits;
int32_t fMinIntegerDigits;
int32_t fMaxFractionDigits;
int32_t fMinFractionDigits;
UBool fParseIntegerOnly;
// ISO currency code
UChar fCurrency[4];
friend class ICUNumberFormatFactory; // access to makeInstance, EStyles
friend class ICUNumberFormatService;
};
#if !UCONFIG_NO_SERVICE
/**
* A NumberFormatFactory is used to register new number formats. The factory
* should be able to create any of the predefined formats for each locale it
* supports. When registered, the locales it supports extend or override the
* locale already supported by ICU.
*
* @stable ICU 2.6
*/
class U_I18N_API NumberFormatFactory : public UObject {
public:
/**
* Destructor
* @stable ICU 3.0
*/
virtual ~NumberFormatFactory();
/**
* Return true if this factory will be visible. Default is true.
* If not visible, the locales supported by this factory will not
* be listed by getAvailableLocales.
* @stable ICU 2.6
*/
virtual UBool visible(void) const = 0;
/**
* Return the locale names directly supported by this factory. The number of names
* is returned in count;
* @stable ICU 2.6
*/
virtual const UnicodeString * getSupportedIDs(int32_t &count, UErrorCode& status) const = 0;
/**
* Return a number format of the appropriate type. If the locale
* is not supported, return null. If the locale is supported, but
* the type is not provided by this service, return null. Otherwise
* return an appropriate instance of NumberFormat.
* @stable ICU 2.6
*/
virtual NumberFormat* createFormat(const Locale& loc, UNumberFormatStyle formatType) = 0;
};
/**
* A NumberFormatFactory that supports a single locale. It can be visible or invisible.
* @stable ICU 2.6
*/
class U_I18N_API SimpleNumberFormatFactory : public NumberFormatFactory {
protected:
/**
* True if the locale supported by this factory is visible.
* @stable ICU 2.6
*/
const UBool _visible;
/**
* The locale supported by this factory, as a UnicodeString.
* @stable ICU 2.6
*/
UnicodeString _id;
public:
/**
* @stable ICU 2.6
*/
SimpleNumberFormatFactory(const Locale& locale, UBool visible = TRUE);
/**
* @stable ICU 3.0
*/
virtual ~SimpleNumberFormatFactory();
/**
* @stable ICU 2.6
*/
virtual UBool visible(void) const;
/**
* @stable ICU 2.6
*/
virtual const UnicodeString * getSupportedIDs(int32_t &count, UErrorCode& status) const;
};
#endif /* #if !UCONFIG_NO_SERVICE */
// -------------------------------------
inline UBool
NumberFormat::isParseIntegerOnly() const
{
return fParseIntegerOnly;
}
inline UnicodeString&
NumberFormat::format(const Formattable& obj,
UnicodeString& appendTo,
UErrorCode& status) const {
return Format::format(obj, appendTo, status);
}
U_NAMESPACE_END
#endif /* #if !UCONFIG_NO_FORMATTING */
#endif // _NUMFMT
//eof
+174
View File
@@ -0,0 +1,174 @@
/*
*******************************************************************************
* Copyright (C) 2009, 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"
/**
* \file
* \brief C++ API: NumberingSystem object
*/
#if !UCONFIG_NO_FORMATTING
#include "unicode/format.h"
#include "unicode/uobject.h"
U_NAMESPACE_BEGIN
/**
* 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.
* 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.
*
* @draft ICU 4.2
*/
NumberingSystem();
/**
* Copy constructor.
* @draft ICU 4.2
*/
NumberingSystem(const NumberingSystem& other);
/**
* Destructor.
* @draft ICU 4.2
*/
virtual ~NumberingSystem();
/**
* Create the default numbering system associated with the specified locale.
* @param inLocale The given locale.
* @param status ICU status
* @draft ICU 4.2
*/
static NumberingSystem* U_EXPORT2 createInstance(const Locale & inLocale, UErrorCode& status);
/**
* Create the default numbering system associated with the default locale.
* @draft 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
* @draft 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.
* @draft ICU 4.2
*/
static StringEnumeration * U_EXPORT2 getAvailableNames(UErrorCode& status);
/**
* Create a numbering system from one of the predefined numbering systems known to ICU.
* @param name The name of the numbering system.
* @param status ICU status
* @draft ICU 4.2
*/
static NumberingSystem* U_EXPORT2 createInstanceByName(const char* name, UErrorCode& status);
/**
* Returns the radix of this numbering system.
* @draft ICU 4.2
*/
int32_t getRadix();
/**
* Returns the description string of this numbering system, which is either
* the string of digits in the case of simple systems, or the ruleset name
* in the case of algorithmic systems.
* @draft ICU 4.2
*/
virtual UnicodeString getDescription();
/**
* Returns TRUE if the given numbering system is algorithmic
*
* @return TRUE if the numbering system is algorithmic.
* Otherwise, return FALSE.
* @draft ICU 4.2
*/
UBool isAlgorithmic() const;
/**
* ICU "poor man's RTTI", returns a UClassID for this class.
*
* @draft ICU 4.2
*
*/
static UClassID U_EXPORT2 getStaticClassID(void);
/**
* ICU "poor man's RTTI", returns a UClassID for the actual class.
*
* @draft ICU 4.2
*/
virtual UClassID getDynamicClassID() const;
private:
UnicodeString desc;
int32_t radix;
UBool algorithmic;
void setRadix(int32_t radix);
void setAlgorithmic(UBool algorithmic);
void setDesc(UnicodeString desc);
static UBool isValidDigitString(const UnicodeString &str);
UBool hasContiguousDecimalDigits() const;
};
U_NAMESPACE_END
#endif /* #if !UCONFIG_NO_FORMATTING */
#endif // _NUMSYS
//eof
+92
View File
@@ -0,0 +1,92 @@
/*
**********************************************************************
* Copyright (C) 1999-2005, International Business Machines
* Corporation and others. All Rights Reserved.
**********************************************************************
* Date Name Description
* 03/14/00 aliu Creation.
* 06/27/00 aliu Change from C++ class to C struct
**********************************************************************
*/
#ifndef PARSEERR_H
#define PARSEERR_H
#include "unicode/utypes.h"
/**
* \file
* \brief C API: Parse Error Information
*/
/**
* The capacity of the context strings in UParseError.
* @stable ICU 2.0
*/
enum { U_PARSE_CONTEXT_LEN = 16 };
/**
* A UParseError struct is used to returned detailed information about
* parsing errors. It is used by ICU parsing engines that parse long
* rules, patterns, or programs, where the text being parsed is long
* enough that more information than a UErrorCode is needed to
* localize the error.
*
* <p>The line, offset, and context fields are optional; parsing
* engines may choose not to use to use them.
*
* <p>The preContext and postContext strings include some part of the
* context surrounding the error. If the source text is "let for=7"
* and "for" is the error (e.g., because it is a reserved word), then
* some examples of what a parser might produce are the following:
*
* <pre>
* preContext postContext
* "" "" The parser does not support context
* "let " "=7" Pre- and post-context only
* "let " "for=7" Pre- and post-context and error text
* "" "for" Error text only
* </pre>
*
* <p>Examples of engines which use UParseError (or may use it in the
* future) are Transliterator, RuleBasedBreakIterator, and
* RegexPattern.
*
* @stable ICU 2.0
*/
typedef struct UParseError {
/**
* The line on which the error occured. If the parser uses this
* field, it sets it to the line number of the source text line on
* which the error appears, which will be be a value >= 1. If the
* parse does not support line numbers, the value will be <= 0.
* @stable ICU 2.0
*/
int32_t line;
/**
* The character offset to the error. If the line field is >= 1,
* then this is the offset from the start of the line. Otherwise,
* this is the offset from the start of the text. If the parser
* does not support this field, it will have a value < 0.
* @stable ICU 2.0
*/
int32_t offset;
/**
* Textual context before the error. Null-terminated. The empty
* string if not supported by parser.
* @stable ICU 2.0
*/
UChar preContext[U_PARSE_CONTEXT_LEN];
/**
* The error itself and/or textual context after the error.
* Null-terminated. The empty string if not supported by parser.
* @stable ICU 2.0
*/
UChar postContext[U_PARSE_CONTEXT_LEN];
} UParseError;
#endif
+230
View File
@@ -0,0 +1,230 @@
/*
* Copyright (C) 1997-2005, International Business Machines Corporation and others. All Rights Reserved.
*******************************************************************************
*
* File PARSEPOS.H
*
* Modification History:
*
* Date Name Description
* 07/09/97 helena Converted from java.
* 07/17/98 stephen Added errorIndex support.
* 05/11/99 stephen Cleaned up.
*******************************************************************************
*/
#ifndef PARSEPOS_H
#define PARSEPOS_H
#include "unicode/utypes.h"
#include "unicode/uobject.h"
U_NAMESPACE_BEGIN
/**
* \file
* \brief C++ API: Canonical Iterator
*/
/**
* <code>ParsePosition</code> is a simple class used by <code>Format</code>
* and its subclasses to keep track of the current position during parsing.
* The <code>parseObject</code> method in the various <code>Format</code>
* classes requires a <code>ParsePosition</code> object as an argument.
*
* <p>
* By design, as you parse through a string with different formats,
* you can use the same <code>ParsePosition</code>, since the index parameter
* records the current position.
*
* The ParsePosition class is not suitable for subclassing.
*
* @version 1.3 10/30/97
* @author Mark Davis, Helena Shih
* @see java.text.Format
*/
class U_COMMON_API ParsePosition : public UObject {
public:
/**
* Default constructor, the index starts with 0 as default.
* @stable ICU 2.0
*/
ParsePosition()
: UObject(),
index(0),
errorIndex(-1)
{}
/**
* Create a new ParsePosition with the given initial index.
* @param newIndex the new text offset.
* @stable ICU 2.0
*/
ParsePosition(int32_t newIndex)
: UObject(),
index(newIndex),
errorIndex(-1)
{}
/**
* Copy constructor
* @param copy the object to be copied from.
* @stable ICU 2.0
*/
ParsePosition(const ParsePosition& copy)
: UObject(copy),
index(copy.index),
errorIndex(copy.errorIndex)
{}
/**
* Destructor
* @stable ICU 2.0
*/
virtual ~ParsePosition();
/**
* Assignment operator
* @stable ICU 2.0
*/
ParsePosition& operator=(const ParsePosition& copy);
/**
* Equality operator.
* @return TRUE if the two parse positions are equal, FALSE otherwise.
* @stable ICU 2.0
*/
UBool operator==(const ParsePosition& that) const;
/**
* Equality operator.
* @return TRUE if the two parse positions are not equal, FALSE otherwise.
* @stable ICU 2.0
*/
UBool operator!=(const ParsePosition& that) const;
/**
* Clone this object.
* Clones can be used concurrently in multiple threads.
* If an error occurs, then NULL is returned.
* The caller must delete the clone.
*
* @return a clone of this object
*
* @see getDynamicClassID
* @stable ICU 2.8
*/
ParsePosition *clone() const;
/**
* Retrieve the current parse position. On input to a parse method, this
* is the index of the character at which parsing will begin; on output, it
* is the index of the character following the last character parsed.
* @return the current index.
* @stable ICU 2.0
*/
int32_t getIndex(void) const;
/**
* Set the current parse position.
* @param index the new index.
* @stable ICU 2.0
*/
void setIndex(int32_t index);
/**
* Set the index at which a parse error occurred. Formatters
* should set this before returning an error code from their
* parseObject method. The default value is -1 if this is not
* set.
* @stable ICU 2.0
*/
void setErrorIndex(int32_t ei);
/**
* Retrieve the index at which an error occurred, or -1 if the
* error index has not been set.
* @stable ICU 2.0
*/
int32_t getErrorIndex(void) const;
/**
* ICU "poor man's RTTI", returns a UClassID for this class.
*
* @stable ICU 2.2
*/
static UClassID U_EXPORT2 getStaticClassID();
/**
* ICU "poor man's RTTI", returns a UClassID for the actual class.
*
* @stable ICU 2.2
*/
virtual UClassID getDynamicClassID() const;
private:
/**
* Input: the place you start parsing.
* <br>Output: position where the parse stopped.
* This is designed to be used serially,
* with each call setting index up for the next one.
*/
int32_t index;
/**
* The index at which a parse error occurred.
*/
int32_t errorIndex;
};
inline ParsePosition&
ParsePosition::operator=(const ParsePosition& copy)
{
index = copy.index;
errorIndex = copy.errorIndex;
return *this;
}
inline UBool
ParsePosition::operator==(const ParsePosition& copy) const
{
if(index != copy.index || errorIndex != copy.errorIndex)
return FALSE;
else
return TRUE;
}
inline UBool
ParsePosition::operator!=(const ParsePosition& copy) const
{
return !operator==(copy);
}
inline int32_t
ParsePosition::getIndex() const
{
return index;
}
inline void
ParsePosition::setIndex(int32_t offset)
{
this->index = offset;
}
inline int32_t
ParsePosition::getErrorIndex() const
{
return errorIndex;
}
inline void
ParsePosition::setErrorIndex(int32_t ei)
{
this->errorIndex = ei;
}
U_NAMESPACE_END
#endif
+381
View File
@@ -0,0 +1,381 @@
/*
******************************************************************************
*
* Copyright (C) 1997-2009, International Business Machines
* Corporation and others. All Rights Reserved.
*
******************************************************************************
*
* FILE NAME : platform.h
*
* Date Name Description
* 05/13/98 nos Creation (content moved here from ptypes.h).
* 03/02/99 stephen Added AS400 support.
* 03/30/99 stephen Added Linux support.
* 04/13/99 stephen Reworked for autoconf.
******************************************************************************
*/
#ifndef _PLATFORM_H
#define _PLATFORM_H
/**
* \file
* \brief Basic types for the platform
*/
/* Define the platform we're on. */
#ifndef U_HAIKU
#define U_HAIKU
#endif
/**
* \def U_HAVE_DIRENT_H
* Define whether dirent.h is available */
#ifndef U_HAVE_DIRENT_H
#define U_HAVE_DIRENT_H 1
#endif
/** Define whether inttypes.h is available */
#ifndef U_HAVE_INTTYPES_H
#define U_HAVE_INTTYPES_H 1
#endif
/**
* Define what support for C++ streams is available.
* If U_IOSTREAM_SOURCE is set to 199711, then &lt;iostream&gt; is available
* (1997711 is the date the ISO/IEC C++ FDIS was published), and then
* one should qualify streams using the std namespace in ICU header
* files.
* If U_IOSTREAM_SOURCE is set to 198506, then &lt;iostream.h&gt; is
* available instead (198506 is the date when Stroustrup published
* "An Extensible I/O Facility for C++" at the summer USENIX conference).
* If U_IOSTREAM_SOURCE is 0, then C++ streams are not available and
* support for them will be silently suppressed in ICU.
*
*/
#ifndef U_IOSTREAM_SOURCE
#define U_IOSTREAM_SOURCE 199711
#endif
/**
* \def U_HAVE_STD_STRING
* Define whether the standard C++ (STL) <string> header is available.
* For platforms that do not use platform.h and do not define this constant
* in their platform-specific headers, std_string.h defaults
* U_HAVE_STD_STRING to 1.
* @draft ICU 4.2
*/
#ifndef U_HAVE_STD_STRING
#define U_HAVE_STD_STRING 1
#endif
/** @{ Determines whether specific types are available */
#ifndef U_HAVE_INT8_T
#define U_HAVE_INT8_T 1
#endif
#ifndef U_HAVE_UINT8_T
#define U_HAVE_UINT8_T 1
#endif
#ifndef U_HAVE_INT16_T
#define U_HAVE_INT16_T 1
#endif
#ifndef U_HAVE_UINT16_T
#define U_HAVE_UINT16_T 1
#endif
#ifndef U_HAVE_INT32_T
#define U_HAVE_INT32_T 1
#endif
#ifndef U_HAVE_UINT32_T
#define U_HAVE_UINT32_T 1
#endif
#ifndef U_HAVE_INT64_T
#define U_HAVE_INT64_T 1
#endif
#ifndef U_HAVE_UINT64_T
#define U_HAVE_UINT64_T 1
#endif
/** @} */
/*===========================================================================*/
/** @{ Generic data types */
/*===========================================================================*/
#include <sys/types.h>
/* If your platform does not have the <inttypes.h> header, you may
need to edit the typedefs below. */
#if U_HAVE_INTTYPES_H
/* autoconf 2.13 sometimes can't properly find the data types in <inttypes.h> */
/* os/390 needs <inttypes.h>, but it doesn't have int8_t, and it sometimes */
/* doesn't have uint8_t depending on the OS version. */
/* So we have this work around. */
#ifdef OS390
/* The features header is needed to get (u)int64_t sometimes. */
#include <features.h>
#if ! U_HAVE_INT8_T
typedef signed char int8_t;
#endif
#if !defined(__uint8_t)
#define __uint8_t 1
typedef unsigned char uint8_t;
#endif
#endif /* OS390 */
#include <inttypes.h>
#else /* U_HAVE_INTTYPES_H */
#if ! U_HAVE_INT8_T
typedef signed char int8_t;
#endif
#if ! U_HAVE_UINT8_T
typedef unsigned char uint8_t;
#endif
#if ! U_HAVE_INT16_T
typedef signed short int16_t;
#endif
#if ! U_HAVE_UINT16_T
typedef unsigned short uint16_t;
#endif
#if ! U_HAVE_INT32_T
typedef signed int int32_t;
#endif
#if ! U_HAVE_UINT32_T
typedef unsigned int uint32_t;
#endif
#if ! U_HAVE_INT64_T
typedef signed long long int64_t;
/* else we may not have a 64-bit type */
#endif
#if ! U_HAVE_UINT64_T
typedef unsigned long long uint64_t;
/* else we may not have a 64-bit type */
#endif
#endif
/** @} */
/*===========================================================================*/
/** @{ Compiler and environment features */
/*===========================================================================*/
/* Define whether namespace is supported */
#ifndef U_HAVE_NAMESPACE
#define U_HAVE_NAMESPACE 1
#endif
/* Determines the endianness of the platform
It's done this way in case multiple architectures are being built at once.
For example, Darwin supports fat binaries, which can be both PPC and x86 based. */
#if defined(BYTE_ORDER) && defined(BIG_ENDIAN)
#define U_IS_BIG_ENDIAN (BYTE_ORDER == BIG_ENDIAN)
#else
#define U_IS_BIG_ENDIAN 0
#endif
/* 1 or 0 to enable or disable threads. If undefined, default is: enable threads. */
#define ICU_USE_THREADS 1
/* On strong memory model CPUs (e.g. x86 CPUs), we use a safe & quick double check lock. */
#if defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__))
#define UMTX_STRONG_MEMORY_MODEL 1
#endif
#ifndef U_DEBUG
#define U_DEBUG 0
#endif
#ifndef U_RELEASE
#define U_RELEASE 1
#endif
/* Determine whether to disable renaming or not. This overrides the
setting in umachine.h which is for all platforms. */
#ifndef U_DISABLE_RENAMING
#define U_DISABLE_RENAMING 0
#endif
/* Determine whether to override new and delete. */
#ifndef U_OVERRIDE_CXX_ALLOCATION
#define U_OVERRIDE_CXX_ALLOCATION 1
#endif
/* Determine whether to override placement new and delete for STL. */
#ifndef U_HAVE_PLACEMENT_NEW
#define U_HAVE_PLACEMENT_NEW 1
#endif
/* Determine whether to enable tracing. */
#ifndef U_ENABLE_TRACING
#define U_ENABLE_TRACING 0
#endif
/* Do we allow ICU users to use the draft APIs by default? */
#ifndef U_DEFAULT_SHOW_DRAFT
#define U_DEFAULT_SHOW_DRAFT 1
#endif
/* Define the library suffix in a C syntax. */
#define U_HAVE_LIB_SUFFIX 0
#define U_LIB_SUFFIX_C_NAME
#define U_LIB_SUFFIX_C_NAME_STRING ""
/** @} */
/*===========================================================================*/
/** @{ Character data types */
/*===========================================================================*/
#if ((defined(OS390) && (!defined(__CHARSET_LIB) || !__CHARSET_LIB))) || defined(OS400)
# define U_CHARSET_FAMILY 1
#endif
/** @} */
/*===========================================================================*/
/** @{ Information about wchar support */
/*===========================================================================*/
#ifndef U_HAVE_WCHAR_H
#define U_HAVE_WCHAR_H 1
#endif
#ifndef U_SIZEOF_WCHAR_T
#define U_SIZEOF_WCHAR_T 4
#endif
#ifndef U_HAVE_WCSCPY
#define U_HAVE_WCSCPY 1
#endif
/** @} */
/**
* @{
* \def U_DECLARE_UTF16
* Do not use this macro. Use the UNICODE_STRING or U_STRING_DECL macros
* instead.
* @internal
*/
#if 1 || defined(U_CHECK_UTF16_STRING)
#if (defined(__xlC__) && defined(__IBM_UTF_LITERAL) && U_SIZEOF_WCHAR_T != 2) \
|| (defined(__HP_aCC) && __HP_aCC >= 035000) \
|| (defined(__HP_cc) && __HP_cc >= 111106)
#define U_DECLARE_UTF16(string) u ## string
#elif (defined(__SUNPRO_CC) && __SUNPRO_CC >= 0x550)
/* || (defined(__SUNPRO_C) && __SUNPRO_C >= 0x580) */
/* Sun's C compiler has issues with this notation, and it's unreliable. */
#define U_DECLARE_UTF16(string) U ## string
#elif U_SIZEOF_WCHAR_T == 2 \
&& (U_CHARSET_FAMILY == 0 || ((defined(OS390) || defined(OS400)) && defined(__UCS2__)))
#define U_DECLARE_UTF16(string) L ## string
#endif
#endif
/** @} */
/*===========================================================================*/
/** @{ Information about POSIX support */
/*===========================================================================*/
#ifndef U_HAVE_NL_LANGINFO_CODESET
#define U_HAVE_NL_LANGINFO_CODESET 0
#endif
#ifndef U_NL_LANGINFO_CODESET
#define U_NL_LANGINFO_CODESET -1
#endif
#if 1
#define U_TZSET tzset
#endif
#if 1
#define U_TIMEZONE timezone
#endif
#if 1
#define U_TZNAME tzname
#endif
#define U_HAVE_MMAP 1
#define U_HAVE_POPEN 1
/** @} */
/*===========================================================================*/
/** @{ Symbol import-export control */
/*===========================================================================*/
#if 0
#define U_EXPORT __attribute__((visibility("default")))
#elif (defined(__SUNPRO_CC) && __SUNPRO_CC >= 0x550) \
|| (defined(__SUNPRO_C) && __SUNPRO_C >= 0x550)
#define U_EXPORT __global
/*#elif defined(__HP_aCC) || defined(__HP_cc)
#define U_EXPORT __declspec(dllexport)*/
#else
#define U_EXPORT
#endif
/* U_CALLCONV is releated to U_EXPORT2 */
#define U_EXPORT2
/* cygwin needs to export/import data */
#ifdef U_CYGWIN
#define U_IMPORT __declspec(dllimport)
#else
#define U_IMPORT
#endif
/* @} */
/*===========================================================================*/
/** @{ Code alignment and C function inlining */
/*===========================================================================*/
#ifndef U_INLINE
# ifdef __cplusplus
# define U_INLINE inline
# else
# define U_INLINE __inline__
# endif
#endif
#ifndef U_ALIGN_CODE
#define U_ALIGN_CODE(n)
#endif
/** @} */
/*===========================================================================*/
/** @{ Programs used by ICU code */
/*===========================================================================*/
/**
* \def U_MAKE
* What program to execute to run 'make'
*/
#ifndef U_MAKE
#define U_MAKE "make"
#endif
/** @} */
#endif
+381
View File
@@ -0,0 +1,381 @@
/*
******************************************************************************
*
* Copyright (C) 1997-2009, International Business Machines
* Corporation and others. All Rights Reserved.
*
******************************************************************************
*
* FILE NAME : platform.h
*
* Date Name Description
* 05/13/98 nos Creation (content moved here from ptypes.h).
* 03/02/99 stephen Added AS400 support.
* 03/30/99 stephen Added Linux support.
* 04/13/99 stephen Reworked for autoconf.
******************************************************************************
*/
#ifndef _PLATFORM_H
#define _PLATFORM_H
/**
* \file
* \brief Basic types for the platform
*/
/* Define the platform we're on. */
#ifndef @platform@
#define @platform@
#endif
/**
* \def U_HAVE_DIRENT_H
* Define whether dirent.h is available */
#ifndef U_HAVE_DIRENT_H
#define U_HAVE_DIRENT_H @U_HAVE_DIRENT_H@
#endif
/** Define whether inttypes.h is available */
#ifndef U_HAVE_INTTYPES_H
#define U_HAVE_INTTYPES_H @U_HAVE_INTTYPES_H@
#endif
/**
* Define what support for C++ streams is available.
* If U_IOSTREAM_SOURCE is set to 199711, then &lt;iostream&gt; is available
* (1997711 is the date the ISO/IEC C++ FDIS was published), and then
* one should qualify streams using the std namespace in ICU header
* files.
* If U_IOSTREAM_SOURCE is set to 198506, then &lt;iostream.h&gt; is
* available instead (198506 is the date when Stroustrup published
* "An Extensible I/O Facility for C++" at the summer USENIX conference).
* If U_IOSTREAM_SOURCE is 0, then C++ streams are not available and
* support for them will be silently suppressed in ICU.
*
*/
#ifndef U_IOSTREAM_SOURCE
#define U_IOSTREAM_SOURCE @U_IOSTREAM_SOURCE@
#endif
/**
* \def U_HAVE_STD_STRING
* Define whether the standard C++ (STL) <string> header is available.
* For platforms that do not use platform.h and do not define this constant
* in their platform-specific headers, std_string.h defaults
* U_HAVE_STD_STRING to 1.
* @draft ICU 4.2
*/
#ifndef U_HAVE_STD_STRING
#define U_HAVE_STD_STRING @U_HAVE_STD_STRING@
#endif
/** @{ Determines whether specific types are available */
#ifndef U_HAVE_INT8_T
#define U_HAVE_INT8_T @HAVE_INT8_T@
#endif
#ifndef U_HAVE_UINT8_T
#define U_HAVE_UINT8_T @HAVE_UINT8_T@
#endif
#ifndef U_HAVE_INT16_T
#define U_HAVE_INT16_T @HAVE_INT16_T@
#endif
#ifndef U_HAVE_UINT16_T
#define U_HAVE_UINT16_T @HAVE_UINT16_T@
#endif
#ifndef U_HAVE_INT32_T
#define U_HAVE_INT32_T @HAVE_INT32_T@
#endif
#ifndef U_HAVE_UINT32_T
#define U_HAVE_UINT32_T @HAVE_UINT32_T@
#endif
#ifndef U_HAVE_INT64_T
#define U_HAVE_INT64_T @HAVE_INT64_T@
#endif
#ifndef U_HAVE_UINT64_T
#define U_HAVE_UINT64_T @HAVE_UINT64_T@
#endif
/** @} */
/*===========================================================================*/
/** @{ Generic data types */
/*===========================================================================*/
#include <sys/types.h>
/* If your platform does not have the <inttypes.h> header, you may
need to edit the typedefs below. */
#if U_HAVE_INTTYPES_H
/* autoconf 2.13 sometimes can't properly find the data types in <inttypes.h> */
/* os/390 needs <inttypes.h>, but it doesn't have int8_t, and it sometimes */
/* doesn't have uint8_t depending on the OS version. */
/* So we have this work around. */
#ifdef OS390
/* The features header is needed to get (u)int64_t sometimes. */
#include <features.h>
#if ! U_HAVE_INT8_T
typedef signed char int8_t;
#endif
#if !defined(__uint8_t)
#define __uint8_t 1
typedef unsigned char uint8_t;
#endif
#endif /* OS390 */
#include <inttypes.h>
#else /* U_HAVE_INTTYPES_H */
#if ! U_HAVE_INT8_T
typedef signed char int8_t;
#endif
#if ! U_HAVE_UINT8_T
typedef unsigned char uint8_t;
#endif
#if ! U_HAVE_INT16_T
typedef signed short int16_t;
#endif
#if ! U_HAVE_UINT16_T
typedef unsigned short uint16_t;
#endif
#if ! U_HAVE_INT32_T
typedef signed int int32_t;
#endif
#if ! U_HAVE_UINT32_T
typedef unsigned int uint32_t;
#endif
#if ! U_HAVE_INT64_T
typedef signed long long int64_t;
/* else we may not have a 64-bit type */
#endif
#if ! U_HAVE_UINT64_T
typedef unsigned long long uint64_t;
/* else we may not have a 64-bit type */
#endif
#endif
/** @} */
/*===========================================================================*/
/** @{ Compiler and environment features */
/*===========================================================================*/
/* Define whether namespace is supported */
#ifndef U_HAVE_NAMESPACE
#define U_HAVE_NAMESPACE @U_HAVE_NAMESPACE@
#endif
/* Determines the endianness of the platform
It's done this way in case multiple architectures are being built at once.
For example, Darwin supports fat binaries, which can be both PPC and x86 based. */
#if defined(BYTE_ORDER) && defined(BIG_ENDIAN)
#define U_IS_BIG_ENDIAN (BYTE_ORDER == BIG_ENDIAN)
#else
#define U_IS_BIG_ENDIAN @U_IS_BIG_ENDIAN@
#endif
/* 1 or 0 to enable or disable threads. If undefined, default is: enable threads. */
#define ICU_USE_THREADS @ICU_USE_THREADS@
/* On strong memory model CPUs (e.g. x86 CPUs), we use a safe & quick double check lock. */
#if defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__))
#define UMTX_STRONG_MEMORY_MODEL 1
#endif
#ifndef U_DEBUG
#define U_DEBUG @ENABLE_DEBUG@
#endif
#ifndef U_RELEASE
#define U_RELEASE @ENABLE_RELEASE@
#endif
/* Determine whether to disable renaming or not. This overrides the
setting in umachine.h which is for all platforms. */
#ifndef U_DISABLE_RENAMING
#define U_DISABLE_RENAMING @U_DISABLE_RENAMING@
#endif
/* Determine whether to override new and delete. */
#ifndef U_OVERRIDE_CXX_ALLOCATION
#define U_OVERRIDE_CXX_ALLOCATION @U_OVERRIDE_CXX_ALLOCATION@
#endif
/* Determine whether to override placement new and delete for STL. */
#ifndef U_HAVE_PLACEMENT_NEW
#define U_HAVE_PLACEMENT_NEW @U_HAVE_PLACEMENT_NEW@
#endif
/* Determine whether to enable tracing. */
#ifndef U_ENABLE_TRACING
#define U_ENABLE_TRACING @U_ENABLE_TRACING@
#endif
/* Do we allow ICU users to use the draft APIs by default? */
#ifndef U_DEFAULT_SHOW_DRAFT
#define U_DEFAULT_SHOW_DRAFT @U_DEFAULT_SHOW_DRAFT@
#endif
/* Define the library suffix in a C syntax. */
#define U_HAVE_LIB_SUFFIX @U_HAVE_LIB_SUFFIX@
#define U_LIB_SUFFIX_C_NAME @ICULIBSUFFIXCNAME@
#define U_LIB_SUFFIX_C_NAME_STRING "@ICULIBSUFFIXCNAME@"
/** @} */
/*===========================================================================*/
/** @{ Character data types */
/*===========================================================================*/
#if ((defined(OS390) && (!defined(__CHARSET_LIB) || !__CHARSET_LIB))) || defined(OS400)
# define U_CHARSET_FAMILY 1
#endif
/** @} */
/*===========================================================================*/
/** @{ Information about wchar support */
/*===========================================================================*/
#ifndef U_HAVE_WCHAR_H
#define U_HAVE_WCHAR_H @U_HAVE_WCHAR_H@
#endif
#ifndef U_SIZEOF_WCHAR_T
#define U_SIZEOF_WCHAR_T @U_SIZEOF_WCHAR_T@
#endif
#ifndef U_HAVE_WCSCPY
#define U_HAVE_WCSCPY @U_HAVE_WCSCPY@
#endif
/** @} */
/**
* @{
* \def U_DECLARE_UTF16
* Do not use this macro. Use the UNICODE_STRING or U_STRING_DECL macros
* instead.
* @internal
*/
#if @U_CHECK_UTF16_STRING@ || defined(U_CHECK_UTF16_STRING)
#if (defined(__xlC__) && defined(__IBM_UTF_LITERAL) && U_SIZEOF_WCHAR_T != 2) \
|| (defined(__HP_aCC) && __HP_aCC >= 035000) \
|| (defined(__HP_cc) && __HP_cc >= 111106)
#define U_DECLARE_UTF16(string) u ## string
#elif (defined(__SUNPRO_CC) && __SUNPRO_CC >= 0x550)
/* || (defined(__SUNPRO_C) && __SUNPRO_C >= 0x580) */
/* Sun's C compiler has issues with this notation, and it's unreliable. */
#define U_DECLARE_UTF16(string) U ## string
#elif U_SIZEOF_WCHAR_T == 2 \
&& (U_CHARSET_FAMILY == 0 || ((defined(OS390) || defined(OS400)) && defined(__UCS2__)))
#define U_DECLARE_UTF16(string) L ## string
#endif
#endif
/** @} */
/*===========================================================================*/
/** @{ Information about POSIX support */
/*===========================================================================*/
#ifndef U_HAVE_NL_LANGINFO_CODESET
#define U_HAVE_NL_LANGINFO_CODESET @U_HAVE_NL_LANGINFO_CODESET@
#endif
#ifndef U_NL_LANGINFO_CODESET
#define U_NL_LANGINFO_CODESET @U_NL_LANGINFO_CODESET@
#endif
#if @U_HAVE_TZSET@
#define U_TZSET @U_TZSET@
#endif
#if @U_HAVE_TIMEZONE@
#define U_TIMEZONE @U_TIMEZONE@
#endif
#if @U_HAVE_TZNAME@
#define U_TZNAME @U_TZNAME@
#endif
#define U_HAVE_MMAP @HAVE_MMAP@
#define U_HAVE_POPEN @U_HAVE_POPEN@
/** @} */
/*===========================================================================*/
/** @{ Symbol import-export control */
/*===========================================================================*/
#if @U_USE_GCC_VISIBILITY_ATTRIBUTE@
#define U_EXPORT __attribute__((visibility("default")))
#elif (defined(__SUNPRO_CC) && __SUNPRO_CC >= 0x550) \
|| (defined(__SUNPRO_C) && __SUNPRO_C >= 0x550)
#define U_EXPORT __global
/*#elif defined(__HP_aCC) || defined(__HP_cc)
#define U_EXPORT __declspec(dllexport)*/
#else
#define U_EXPORT
#endif
/* U_CALLCONV is releated to U_EXPORT2 */
#define U_EXPORT2
/* cygwin needs to export/import data */
#ifdef U_CYGWIN
#define U_IMPORT __declspec(dllimport)
#else
#define U_IMPORT
#endif
/* @} */
/*===========================================================================*/
/** @{ Code alignment and C function inlining */
/*===========================================================================*/
#ifndef U_INLINE
# ifdef __cplusplus
# define U_INLINE inline
# else
# define U_INLINE @U_INLINE@
# endif
#endif
#ifndef U_ALIGN_CODE
#define U_ALIGN_CODE(n)
#endif
/** @} */
/*===========================================================================*/
/** @{ Programs used by ICU code */
/*===========================================================================*/
/**
* \def U_MAKE
* What program to execute to run 'make'
*/
#ifndef U_MAKE
#define U_MAKE "@U_MAKE@"
#endif
/** @} */
#endif
+541
View File
@@ -0,0 +1,541 @@
/*
*******************************************************************************
* Copyright (C) 2007-2009, International Business Machines Corporation and
* others. All Rights Reserved.
*******************************************************************************
*
* File PLURFMT.H
*
* Modification History:*
* Date Name Description
*
********************************************************************************
*/
#ifndef PLURFMT
#define PLURFMT
#include "unicode/utypes.h"
/**
* \file
* \brief C++ API: PluralFormat object
*/
#if !UCONFIG_NO_FORMATTING
#include "unicode/numfmt.h"
#include "unicode/plurrule.h"
U_NAMESPACE_BEGIN
class Hashtable;
/**
* <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 users 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., paucal 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 locales. Thus, the programmer
* need not worry about the plural cases of a language. On the flip side,
* the localizer does not have to specify the plural cases; he can simply
* use the predefined keywords. The whole plural formatting of messages can
* be done using localized patterns from resource bundles.
* </ul>
* </p>
* <h4>Usage of <code>PluralFormat</code></h4>
* <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
* used locale. The pattern is a sequence of
* <code><i>caseKeyword</i>{<i>message</i>}</code> clauses, separated by white
* space characters. Each clause assigns the message <code><i>message</i></code>
* to the plural case identified by <code><i>caseKeyword</i></code>.
* </p><p>
* You always have to define a message text for the default plural case
* "<code>other</code>" which is contained in every rule set. If the plural
* rules of the <code>PluralFormat</code> object do not contain a plural case
* identified by <code><i>caseKeyword</i></code>, U_DEFAULT_KEYWORD_MISSING
* will be set to status.
* 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. If you specify more than one message for the same plural case,
* U_DUPLICATE_KEYWORD will be set to status.
* <br/>
* Spaces between <code><i>caseKeyword</i></code> and
* <code><i>message</i></code> will be ignored; spaces within
* <code><i>message</i></code> will be preserved.
* </p><p>
* The message text for a particular plural case may contain other message
* format patterns. <code>PluralFormat</code> preserves these so that you
* can use the strings produced by <code>PluralFormat</code> with other
* formatters. If you are using <code>PluralFormat</code> inside a
* <code>MessageFormat</code> pattern, <code>MessageFormat</code> will
* automatically evaluate the resulting format pattern.<br/>
* Thus, curly braces (<code>{</code>, <code>}</code>) are <i>only</i> allowed
* in message texts to define a nested format pattern.<br/>
* The pound sign (<code>#</code>) will be interpreted as the number placeholder
* in the message text, if it is not contained in curly braces (to preserve
* <code>NumberFormat</code> patterns). <code>PluralFormat</code> will
* replace each of those pound signs by the number passed to the
* <code>format()</code> method. It will be formatted using a
* <code>NumberFormat</code> for the <code>PluralFormat</code>'s locale. If you
* need special number formatting, you have to explicitly specify a
* <code>NumberFormat</code> for the <code>PluralFormat</code> to use.
* </p>
* Example
* <pre>
* UErrorCode status = U_ZERO_ERROR;
* MessageFormat* msgFmt = new MessageFormat(UnicodeString("{0, plural,
* one{{0, number, C''est #,##0.0# fichier}} other {Ce sont # fichiers}} dans la liste."),
* Locale("fr"), status);
* if (U_FAILURE(status)) {
* return;
* }
* Formattable args1[] = {(int32_t)0};
* Formattable args2[] = {(int32_t)3};
* FieldPosition ignore(FieldPosition::DONT_CARE);
* UnicodeString result;
* msgFmt->format(args1, 1, result, ignore, status);
* cout << result << endl;
* result.remove();
* msgFmt->format(args2, 1, result, ignore, status);
* cout << result << endl;
* </pre>
* Produces the output:<br/>
* <code>C'est 0,0 fichier dans la liste.</code><br/>
* <code>Ce sont 3 fichiers dans la liste."</code>
* <p>
* <strong>Note:</strong><br/>
* Currently <code>PluralFormat</code>
* does not make use of quotes like <code>MessageFormat</code>.
* If you use plural format strings with <code>MessageFormat</code> and want
* to use a quote sign "<code>'</code>", you have to write "<code>''</code>".
* <code>MessageFormat</code> unquotes this pattern and passes the unquoted
* pattern to <code>PluralFormat</code>. It's a bit trickier if you use
* nested formats that do quoting. In the example above, we wanted to insert
* "<code>'</code>" in the number format pattern. Since
* <code>NumberFormat</code> supports quotes, we had to insert
* "<code>''</code>". But since <code>MessageFormat</code> unquotes the
* pattern before it gets passed to <code>PluralFormat</code>, we have to
* double these quotes, i.e. write "<code>''''</code>".
* </p>
* <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 <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 <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 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 <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);
/**
* 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);
/**
* 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
* <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(double number,
UnicodeString& appendTo,
FieldPosition& pos,
UErrorCode& status) const;
/**
* 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, UErrorCode& status)}.
* @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.
* @stable ICU 4.0
*/
void setLocale(const Locale& locale, UErrorCode& status);
/**
* 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 UBool operator==(const Format& other) const;
/**
* 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 UBool 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 Format* clone(void) const;
/**
* Redeclared Format method.
*
* @param obj The object to be formatted into a string.
* @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;
/**
* 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;
/**
* ICU "poor man's RTTI", returns a UClassID for this class.
*
* @stable ICU 4.0
*
*/
static UClassID U_EXPORT2 getStaticClassID(void);
/**
* ICU "poor man's RTTI", returns a UClassID for the actual class.
*
* @stable ICU 4.0
*/
virtual UClassID getDynamicClassID() const;
private:
typedef enum fmtToken {
none,
tLetter,
tNumber,
tSpace,
tNumberSign,
tLeftBrace,
tRightBrace
}fmtToken;
Locale locale;
PluralRules* pluralRules;
UnicodeString pattern;
Hashtable *fParsedValuesHash;
NumberFormat* numberFormat;
NumberFormat* replacedNumberFormat;
PluralFormat(); // default constructor not implemented
void init(const PluralRules* rules, const Locale& curlocale, UErrorCode& status);
UBool inRange(UChar ch, fmtToken& type);
UBool checkSufficientDefinition();
void parsingFailure();
UnicodeString insertFormattedNumber(double number,
UnicodeString& message,
UnicodeString& appendTo,
FieldPosition& pos) const;
void copyHashtable(Hashtable *other, UErrorCode& status);
};
U_NAMESPACE_END
#endif /* #if !UCONFIG_NO_FORMATTING */
#endif // _PLURFMT
//eof
+293
View File
@@ -0,0 +1,293 @@
/*
*******************************************************************************
* Copyright (C) 2008-2009, 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"
/**
* \file
* \brief C++ API: PluralRules object
*/
#if !UCONFIG_NO_FORMATTING
#include "unicode/format.h"
U_NAMESPACE_BEGIN
class Hashtable;
class RuleChain;
class RuleParser;
/**
* Defines rules for mapping positive long 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.
*
* 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
* within_relation = expr ('not')? 'within' range
* expr = 'n' ('mod' value)?
* value = digit+
* digit = 0|1|2|3|4|5|6|7|8|9
* range = value'..'value
* \endcode
* </pre></p>
* <p>
* The difference between 'in' and 'within' is that 'in' only includes
* integers in the specified range, while 'within' includes all values.</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>
*/
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 null.
*
* @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. NULL 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. NULL if there is an error.
* @stable ICU 4.0
*/
static PluralRules* U_EXPORT2 createDefaultRules(UErrorCode& status);
/**
* Provides access to the predefined <code>PluralRules</code> for a given
* locale.
*
* @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);
/**
* Given a 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(int32_t number) const;
/**
* Given a 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;
/**
* 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;
/**
* 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.
* @internal 4.0
* @stable ICU 4.0
*/
UnicodeString getKeywordOther() const;
/**
* 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 UBool 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
*/
UBool 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(void);
/**
* ICU "poor man's RTTI", returns a UClassID for the actual class.
*
* @stable ICU 4.0
*/
virtual UClassID getDynamicClassID() const;
private:
Hashtable *fLocaleStringsHash;
UnicodeString mLocaleName;
RuleChain *mRules;
RuleParser *mParser;
PluralRules(); // default constructor not implemented
int32_t getRepeatLimit() const;
void parseDescription(UnicodeString& ruleData, RuleChain& rules, UErrorCode &status);
void getNextLocale(const UnicodeString& localeData, int32_t* curIndex, UnicodeString& localeName);
void addRules(RuleChain& rules);
int32_t getNumberValue(const UnicodeString& token) const;
UnicodeString getRuleFromResource(const Locale& locale, UErrorCode& status);
};
U_NAMESPACE_END
#endif /* #if !UCONFIG_NO_FORMATTING */
#endif // _PLURRULE
//eof
+273
View File
@@ -0,0 +1,273 @@
/*
******************************************************************************
*
* Copyright (C) 1997-2006, International Business Machines
* Corporation and others. All Rights Reserved.
*
******************************************************************************
*
* FILE NAME : ppalmos.h
*
* Date Name Description
* 05/10/04 Ken Krugler Creation (copied from pwin32.h & modified).
******************************************************************************
*/
#ifndef U_PPALMOS_H
#define U_PPALMOS_H
/**
* \file
* \brief Configuration constants for the Palm OS platform
*/
/* Define the platform we're on. */
#ifndef U_PALMOS
#define U_PALMOS
#endif
/* _MSC_VER is used to detect the Microsoft compiler. */
#if defined(_MSC_VER)
#define U_INT64_IS_LONG_LONG 0
#else
#define U_INT64_IS_LONG_LONG 1
#endif
/* Define whether inttypes.h is available */
#ifndef U_HAVE_INTTYPES_H
#define U_HAVE_INTTYPES_H 1
#endif
/*
* Define what support for C++ streams is available.
* If U_IOSTREAM_SOURCE is set to 199711, then <iostream> is available
* (1997711 is the date the ISO/IEC C++ FDIS was published), and then
* one should qualify streams using the std namespace in ICU header
* files.
* If U_IOSTREAM_SOURCE is set to 198506, then <iostream.h> is
* available instead (198506 is the date when Stroustrup published
* "An Extensible I/O Facility for C++" at the summer USENIX conference).
* If U_IOSTREAM_SOURCE is 0, then C++ streams are not available and
* support for them will be silently suppressed in ICU.
*
*/
#ifndef U_IOSTREAM_SOURCE
#define U_IOSTREAM_SOURCE 199711
#endif
/* Determines whether specific types are available */
#ifndef U_HAVE_INT8_T
#define U_HAVE_INT8_T U_HAVE_INTTYPES_H
#endif
#ifndef U_HAVE_UINT8_T
#define U_HAVE_UINT8_T U_HAVE_INTTYPES_H
#endif
#ifndef U_HAVE_INT16_T
#define U_HAVE_INT16_T U_HAVE_INTTYPES_H
#endif
#ifndef U_HAVE_UINT16_T
#define U_HAVE_UINT16_T U_HAVE_INTTYPES_H
#endif
#ifndef U_HAVE_INT32_T
#define U_HAVE_INT32_T U_HAVE_INTTYPES_H
#endif
#ifndef U_HAVE_UINT32_T
#define U_HAVE_UINT32_T U_HAVE_INTTYPES_H
#endif
#ifndef U_HAVE_INT64_T
#define U_HAVE_INT64_T U_HAVE_INTTYPES_H
#endif
#ifndef U_HAVE_UINT64_T
#define U_HAVE_UINT64_T U_HAVE_INTTYPES_H
#endif
/*===========================================================================*/
/* Generic data types */
/*===========================================================================*/
/* If your platform does not have the <inttypes.h> header, you may
need to edit the typedefs below. */
#if U_HAVE_INTTYPES_H
#include <inttypes.h>
#else /* U_HAVE_INTTYPES_H */
#if ! U_HAVE_INT8_T
typedef signed char int8_t;
#endif
#if ! U_HAVE_UINT8_T
typedef unsigned char uint8_t;
#endif
#if ! U_HAVE_INT16_T
typedef signed short int16_t;
#endif
#if ! U_HAVE_UINT16_T
typedef unsigned short uint16_t;
#endif
#if ! U_HAVE_INT32_T
typedef signed int int32_t;
#endif
#if ! U_HAVE_UINT32_T
typedef unsigned int uint32_t;
#endif
#if ! U_HAVE_INT64_T
#if U_INT64_IS_LONG_LONG
typedef signed long long int64_t;
#else
typedef signed __int64 int64_t;
#endif
#endif
#if ! U_HAVE_UINT64_T
#if U_INT64_IS_LONG_LONG
typedef unsigned long long uint64_t;
#else
typedef unsigned __int64 uint64_t;
#endif
#endif
#endif
/*===========================================================================*/
/* Compiler and environment features */
/*===========================================================================*/
/* Define whether namespace is supported */
#ifndef U_HAVE_NAMESPACE
#define U_HAVE_NAMESPACE 1
#endif
/* Determines the endianness of the platform */
#define U_IS_BIG_ENDIAN 0
/* 1 or 0 to enable or disable threads. If undefined, default is: enable threads. */
#define ICU_USE_THREADS 1
#ifndef U_DEBUG
#ifdef _DEBUG
#define U_DEBUG 1
#else
#define U_DEBUG 0
#endif
#endif
#ifndef U_RELEASE
#ifdef NDEBUG
#define U_RELEASE 1
#else
#define U_RELEASE 0
#endif
#endif
/* Determine whether to disable renaming or not. This overrides the
setting in umachine.h which is for all platforms. */
#ifndef U_DISABLE_RENAMING
#define U_DISABLE_RENAMING 0
#endif
/* Determine whether to override new and delete. */
#ifndef U_OVERRIDE_CXX_ALLOCATION
#define U_OVERRIDE_CXX_ALLOCATION 1
#endif
/* Determine whether to override placement new and delete for STL. */
#ifndef U_HAVE_PLACEMENT_NEW
#define U_HAVE_PLACEMENT_NEW 0
#endif
/* Determine whether to override new and delete for MFC. */
#if !defined(U_HAVE_DEBUG_LOCATION_NEW) && defined(_MSC_VER)
#define U_HAVE_DEBUG_LOCATION_NEW 0
#endif
/* Determine whether to enable tracing. */
#ifndef U_ENABLE_TRACING
#define U_ENABLE_TRACING 1
#endif
/* Do we allow ICU users to use the draft APIs by default? */
#ifndef U_DEFAULT_SHOW_DRAFT
#define U_DEFAULT_SHOW_DRAFT 1
#endif
/* Define the library suffix in a C syntax. */
#define U_HAVE_LIB_SUFFIX 0
#define U_LIB_SUFFIX_C_NAME
#define U_LIB_SUFFIX_C_NAME_STRING ""
/*===========================================================================*/
/* Information about wchar support */
/*===========================================================================*/
#define U_HAVE_WCHAR_H 1
#define U_SIZEOF_WCHAR_T 2
#define U_HAVE_WCSCPY 0
/*===========================================================================*/
/* Information about POSIX support */
/*===========================================================================*/
/* TODO: Fix Palm OS's determination of a timezone */
#if 0
#define U_TZSET _tzset
#endif
#if 0
#define U_TIMEZONE _timezone
#endif
#if 0
#define U_TZNAME _tzname
#endif
#define U_HAVE_MMAP 0
#define U_HAVE_POPEN 0
/*===========================================================================*/
/* Symbol import-export control */
/*===========================================================================*/
#define U_EXPORT
#define U_EXPORT2
#define U_IMPORT
/*===========================================================================*/
/* Code alignment and C function inlining */
/*===========================================================================*/
#ifndef U_INLINE
# ifdef __cplusplus
# define U_INLINE inline
# else
# define U_INLINE __inline
# endif
#endif
#if defined(_MSC_VER) && defined(_M_IX86)
#define U_ALIGN_CODE(val) __asm align val
#else
#define U_ALIGN_CODE(val)
#endif
/*===========================================================================*/
/* Programs used by ICU code */
/*===========================================================================*/
#ifndef U_MAKE
#define U_MAKE "nmake"
#define U_MAKE_IS_NMAKE 1
#endif
#endif
+193
View File
@@ -0,0 +1,193 @@
/*
******************************************************************************
*
* Copyright (C) 1997-2009, International Business Machines
* Corporation and others. All Rights Reserved.
*
******************************************************************************
*
* FILE NAME : putil.h
*
* Date Name Description
* 05/14/98 nos Creation (content moved here from utypes.h).
* 06/17/99 erm Added IEEE_754
* 07/22/98 stephen Added IEEEremainder, max, min, trunc
* 08/13/98 stephen Added isNegativeInfinity, isPositiveInfinity
* 08/24/98 stephen Added longBitsFromDouble
* 03/02/99 stephen Removed openFile(). Added AS400 support.
* 04/15/99 stephen Converted to C
* 11/15/99 helena Integrated S/390 changes for IEEE support.
* 01/11/00 helena Added u_getVersion.
******************************************************************************
*/
#ifndef PUTIL_H
#define PUTIL_H
#include "unicode/utypes.h"
/**
* \file
* \brief C API: Platform Utilities
*/
/** Define this to 1 if your platform supports IEEE 754 floating point,
to 0 if it does not. */
#ifndef IEEE_754
# define IEEE_754 1
#endif
/*==========================================================================*/
/* Platform utilities */
/*==========================================================================*/
/**
* Platform utilities isolates the platform dependencies of the
* libarary. For each platform which this code is ported to, these
* functions may have to be re-implemented.
*/
/**
* Return the ICU data directory.
* The data directory is where common format ICU data files (.dat files)
* are loaded from. Note that normal use of the built-in ICU
* facilities does not require loading of an external data file;
* unless you are adding custom data to ICU, the data directory
* does not need to be set.
*
* The data directory is determined as follows:
* If u_setDataDirectory() has been called, that is it, otherwise
* if the ICU_DATA environment variable is set, use that, otherwise
* If a data directory was specifed at ICU build time
* <code>
* \code
* #define ICU_DATA_DIR "path"
* \endcode
* </code> use that,
* otherwise no data directory is available.
*
* @return the data directory, or an empty string ("") if no data directory has
* been specified.
*
* @stable ICU 2.0
*/
U_STABLE const char* U_EXPORT2 u_getDataDirectory(void);
/**
* Set the ICU data directory.
* The data directory is where common format ICU data files (.dat files)
* are loaded from. Note that normal use of the built-in ICU
* facilities does not require loading of an external data file;
* unless you are adding custom data to ICU, the data directory
* does not need to be set.
*
* This function should be called at most once in a process, before the
* first ICU operation (e.g., u_init()) that will require the loading of an
* ICU data file.
* This function is not thread-safe. Use it before calling ICU APIs from
* multiple threads.
*
* @param directory The directory to be set.
*
* @see u_init
* @stable ICU 2.0
*/
U_STABLE void U_EXPORT2 u_setDataDirectory(const char *directory);
#if !U_CHARSET_IS_UTF8
/**
* Please use ucnv_getDefaultName() instead.
* Return the default codepage for this platform and locale.
* This function can call setlocale() on Unix platforms. Please read the
* platform documentation on setlocale() before calling this function.
* @return the default codepage for this platform
* @internal
*/
U_INTERNAL const char* U_EXPORT2 uprv_getDefaultCodepage(void);
#endif
/**
* Please use uloc_getDefault() instead.
* Return the default locale ID string by querying ths system, or
* zero if one cannot be found.
* This function can call setlocale() on Unix platforms. Please read the
* platform documentation on setlocale() before calling this function.
* @return the default locale ID string
* @internal
*/
U_INTERNAL const char* U_EXPORT2 uprv_getDefaultLocaleID(void);
/**
* @{
* Filesystem file and path separator characters.
* Example: '/' and ':' on Unix, '\\' and ';' on Windows.
* @stable ICU 2.0
*/
#ifdef XP_MAC
# define U_FILE_SEP_CHAR ':'
# define U_FILE_ALT_SEP_CHAR ':'
# define U_PATH_SEP_CHAR ';'
# define U_FILE_SEP_STRING ":"
# define U_FILE_ALT_SEP_STRING ":"
# define U_PATH_SEP_STRING ";"
#elif defined(U_WINDOWS)
# define U_FILE_SEP_CHAR '\\'
# define U_FILE_ALT_SEP_CHAR '/'
# define U_PATH_SEP_CHAR ';'
# define U_FILE_SEP_STRING "\\"
# define U_FILE_ALT_SEP_STRING "/"
# define U_PATH_SEP_STRING ";"
#else
# define U_FILE_SEP_CHAR '/'
# define U_FILE_ALT_SEP_CHAR '/'
# define U_PATH_SEP_CHAR ':'
# define U_FILE_SEP_STRING "/"
# define U_FILE_ALT_SEP_STRING "/"
# define U_PATH_SEP_STRING ":"
#endif
/** @} */
/**
* Convert char characters to UChar characters.
* This utility function is useful only for "invariant characters"
* that are encoded in the platform default encoding.
* They are a small, constant subset of the encoding and include
* just the latin letters, digits, and some punctuation.
* For details, see U_CHARSET_FAMILY.
*
* @param cs Input string, points to <code>length</code>
* character bytes from a subset of the platform encoding.
* @param us Output string, points to memory for <code>length</code>
* Unicode characters.
* @param length The number of characters to convert; this may
* include the terminating <code>NUL</code>.
*
* @see U_CHARSET_FAMILY
* @stable ICU 2.0
*/
U_STABLE void U_EXPORT2
u_charsToUChars(const char *cs, UChar *us, int32_t length);
/**
* Convert UChar characters to char characters.
* This utility function is useful only for "invariant characters"
* that can be encoded in the platform default encoding.
* They are a small, constant subset of the encoding and include
* just the latin letters, digits, and some punctuation.
* For details, see U_CHARSET_FAMILY.
*
* @param us Input string, points to <code>length</code>
* Unicode characters that can be encoded with the
* codepage-invariant subset of the platform encoding.
* @param cs Output string, points to memory for <code>length</code>
* character bytes.
* @param length The number of characters to convert; this may
* include the terminating <code>NUL</code>.
*
* @see U_CHARSET_FAMILY
* @stable ICU 2.0
*/
U_STABLE void U_EXPORT2
u_UCharsToChars(const UChar *us, char *cs, int32_t length);
#endif
+342
View File
@@ -0,0 +1,342 @@
/*
******************************************************************************
*
* Copyright (C) 1997-2009, International Business Machines
* Corporation and others. All Rights Reserved.
*
******************************************************************************
*
* FILE NAME : platform.h
*
* Date Name Description
* 05/13/98 nos Creation (content moved here from ptypes.h).
* 03/02/99 stephen Added AS400 support.
* 03/30/99 stephen Added Linux support.
* 04/13/99 stephen Reworked for autoconf.
******************************************************************************
*/
/**
* \file
* \brief Configuration constants for the Windows platform
*/
/** Define the platform we're on. */
#ifndef U_WINDOWS
#define U_WINDOWS
#endif
#if defined(__BORLANDC__)
#define U_HAVE_PLACEMENT_NEW 0
#define __STDC_CONSTANT_MACROS
#endif
/** _MSC_VER is used to detect the Microsoft compiler. */
#if defined(_MSC_VER)
#define U_INT64_IS_LONG_LONG 0
#else
#define U_INT64_IS_LONG_LONG 1
#endif
/** Define whether inttypes.h is available */
#ifndef U_HAVE_INTTYPES_H
# if defined(__BORLANDC__) || defined(__MINGW32__)
# define U_HAVE_INTTYPES_H 1
# else
# define U_HAVE_INTTYPES_H 0
# endif
#endif
/**
* Define what support for C++ streams is available.
* If U_IOSTREAM_SOURCE is set to 199711, then &lt;iostream&gt; is available
* (1997711 is the date the ISO/IEC C++ FDIS was published), and then
* one should qualify streams using the std namespace in ICU header
* files.
* If U_IOSTREAM_SOURCE is set to 198506, then &lt;iostream.h&gt; is
* available instead (198506 is the date when Stroustrup published
* "An Extensible I/O Facility for C++" at the summer USENIX conference).
* If U_IOSTREAM_SOURCE is 0, then C++ streams are not available and
* support for them will be silently suppressed in ICU.
*
*/
#ifndef U_IOSTREAM_SOURCE
#define U_IOSTREAM_SOURCE 199711
#endif
/** @{
* Determines whether specific types are available */
#ifndef U_HAVE_INT8_T
#define U_HAVE_INT8_T U_HAVE_INTTYPES_H
#endif
#ifndef U_HAVE_UINT8_T
#define U_HAVE_UINT8_T U_HAVE_INTTYPES_H
#endif
#ifndef U_HAVE_INT16_T
#define U_HAVE_INT16_T U_HAVE_INTTYPES_H
#endif
#ifndef U_HAVE_UINT16_T
#define U_HAVE_UINT16_T U_HAVE_INTTYPES_H
#endif
#ifndef U_HAVE_INT32_T
#define U_HAVE_INT32_T U_HAVE_INTTYPES_H
#endif
#ifndef U_HAVE_UINT32_T
#define U_HAVE_UINT32_T U_HAVE_INTTYPES_H
#endif
#ifndef U_HAVE_INT64_T
#define U_HAVE_INT64_T U_HAVE_INTTYPES_H
#endif
#ifndef U_HAVE_UINT64_T
#define U_HAVE_UINT64_T U_HAVE_INTTYPES_H
#endif
/** @} */
/** Define 64 bit limits */
#if !U_INT64_IS_LONG_LONG
# ifndef INT64_C
# define INT64_C(x) ((int64_t)x)
# endif
# ifndef UINT64_C
# define UINT64_C(x) ((uint64_t)x)
# endif
/** else use the umachine.h definition */
#endif
/*===========================================================================*/
/** @{
* Generic data types */
/*===========================================================================*/
/** If your platform does not have the <inttypes.h> header, you may
need to edit the typedefs below. */
#if U_HAVE_INTTYPES_H
#include <inttypes.h>
#else /* U_HAVE_INTTYPES_H */
#if ! U_HAVE_INT8_T
typedef signed char int8_t;
#endif
#if ! U_HAVE_UINT8_T
typedef unsigned char uint8_t;
#endif
#if ! U_HAVE_INT16_T
typedef signed short int16_t;
#endif
#if ! U_HAVE_UINT16_T
typedef unsigned short uint16_t;
#endif
#if ! U_HAVE_INT32_T
typedef signed int int32_t;
#endif
#if ! U_HAVE_UINT32_T
typedef unsigned int uint32_t;
#endif
#if ! U_HAVE_INT64_T
#if U_INT64_IS_LONG_LONG
typedef signed long long int64_t;
#else
typedef signed __int64 int64_t;
#endif
#endif
#if ! U_HAVE_UINT64_T
#if U_INT64_IS_LONG_LONG
typedef unsigned long long uint64_t;
#else
typedef unsigned __int64 uint64_t;
#endif
#endif
#endif
/**
* @}
*/
/*===========================================================================*/
/** Compiler and environment features */
/*===========================================================================*/
/** Define whether namespace is supported */
#ifndef U_HAVE_NAMESPACE
#define U_HAVE_NAMESPACE 1
#endif
/** Determines the endianness of the platform */
#define U_IS_BIG_ENDIAN 0
/** 1 or 0 to enable or disable threads. If undefined, default is: enable threads. */
#define ICU_USE_THREADS 1
/* On strong memory model CPUs (e.g. x86 CPUs), we use a safe & quick double check mutex lock. */
/**
Microsoft can define _M_IX86, _M_AMD64 (before Visual Studio 8) or _M_X64 (starting in Visual Studio 8).
Intel can define _M_IX86 or _M_X64
*/
#if defined(_M_IX86) || defined(_M_AMD64) || defined(_M_X64) || (defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__)))
#define UMTX_STRONG_MEMORY_MODEL 1
#endif
/** Enable or disable debugging options **/
#ifndef U_DEBUG
#ifdef _DEBUG
#define U_DEBUG 1
#else
#define U_DEBUG 0
#endif
#endif
/** Enable or disable release options **/
#ifndef U_RELEASE
#ifdef NDEBUG
#define U_RELEASE 1
#else
#define U_RELEASE 0
#endif
#endif
/** Determine whether to disable renaming or not. This overrides the
setting in umachine.h which is for all platforms. */
#ifndef U_DISABLE_RENAMING
#define U_DISABLE_RENAMING 0
#endif
/** Determine whether to override new and delete. */
#ifndef U_OVERRIDE_CXX_ALLOCATION
#define U_OVERRIDE_CXX_ALLOCATION 1
#endif
/** Determine whether to override placement new and delete for STL. */
#ifndef U_HAVE_PLACEMENT_NEW
#define U_HAVE_PLACEMENT_NEW 1
#endif
/** Determine whether to override new and delete for MFC. */
#if !defined(U_HAVE_DEBUG_LOCATION_NEW) && defined(_MSC_VER)
#define U_HAVE_DEBUG_LOCATION_NEW 1
#endif
/** Determine whether to enable tracing. */
#ifndef U_ENABLE_TRACING
#define U_ENABLE_TRACING 0
#endif
/** Do we allow ICU users to use the draft APIs by default? */
#ifndef U_DEFAULT_SHOW_DRAFT
#define U_DEFAULT_SHOW_DRAFT 1
#endif
/** @{ Define the library suffix in a C syntax. */
#define U_HAVE_LIB_SUFFIX 0
#define U_LIB_SUFFIX_C_NAME
#define U_LIB_SUFFIX_C_NAME_STRING ""
/** @} */
/*===========================================================================*/
/** @{ Information about wchar support */
/*===========================================================================*/
#define U_HAVE_WCHAR_H 1
#define U_SIZEOF_WCHAR_T 2
#define U_HAVE_WCSCPY 1
/** @} */
/**
* \def U_DECLARE_UTF16
* Do not use this macro. Use the UNICODE_STRING or U_STRING_DECL macros
* instead.
* @internal
*/
#if 1
#define U_DECLARE_UTF16(string) L ## string
#endif
/*===========================================================================*/
/** @{ Information about POSIX support */
/*===========================================================================*/
#if 1
#define U_TZSET _tzset
#endif
#if 1
#define U_TIMEZONE _timezone
#endif
#if 1
#define U_TZNAME _tzname
#endif
#if 1
#define U_DAYLIGHT _daylight
#endif
#define U_HAVE_MMAP 0
#define U_HAVE_POPEN 0
/** @} */
/*===========================================================================*/
/** @{ Symbol import-export control */
/*===========================================================================*/
#ifdef U_STATIC_IMPLEMENTATION
#define U_EXPORT
#else
#define U_EXPORT __declspec(dllexport)
#endif
#define U_EXPORT2 __cdecl
#define U_IMPORT __declspec(dllimport)
/** @} */
/*===========================================================================*/
/** @{ Code alignment and C function inlining */
/*===========================================================================*/
#ifndef U_INLINE
# ifdef __cplusplus
# define U_INLINE inline
# else
# define U_INLINE __inline
# endif
#endif
#if defined(_MSC_VER) && defined(_M_IX86) && !defined(_MANAGED)
#define U_ALIGN_CODE(val) __asm align val
#else
#define U_ALIGN_CODE(val)
#endif
/**
* Flag for workaround of MSVC 2003 optimization bugs
*/
#if defined(_MSC_VER) && (_MSC_VER < 1400)
#define U_HAVE_MSVC_2003_OR_EARLIER
#endif
/** @} */
/*===========================================================================*/
/** @{ Programs used by ICU code */
/*===========================================================================*/
#ifndef U_MAKE
#define U_MAKE "nmake"
#define U_MAKE_IS_NMAKE 1
#endif
/** @} */
+722
View File
@@ -0,0 +1,722 @@
/*
***************************************************************************
* Copyright (C) 1999-2008 International Business Machines Corporation *
* and others. All rights reserved. *
***************************************************************************
**********************************************************************
* Date Name Description
* 10/22/99 alan Creation.
* 11/11/99 rgillam Complete port from Java.
**********************************************************************
*/
#ifndef RBBI_H
#define RBBI_H
#include "unicode/utypes.h"
/**
* \file
* \brief C++ API: Rule Based Break Iterator
*/
#if !UCONFIG_NO_BREAK_ITERATION
#include "unicode/brkiter.h"
#include "unicode/udata.h"
#include "unicode/parseerr.h"
#include "unicode/schriter.h"
#include "unicode/uchriter.h"
struct UTrie;
U_NAMESPACE_BEGIN
/** @internal */
struct RBBIDataHeader;
class RuleBasedBreakIteratorTables;
class BreakIterator;
class RBBIDataWrapper;
class UStack;
class LanguageBreakEngine;
class UnhandledEngine;
struct RBBIStateTable;
/**
*
* A subclass of BreakIterator whose behavior is specified using a list of rules.
* <p>Instances of this class are most commonly created by the factory methods of
* BreakIterator::createWordInstance(), BreakIterator::createLineInstance(), etc.,
* and then used via the abstract API in class BreakIterator</p>
*
* <p>See the ICU User Guide for information on Break Iterator Rules.</p>
*
* <p>This class is not intended to be subclassed. (Class DictionaryBasedBreakIterator
* is a subclass, but that relationship is effectively internal to the ICU
* implementation. The subclassing interface to RulesBasedBreakIterator is
* not part of the ICU API, and may not remain stable.</p>
*
*/
class U_COMMON_API RuleBasedBreakIterator : public BreakIterator {
protected:
/**
* The UText through which this BreakIterator accesses the text
* @internal
*/
UText *fText;
/**
* A character iterator that refers to the same text as the UText, above.
* Only included for compatibility with old API, which was based on CharacterIterators.
* Value may be adopted from outside, or one of fSCharIter or fDCharIter, below.
*/
CharacterIterator *fCharIter;
/**
* When the input text is provided by a UnicodeString, this will point to
* a characterIterator that wraps that data. Needed only for the
* implementation of getText(), a backwards compatibility issue.
*/
StringCharacterIterator *fSCharIter;
/**
* When the input text is provided by a UText, this
* dummy CharacterIterator over an empty string will
* be returned from getText()
*/
UCharCharacterIterator *fDCharIter;
/**
* The rule data for this BreakIterator instance
* @internal
*/
RBBIDataWrapper *fData;
/** Index of the Rule {tag} values for the most recent match.
* @internal
*/
int32_t fLastRuleStatusIndex;
/**
* Rule tag value valid flag.
* Some iterator operations don't intrinsically set the correct tag value.
* This flag lets us lazily compute the value if we are ever asked for it.
* @internal
*/
UBool fLastStatusIndexValid;
/**
* Counter for the number of characters encountered with the "dictionary"
* flag set.
* @internal
*/
uint32_t fDictionaryCharCount;
/**
* When a range of characters is divided up using the dictionary, the break
* positions that are discovered are stored here, preventing us from having
* to use either the dictionary or the state table again until the iterator
* leaves this range of text. Has the most impact for line breaking.
* @internal
*/
int32_t* fCachedBreakPositions;
/**
* The number of elements in fCachedBreakPositions
* @internal
*/
int32_t fNumCachedBreakPositions;
/**
* if fCachedBreakPositions is not null, this indicates which item in the
* cache the current iteration position refers to
* @internal
*/
int32_t fPositionInCache;
/**
*
* If present, UStack of LanguageBreakEngine objects that might handle
* dictionary characters. Searched from top to bottom to find an object to
* handle a given character.
* @internal
*/
UStack *fLanguageBreakEngines;
/**
*
* If present, the special LanguageBreakEngine used for handling
* characters that are in the dictionary set, but not handled by any
* LangugageBreakEngine.
* @internal
*/
UnhandledEngine *fUnhandledBreakEngine;
/**
*
* The type of the break iterator, or -1 if it has not been set.
* @internal
*/
int32_t fBreakType;
protected:
//=======================================================================
// constructors
//=======================================================================
/**
* Constant to be used in the constructor
* RuleBasedBreakIterator(RBBIDataHeader*, EDontAdopt, UErrorCode &);
* which does not adopt the memory indicated by the RBBIDataHeader*
* parameter.
*
* @internal
*/
enum EDontAdopt {
kDontAdopt
};
/**
* Constructor from a flattened set of RBBI data in malloced memory.
* RulesBasedBreakIterators built from a custom set of rules
* are created via this constructor; the rules are compiled
* into memory, then the break iterator is constructed here.
*
* The break iterator adopts the memory, and will
* free it when done.
* @internal
*/
RuleBasedBreakIterator(RBBIDataHeader* data, UErrorCode &status);
/**
* Constructor from a flattened set of RBBI data in memory which need not
* be malloced (e.g. it may be a memory-mapped file, etc.).
*
* This version does not adopt the memory, and does not
* free it when done.
* @internal
*/
RuleBasedBreakIterator(const RBBIDataHeader* data, enum EDontAdopt dontAdopt, UErrorCode &status);
friend class RBBIRuleBuilder;
/** @internal */
friend class BreakIterator;
public:
/** Default constructor. Creates an empty shell of an iterator, with no
* rules or text to iterate over. Object can subsequently be assigned to.
* @stable ICU 2.2
*/
RuleBasedBreakIterator();
/**
* Copy constructor. Will produce a break iterator with the same behavior,
* and which iterates over the same text, as the one passed in.
* @param that The RuleBasedBreakIterator passed to be copied
* @stable ICU 2.0
*/
RuleBasedBreakIterator(const RuleBasedBreakIterator& that);
/**
* Construct a RuleBasedBreakIterator from a set of rules supplied as a string.
* @param rules The break rules to be used.
* @param parseError In the event of a syntax error in the rules, provides the location
* within the rules of the problem.
* @param status Information on any errors encountered.
* @stable ICU 2.2
*/
RuleBasedBreakIterator( const UnicodeString &rules,
UParseError &parseError,
UErrorCode &status);
/**
* This constructor uses the udata interface to create a BreakIterator
* whose internal tables live in a memory-mapped file. "image" is an
* ICU UDataMemory handle for the pre-compiled break iterator tables.
* @param image handle to the memory image for the break iterator data.
* Ownership of the UDataMemory handle passes to the Break Iterator,
* which will be responsible for closing it when it is no longer needed.
* @param status Information on any errors encountered.
* @see udata_open
* @see #getBinaryRules
* @stable ICU 2.8
*/
RuleBasedBreakIterator(UDataMemory* image, UErrorCode &status);
/**
* Destructor
* @stable ICU 2.0
*/
virtual ~RuleBasedBreakIterator();
/**
* Assignment operator. Sets this iterator to have the same behavior,
* and iterate over the same text, as the one passed in.
* @param that The RuleBasedBreakItertor passed in
* @return the newly created RuleBasedBreakIterator
* @stable ICU 2.0
*/
RuleBasedBreakIterator& operator=(const RuleBasedBreakIterator& that);
/**
* Equality operator. Returns TRUE if both BreakIterators are of the
* same class, have the same behavior, and iterate over the same text.
* @param that The BreakIterator to be compared for equality
* @return TRUE if both BreakIterators are of the
* same class, have the same behavior, and iterate over the same text.
* @stable ICU 2.0
*/
virtual UBool operator==(const BreakIterator& that) const;
/**
* Not-equal operator. If operator== returns TRUE, this returns FALSE,
* and vice versa.
* @param that The BreakIterator to be compared for inequality
* @return TRUE if both BreakIterators are not same.
* @stable ICU 2.0
*/
UBool operator!=(const BreakIterator& that) const;
/**
* Returns a newly-constructed RuleBasedBreakIterator with the same
* behavior, and iterating over the same text, as this one.
* Differs from the copy constructor in that it is polymorphic, and
* will correctly clone (copy) a derived class.
* clone() is thread safe. Multiple threads may simultaeneously
* clone the same source break iterator.
* @return a newly-constructed RuleBasedBreakIterator
* @stable ICU 2.0
*/
virtual BreakIterator* clone() const;
/**
* Compute a hash code for this BreakIterator
* @return A hash code
* @stable ICU 2.0
*/
virtual int32_t hashCode(void) const;
/**
* Returns the description used to create this iterator
* @return the description used to create this iterator
* @stable ICU 2.0
*/
virtual const UnicodeString& getRules(void) const;
//=======================================================================
// BreakIterator overrides
//=======================================================================
/**
* <p>
* Return a CharacterIterator over the text being analyzed.
* The returned character iterator is owned by the break iterator, and must
* not be deleted by the caller. Repeated calls to this function may
* return the same CharacterIterator.
* </p>
* <p>
* The returned character iterator must not be used concurrently with
* the break iterator. If concurrent operation is needed, clone the
* returned character iterator first and operate on the clone.
* </p>
* <p>
* When the break iterator is operating on text supplied via a UText,
* this function will fail. Lacking any way to signal failures, it
* returns an CharacterIterator containing no text.
* The function getUText() provides similar functionality,
* is reliable, and is more efficient.
* </p>
*
* TODO: deprecate this function?
*
* @return An iterator over the text being analyzed.
* @stable ICU 2.0
*/
virtual CharacterIterator& getText(void) const;
/**
* Get a UText for the text being analyzed.
* The returned UText is a shallow clone of the UText used internally
* by the break iterator implementation. It can safely be used to
* access the text without impacting any break iterator operations,
* but the underlying text itself must not be altered.
*
* @param fillIn A UText to be filled in. If NULL, a new UText will be
* allocated to hold the result.
* @param status receives any error codes.
* @return The current UText for this break iterator. If an input
* UText was provided, it will always be returned.
* @stable ICU 3.4
*/
virtual UText *getUText(UText *fillIn, UErrorCode &status) const;
/**
* Set the iterator to analyze a new piece of text. This function resets
* the current iteration position to the beginning of the text.
* @param newText An iterator over the text to analyze. The BreakIterator
* takes ownership of the character iterator. The caller MUST NOT delete it!
* @stable ICU 2.0
*/
virtual void adoptText(CharacterIterator* newText);
/**
* Set the iterator to analyze a new piece of text. This function resets
* the current iteration position to the beginning of the text.
* @param newText The text to analyze.
* @stable ICU 2.0
*/
virtual void setText(const UnicodeString& newText);
/**
* Reset the break iterator to operate over the text represented by
* the UText. The iterator position is reset to the start.
*
* This function makes a shallow clone of the supplied UText. This means
* that the caller is free to immediately close or otherwise reuse the
* Utext that was passed as a parameter, but that the underlying text itself
* must not be altered while being referenced by the break iterator.
*
* @param text The UText used to change the text.
* @param status Receives any error codes.
* @stable ICU 3.4
*/
virtual void setText(UText *text, UErrorCode &status);
/**
* Sets the current iteration position to the beginning of the text.
* @return The offset of the beginning of the text.
* @stable ICU 2.0
*/
virtual int32_t first(void);
/**
* Sets the current iteration position to the end of the text.
* @return The text's past-the-end offset.
* @stable ICU 2.0
*/
virtual int32_t last(void);
/**
* Advances the iterator either forward or backward the specified number of steps.
* Negative values move backward, and positive values move forward. This is
* equivalent to repeatedly calling next() or previous().
* @param n The number of steps to move. The sign indicates the direction
* (negative is backwards, and positive is forwards).
* @return The character offset of the boundary position n boundaries away from
* the current one.
* @stable ICU 2.0
*/
virtual int32_t next(int32_t n);
/**
* Advances the iterator to the next boundary position.
* @return The position of the first boundary after this one.
* @stable ICU 2.0
*/
virtual int32_t next(void);
/**
* Moves the iterator backwards, to the last boundary preceding this one.
* @return The position of the last boundary position preceding this one.
* @stable ICU 2.0
*/
virtual int32_t previous(void);
/**
* Sets the iterator to refer to the first boundary position following
* the specified position.
* @param offset The position from which to begin searching for a break position.
* @return The position of the first break after the current position.
* @stable ICU 2.0
*/
virtual int32_t following(int32_t offset);
/**
* Sets the iterator to refer to the last boundary position before the
* specified position.
* @param offset The position to begin searching for a break from.
* @return The position of the last boundary before the starting position.
* @stable ICU 2.0
*/
virtual int32_t preceding(int32_t offset);
/**
* Returns true if the specfied position is a boundary position. As a side
* effect, leaves the iterator pointing to the first boundary position at
* or after "offset".
* @param offset the offset to check.
* @return True if "offset" is a boundary position.
* @stable ICU 2.0
*/
virtual UBool isBoundary(int32_t offset);
/**
* Returns the current iteration position.
* @return The current iteration position.
* @stable ICU 2.0
*/
virtual int32_t current(void) const;
/**
* Return the status tag from the break rule that determined the most recently
* returned break position. For break rules that do not specify a
* status, a default value of 0 is returned. If more than one break rule
* would cause a boundary to be located at some position in the text,
* the numerically largest of the applicable status values is returned.
* <p>
* Of the standard types of ICU break iterators, only word break and
* line break provide status values. The values are defined in
* the header file ubrk.h. For Word breaks, the status allows distinguishing between words
* that contain alphabetic letters, "words" that appear to be numbers,
* punctuation and spaces, words containing ideographic characters, and
* more. For Line Break, the status distinguishes between hard (mandatory) breaks
* and soft (potential) break positions.
* <p>
* <code>getRuleStatus()</code> can be called after obtaining a boundary
* position from <code>next()</code>, <code>previous()</code>, or
* any other break iterator functions that returns a boundary position.
* <p>
* When creating custom break rules, one is free to define whatever
* status values may be convenient for the application.
* <p>
* Note: this function is not thread safe. It should not have been
* declared const, and the const remains only for compatibility
* reasons. (The function is logically const, but not bit-wise const).
* <p>
* @return the status from the break rule that determined the most recently
* returned break position.
*
* @see UWordBreak
* @stable ICU 2.2
*/
virtual int32_t getRuleStatus() const;
/**
* Get the status (tag) values from the break rule(s) that determined the most
* recently returned break position.
* <p>
* The returned status value(s) are stored into an array provided by the caller.
* The values are stored in sorted (ascending) order.
* If the capacity of the output array is insufficient to hold the data,
* the output will be truncated to the available length, and a
* U_BUFFER_OVERFLOW_ERROR will be signaled.
*
* @param fillInVec an array to be filled in with the status values.
* @param capacity the length of the supplied vector. A length of zero causes
* the function to return the number of status values, in the
* normal way, without attemtping to store any values.
* @param status receives error codes.
* @return The number of rule status values from rules that determined
* the most recent boundary returned by the break iterator.
* In the event of a U_BUFFER_OVERFLOW_ERROR, the return value
* is the total number of status values that were available,
* not the reduced number that were actually returned.
* @see getRuleStatus
* @stable ICU 3.0
*/
virtual int32_t getRuleStatusVec(int32_t *fillInVec, int32_t capacity, UErrorCode &status);
/**
* 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(void) const;
/**
* Returns 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(void);
/*
* Create a clone (copy) of this break iterator in memory provided
* by the caller. The idea is to increase performance by avoiding
* a storage allocation. Use of this functoin is NOT RECOMMENDED.
* Performance gains are minimal, and correct buffer management is
* tricky. Use clone() instead.
*
* @param stackBuffer The pointer to the memory into which the cloned object
* should be placed. If NULL, allocate heap memory
* for the cloned object.
* @param BufferSize The size of the buffer. If zero, return the required
* buffer size, but do not clone the object. If the
* size was too small (but not zero), allocate heap
* storage for the cloned object.
*
* @param status Error status. U_SAFECLONE_ALLOCATED_WARNING will be
* returned if the the provided buffer was too small, and
* the clone was therefore put on the heap.
*
* @return Pointer to the clone object. This may differ from the stackBuffer
* address if the byte alignment of the stack buffer was not suitable
* or if the stackBuffer was too small to hold the clone.
* @stable ICU 2.0
*/
virtual BreakIterator * createBufferClone(void *stackBuffer,
int32_t &BufferSize,
UErrorCode &status);
/**
* Return the binary form of compiled break rules,
* which can then be used to create a new break iterator at some
* time in the future. Creating a break iterator from pre-compiled rules
* is much faster than building one from the source form of the
* break rules.
*
* The binary data can only be used with the same version of ICU
* and on the same platform type (processor endian-ness)
*
* @param length Returns the length of the binary data. (Out paramter.)
*
* @return A pointer to the binary (compiled) rule data. The storage
* belongs to the RulesBasedBreakIterator object, not the
* caller, and must not be modified or deleted.
* @internal
*/
virtual const uint8_t *getBinaryRules(uint32_t &length);
protected:
//=======================================================================
// implementation
//=======================================================================
/**
* Dumps caches and performs other actions associated with a complete change
* in text or iteration position.
* @internal
*/
virtual void reset(void);
#if 0
/**
* Return true if the category lookup for this char
* indicates that it is in the set of dictionary lookup chars.
* This function is intended for use by dictionary based break iterators.
* @return true if the category lookup for this char
* indicates that it is in the set of dictionary lookup chars.
* @internal
*/
virtual UBool isDictionaryChar(UChar32);
/**
* Get the type of the break iterator.
* @internal
*/
virtual int32_t getBreakType() const;
#endif
/**
* Set the type of the break iterator.
* @internal
*/
virtual void setBreakType(int32_t type);
/**
* Common initialization function, used by constructors and bufferClone.
* (Also used by DictionaryBasedBreakIterator::createBufferClone().)
* @internal
*/
void init();
private:
/**
* This method backs the iterator back up to a "safe position" in the text.
* This is a position that we know, without any context, must be a break position.
* The various calling methods then iterate forward from this safe position to
* the appropriate position to return. (For more information, see the description
* of buildBackwardsStateTable() in RuleBasedBreakIterator.Builder.)
* @param statetable state table used of moving backwards
* @internal
*/
int32_t handlePrevious(const RBBIStateTable *statetable);
/**
* This method is the actual implementation of the next() method. All iteration
* vectors through here. This method initializes the state machine to state 1
* and advances through the text character by character until we reach the end
* of the text or the state machine transitions to state 0. We update our return
* value every time the state machine passes through a possible end state.
* @param statetable state table used of moving forwards
* @internal
*/
int32_t handleNext(const RBBIStateTable *statetable);
protected:
/**
* This is the function that actually implements dictionary-based
* breaking. Covering at least the range from startPos to endPos,
* it checks for dictionary characters, and if it finds them determines
* the appropriate object to deal with them. It may cache found breaks in
* fCachedBreakPositions as it goes. It may well also look at text outside
* the range startPos to endPos.
* If going forward, endPos is the normal Unicode break result, and
* if goind in reverse, startPos is the normal Unicode break result
* @param startPos The start position of a range of text
* @param endPos The end position of a range of text
* @param reverse The call is for the reverse direction
* @internal
*/
int32_t checkDictionary(int32_t startPos, int32_t endPos, UBool reverse);
private:
/**
* This function returns the appropriate LanguageBreakEngine for a
* given character c.
* @param c A character in the dictionary set
* @internal
*/
const LanguageBreakEngine *getLanguageBreakEngine(UChar32 c);
/**
* @internal
*/
void makeRuleStatusValid();
};
//------------------------------------------------------------------------------
//
// Inline Functions Definitions ...
//
//------------------------------------------------------------------------------
inline UBool RuleBasedBreakIterator::operator!=(const BreakIterator& that) const {
return !operator==(that);
}
U_NAMESPACE_END
#endif /* #if !UCONFIG_NO_BREAK_ITERATION */
#endif
File diff suppressed because it is too large Load Diff
+361
View File
@@ -0,0 +1,361 @@
/*
*******************************************************************************
* Copyright (C) 2007-2008, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
*/
#ifndef RBTZ_H
#define RBTZ_H
#include "unicode/utypes.h"
/**
* \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 UBool operator==(const TimeZone& that) const;
/**
* 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 UBool operator!=(const TimeZone& that) const;
/**
* Adds the <code>TimeZoneRule</code> which represents time transitions.
* The <code>TimeZoneRule</code> 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 <code>TimeZoneRule</code> is adopted by this
* <code>RuleBasedTimeZone</code> on successful completion of this method,
* thus, the caller must not delete it when no error is returned.
* After all rules are added, the caller must call complete() method to
* make this <code>RuleBasedTimeZone</code> ready to handle common time
* zone functions.
* @param rule The <code>TimeZoneRule</code>.
* @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
* calcuation 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 TimeZone* clone(void) const;
/**
* 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;
/**
* 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;
/**
* 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;
/**
* 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);
/**
* 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(void) const;
/**
* 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(void) const;
/**
* 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;
/**
* 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;
/**
* 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*/;
/**
* 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*/;
/**
* 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*/;
/**
* 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-NULL <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*/;
/**
* Get time zone offsets from local wall time.
* @internal
*/
virtual void getOffsetFromLocal(UDate date, int32_t nonExistingTimeOpt, int32_t duplicatedTimeOpt,
int32_t& rawOffset, int32_t& dstOffset, UErrorCode& status) /*const*/;
private:
void deleteRules(void);
void deleteTransitions(void);
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;
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(void);
/**
* 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(void) const;
};
U_NAMESPACE_END
#endif /* #if !UCONFIG_NO_FORMATTING */
#endif // RBTZ_H
//eof
File diff suppressed because it is too large Load Diff
+259
View File
@@ -0,0 +1,259 @@
/*
**************************************************************************
* Copyright (C) 1999-2005, International Business Machines Corporation and
* others. All Rights Reserved.
**************************************************************************
* Date Name Description
* 11/17/99 aliu Creation. Ported from java. Modified to
* match current UnicodeString API. Forced
* to use name "handleReplaceBetween" because
* of existing methods in UnicodeString.
**************************************************************************
*/
#ifndef REP_H
#define REP_H
#include "unicode/uobject.h"
/**
* \file
* \brief C++ API: Replaceable String
*/
U_NAMESPACE_BEGIN
class UnicodeString;
/**
* <code>Replaceable</code> is an abstract base class representing a
* string of characters that supports the replacement of a range of
* itself with a new string of characters. It is used by APIs that
* change a piece of text while retaining metadata. Metadata is data
* other than the Unicode characters returned by char32At(). One
* example of metadata is style attributes; another is an edit
* history, marking each character with an author and revision number.
*
* <p>An implicit aspect of the <code>Replaceable</code> API is that
* during a replace operation, new characters take on the metadata of
* the old characters. For example, if the string "the <b>bold</b>
* font" has range (4, 8) replaced with "strong", then it becomes "the
* <b>strong</b> font".
*
* <p><code>Replaceable</code> specifies ranges using a start
* offset and a limit offset. The range of characters thus specified
* includes the characters at offset start..limit-1. That is, the
* start offset is inclusive, and the limit offset is exclusive.
*
* <p><code>Replaceable</code> also includes API to access characters
* in the string: <code>length()</code>, <code>charAt()</code>,
* <code>char32At()</code>, and <code>extractBetween()</code>.
*
* <p>For a subclass to support metadata, typical behavior of
* <code>replace()</code> is the following:
* <ul>
* <li>Set the metadata of the new text to the metadata of the first
* character replaced</li>
* <li>If no characters are replaced, use the metadata of the
* previous character</li>
* <li>If there is no previous character (i.e. start == 0), use the
* following character</li>
* <li>If there is no following character (i.e. the replaceable was
* empty), use default metadata.<br>
* <li>If the code point U+FFFF is seen, it should be interpreted as
* a special marker having no metadata<li>
* </li>
* </ul>
* If this is not the behavior, the subclass should document any differences.
* @author Alan Liu
* @stable ICU 2.0
*/
class U_COMMON_API Replaceable : public UObject {
public:
/**
* Destructor.
* @stable ICU 2.0
*/
virtual ~Replaceable();
/**
* Returns the number of 16-bit code units in the text.
* @return number of 16-bit code units in text
* @stable ICU 1.8
*/
inline int32_t length() const;
/**
* Returns the 16-bit code unit at the given offset into the text.
* @param offset an integer between 0 and <code>length()</code>-1
* inclusive
* @return 16-bit code unit of text at given offset
* @stable ICU 1.8
*/
inline UChar charAt(int32_t offset) const;
/**
* Returns the 32-bit code point at the given 16-bit offset into
* the text. This assumes the text is stored as 16-bit code units
* with surrogate pairs intermixed. If the offset of a leading or
* trailing code unit of a surrogate pair is given, return the
* code point of the surrogate pair.
*
* @param offset an integer between 0 and <code>length()</code>-1
* inclusive
* @return 32-bit code point of text at given offset
* @stable ICU 1.8
*/
inline UChar32 char32At(int32_t offset) const;
/**
* Copies characters in the range [<tt>start</tt>, <tt>limit</tt>)
* into the UnicodeString <tt>target</tt>.
* @param start offset of first character which will be copied
* @param limit offset immediately following the last character to
* be copied
* @param target UnicodeString into which to copy characters.
* @return A reference to <TT>target</TT>
* @stable ICU 2.1
*/
virtual void extractBetween(int32_t start,
int32_t limit,
UnicodeString& target) const = 0;
/**
* Replaces a substring of this object with the given text. If the
* characters being replaced have metadata, the new characters
* that replace them should be given the same metadata.
*
* <p>Subclasses must ensure that if the text between start and
* limit is equal to the replacement text, that replace has no
* effect. That is, any metadata
* should be unaffected. In addition, subclasses are encouraged to
* check for initial and trailing identical characters, and make a
* smaller replacement if possible. This will preserve as much
* metadata as possible.
* @param start the beginning index, inclusive; <code>0 <= start
* <= limit</code>.
* @param limit the ending index, exclusive; <code>start <= limit
* <= length()</code>.
* @param text the text to replace characters <code>start</code>
* to <code>limit - 1</code>
* @stable ICU 2.0
*/
virtual void handleReplaceBetween(int32_t start,
int32_t limit,
const UnicodeString& text) = 0;
// Note: All other methods in this class take the names of
// existing UnicodeString methods. This method is the exception.
// It is named differently because all replace methods of
// UnicodeString return a UnicodeString&. The 'between' is
// required in order to conform to the UnicodeString naming
// convention; API taking start/length are named <operation>, and
// those taking start/limit are named <operationBetween>. The
// 'handle' is added because 'replaceBetween' and
// 'doReplaceBetween' are already taken.
/**
* Copies a substring of this object, retaining metadata.
* This method is used to duplicate or reorder substrings.
* The destination index must not overlap the source range.
*
* @param start the beginning index, inclusive; <code>0 <= start <=
* limit</code>.
* @param limit the ending index, exclusive; <code>start <= limit <=
* length()</code>.
* @param dest the destination index. The characters from
* <code>start..limit-1</code> will be copied to <code>dest</code>.
* Implementations of this method may assume that <code>dest <= start ||
* dest >= limit</code>.
* @stable ICU 2.0
*/
virtual void copy(int32_t start, int32_t limit, int32_t dest) = 0;
/**
* Returns true if this object contains metadata. If a
* Replaceable object has metadata, calls to the Replaceable API
* must be made so as to preserve metadata. If it does not, calls
* to the Replaceable API may be optimized to improve performance.
* The default implementation returns true.
* @return true if this object contains metadata
* @stable ICU 2.2
*/
virtual UBool hasMetaData() const;
/**
* Clone this object, an instance of a subclass of Replaceable.
* Clones can be used concurrently in multiple threads.
* If a subclass does not implement clone(), or if an error occurs,
* then NULL is returned.
* The clone functions in all subclasses return a pointer to a Replaceable
* because some compilers do not support covariant (same-as-this)
* return types; cast to the appropriate subclass if necessary.
* The caller must delete the clone.
*
* @return a clone of this object
*
* @see getDynamicClassID
* @stable ICU 2.6
*/
virtual Replaceable *clone() const;
protected:
/**
* Default constructor.
* @stable ICU 2.4
*/
Replaceable();
/*
* Assignment operator not declared. The compiler will provide one
* which does nothing since this class does not contain any data members.
* API/code coverage may show the assignment operator as present and
* untested - ignore.
* Subclasses need this assignment operator if they use compiler-provided
* assignment operators of their own. An alternative to not declaring one
* here would be to declare and empty-implement a protected or public one.
Replaceable &Replaceable::operator=(const Replaceable &);
*/
/**
* Virtual version of length().
* @stable ICU 2.4
*/
virtual int32_t getLength() const = 0;
/**
* Virtual version of charAt().
* @stable ICU 2.4
*/
virtual UChar getCharAt(int32_t offset) const = 0;
/**
* Virtual version of char32At().
* @stable ICU 2.4
*/
virtual UChar32 getChar32At(int32_t offset) const = 0;
};
inline int32_t
Replaceable::length() const {
return getLength();
}
inline UChar
Replaceable::charAt(int32_t offset) const {
return getCharAt(offset);
}
inline UChar32
Replaceable::char32At(int32_t offset) const {
return getChar32At(offset);
}
// There is no rep.cpp, see unistr.cpp for Replaceable function implementations.
U_NAMESPACE_END
#endif
+485
View File
@@ -0,0 +1,485 @@
/*
******************************************************************************
*
* Copyright (C) 1996-2007, International Business Machines Corporation
* and others. All Rights Reserved.
*
******************************************************************************
*
* File resbund.h
*
* CREATED BY
* Richard Gillam
*
* Modification History:
*
* Date Name Description
* 2/5/97 aliu Added scanForLocaleInFile. Added
* constructor which attempts to read resource bundle
* from a specific file, without searching other files.
* 2/11/97 aliu Added UErrorCode return values to constructors. Fixed
* infinite loops in scanForFile and scanForLocale.
* Modified getRawResourceData to not delete storage
* in localeData and resourceData which it doesn't own.
* Added Mac compatibility #ifdefs for tellp() and
* ios::nocreate.
* 2/18/97 helena Updated with 100% documentation coverage.
* 3/13/97 aliu Rewrote to load in entire resource bundle and store
* it as a Hashtable of ResourceBundleData objects.
* Added state table to govern parsing of files.
* Modified to load locale index out of new file
* distinct from default.txt.
* 3/25/97 aliu Modified to support 2-d arrays, needed for timezone
* data. Added support for custom file suffixes. Again,
* needed to support timezone data.
* 4/7/97 aliu Cleaned up.
* 03/02/99 stephen Removed dependency on FILE*.
* 03/29/99 helena Merged Bertrand and Stephen's changes.
* 06/11/99 stephen Removed parsing of .txt files.
* Reworked to use new binary format.
* Cleaned up.
* 06/14/99 stephen Removed methods taking a filename suffix.
* 11/09/99 weiv Added getLocale(), fRealLocale, removed fRealLocaleID
******************************************************************************
*/
#ifndef RESBUND_H
#define RESBUND_H
#include "unicode/utypes.h"
#include "unicode/uobject.h"
#include "unicode/ures.h"
#include "unicode/unistr.h"
#include "unicode/locid.h"
/**
* \file
* \brief C++ API: Resource Bundle
*/
U_NAMESPACE_BEGIN
/**
* A class representing a collection of resource information pertaining to a given
* locale. A resource bundle provides a way of accessing locale- specfic information in
* a data file. You create a resource bundle that manages the resources for a given
* locale and then ask it for individual resources.
* <P>
* Resource bundles in ICU4C are currently defined using text files which conform to the following
* <a href="http://source.icu-project.org/repos/icu/icuhtml/trunk/design/bnf_rb.txt">BNF definition</a>.
* More on resource bundle concepts and syntax can be found in the
* <a href="http://icu-project.org/userguide/ResourceManagement.html">Users Guide</a>.
* <P>
*
* The ResourceBundle class is not suitable for subclassing.
*
* @stable ICU 2.0
*/
class U_COMMON_API ResourceBundle : public UObject {
public:
/**
* Constructor
*
* @param packageName The packageName and locale together point to an ICU udata object,
* as defined by <code> udata_open( packageName, "res", locale, err) </code>
* or equivalent. Typically, packageName will refer to a (.dat) file, or to
* a package registered with udata_setAppData(). Using a full file or directory
* pathname for packageName is deprecated.
* @param locale This is the locale this resource bundle is for. To get resources
* for the French locale, for example, you would create a
* ResourceBundle passing Locale::FRENCH for the "locale" parameter,
* and all subsequent calls to that resource bundle will return
* resources that pertain to the French locale. If the caller doesn't
* pass a locale parameter, the default locale for the system (as
* returned by Locale::getDefault()) will be used.
* @param err The Error Code.
* The UErrorCode& err parameter is used to return status information to the user. To
* check whether the construction succeeded or not, you should check the value of
* U_SUCCESS(err). If you wish more detailed information, you can check for
* informational error results which still indicate success. U_USING_FALLBACK_WARNING
* indicates that a fall back locale was used. For example, 'de_CH' was requested,
* but nothing was found there, so 'de' was used. U_USING_DEFAULT_WARNING indicates that
* the default locale data was used; neither the requested locale nor any of its
* fall back locales could be found.
* @stable ICU 2.0
*/
ResourceBundle(const UnicodeString& packageName,
const Locale& locale,
UErrorCode& err);
/**
* Construct a resource bundle for the default bundle in the specified package.
*
* @param packageName The packageName and locale together point to an ICU udata object,
* as defined by <code> udata_open( packageName, "res", locale, err) </code>
* or equivalent. Typically, packageName will refer to a (.dat) file, or to
* a package registered with udata_setAppData(). Using a full file or directory
* pathname for packageName is deprecated.
* @param err A UErrorCode value
* @stable ICU 2.0
*/
ResourceBundle(const UnicodeString& packageName,
UErrorCode& err);
/**
* Construct a resource bundle for the ICU default bundle.
*
* @param err A UErrorCode value
* @stable ICU 2.0
*/
ResourceBundle(UErrorCode &err);
/**
* Standard constructor, onstructs a resource bundle for the locale-specific
* bundle in the specified package.
*
* @param packageName The packageName and locale together point to an ICU udata object,
* as defined by <code> udata_open( packageName, "res", locale, err) </code>
* or equivalent. Typically, packageName will refer to a (.dat) file, or to
* a package registered with udata_setAppData(). Using a full file or directory
* pathname for packageName is deprecated.
* NULL is used to refer to ICU data.
* @param locale The locale for which to open a resource bundle.
* @param err A UErrorCode value
* @stable ICU 2.0
*/
ResourceBundle(const char* packageName,
const Locale& locale,
UErrorCode& err);
/**
* Copy constructor.
*
* @param original The resource bundle to copy.
* @stable ICU 2.0
*/
ResourceBundle(const ResourceBundle &original);
/**
* Constructor from a C UResourceBundle. The resource bundle is
* copied and not adopted. ures_close will still need to be used on the
* original resource bundle.
*
* @param res A pointer to the C resource bundle.
* @param status A UErrorCode value.
* @stable ICU 2.0
*/
ResourceBundle(UResourceBundle *res,
UErrorCode &status);
/**
* Assignment operator.
*
* @param other The resource bundle to copy.
* @stable ICU 2.0
*/
ResourceBundle&
operator=(const ResourceBundle& other);
/** Destructor.
* @stable ICU 2.0
*/
virtual ~ResourceBundle();
/**
* Clone this object.
* Clones can be used concurrently in multiple threads.
* If an error occurs, then NULL is returned.
* The caller must delete the clone.
*
* @return a clone of this object
*
* @see getDynamicClassID
* @stable ICU 2.8
*/
ResourceBundle *clone() const;
/**
* Returns the size of a resource. Size for scalar types is always 1, and for vector/table types is
* the number of child resources.
* @warning Integer array is treated as a scalar type. There are no
* APIs to access individual members of an integer array. It
* is always returned as a whole.
*
* @return number of resources in a given resource.
* @stable ICU 2.0
*/
int32_t
getSize(void) const;
/**
* returns a string from a string resource type
*
* @param status fills in the outgoing error code
* could be <TT>U_MISSING_RESOURCE_ERROR</TT> if the key is not found
* could be a warning
* e.g.: <TT>U_USING_FALLBACK_WARNING</TT>,<TT>U_USING_DEFAULT_WARNING </TT>
* @return a pointer to a zero-terminated UChar array which lives in a memory mapped/DLL file.
* @stable ICU 2.0
*/
UnicodeString
getString(UErrorCode& status) const;
/**
* returns a binary data from a resource. Can be used at most primitive resource types (binaries,
* strings, ints)
*
* @param len fills in the length of resulting byte chunk
* @param status fills in the outgoing error code
* could be <TT>U_MISSING_RESOURCE_ERROR</TT> if the key is not found
* could be a warning
* e.g.: <TT>U_USING_FALLBACK_WARNING</TT>,<TT>U_USING_DEFAULT_WARNING </TT>
* @return a pointer to a chunk of unsigned bytes which live in a memory mapped/DLL file.
* @stable ICU 2.0
*/
const uint8_t*
getBinary(int32_t& len, UErrorCode& status) const;
/**
* returns an integer vector from a resource.
*
* @param len fills in the length of resulting integer vector
* @param status fills in the outgoing error code
* could be <TT>U_MISSING_RESOURCE_ERROR</TT> if the key is not found
* could be a warning
* e.g.: <TT>U_USING_FALLBACK_WARNING</TT>,<TT>U_USING_DEFAULT_WARNING </TT>
* @return a pointer to a vector of integers that lives in a memory mapped/DLL file.
* @stable ICU 2.0
*/
const int32_t*
getIntVector(int32_t& len, UErrorCode& status) const;
/**
* returns an unsigned integer from a resource.
* This integer is originally 28 bits.
*
* @param status fills in the outgoing error code
* could be <TT>U_MISSING_RESOURCE_ERROR</TT> if the key is not found
* could be a warning
* e.g.: <TT>U_USING_FALLBACK_WARNING</TT>,<TT>U_USING_DEFAULT_WARNING </TT>
* @return an unsigned integer value
* @stable ICU 2.0
*/
uint32_t
getUInt(UErrorCode& status) const;
/**
* returns a signed integer from a resource.
* This integer is originally 28 bit and the sign gets propagated.
*
* @param status fills in the outgoing error code
* could be <TT>U_MISSING_RESOURCE_ERROR</TT> if the key is not found
* could be a warning
* e.g.: <TT>U_USING_FALLBACK_WARNING</TT>,<TT>U_USING_DEFAULT_WARNING </TT>
* @return a signed integer value
* @stable ICU 2.0
*/
int32_t
getInt(UErrorCode& status) const;
/**
* Checks whether the resource has another element to iterate over.
*
* @return TRUE if there are more elements, FALSE if there is no more elements
* @stable ICU 2.0
*/
UBool
hasNext(void) const;
/**
* Resets the internal context of a resource so that iteration starts from the first element.
*
* @stable ICU 2.0
*/
void
resetIterator(void);
/**
* Returns the key associated with this resource. Not all the resources have a key - only
* those that are members of a table.
*
* @return a key associated to this resource, or NULL if it doesn't have a key
* @stable ICU 2.0
*/
const char*
getKey(void) const;
/**
* Gets the locale ID of the resource bundle as a string.
* Same as getLocale().getName() .
*
* @return the locale ID of the resource bundle as a string
* @stable ICU 2.0
*/
const char*
getName(void) const;
/**
* Returns the type of a resource. Available types are defined in enum UResType
*
* @return type of the given resource.
* @stable ICU 2.0
*/
UResType
getType(void) const;
/**
* Returns the next resource in a given resource or NULL if there are no more resources
*
* @param status fills in the outgoing error code
* @return ResourceBundle object.
* @stable ICU 2.0
*/
ResourceBundle
getNext(UErrorCode& status);
/**
* Returns the next string in a resource or NULL if there are no more resources
* to iterate over.
*
* @param status fills in the outgoing error code
* @return an UnicodeString object.
* @stable ICU 2.0
*/
UnicodeString
getNextString(UErrorCode& status);
/**
* Returns the next string in a resource or NULL if there are no more resources
* to iterate over.
*
* @param key fill in for key associated with this string
* @param status fills in the outgoing error code
* @return an UnicodeString object.
* @stable ICU 2.0
*/
UnicodeString
getNextString(const char ** key,
UErrorCode& status);
/**
* Returns the resource in a resource at the specified index.
*
* @param index an index to the wanted resource.
* @param status fills in the outgoing error code
* @return ResourceBundle object. If there is an error, resource is invalid.
* @stable ICU 2.0
*/
ResourceBundle
get(int32_t index,
UErrorCode& status) const;
/**
* Returns the string in a given resource at the specified index.
*
* @param index an index to the wanted string.
* @param status fills in the outgoing error code
* @return an UnicodeString object. If there is an error, string is bogus
* @stable ICU 2.0
*/
UnicodeString
getStringEx(int32_t index,
UErrorCode& status) const;
/**
* Returns a resource in a resource that has a given key. This procedure works only with table
* resources.
*
* @param key a key associated with the wanted resource
* @param status fills in the outgoing error code.
* @return ResourceBundle object. If there is an error, resource is invalid.
* @stable ICU 2.0
*/
ResourceBundle
get(const char* key,
UErrorCode& status) const;
/**
* Returns a string in a resource that has a given key. This procedure works only with table
* resources.
*
* @param key a key associated with the wanted string
* @param status fills in the outgoing error code
* @return an UnicodeString object. If there is an error, string is bogus
* @stable ICU 2.0
*/
UnicodeString
getStringEx(const char* key,
UErrorCode& status) const;
/**
* Return the version number associated with this ResourceBundle as a string. Please
* use getVersion, as this method is going to be deprecated.
*
* @return A version number string as specified in the resource bundle or its parent.
* The caller does not own this string.
* @see getVersion
* @deprecated ICU 2.8 Use getVersion instead.
*/
const char*
getVersionNumber(void) const;
/**
* Return the version number associated with this ResourceBundle as a UVersionInfo array.
*
* @param versionInfo A UVersionInfo array that is filled with the version number
* as specified in the resource bundle or its parent.
* @stable ICU 2.0
*/
void
getVersion(UVersionInfo versionInfo) const;
/**
* Return the Locale associated with this ResourceBundle.
*
* @return a Locale object
* @deprecated ICU 2.8 Use getLocale(ULocDataLocaleType type, UErrorCode &status) overload instead.
*/
const Locale&
getLocale(void) const;
/**
* Return the Locale associated with this ResourceBundle.
* @param type You can choose between requested, valid and actual
* locale. For description see the definition of
* ULocDataLocaleType in uloc.h
* @param status just for catching illegal arguments
*
* @return a Locale object
* @stable ICU 2.8
*/
const Locale
getLocale(ULocDataLocaleType type, UErrorCode &status) const;
/**
* This API implements multilevel fallback
* @internal
*/
ResourceBundle
getWithFallback(const char* key, UErrorCode& status);
/**
* ICU "poor man's RTTI", returns a UClassID for the actual class.
*
* @stable ICU 2.2
*/
virtual UClassID getDynamicClassID() const;
/**
* ICU "poor man's RTTI", returns a UClassID for this class.
*
* @stable ICU 2.2
*/
static UClassID U_EXPORT2 getStaticClassID();
private:
ResourceBundle(); // default constructor not implemented
UResourceBundle *fResource;
void constructForLocale(const UnicodeString& path, const Locale& locale, UErrorCode& error);
Locale *fLocale;
};
U_NAMESPACE_END
#endif
+187
View File
@@ -0,0 +1,187 @@
/*
******************************************************************************
*
* Copyright (C) 1998-2005, International Business Machines
* Corporation and others. All Rights Reserved.
*
******************************************************************************
*
* File schriter.h
*
* Modification History:
*
* Date Name Description
* 05/05/99 stephen Cleaned up.
******************************************************************************
*/
#ifndef SCHRITER_H
#define SCHRITER_H
#include "unicode/utypes.h"
#include "unicode/chariter.h"
#include "unicode/uchriter.h"
/**
* \file
* \brief C++ API: String Character Iterator
*/
U_NAMESPACE_BEGIN
/**
* A concrete subclass of CharacterIterator that iterates over the
* characters (code units or code points) in a UnicodeString.
* It's possible not only to create an
* iterator that iterates over an entire UnicodeString, but also to
* create one that iterates over only a subrange of a UnicodeString
* (iterators over different subranges of the same UnicodeString don't
* compare equal).
* @see CharacterIterator
* @see ForwardCharacterIterator
* @stable ICU 2.0
*/
class U_COMMON_API StringCharacterIterator : public UCharCharacterIterator {
public:
/**
* Create an iterator over the UnicodeString referred to by "textStr".
* The UnicodeString object is copied.
* The iteration range is the whole string, and the starting position is 0.
* @param textStr The unicode string used to create an iterator
* @stable ICU 2.0
*/
StringCharacterIterator(const UnicodeString& textStr);
/**
* Create an iterator over the UnicodeString referred to by "textStr".
* The iteration range is the whole string, and the starting
* position is specified by "textPos". If "textPos" is outside the valid
* iteration range, the behavior of this object is undefined.
* @param textStr The unicode string used to create an iterator
* @param textPos The starting position of the iteration
* @stable ICU 2.0
*/
StringCharacterIterator(const UnicodeString& textStr,
int32_t textPos);
/**
* Create an iterator over the UnicodeString referred to by "textStr".
* The UnicodeString object is copied.
* The iteration range begins with the code unit specified by
* "textBegin" and ends with the code unit BEFORE the code unit specfied
* by "textEnd". The starting position is specified by "textPos". If
* "textBegin" and "textEnd" don't form a valid range on "text" (i.e.,
* textBegin >= textEnd or either is negative or greater than text.size()),
* or "textPos" is outside the range defined by "textBegin" and "textEnd",
* the behavior of this iterator is undefined.
* @param textStr The unicode string used to create the StringCharacterIterator
* @param textBegin The begin position of the iteration range
* @param textEnd The end position of the iteration range
* @param textPos The starting position of the iteration
* @stable ICU 2.0
*/
StringCharacterIterator(const UnicodeString& textStr,
int32_t textBegin,
int32_t textEnd,
int32_t textPos);
/**
* Copy constructor. The new iterator iterates over the same range
* of the same string as "that", and its initial position is the
* same as "that"'s current position.
* The UnicodeString object in "that" is copied.
* @param that The StringCharacterIterator to be copied
* @stable ICU 2.0
*/
StringCharacterIterator(const StringCharacterIterator& that);
/**
* Destructor.
* @stable ICU 2.0
*/
virtual ~StringCharacterIterator();
/**
* Assignment operator. *this is altered to iterate over the same
* range of the same string as "that", and refers to the same
* character within that string as "that" does.
* @param that The object to be copied.
* @return the newly created object.
* @stable ICU 2.0
*/
StringCharacterIterator&
operator=(const StringCharacterIterator& that);
/**
* Returns true if the iterators iterate over the same range of the
* same string and are pointing at the same character.
* @param that The ForwardCharacterIterator to be compared for equality
* @return true if the iterators iterate over the same range of the
* same string and are pointing at the same character.
* @stable ICU 2.0
*/
virtual UBool operator==(const ForwardCharacterIterator& that) const;
/**
* Returns a new StringCharacterIterator referring to the same
* character in the same range of the same string as this one. The
* caller must delete the new iterator.
* @return the newly cloned object.
* @stable ICU 2.0
*/
virtual CharacterIterator* clone(void) const;
/**
* Sets the iterator to iterate over the provided string.
* @param newText The string to be iterated over
* @stable ICU 2.0
*/
void setText(const UnicodeString& newText);
/**
* Copies the UnicodeString under iteration into the UnicodeString
* referred to by "result". Even if this iterator iterates across
* only a part of this string, the whole string is copied.
* @param result Receives a copy of the text under iteration.
* @stable ICU 2.0
*/
virtual void getText(UnicodeString& result);
/**
* Return a class ID for this object (not really public)
* @return a class ID for this object.
* @stable ICU 2.0
*/
virtual UClassID getDynamicClassID(void) const;
/**
* Return a class ID for this class (not really public)
* @return a class ID for this class
* @stable ICU 2.0
*/
static UClassID U_EXPORT2 getStaticClassID(void);
protected:
/**
* Default constructor, iteration over empty string.
* @stable ICU 2.0
*/
StringCharacterIterator();
/**
* Sets the iterator to iterate over the provided string.
* @param newText The string to be iterated over
* @param newTextLength The length of the String
* @stable ICU 2.0
*/
void setText(const UChar* newText, int32_t newTextLength);
/**
* Copy of the iterated string object.
* @stable ICU 2.0
*/
UnicodeString text;
};
U_NAMESPACE_END
#endif
+569
View File
@@ -0,0 +1,569 @@
/*
**********************************************************************
* Copyright (C) 2001-2008 IBM and others. All rights reserved.
**********************************************************************
* Date Name Description
* 03/22/2000 helena Creation.
**********************************************************************
*/
#ifndef SEARCH_H
#define SEARCH_H
#include "unicode/utypes.h"
/**
* \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 occurances 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.getMatchLength());
* }
* </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(void) 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(void) 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(void) 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>NULL</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>NULL</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(void) 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(void) 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 UBool 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
*/
UBool 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(void) 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 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 USEARCH_DONE
* @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
* @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>NULL</tt>, no break detection is attempted.
* @see #handleNext
* @see #handlePrev
* @stable ICU 2.0
*/
SearchIterator(const UnicodeString &text,
BreakIterator *breakiter = NULL);
/**
* 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>NULL</tt>, no break detection is attempted.
* @see #handleNext
* @see #handlePrev
* @stable ICU 2.0
*/
SearchIterator(CharacterIterator &text, BreakIterator *breakiter = NULL);
// 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 UBool SearchIterator::operator!=(const SearchIterator &that) const
{
return !operator==(that);
}
U_NAMESPACE_END
#endif /* #if !UCONFIG_NO_COLLATION */
#endif
+927
View File
@@ -0,0 +1,927 @@
/*
********************************************************************************
* Copyright (C) 1997-2009, 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"
/**
* \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 UBool operator==(const TimeZone& that) const;
/**
* 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 specfied 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 specfied 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 specfied 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 specfied 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 specfied 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;
/**
* 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;
/**
* 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;
/**
* Get time zone offsets from local wall time.
* @internal
*/
virtual void getOffsetFromLocal(UDate date, int32_t nonExistingTimeOpt, int32_t duplicatedTimeOpt,
int32_t& rawOffset, int32_t& dstOffset, UErrorCode& status) /*const*/;
/**
* 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(void) const;
/**
* 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);
/**
* 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. A positive number, typically one hour (3600000).
* @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. A positive number, typically one hour (3600000).
* @stable ICU 2.0
*/
virtual int32_t getDSTSavings(void) const;
/**
* 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(void) const;
/**
* 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;
/**
* 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;
/**
* 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 TimeZone* clone(void) const;
/**
* 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*/;
/**
* 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*/;
/**
* 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*/;
/**
* 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-NULL <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*/;
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(void) 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() ==
* . Derived::getStaticClassID()) ...
* </pre>
* @return The class ID for all objects of this class.
* @stable ICU 2.0
*/
static UClassID U_EXPORT2 getStaticClassID(void);
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(); // 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 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.
*/
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 initTransitionRules(UErrorCode& status);
void clearTransitionRules(void);
void deleteTransitionRules(void);
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 // _SIMPLETZ
File diff suppressed because it is too large Load Diff
+324
View File
@@ -0,0 +1,324 @@
/*
*****************************************************************************
* Copyright (C) 1996-2006, 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"
/**
* \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;
/**
*
* 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
* @deprecated ICU 2.8 Use Collator::getSortKey(...) instead
*/
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.
* @deprecated ICU 2.8 Use Collator::getSortKey(...) instead
*/
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.
* @deprecated ICU 2.8 Use Collator::getSortKey(...) instead
*/
CollationKey(const uint8_t* values,
int32_t count);
/**
* Copy constructor.
* @param other the object to be copied.
* @deprecated ICU 2.8 Use Collator::getSortKey(...) instead
*/
CollationKey(const CollationKey& other);
/**
* Sort key destructor.
* @deprecated ICU 2.8 Use Collator::getSortKey(...) instead
*/
virtual ~CollationKey();
/**
* Assignment operator
* @param other the object to be copied.
* @deprecated ICU 2.8 Use Collator::getSortKey(...) instead
*/
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.
* @deprecated ICU 2.8 Use Collator::getSortKey(...) instead
*/
UBool 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.
* @deprecated ICU 2.8 Use Collator::getSortKey(...) instead
*/
UBool 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.
* @deprecated ICU 2.8 Use Collator::getSortKey(...) instead
*/
UBool isBogus(void) 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.
* @deprecated ICU 2.8 Use Collator::getSortKey(...) instead
*/
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
/**
* 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;
/**
* 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.
* @deprecated ICU 2.8 Use Collator::getSortKey(...) instead
*/
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
* @deprecated ICU 2.8 Use Collator::getSortKey(...) instead
*/
int32_t hashCode(void) const;
/**
* ICU "poor man's RTTI", returns a UClassID for the actual class.
* @deprecated ICU 2.8 Use Collator::getSortKey(...) instead
*/
virtual UClassID getDynamicClassID() const;
/**
* ICU "poor man's RTTI", returns a UClassID for this class.
* @deprecated ICU 2.8 Use Collator::getSortKey(...) instead
*/
static UClassID U_EXPORT2 getStaticClassID();
private:
/**
* Returns an array of the collation key values as 16-bit integers.
* The caller owns the storage and must delete it.
* @param values Output param of the collation key values.
* @param count output parameter of the number of collation key values
* @return a pointer to an array of 16-bit collation key values.
*/
void adopt(uint8_t *values, int32_t count);
/*
* Creates a collation key with a string.
*/
/**
* If this CollationKey has capacity less than newSize,
* its internal capacity will be increased to newSize.
* @param newSize minimum size this CollationKey has to have
* @return this CollationKey
*/
CollationKey& ensureCapacity(int32_t newSize);
/**
* Set the CollationKey to a "bogus" or invalid state
* @return this CollationKey
*/
CollationKey& setToBogus(void);
/**
* Resets this CollationKey to an empty state
* @return this CollationKey
*/
CollationKey& reset(void);
/**
* Allow private access to RuleBasedCollator
*/
friend class RuleBasedCollator;
/**
* Bogus status
*/
UBool fBogus;
/**
* Size of fBytes used to store the sortkey. i.e. up till the
* null-termination.
*/
int32_t fCount;
/**
* Full size of the fBytes
*/
int32_t fCapacity;
/**
* Unique hash value of this CollationKey
*/
int32_t fHashCode;
/**
* Array to store the sortkey
*/
uint8_t* fBytes;
};
inline UBool
CollationKey::operator!=(const CollationKey& other) const
{
return !(*this == other);
}
inline UBool
CollationKey::isBogus() const
{
return fBogus;
}
inline const uint8_t*
CollationKey::getByteArray(int32_t &count) const
{
count = fCount;
return fBytes;
}
U_NAMESPACE_END
#endif /* #if !UCONFIG_NO_COLLATION */
#endif
+78
View File
@@ -0,0 +1,78 @@
/*
*******************************************************************************
*
* Copyright (C) 2009, International Business Machines
* Corporation and others. All Rights Reserved.
*
*******************************************************************************
* file name: std_string.h
* encoding: US-ASCII
* tab size: 8 (not used)
* indentation:4
*
* created on: 2009feb19
* created by: Markus W. Scherer
*/
#ifndef __STD_STRING_H__
#define __STD_STRING_H__
/**
* \file
* \brief C++ API: Central ICU header for including the C++ standard <string>
* header and for related definitions.
*/
#include "unicode/utypes.h"
/**
* \def U_HAVE_STD_STRING
* Define whether the standard C++ (STL) <string> header is available.
* @draft ICU 4.2
*/
#ifndef U_HAVE_STD_STRING
#define U_HAVE_STD_STRING 1
#endif
#if U_HAVE_STD_STRING
#include <string>
/**
* \def U_STD_NS
* Define the namespace to use for standard C++ (STL) classes.
* Either std or empty.
* @draft ICU 4.2
*/
/**
* \def U_STD_NSQ
* Define the namespace qualifier to use for standard C++ (STL) classes.
* Either std:: or empty.
* For example,
* U_STD_NSQ string StringFromUnicodeString(const UnicodeString &unistr);
* @draft ICU 4.2
*/
/**
* \def U_STD_NS_USE
* This is used to specify that the rest of the code uses the
* standard (STL) namespace.
* Either "using namespace std;" or empty.
* @draft ICU 4.2
*/
#ifndef U_STD_NSQ
# if U_HAVE_NAMESPACE
# define U_STD_NS std
# define U_STD_NSQ U_STD_NS::
# define U_STD_NS_USE using namespace U_STD_NS;
# else
# define U_STD_NS
# define U_STD_NSQ
# define U_STD_NS_USE
# endif
#endif
#endif // U_HAVE_STD_STRING
#endif // __STD_STRING_H__
+271
View File
@@ -0,0 +1,271 @@
/*
*******************************************************************************
*
* Copyright (C) 2002-2007, International Business Machines
* Corporation and others. All Rights Reserved.
*
*******************************************************************************
*/
#ifndef STRENUM_H
#define STRENUM_H
#include "unicode/uobject.h"
#include "unicode/unistr.h"
/**
* \file
* \brief C++ API: String Enumeration
*/
U_NAMESPACE_BEGIN
/**
* Base class for 'pure' C++ implementations of uenum api. Adds a
* method that returns the next UnicodeString since in C++ this can
* be a common storage format for strings.
*
* <p>The model is that the enumeration is over strings maintained by
* a 'service.' At any point, the service might change, invalidating
* the enumerator (though this is expected to be rare). The iterator
* returns an error if this has occurred. Lack of the error is no
* guarantee that the service didn't change immediately after the
* call, so the returned string still might not be 'valid' on
* subsequent use.</p>
*
* <p>Strings may take the form of const char*, const UChar*, or const
* UnicodeString*. The type you get is determine by the variant of
* 'next' that you call. In general the StringEnumeration is
* optimized for one of these types, but all StringEnumerations can
* return all types. Returned strings are each terminated with a NUL.
* Depending on the service data, they might also include embedded NUL
* characters, so API is provided to optionally return the true
* length, counting the embedded NULs but not counting the terminating
* NUL.</p>
*
* <p>The pointers returned by next, unext, and snext become invalid
* upon any subsequent call to the enumeration's destructor, next,
* unext, snext, or reset.</p>
*
* ICU 2.8 adds some default implementations and helper functions
* for subclasses.
*
* @stable ICU 2.4
*/
class U_COMMON_API StringEnumeration : public UObject {
public:
/**
* Destructor.
* @stable ICU 2.4
*/
virtual ~StringEnumeration();
/**
* Clone this object, an instance of a subclass of StringEnumeration.
* Clones can be used concurrently in multiple threads.
* If a subclass does not implement clone(), or if an error occurs,
* then NULL is returned.
* The clone functions in all subclasses return a base class pointer
* because some compilers do not support covariant (same-as-this)
* return types; cast to the appropriate subclass if necessary.
* The caller must delete the clone.
*
* @return a clone of this object
*
* @see getDynamicClassID
* @stable ICU 2.8
*/
virtual StringEnumeration *clone() const;
/**
* <p>Return the number of elements that the iterator traverses. If
* the iterator is out of sync with its service, status is set to
* U_ENUM_OUT_OF_SYNC_ERROR, and the return value is zero.</p>
*
* <p>The return value will not change except possibly as a result of
* a subsequent call to reset, or if the iterator becomes out of sync.</p>
*
* <p>This is a convenience function. It can end up being very
* expensive as all the items might have to be pre-fetched
* (depending on the storage format of the data being
* traversed).</p>
*
* @param status the error code.
* @return number of elements in the iterator.
*
* @stable ICU 2.4 */
virtual int32_t count(UErrorCode& status) const = 0;
/**
* <p>Returns the next element as a NUL-terminated char*. If there
* are no more elements, returns NULL. If the resultLength pointer
* is not NULL, the length of the string (not counting the
* terminating NUL) is returned at that address. If an error
* status is returned, the value at resultLength is undefined.</p>
*
* <p>The returned pointer is owned by this iterator and must not be
* deleted by the caller. The pointer is valid until the next call
* to next, unext, snext, reset, or the enumerator's destructor.</p>
*
* <p>If the iterator is out of sync with its service, status is set
* to U_ENUM_OUT_OF_SYNC_ERROR and NULL is returned.</p>
*
* <p>If the native service string is a UChar* string, it is
* converted to char* with the invariant converter. If the
* conversion fails (because a character cannot be converted) then
* status is set to U_INVARIANT_CONVERSION_ERROR and the return
* value is undefined (though not NULL).</p>
*
* Starting with ICU 2.8, the default implementation calls snext()
* and handles the conversion.
*
* @param status the error code.
* @param resultLength a pointer to receive the length, can be NULL.
* @return a pointer to the string, or NULL.
*
* @stable ICU 2.4
*/
virtual const char* next(int32_t *resultLength, UErrorCode& status);
/**
* <p>Returns the next element as a NUL-terminated UChar*. If there
* are no more elements, returns NULL. If the resultLength pointer
* is not NULL, the length of the string (not counting the
* terminating NUL) is returned at that address. If an error
* status is returned, the value at resultLength is undefined.</p>
*
* <p>The returned pointer is owned by this iterator and must not be
* deleted by the caller. The pointer is valid until the next call
* to next, unext, snext, reset, or the enumerator's destructor.</p>
*
* <p>If the iterator is out of sync with its service, status is set
* to U_ENUM_OUT_OF_SYNC_ERROR and NULL is returned.</p>
*
* Starting with ICU 2.8, the default implementation calls snext()
* and handles the conversion.
*
* @param status the error code.
* @param resultLength a ponter to receive the length, can be NULL.
* @return a pointer to the string, or NULL.
*
* @stable ICU 2.4
*/
virtual const UChar* unext(int32_t *resultLength, UErrorCode& status);
/**
* <p>Returns the next element a UnicodeString*. If there are no
* more elements, returns NULL.</p>
*
* <p>The returned pointer is owned by this iterator and must not be
* deleted by the caller. The pointer is valid until the next call
* to next, unext, snext, reset, or the enumerator's destructor.</p>
*
* <p>If the iterator is out of sync with its service, status is set
* to U_ENUM_OUT_OF_SYNC_ERROR and NULL is returned.</p>
*
* @param status the error code.
* @return a pointer to the string, or NULL.
*
* @stable ICU 2.4
*/
virtual const UnicodeString* snext(UErrorCode& status) = 0;
/**
* <p>Resets the iterator. This re-establishes sync with the
* service and rewinds the iterator to start at the first
* element.</p>
*
* <p>Previous pointers returned by next, unext, or snext become
* invalid, and the value returned by count might change.</p>
*
* @param status the error code.
*
* @stable ICU 2.4
*/
virtual void reset(UErrorCode& status) = 0;
/**
* Compares this enumeration to other to check if both are equal
*
* @param that The other string enumeration to compare this object to
* @return TRUE if the enumerations are equal. FALSE if not.
* @stable ICU 3.6
*/
virtual UBool operator==(const StringEnumeration& that)const;
/**
* Compares this enumeration to other to check if both are not equal
*
* @param that The other string enumeration to compare this object to
* @return TRUE if the enumerations are equal. FALSE if not.
* @stable ICU 3.6
*/
virtual UBool operator!=(const StringEnumeration& that)const;
protected:
/**
* UnicodeString field for use with default implementations and subclasses.
* @stable ICU 2.8
*/
UnicodeString unistr;
/**
* char * default buffer for use with default implementations and subclasses.
* @stable ICU 2.8
*/
char charsBuffer[32];
/**
* char * buffer for use with default implementations and subclasses.
* Allocated in constructor and in ensureCharsCapacity().
* @stable ICU 2.8
*/
char *chars;
/**
* Capacity of chars, for use with default implementations and subclasses.
* @stable ICU 2.8
*/
int32_t charsCapacity;
/**
* Default constructor for use with default implementations and subclasses.
* @stable ICU 2.8
*/
StringEnumeration();
/**
* Ensures that chars is at least as large as the requested capacity.
* For use with default implementations and subclasses.
*
* @param capacity Requested capacity.
* @param status ICU in/out error code.
* @stable ICU 2.8
*/
void ensureCharsCapacity(int32_t capacity, UErrorCode &status);
/**
* Converts s to Unicode and sets unistr to the result.
* For use with default implementations and subclasses,
* especially for implementations of snext() in terms of next().
* This is provided with a helper function instead of a default implementation
* of snext() to avoid potential infinite loops between next() and snext().
*
* For example:
* \code
* const UnicodeString* snext(UErrorCode& status) {
* int32_t resultLength=0;
* const char *s=next(&resultLength, status);
* return setChars(s, resultLength, status);
* }
* \endcode
*
* @param s String to be converted to Unicode.
* @param length Length of the string.
* @param status ICU in/out error code.
* @return A pointer to unistr.
* @stable ICU 2.8
*/
UnicodeString *setChars(const char *s, int32_t length, UErrorCode &status);
};
U_NAMESPACE_END
/* STRENUM_H */
#endif
+188
View File
@@ -0,0 +1,188 @@
// Copyright (C) 2009, International Business Machines
// Corporation and others. All Rights Reserved.
//
// Copyright 2001 and onwards Google Inc.
// Author: Sanjay Ghemawat
// This code is a contribution of Google code, and the style used here is
// a compromise between the original Google code and the ICU coding guidelines.
// For example, data types are ICU-ified (size_t,int->int32_t),
// and API comments doxygen-ified, but function names and behavior are
// as in the original, if possible.
// Assertion-style error handling, not available in ICU, was changed to
// parameter "pinning" similar to UnicodeString.
//
// In addition, this is only a partial port of the original Google code,
// limited to what was needed so far. The (nearly) complete original code
// is in the ICU svn repository at icuhtml/trunk/design/strings/contrib
// (see ICU ticket 6765, r25517).
#ifndef __STRINGPIECE_H__
#define __STRINGPIECE_H__
/**
* \file
* \brief C++ API: StringPiece: Read-only byte string wrapper class.
*/
#include "unicode/utypes.h"
#include "unicode/uobject.h"
#include "unicode/std_string.h"
// Arghh! I wish C++ literals were "string".
U_NAMESPACE_BEGIN
/**
* A string-like object that points to a sized piece of memory.
*
* We provide non-explicit singleton constructors so users can pass
* in a "const char*" or a "string" wherever a "StringPiece" is
* expected.
*
* Functions or methods may use const StringPiece& parameters to accept either
* a "const char*" or a "string" value that will be implicitly converted to
* a StringPiece.
*
* Systematic usage of StringPiece is encouraged as it will reduce unnecessary
* conversions from "const char*" to "string" and back again.
*
* @draft ICU 4.2
*/
class U_COMMON_API StringPiece : public UMemory {
private:
const char* ptr_;
int32_t length_;
public:
/**
* Default constructor, creates an empty StringPiece.
* @draft ICU 4.2
*/
StringPiece() : ptr_(NULL), length_(0) { }
/**
* Constructs from a NUL-terminated const char * pointer.
* @param str a NUL-terminated const char * pointer
* @draft ICU 4.2
*/
StringPiece(const char* str);
#if U_HAVE_STD_STRING
/**
* Constructs from a std::string.
* @draft ICU 4.2
*/
StringPiece(const U_STD_NSQ string& str)
: ptr_(str.data()), length_(static_cast<int32_t>(str.size())) { }
#endif
/**
* Constructs from a const char * pointer and a specified length.
* @param offset a const char * pointer (need not be terminated)
* @param len the length of the string; must be non-negative
* @draft ICU 4.2
*/
StringPiece(const char* offset, int32_t len) : ptr_(offset), length_(len) { }
/**
* Substring of another StringPiece.
* @param x the other StringPiece
* @param pos start position in x; must be non-negative and <= x.length().
* @draft ICU 4.2
*/
StringPiece(const StringPiece& x, int32_t pos);
/**
* Substring of another StringPiece.
* @param x the other StringPiece
* @param pos start position in x; must be non-negative and <= x.length().
* @param len length of the substring;
* must be non-negative and will be pinned to at most x.length() - pos.
* @draft ICU 4.2
*/
StringPiece(const StringPiece& x, int32_t pos, int32_t len);
/**
* Returns the string pointer. May be NULL if it is empty.
*
* data() may return a pointer to a buffer with embedded NULs, and the
* returned buffer may or may not be null terminated. Therefore it is
* typically a mistake to pass data() to a routine that expects a NUL
* terminated string.
* @return the string pointer
* @draft ICU 4.2
*/
const char* data() const { return ptr_; }
/**
* Returns the string length. Same as length().
* @return the string length
* @draft ICU 4.2
*/
int32_t size() const { return length_; }
/**
* Returns the string length. Same as size().
* @return the string length
* @draft ICU 4.2
*/
int32_t length() const { return length_; }
/**
* Returns whether the string is empty.
* @return TRUE if the string is empty
* @draft ICU 4.2
*/
UBool empty() const { return length_ == 0; }
/**
* Sets to an empty string.
* @draft ICU 4.2
*/
void clear() { ptr_ = NULL; length_ = 0; }
/**
* Removes the first n string units.
* @param n prefix length, must be non-negative and <=length()
* @draft ICU 4.2
*/
void remove_prefix(int32_t n) {
if (n >= 0) {
if (n > length_) {
n = length_;
}
ptr_ += n;
length_ -= n;
}
}
/**
* Removes the last n string units.
* @param n suffix length, must be non-negative and <=length()
* @draft ICU 4.2
*/
void remove_suffix(int32_t n) {
if (n >= 0) {
if (n <= length_) {
length_ -= n;
} else {
length_ = 0;
}
}
}
/**
* Maximum integer, used as a default value for substring methods.
* @draft ICU 4.2
*/
static const int32_t npos = 0x7fffffff;
/**
* Returns a substring of this StringPiece.
* @param pos start position; must be non-negative and <= length().
* @param len length of the substring;
* must be non-negative and will be pinned to at most length() - pos.
* @return the substring StringPiece
* @draft ICU 4.2
*/
StringPiece substr(int32_t pos, int32_t len = npos) const {
return StringPiece(*this, pos, len);
}
};
U_NAMESPACE_END
#endif // __STRINGPIECE_H__
+518
View File
@@ -0,0 +1,518 @@
/*
**********************************************************************
* Copyright (C) 2001-2008 IBM and others. All rights reserved.
**********************************************************************
* Date Name Description
* 03/22/2000 helena Creation.
**********************************************************************
*/
#ifndef STSEARCH_H
#define STSEARCH_H
#include "unicode/utypes.h"
/**
* \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="http://source.icu-project.org/repos/icu/icuhtml/trunk/design/collation/ICU_collation_design.htm">
* "ICU Collation Design Document"</a> for more information.
* <p>
* The algorithm implemented is a modified form of the Boyer Moore's search.
* For more information 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, for further information on the algorithm.
* <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 occurances 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 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>
* 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 StringSearch to the new collator attributes,
* 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,
* StringSearch 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(), NULL, 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.getMatchLength());
* }
* </code></pre>
* <p>
* Note, StringSearch is not to be subclassed.
* </p>
* @see SearchIterator
* @see RuleBasedCollator
* @since ICU 2.0
*/
class U_I18N_API StringSearch : 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>NULL</tt> can be passed in instead.
* @param status for errors if any. If pattern or text is NULL, 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>NULL</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>NULL</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>NULL</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(void);
/**
* Clone this object.
* Clones can be used concurrently in multiple threads.
* If an error occurs, then NULL 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 UBool operator==(const SearchIterator &that) const;
// 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);
/**
* 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(void) const;
/**
* 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);
/**
* 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);
/**
* 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. This method causes internal data such as Boyer-Moore
* shift tables to be recalculated, but the iterator's position is
* unchanged.
* @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.
* Internal data like the Boyer Moore table will be recalculated, but
* the iterator's position is unchanged.
* @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();
/**
* 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 SearchIterator * safeClone(void) const;
/**
* ICU "poor man's RTTI", returns a UClassID for the actual class.
*
* @stable ICU 2.2
*/
virtual UClassID getDynamicClassID() const;
/**
* 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);
/**
* 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);
private :
StringSearch(); // default constructor not implemented
// private data members ----------------------------------------------
/**
* RuleBasedCollator, contains exactly the same UCollator * in m_strsrch_
* @stable ICU 2.0
*/
RuleBasedCollator m_collator_;
/**
* 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
+112
View File
@@ -0,0 +1,112 @@
/*
**********************************************************************
* Copyright (c) 2000-2005, International Business Machines
* Corporation and others. All Rights Reserved.
**********************************************************************
* Date Name Description
* 02/04/00 aliu Creation.
**********************************************************************
*/
#ifndef SYMTABLE_H
#define SYMTABLE_H
#include "unicode/utypes.h"
#include "unicode/uobject.h"
/**
* \file
* \brief C++ API: An interface that defines both lookup protocol and parsing of
* symbolic names.
*/
U_NAMESPACE_BEGIN
class ParsePosition;
class UnicodeFunctor;
class UnicodeSet;
class UnicodeString;
/**
* An interface that defines both lookup protocol and parsing of
* symbolic names.
*
* <p>A symbol table maintains two kinds of mappings. The first is
* between symbolic names and their values. For example, if the
* variable with the name "start" is set to the value "alpha"
* (perhaps, though not necessarily, through an expression such as
* "$start=alpha"), then the call lookup("start") will return the
* char[] array ['a', 'l', 'p', 'h', 'a'].
*
* <p>The second kind of mapping is between character values and
* UnicodeMatcher objects. This is used by RuleBasedTransliterator,
* which uses characters in the private use area to represent objects
* such as UnicodeSets. If U+E015 is mapped to the UnicodeSet [a-z],
* then lookupMatcher(0xE015) will return the UnicodeSet [a-z].
*
* <p>Finally, a symbol table defines parsing behavior for symbolic
* names. All symbolic names start with the SYMBOL_REF character.
* When a parser encounters this character, it calls parseReference()
* with the position immediately following the SYMBOL_REF. The symbol
* table parses the name, if there is one, and returns it.
*
* @stable ICU 2.8
*/
class U_COMMON_API SymbolTable /* not : public UObject because this is an interface/mixin class */ {
public:
/**
* The character preceding a symbol reference name.
* @stable ICU 2.8
*/
enum { SYMBOL_REF = 0x0024 /*$*/ };
/**
* Destructor.
* @stable ICU 2.8
*/
virtual ~SymbolTable();
/**
* Lookup the characters associated with this string and return it.
* Return <tt>NULL</tt> if no such name exists. The resultant
* string may have length zero.
* @param s the symbolic name to lookup
* @return a string containing the name's value, or <tt>NULL</tt> if
* there is no mapping for s.
* @stable ICU 2.8
*/
virtual const UnicodeString* lookup(const UnicodeString& s) const = 0;
/**
* Lookup the UnicodeMatcher associated with the given character, and
* return it. Return <tt>NULL</tt> if not found.
* @param ch a 32-bit code point from 0 to 0x10FFFF inclusive.
* @return the UnicodeMatcher object represented by the given
* character, or NULL if there is no mapping for ch.
* @stable ICU 2.8
*/
virtual const UnicodeFunctor* lookupMatcher(UChar32 ch) const = 0;
/**
* Parse a symbol reference name from the given string, starting
* at the given position. If no valid symbol reference name is
* found, return the empty string and leave pos unchanged. That is, if the
* character at pos cannot start a name, or if pos is at or after
* text.length(), then return an empty string. This indicates an
* isolated SYMBOL_REF character.
* @param text the text to parse for the name
* @param pos on entry, the index of the first character to parse.
* This is the character following the SYMBOL_REF character. On
* exit, the index after the last parsed character. If the parse
* failed, pos is unchanged on exit.
* @param limit the index after the last character to be parsed.
* @return the parsed name, or an empty string if there is no
* valid symbolic name at the given position.
* @stable ICU 2.8
*/
virtual UnicodeString parseReference(const UnicodeString& text,
ParsePosition& pos, int32_t limit) const = 0;
};
U_NAMESPACE_END
#endif
+941
View File
@@ -0,0 +1,941 @@
/*
******************************************************************************
* Copyright (C) 1996-2009, International Business Machines Corporation and
* others. All Rights Reserved.
******************************************************************************
*/
/**
* \file
* \brief C++ API: RuleBasedCollator class provides the simple implementation of Collator.
*/
/**
* 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)
*/
#ifndef TBLCOLL_H
#define TBLCOLL_H
#include "unicode/utypes.h"
#if !UCONFIG_NO_COLLATION
#include "unicode/coll.h"
#include "unicode/ucol.h"
#include "unicode/sortkey.h"
#include "unicode/normlzr.h"
U_NAMESPACE_BEGIN
/**
* @stable ICU 2.0
*/
class StringSearch;
/**
* @stable ICU 2.0
*/
class CollationElementIterator;
/**
* The RuleBasedCollator class provides the simple implementation of
* Collator, using data-driven tables. The user can create a customized
* table-based collation.
* <P>
* <em>Important: </em>The ICU collation service has been reimplemented
* in order to achieve better performance and UCA compliance.
* For details, see the
* <a href="http://source.icu-project.org/repos/icu/icuhtml/trunk/design/collation/ICU_collation_design.htm">
* collation design document</a>.
* <p>
* RuleBasedCollator is a thin C++ wrapper over the C implementation.
* <p>
* For more information about the collation service see
* <a href="http://icu-project.org/userguide/Collate_Intro.html">the users 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/unicode/reports/tr10/">UCA 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="http://icu-project.org/userguide/Collate_Customization.html">
* Collation customization</a> section of the users guide.
* <p>
* Note, RuleBasedCollator is not to be subclassed.
* @see Collator
* @version 2.0 11/15/2001
*/
class U_I18N_API RuleBasedCollator : public Collator
{
public:
// constructor -------------------------------------------------------------
/**
* 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.
* @see Locale
* @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 default strength for comparison
* @param status reporting a success or an error.
* @see Locale
* @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.
* @see Locale
* @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 default strength for comparison
* @param decompositionMode the normalisation mode
* @param status reporting a success or an error.
* @see Locale
* @stable ICU 2.0
*/
RuleBasedCollator(const UnicodeString& rules,
ECollationStrength collationStrength,
UColAttributeValue decompositionMode,
UErrorCode& status);
/**
* Copy constructor.
* @param other the RuleBasedCollator object to be copied
* @see Locale
* @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 usualy should be UCA.
* @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 fallback collator, usually UCA. Base is required to be
* present through the lifetime of the collator. Currently
* it cannot be NULL.
* @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 --------------------------------------------------------------
/**
* Destructor.
* @stable ICU 2.0
*/
virtual ~RuleBasedCollator();
// public methods ----------------------------------------------------------
/**
* Assignment operator.
* @param other other RuleBasedCollator object to compare with.
* @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 UBool operator==(const Collator& other) const;
/**
* Returns true if argument is not the same as this object.
* @param other Collator object to be compared
* @return returns true if argument is not the same as this object.
* @stable ICU 2.0
*/
virtual UBool operator!=(const Collator& other) const;
/**
* Makes a deep copy of the object.
* The caller owns the returned object.
* @return the cloned object.
* @stable ICU 2.0
*/
virtual Collator* clone(void) const;
/**
* 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;
/**
* Compares a range of character data stored in two different strings based
* on the collation rules. Returns information about whether a string is
* less than, greater than or equal to another string in a language.
* This can be overriden in a subclass.
* @param source the source string.
* @param target the target string to be compared with the source string.
* @return the comparison result. GREATER if the source string is greater
* than the target string, LESS if the source is less than the
* target. Otherwise, returns EQUAL.
* @deprecated ICU 2.6 Use overload with UErrorCode&
*/
virtual EComparisonResult compare(const UnicodeString& source,
const UnicodeString& target) const;
/**
* 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;
/**
* Compares a range of character data stored in two different strings based
* on the collation rules up to the specified length. Returns information
* about whether a string is less than, greater than or equal to another
* string in a language. This can be overriden in a subclass.
* @param source the source string.
* @param target the target string to be compared with the source string.
* @param length compares up to the specified length
* @return the comparison result. GREATER if the source string is greater
* than the target string, LESS if the source is less than the
* target. Otherwise, returns EQUAL.
* @deprecated ICU 2.6 Use overload with UErrorCode&
*/
virtual EComparisonResult compare(const UnicodeString& source,
const UnicodeString& target,
int32_t length) const;
/**
* 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;
/**
* 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.
* <p>Example of use:
* <pre>
* . UChar ABC[] = {0x41, 0x42, 0x43, 0}; // = "ABC"
* . UChar abc[] = {0x61, 0x62, 0x63, 0}; // = "abc"
* . UErrorCode status = U_ZERO_ERROR;
* . Collator *myCollation =
* . Collator::createInstance(Locale::US, status);
* . if (U_FAILURE(status)) return;
* . myCollation->setStrength(Collator::PRIMARY);
* . // result would be Collator::EQUAL ("abc" == "ABC")
* . // (no primary difference between "abc" and "ABC")
* . Collator::EComparisonResult result =
* . myCollation->compare(abc, 3, ABC, 3);
* . myCollation->setStrength(Collator::TERTIARY);
* . // result would be Collator::LESS ("abc" &lt;&lt;&lt; "ABC")
* . // (with tertiary difference between "abc" and "ABC")
* . result = myCollation->compare(abc, 3, ABC, 3);
* </pre>
* @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.
* @return Returns a byte value. GREATER if source is greater than target;
* EQUAL if source is equal to target; LESS if source is less than
* target
* @deprecated ICU 2.6 Use overload with UErrorCode&
*/
virtual EComparisonResult compare(const UChar* source, int32_t sourceLength,
const UChar* target, int32_t targetLength)
const;
/**
* 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 UChar* source, int32_t sourceLength,
const UChar* target, int32_t targetLength,
UErrorCode &status) const;
/**
* 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
* @draft ICU 4.2
*/
virtual UCollationResult compare(UCharIterator &sIter,
UCharIterator &tIter,
UErrorCode &status) const;
/**
* Transforms a specified region of the string into a series of characters
* that can be compared with CollationKey.compare. Use a CollationKey when
* you need to do repeated comparisions on the same string. For a single
* comparison the compare method will be faster.
* @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
* @deprecated ICU 2.8 Use getSortKey(...) instead
*/
virtual CollationKey& getCollationKey(const UnicodeString& source,
CollationKey& key,
UErrorCode& status) const;
/**
* Transforms a specified region of the string into a series of characters
* that can be compared with CollationKey.compare. Use a CollationKey when
* you need to do repeated comparisions on the same string. For a single
* comparison the compare method will be faster.
* @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
* @deprecated ICU 2.8 Use getSortKey(...) instead
*/
virtual CollationKey& getCollationKey(const UChar *source,
int32_t sourceLength,
CollationKey& key,
UErrorCode& status) const;
/**
* Generates the hash code for the rule-based collation object.
* @return the hash code.
* @stable ICU 2.0
*/
virtual int32_t hashCode(void) const;
/**
* 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 const Locale getLocale(ULocDataLocaleType type, UErrorCode& status) const;
/**
* Gets the table-based rules for the collation object.
* @return returns the collation rules that the table collation object was
* created from.
* @stable ICU 2.0
*/
const UnicodeString& getRules(void) 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;
/**
* 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
* @see CollationElementIterator#getMaxExpansion
* @stable ICU 2.0
*/
int32_t getMaxExpansion(int32_t order) const;
/**
* 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(void) const;
/**
* 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(void);
/**
* Returns the binary format of the class's rules. The format is that of
* .col files.
* @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.
* @stable ICU 2.2
*/
uint8_t *cloneRuleData(int32_t &length, UErrorCode &status);
/** 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);
/**
* Returns current rules. Delta defines whether full rules are returned or
* just the tailoring.
* @param delta one of UCOL_TAILORING_ONLY, UCOL_FULL_RULES.
* @param buffer UnicodeString to store the result rules
* @stable ICU 2.2
*/
void getRules(UColRuleOption delta, UnicodeString &buffer);
/**
* 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);
/**
* 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);
/**
* Sets the variable top to a collation element value of a string supplied.
* @param varTop one or more (if contraction) UChars 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 a contraction<br>
* U_PRIMARY_TOO_LONG_ERROR if the primary for the variable top has more than two bytes
* @return a 32 bit value containing the value of the variable top in upper 16 bits. Lower 16 bits are undefined
* @stable ICU 2.0
*/
virtual uint32_t setVariableTop(const UChar *varTop, int32_t len, UErrorCode &status);
/**
* Sets the variable top to a collation element value of a string supplied.
* @param varTop an UnicodeString size 1 or more (if contraction) of UChars 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 a contraction<br>
* U_PRIMARY_TOO_LONG_ERROR if the primary for the variable top has more than two bytes
* @return a 32 bit value containing the value of the variable top in upper 16 bits. Lower 16 bits are undefined
* @stable ICU 2.0
*/
virtual uint32_t setVariableTop(const UnicodeString varTop, UErrorCode &status);
/**
* Sets the variable top to a collation element value supplied. Variable top is set to the upper 16 bits.
* Lower 16 bits are ignored.
* @param varTop CE value, as returned by setVariableTop or ucol)getVariableTop
* @param status error code (not changed by function)
* @stable ICU 2.0
*/
virtual void setVariableTop(const uint32_t varTop, UErrorCode &status);
/**
* Gets the variable top value of a Collator.
* Lower 16 bits are undefined and should be ignored.
* @param status error code (not changed by function). If error code is set, the return value is undefined.
* @stable ICU 2.0
*/
virtual uint32_t getVariableTop(UErrorCode &status) const;
/**
* Get an 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 UCA. The object must be disposed of by using delete
* @stable ICU 2.4
*/
virtual UnicodeSet *getTailoredSet(UErrorCode &status) const;
/**
* Thread safe cloning operation.
* @return pointer to the new clone, user should remove it.
* @stable ICU 2.2
*/
virtual Collator* safeClone(void);
/**
* Get the sort key as an array of bytes from an UnicodeString.
* @param source string to be processed.
* @param result buffer to store result in. If NULL, 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;
/**
* Get the sort key as an array of bytes from an UChar buffer.
* @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 NULL, 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 UChar *source, int32_t sourceLength,
uint8_t *result, int32_t resultLength) const;
/**
* Determines the minimum strength that will be use in comparison or
* transformation.
* <p>E.g. with strength == SECONDARY, the tertiary difference is ignored
* <p>E.g. with strength == PRIMARY, the secondary and tertiary difference
* are ignored.
* @return the current comparison level.
* @see RuleBasedCollator#setStrength
* @deprecated ICU 2.6 Use getAttribute(UCOL_STRENGTH...) instead
*/
virtual ECollationStrength getStrength(void) const;
/**
* Sets the minimum strength to be used in comparison or transformation.
* @see RuleBasedCollator#getStrength
* @param newStrength the new comparison level.
* @deprecated ICU 2.6 Use setAttribute(UCOL_STRENGTH...) instead
*/
virtual void setStrength(ECollationStrength newStrength);
private:
// private static constants -----------------------------------------------
enum {
/* need look up in .commit() */
CHARINDEX = 0x70000000,
/* Expand index follows */
EXPANDCHARINDEX = 0x7E000000,
/* contract indexes follows */
CONTRACTCHARINDEX = 0x7F000000,
/* unmapped character values */
UNMAPPED = 0xFFFFFFFF,
/* primary strength increment */
PRIMARYORDERINCREMENT = 0x00010000,
/* secondary strength increment */
SECONDARYORDERINCREMENT = 0x00000100,
/* tertiary strength increment */
TERTIARYORDERINCREMENT = 0x00000001,
/* mask off anything but primary order */
PRIMARYORDERMASK = 0xffff0000,
/* mask off anything but secondary order */
SECONDARYORDERMASK = 0x0000ff00,
/* mask off anything but tertiary order */
TERTIARYORDERMASK = 0x000000ff,
/* mask off ignorable char order */
IGNORABLEMASK = 0x0000ffff,
/* use only the primary difference */
PRIMARYDIFFERENCEONLY = 0xffff0000,
/* use only the primary and secondary difference */
SECONDARYDIFFERENCEONLY = 0xffffff00,
/* primary order shift */
PRIMARYORDERSHIFT = 16,
/* secondary order shift */
SECONDARYORDERSHIFT = 8,
/* starting value for collation elements */
COLELEMENTSTART = 0x02020202,
/* testing mask for primary low element */
PRIMARYLOWZEROMASK = 0x00FF0000,
/* reseting value for secondaries and tertiaries */
RESETSECONDARYTERTIARY = 0x00000202,
/* reseting value for tertiaries */
RESETTERTIARY = 0x00000002,
PRIMIGNORABLE = 0x0202
};
// private data members ---------------------------------------------------
UBool dataIsOwned;
UBool isWriteThroughAlias;
/**
* c struct for collation. All initialisation for it has to be done through
* setUCollator().
*/
UCollator *ucollator;
/**
* Rule UnicodeString
*/
UnicodeString urulestring;
// friend classes --------------------------------------------------------
/**
* Used to iterate over collation elements in a character source.
*/
friend class CollationElementIterator;
/**
* Collator ONLY needs access to RuleBasedCollator(const Locale&,
* UErrorCode&)
*/
friend class Collator;
/**
* Searching over collation elements in a character source
*/
friend class StringSearch;
// private constructors --------------------------------------------------
/**
* Default constructor
*/
RuleBasedCollator();
/**
* RuleBasedCollator constructor. This constructor takes a locale. The
* only caller of this class should be Collator::createInstance(). If
* createInstance() happens to know that the requested locale's collation is
* implemented as a RuleBasedCollator, it can then call this constructor.
* OTHERWISE IT SHOULDN'T, since this constructor ALWAYS RETURNS A VALID
* COLLATION TABLE. It does this by falling back to defaults.
* @param desiredLocale locale used
* @param status error code status
*/
RuleBasedCollator(const Locale& desiredLocale, UErrorCode& status);
/**
* common constructor implementation
*
* @param rules the collation rules to build the collation table from.
* @param collationStrength default strength for comparison
* @param decompositionMode the normalisation mode
* @param status reporting a success or an error.
*/
void
construct(const UnicodeString& rules,
UColAttributeValue collationStrength,
UColAttributeValue decompositionMode,
UErrorCode& status);
// private methods -------------------------------------------------------
/**
* Creates the c struct for ucollator
* @param locale desired locale
* @param status error status
*/
void setUCollator(const Locale& locale, UErrorCode& status);
/**
* Creates the c struct for ucollator
* @param locale desired locale name
* @param status error status
*/
void setUCollator(const char* locale, UErrorCode& status);
/**
* Creates the c struct for ucollator. This used internally by StringSearch.
* Hence the responsibility of cleaning up the ucollator is not done by
* this RuleBasedCollator. The isDataOwned flag is set to FALSE.
* @param collator new ucollator data
* @param rules corresponding collation rules
*/
void setUCollator(UCollator *collator);
public:
/**
* Get UCollator data struct. Used only by StringSearch & intltest.
* @return UCollator data struct
* @internal
*/
const UCollator * getUCollator();
protected:
/**
* Used internally by registraton to define the requested and valid locales.
* @param requestedLocale the requsted locale
* @param validLocale the valid locale
* @param actualLocale the actual locale
* @internal
*/
virtual void setLocales(const Locale& requestedLocale, const Locale& validLocale, const Locale& actualLocale);
private:
// if not owned and not a write through alias, copy the ucollator
void checkOwned(void);
// utility to init rule string used by checkOwned and construct
void setRuleStringFromCollator();
/**
* Converts C's UCollationResult to EComparisonResult
* @param result member of the enum UComparisonResult
* @return EComparisonResult equivalent of UCollationResult
* @deprecated ICU 2.6. We will not need it.
*/
Collator::EComparisonResult getEComparisonResult(
const UCollationResult &result) const;
/**
* Converts C's UCollationStrength to ECollationStrength
* @param strength member of the enum UCollationStrength
* @return ECollationStrength equivalent of UCollationStrength
*/
Collator::ECollationStrength getECollationStrength(
const UCollationStrength &strength) const;
/**
* Converts C++'s ECollationStrength to UCollationStrength
* @param strength member of the enum ECollationStrength
* @return UCollationStrength equivalent of ECollationStrength
*/
UCollationStrength getUCollationStrength(
const Collator::ECollationStrength &strength) const;
};
// inline method implementation ---------------------------------------------
inline void RuleBasedCollator::setUCollator(const Locale &locale,
UErrorCode &status)
{
setUCollator(locale.getName(), status);
}
inline void RuleBasedCollator::setUCollator(UCollator *collator)
{
if (ucollator && dataIsOwned) {
ucol_close(ucollator);
}
ucollator = collator;
dataIsOwned = FALSE;
isWriteThroughAlias = TRUE;
setRuleStringFromCollator();
}
inline const UCollator * RuleBasedCollator::getUCollator()
{
return ucollator;
}
inline Collator::EComparisonResult RuleBasedCollator::getEComparisonResult(
const UCollationResult &result) const
{
switch (result)
{
case UCOL_LESS :
return Collator::LESS;
case UCOL_EQUAL :
return Collator::EQUAL;
default :
return Collator::GREATER;
}
}
inline Collator::ECollationStrength RuleBasedCollator::getECollationStrength(
const UCollationStrength &strength) const
{
switch (strength)
{
case UCOL_PRIMARY :
return Collator::PRIMARY;
case UCOL_SECONDARY :
return Collator::SECONDARY;
case UCOL_TERTIARY :
return Collator::TERTIARY;
case UCOL_QUATERNARY :
return Collator::QUATERNARY;
default :
return Collator::IDENTICAL;
}
}
inline UCollationStrength RuleBasedCollator::getUCollationStrength(
const Collator::ECollationStrength &strength) const
{
switch (strength)
{
case Collator::PRIMARY :
return UCOL_PRIMARY;
case Collator::SECONDARY :
return UCOL_SECONDARY;
case Collator::TERTIARY :
return UCOL_TERTIARY;
case Collator::QUATERNARY :
return UCOL_QUATERNARY;
default :
return UCOL_IDENTICAL;
}
}
U_NAMESPACE_END
#endif /* #if !UCONFIG_NO_COLLATION */
#endif
+802
View File
@@ -0,0 +1,802 @@
/*************************************************************************
* Copyright (c) 1997-2009, International Business Machines Corporation
* and others. All Rights Reserved.
**************************************************************************
*
* File TIMEZONE.H
*
* Modification History:
*
* Date Name Description
* 04/21/97 aliu Overhauled header.
* 07/09/97 helena Changed createInstance to createDefault.
* 08/06/97 aliu Removed dependency on internal header for Hashtable.
* 08/10/98 stephen Changed getDisplayName() API conventions to match
* 08/19/98 stephen Changed createTimeZone() to never return 0
* 09/02/98 stephen Sync to JDK 1.2 8/31
* - Added getOffset(... monthlen ...)
* - Added hasSameRules()
* 09/15/98 stephen Added getStaticClassID
* 12/03/99 aliu Moved data out of static table into icudata.dll.
* Hashtable replaced by new static data structures.
* 12/14/99 aliu Made GMT public.
* 08/15/01 grhoten Made GMT private and added the getGMT() function
**************************************************************************
*/
#ifndef TIMEZONE_H
#define TIMEZONE_H
#include "unicode/utypes.h"
/**
* \file
* \brief C++ API: TimeZone object
*/
#if !UCONFIG_NO_FORMATTING
#include "unicode/uobject.h"
#include "unicode/unistr.h"
#include "unicode/ures.h"
U_NAMESPACE_BEGIN
class StringEnumeration;
/**
*
* <code>TimeZone</code> represents a time zone offset, and also figures out daylight
* savings.
*
* <p>
* Typically, you get a <code>TimeZone</code> using <code>createDefault</code>
* which creates a <code>TimeZone</code> based on the time zone where the program
* is running. For example, for a program running in Japan, <code>createDefault</code>
* creates a <code>TimeZone</code> object based on Japanese Standard Time.
*
* <p>
* You can also get a <code>TimeZone</code> using <code>createTimeZone</code> along
* with a time zone ID. For instance, the time zone ID for the US Pacific
* Time zone is "America/Los_Angeles". So, you can get a Pacific Time <code>TimeZone</code> object
* with:
* \htmlonly<blockquote>\endhtmlonly
* <pre>
* TimeZone *tz = TimeZone::createTimeZone("America/Los_Angeles");
* </pre>
* \htmlonly</blockquote>\endhtmlonly
* You can use <code>getAvailableIDs</code> method to iterate through
* all the supported time zone IDs. You can then choose a
* supported ID to get a <code>TimeZone</code>.
* If the time zone you want is not represented by one of the
* supported IDs, then you can create a custom time zone ID with
* the following syntax:
*
* \htmlonly<blockquote>\endhtmlonly
* <pre>
* GMT[+|-]hh[[:]mm]
* </pre>
* \htmlonly</blockquote>\endhtmlonly
*
* For example, you might specify GMT+14:00 as a custom
* time zone ID. The <code>TimeZone</code> that is returned
* when you specify a custom time zone ID does not include
* daylight savings time.
*
* TimeZone is an abstract class representing a time zone. A TimeZone is needed for
* Calendar to produce local time for a particular time zone. A TimeZone comprises
* three basic pieces of information:
* <ul>
* <li>A time zone offset; that, is the number of milliseconds to add or subtract
* from a time expressed in terms of GMT to convert it to the same time in that
* time zone (without taking daylight savings time into account).</li>
* <li>Logic necessary to take daylight savings time into account if daylight savings
* time is observed in that time zone (e.g., the days and hours on which daylight
* savings time begins and ends).</li>
* <li>An ID. This is a text string that uniquely identifies the time zone.</li>
* </ul>
*
* (Only the ID is actually implemented in TimeZone; subclasses of TimeZone may handle
* daylight savings time and GMT offset in different ways. Currently we only have one
* TimeZone subclass: SimpleTimeZone.)
* <P>
* The TimeZone class contains a static list containing a TimeZone object for every
* combination of GMT offset and daylight-savings time rules currently in use in the
* world, each with a unique ID. Each ID consists of a region (usually a continent or
* ocean) and a city in that region, separated by a slash, (for example, US Pacific
* Time is "America/Los_Angeles.") Because older versions of this class used
* three- or four-letter abbreviations instead, there is also a table that maps the older
* abbreviations to the newer ones (for example, "PST" maps to "America/Los_Angeles").
* Anywhere the API requires an ID, you can use either form.
* <P>
* To create a new TimeZone, you call the factory function TimeZone::createTimeZone()
* and pass it a time zone ID. You can use the createEnumeration() function to
* obtain a list of all the time zone IDs recognized by createTimeZone().
* <P>
* You can also use TimeZone::createDefault() to create a TimeZone. This function uses
* platform-specific APIs to produce a TimeZone for the time zone corresponding to
* the client's computer's physical location. For example, if you're in Japan (assuming
* your machine is set up correctly), TimeZone::createDefault() will return a TimeZone
* for Japanese Standard Time ("Asia/Tokyo").
*/
class U_I18N_API TimeZone : public UObject {
public:
/**
* @stable ICU 2.0
*/
virtual ~TimeZone();
/**
* The GMT time zone has a raw offset of zero and does not use daylight
* savings time. This is a commonly used time zone.
* @return the GMT time zone.
* @stable ICU 2.0
*/
static const TimeZone* U_EXPORT2 getGMT(void);
/**
* Creates a <code>TimeZone</code> for the given ID.
* @param ID the ID for a <code>TimeZone</code>, such as "America/Los_Angeles",
* or a custom ID such as "GMT-8:00".
* @return the specified <code>TimeZone</code>, or the GMT zone if the given ID
* cannot be understood. Return result guaranteed to be non-null. If you
* require that the specific zone asked for be returned, check the ID of the
* return result.
* @stable ICU 2.0
*/
static TimeZone* U_EXPORT2 createTimeZone(const UnicodeString& ID);
/**
* Returns an enumeration over all recognized time zone IDs. (i.e.,
* all strings that createTimeZone() accepts)
*
* @return an enumeration object, owned by the caller.
* @stable ICU 2.4
*/
static StringEnumeration* U_EXPORT2 createEnumeration();
/**
* Returns an enumeration over time zone IDs with a given raw
* offset from GMT. There may be several times zones with the
* same GMT offset that differ in the way they handle daylight
* savings time. For example, the state of Arizona doesn't
* observe daylight savings time. If you ask for the time zone
* IDs corresponding to GMT-7:00, you'll get back an enumeration
* over two time zone IDs: "America/Denver," which corresponds to
* Mountain Standard Time in the winter and Mountain Daylight Time
* in the summer, and "America/Phoenix", which corresponds to
* Mountain Standard Time year-round, even in the summer.
*
* @param rawOffset an offset from GMT in milliseconds, ignoring
* the effect of daylight savings time, if any
* @return an enumeration object, owned by the caller
* @stable ICU 2.4
*/
static StringEnumeration* U_EXPORT2 createEnumeration(int32_t rawOffset);
/**
* Returns an enumeration over time zone IDs associated with the
* given country. Some zones are affiliated with no country
* (e.g., "UTC"); these may also be retrieved, as a group.
*
* @param country The ISO 3166 two-letter country code, or NULL to
* retrieve zones not affiliated with any country.
* @return an enumeration object, owned by the caller
* @stable ICU 2.4
*/
static StringEnumeration* U_EXPORT2 createEnumeration(const char* country);
#ifdef U_USE_TIMEZONE_OBSOLETE_2_8
/**
* Returns a list of time zone IDs, one for each time zone with a given GMT offset.
* The return value is a list because there may be several times zones with the same
* GMT offset that differ in the way they handle daylight savings time. For example,
* the state of Arizona doesn't observe Daylight Savings time. So if you ask for
* the time zone IDs corresponding to GMT-7:00, you'll get back two time zone IDs:
* "America/Denver," which corresponds to Mountain Standard Time in the winter and
* Mountain Daylight Time in the summer, and "America/Phoenix", which corresponds to
* Mountain Standard Time year-round, even in the summer.
* <P>
* The caller owns the list that is returned, but does not own the strings contained
* in that list. Delete the array with uprv_free(), but DON'T delete the elements in the array.
*
* <p>NOTE: uprv_free() is declared in the private header source/common/cmemory.h.
*
* @param rawOffset An offset from GMT in milliseconds.
* @param numIDs Receives the number of items in the array that is returned.
* @return An array of UnicodeString pointers, where each UnicodeString is
* a time zone ID for a time zone with the given GMT offset. If
* there is no time zone that matches the GMT offset
* specified, NULL is returned.
* @obsolete ICU 2.8. Use createEnumeration(int32_t) instead since this API will be removed in that release.
*/
static const UnicodeString** createAvailableIDs(int32_t rawOffset, int32_t& numIDs);
/**
* Returns a list of time zone IDs associated with the given
* country. Some zones are affiliated with no country (e.g.,
* "UTC"); these may also be retrieved, as a group.
*
* <P>The caller owns the list that is returned, but does not own
* the strings contained in that list. Delete the array with uprv_free(), but
* <b>DON'T</b> delete the elements in the array.
*
* <p>NOTE: uprv_free() is declared in the private header source/common/cmemory.h.
*
* @param country The ISO 3166 two-letter country code, or NULL to
* retrieve zones not affiliated with any country.
* @param numIDs Receives the number of items in the array that is
* returned.
* @return An array of UnicodeString pointers, where each
* UnicodeString is a time zone ID for a time zone with the given
* country. If there is no time zone that matches the country
* specified, NULL is returned.
* @obsolete ICU 2.8. Use createEnumeration(const char*) instead since this API will be removed in that release.
*/
static const UnicodeString** createAvailableIDs(const char* country,
int32_t& numIDs);
/**
* Returns a list of all time zone IDs supported by the TimeZone class (i.e., all
* IDs that it's legal to pass to createTimeZone()). The caller owns the list that
* is returned, but does not own the strings contained in that list. Delete the array with uprv_free(),
* but DON'T delete the elements in the array.
*
* <p>NOTE: uprv_free() is declared in the private header source/common/cmemory.h.
*
* @param numIDs Receives the number of zone IDs returned.
* @return An array of UnicodeString pointers, where each is a time zone ID
* supported by the TimeZone class.
* @obsolete ICU 2.8. Use createEnumeration(void) instead since this API will be removed in that release.
*/
static const UnicodeString** createAvailableIDs(int32_t& numIDs);
#endif
/**
* Returns the number of IDs in the equivalency group that
* includes the given ID. An equivalency group contains zones
* that have the same GMT offset and rules.
*
* <p>The returned count includes the given ID; it is always >= 1.
* The given ID must be a system time zone. If it is not, returns
* zero.
* @param id a system time zone ID
* @return the number of zones in the equivalency group containing
* 'id', or zero if 'id' is not a valid system ID
* @see #getEquivalentID
* @stable ICU 2.0
*/
static int32_t U_EXPORT2 countEquivalentIDs(const UnicodeString& id);
/**
* Returns an ID in the equivalency group that
* includes the given ID. An equivalency group contains zones
* that have the same GMT offset and rules.
*
* <p>The given index must be in the range 0..n-1, where n is the
* value returned by <code>countEquivalentIDs(id)</code>. For
* some value of 'index', the returned value will be equal to the
* given id. If the given id is not a valid system time zone, or
* if 'index' is out of range, then returns an empty string.
* @param id a system time zone ID
* @param index a value from 0 to n-1, where n is the value
* returned by <code>countEquivalentIDs(id)</code>
* @return the ID of the index-th zone in the equivalency group
* containing 'id', or an empty string if 'id' is not a valid
* system ID or 'index' is out of range
* @see #countEquivalentIDs
* @stable ICU 2.0
*/
static const UnicodeString U_EXPORT2 getEquivalentID(const UnicodeString& id,
int32_t index);
/**
* Creates a new copy of the default TimeZone for this host. Unless the default time
* zone has already been set using adoptDefault() or setDefault(), the default is
* determined by querying the system using methods in TPlatformUtilities. If the
* system routines fail, or if they specify a TimeZone or TimeZone offset which is not
* recognized, the TimeZone indicated by the ID kLastResortID is instantiated
* and made the default.
*
* @return A default TimeZone. Clients are responsible for deleting the time zone
* object returned.
* @stable ICU 2.0
*/
static TimeZone* U_EXPORT2 createDefault(void);
/**
* Sets the default time zone (i.e., what's returned by createDefault()) to be the
* specified time zone. If NULL is specified for the time zone, the default time
* zone is set to the default host time zone. This call adopts the TimeZone object
* passed in; the clent is no longer responsible for deleting it.
*
* @param zone A pointer to the new TimeZone object to use as the default.
* @stable ICU 2.0
*/
static void U_EXPORT2 adoptDefault(TimeZone* zone);
/**
* Same as adoptDefault(), except that the TimeZone object passed in is NOT adopted;
* the caller remains responsible for deleting it.
*
* @param zone The given timezone.
* @system
*/
static void U_EXPORT2 setDefault(const TimeZone& zone);
/**
* Returns the timezone data version currently used by ICU.
* @param status Output param to filled in with a success or an error.
* @return the version string, such as "2007f"
* @stable ICU 3.8
*/
static const char* U_EXPORT2 getTZDataVersion(UErrorCode& status);
/**
* Returns the canonical system timezone ID or the normalized
* custom time zone ID for the given time zone ID.
* @param id The input time zone ID to be canonicalized.
* @param canonicalID Receives the canonical system time zone ID
* or the custom time zone ID in normalized format.
* @param status Recevies the status. When the given time zone ID
* is neither a known system time zone ID nor a
* valid custom time zone ID, U_ILLEGAL_ARGUMENT_ERROR
* is set.
* @return A reference to the result.
* @stable ICU 4.0
*/
static UnicodeString& U_EXPORT2 getCanonicalID(const UnicodeString& id,
UnicodeString& canonicalID, UErrorCode& status);
/**
* Returns the canonical system time zone ID or the normalized
* custom time zone ID for the given time zone ID.
* @param id The input time zone ID to be canonicalized.
* @param canonicalID Receives the canonical system time zone ID
* or the custom time zone ID in normalized format.
* @param isSystemID Receives if the given ID is a known system
* time zone ID.
* @param status Recevies the status. When the given time zone ID
* is neither a known system time zone ID nor a
* valid custom time zone ID, U_ILLEGAL_ARGUMENT_ERROR
* is set.
* @return A reference to the result.
* @stable ICU 4.0
*/
static UnicodeString& U_EXPORT2 getCanonicalID(const UnicodeString& id,
UnicodeString& canonicalID, UBool& isSystemID, UErrorCode& status);
/**
* Returns true if the two TimeZones are equal. (The TimeZone version only compares
* IDs, but subclasses are expected to also compare the fields they add.)
*
* @param that The TimeZone object to be compared with.
* @return True if the given TimeZone is equal to this TimeZone; false
* otherwise.
* @stable ICU 2.0
*/
virtual UBool operator==(const TimeZone& that) const;
/**
* Returns true if the two TimeZones are NOT equal; that is, if operator==() returns
* false.
*
* @param that The TimeZone object to be compared with.
* @return True if the given TimeZone is not equal to this TimeZone; false
* otherwise.
* @stable ICU 2.0
*/
UBool operator!=(const TimeZone& that) const {return !operator==(that);}
/**
* 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 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 = 0;
/**
* 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 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 Output param to filled in with a success or an error.
* @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 = 0;
/**
* 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 2.8
*/
virtual void getOffset(UDate date, UBool local, int32_t& rawOffset,
int32_t& dstOffset, UErrorCode& ec) const;
/**
* 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) = 0;
/**
* 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(void) const = 0;
/**
* Fills in "ID" with the TimeZone's ID.
*
* @param ID Receives this TimeZone's ID.
* @return A reference to 'ID'
* @stable ICU 2.0
*/
UnicodeString& getID(UnicodeString& ID) const;
/**
* Sets the TimeZone's ID to the specified value. This doesn't affect any other
* fields (for example, if you say<
* blockquote><pre>
* . TimeZone* foo = TimeZone::createTimeZone("America/New_York");
* . foo.setID("America/Los_Angeles");
* </pre>\htmlonly</blockquote>\endhtmlonly
* the time zone's GMT offset and daylight-savings rules don't change to those for
* Los Angeles. They're still those for New York. Only the ID has changed.)
*
* @param ID The new time zone ID.
* @stable ICU 2.0
*/
void setID(const UnicodeString& ID);
/**
* Enum for use with getDisplayName
* @stable ICU 2.4
*/
enum EDisplayType {
/**
* Selector for short display name
* @stable ICU 2.4
*/
SHORT = 1,
/**
* Selector for long display name
* @stable ICU 2.4
*/
LONG
};
/**
* Returns a name of this time zone suitable for presentation to the user
* in the default locale.
* This method returns the long name, not including daylight savings.
* If the display name is not available for the locale,
* then this method returns a string in the format
* <code>GMT[+-]hh:mm</code>.
* @param result the human-readable name of this time zone in the default locale.
* @return A reference to 'result'.
* @stable ICU 2.0
*/
UnicodeString& getDisplayName(UnicodeString& result) const;
/**
* Returns a name of this time zone suitable for presentation to the user
* in the specified locale.
* This method returns the long name, not including daylight savings.
* If the display name is not available for the locale,
* then this method returns a string in the format
* <code>GMT[+-]hh:mm</code>.
* @param locale the locale in which to supply the display name.
* @param result the human-readable name of this time zone in the given locale
* or in the default locale if the given locale is not recognized.
* @return A reference to 'result'.
* @stable ICU 2.0
*/
UnicodeString& getDisplayName(const Locale& locale, UnicodeString& result) const;
/**
* Returns a name of this time zone suitable for presentation to the user
* in the default locale.
* If the display name is not available for the locale,
* then this method returns a string in the format
* <code>GMT[+-]hh:mm</code>.
* @param daylight if true, return the daylight savings name.
* @param style either <code>LONG</code> or <code>SHORT</code>
* @param result the human-readable name of this time zone in the default locale.
* @return A reference to 'result'.
* @stable ICU 2.0
*/
UnicodeString& getDisplayName(UBool daylight, EDisplayType style, UnicodeString& result) const;
/**
* Returns a name of this time zone suitable for presentation to the user
* in the specified locale.
* If the display name is not available for the locale,
* then this method returns a string in the format
* <code>GMT[+-]hh:mm</code>.
* @param daylight if true, return the daylight savings name.
* @param style either <code>LONG</code> or <code>SHORT</code>
* @param locale the locale in which to supply the display name.
* @param result the human-readable name of this time zone in the given locale
* or in the default locale if the given locale is not recognized.
* @return A refence to 'result'.
* @stable ICU 2.0
*/
UnicodeString& getDisplayName(UBool daylight, EDisplayType style, const Locale& locale, UnicodeString& result) const;
/**
* Queries if this time zone uses daylight savings time.
* @return true if this time zone uses daylight savings time,
* false, otherwise.
* @stable ICU 2.0
*/
virtual UBool useDaylightTime(void) const = 0;
/**
* 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 = 0;
/**
* 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 2.0
*/
virtual UBool hasSameRules(const TimeZone& other) const;
/**
* 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 TimeZone* clone(void) const = 0;
/**
* Return the class ID for this class. This is useful only for
* comparing to a return value from getDynamicClassID().
* @return The class ID for all objects of this class.
* @stable ICU 2.0
*/
static UClassID U_EXPORT2 getStaticClassID(void);
/**
* Returns a unique class ID POLYMORPHICALLY. 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.
* <P>
* Concrete subclasses of TimeZone must use the UOBJECT_DEFINE_RTTI_IMPLEMENTATION
* macro from uobject.h in their implementation to provide correct RTTI information.
* @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(void) const = 0;
/**
* Returns the amount of time to be added to local standard time
* to get local wall clock time.
* <p>
* The default implementation always returns 3600000 milliseconds
* (i.e., one hour) if this time zone observes Daylight Saving
* Time. Otherwise, 0 (zero) is returned.
* <p>
* If an underlying TimeZone implementation subclass supports
* historical Daylight Saving Time changes, this method returns
* the known latest daylight saving value.
*
* @return the amount of saving time in milliseconds
* @stable ICU 3.6
*/
virtual int32_t getDSTSavings() const;
protected:
/**
* Default constructor. ID is initialized to the empty string.
* @stable ICU 2.0
*/
TimeZone();
/**
* Construct a TimeZone with a given ID.
* @param id a system time zone ID
* @stable ICU 2.0
*/
TimeZone(const UnicodeString &id);
/**
* Copy constructor.
* @param source the object to be copied.
* @stable ICU 2.0
*/
TimeZone(const TimeZone& source);
/**
* Default assignment operator.
* @param right the object to be copied.
* @stable ICU 2.0
*/
TimeZone& operator=(const TimeZone& right);
/**
* Utility function. For internally loading rule data.
* @param top Top resource bundle for tz data
* @param ruleid ID of rule to load
* @param oldbundle Old bundle to reuse or NULL
* @param status Status parameter
* @return either a new bundle or *oldbundle
* @internal
*/
static UResourceBundle* loadRule(const UResourceBundle* top, const UnicodeString& ruleid, UResourceBundle* oldbundle, UErrorCode&status);
private:
friend class ZoneMeta;
static TimeZone* createCustomTimeZone(const UnicodeString&); // Creates a time zone based on the string.
/**
* Resolve a link in Olson tzdata. When the given id is known and it's not a link,
* the id itself is returned. When the given id is known and it is a link, then
* dereferenced zone id is returned. When the given id is unknown, then it returns
* empty string.
* @param linkTo Input zone id string
* @param linkFrom Receives the dereferenced zone id string
* @return The reference to the result (linkFrom)
*/
static UnicodeString& dereferOlsonLink(const UnicodeString& linkTo, UnicodeString& linkFrom);
/**
* Parses the given custom time zone identifier
* @param id id A string of the form GMT[+-]hh:mm, GMT[+-]hhmm, or
* GMT[+-]hh.
* @param sign Receves parsed sign, 1 for positive, -1 for negative.
* @param hour Receives parsed hour field
* @param minute Receives parsed minute field
* @param second Receives parsed second field
* @return Returns TRUE when the given custom id is valid.
*/
static UBool parseCustomID(const UnicodeString& id, int32_t& sign, int32_t& hour,
int32_t& min, int32_t& sec);
/**
* Parse a custom time zone identifier and return the normalized
* custom time zone identifier for the given custom id string.
* @param id a string of the form GMT[+-]hh:mm, GMT[+-]hhmm, or
* GMT[+-]hh.
* @param normalized Receives the normalized custom ID
* @param status Receives the status. When the input ID string is invalid,
* U_ILLEGAL_ARGUMENT_ERROR is set.
* @return The normalized custom id string.
*/
static UnicodeString& getCustomID(const UnicodeString& id, UnicodeString& normalized,
UErrorCode& status);
/**
* Returns the normalized custome time zone ID for the given offset fields.
* @param hour offset hours
* @param min offset minutes
* @param sec offset seconds
* @param netative sign of the offset, TRUE for negative offset.
* @param id Receves the format result (normalized custom ID)
* @return The reference to id
*/
static UnicodeString& formatCustomID(int32_t hour, int32_t min, int32_t sec,
UBool negative, UnicodeString& id);
/**
* Responsible for setting up DEFAULT_ZONE. Uses routines in TPlatformUtilities
* (i.e., platform-specific calls) to get the current system time zone. Failing
* that, uses the platform-specific default time zone. Failing that, uses GMT.
*/
static void initDefault(void);
// See source file for documentation
/**
* Lookup the given name in our system zone table. If found,
* instantiate a new zone of that name and return it. If not
* found, return 0.
* @param name tthe given name of a system time zone.
* @return the TimeZone indicated by the 'name'.
*/
static TimeZone* createSystemTimeZone(const UnicodeString& name);
UnicodeString fID; // this time zone's ID
};
// -------------------------------------
inline UnicodeString&
TimeZone::getID(UnicodeString& ID) const
{
ID = fID;
return ID;
}
// -------------------------------------
inline void
TimeZone::setID(const UnicodeString& ID)
{
fID = ID;
}
U_NAMESPACE_END
#endif /* #if !UCONFIG_NO_FORMATTING */
#endif //_TIMEZONE
//eof
+149
View File
@@ -0,0 +1,149 @@
/*
*******************************************************************************
* Copyright (C) 2009, Google, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
*/
#ifndef __TMUNIT_H__
#define __TMUNIT_H__
/**
* \file
* \brief C++ API: time unit object
*/
#include "unicode/measunit.h"
#if !UCONFIG_NO_FORMATTING
U_NAMESPACE_BEGIN
/**
* Measurement unit for time units.
* @see TimeUnitAmount
* @see TimeUnit
* @draft ICU 4.2
*/
class U_I18N_API TimeUnit: public MeasureUnit {
public:
/**
* Constants for all the time units we supported.
* @draft ICU 4.2
*/
enum UTimeUnitFields {
UTIMEUNIT_YEAR,
UTIMEUNIT_MONTH,
UTIMEUNIT_DAY,
UTIMEUNIT_WEEK,
UTIMEUNIT_HOUR,
UTIMEUNIT_MINUTE,
UTIMEUNIT_SECOND,
UTIMEUNIT_FIELD_COUNT
};
/**
* 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
* @draft ICU 4.2
*/
static TimeUnit* U_EXPORT2 createInstance(UTimeUnitFields timeUnitField,
UErrorCode& status);
/**
* Override clone.
* @draft ICU 4.2
*/
virtual UObject* clone() const;
/**
* Copy operator.
* @draft ICU 4.2
*/
TimeUnit(const TimeUnit& other);
/**
* Assignment operator.
* @draft ICU 4.2
*/
TimeUnit& operator=(const TimeUnit& other);
/**
* Equality operator.
* @return true if 2 objects are the same.
* @draft ICU 4.2
*/
virtual UBool operator==(const UObject& other) const;
/**
* Non-Equality operator.
* @return true if 2 objects are not the same.
* @draft ICU 4.2
*/
UBool operator!=(const UObject& other) const;
/**
* 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.
* @draft ICU 4.2
*/
virtual UClassID getDynamicClassID() const;
/**
* 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.
* @draft ICU 4.2
*/
static UClassID U_EXPORT2 getStaticClassID();
/**
* Get time unit field.
* @return time unit field.
* @draft ICU 4.2
*/
UTimeUnitFields getTimeUnitField() const;
/**
* Destructor.
* @draft ICU 4.2
*/
virtual ~TimeUnit();
private:
UTimeUnitFields fTimeUnitField;
/**
* Constructor
* @internal ICU 4.2
*/
TimeUnit(UTimeUnitFields timeUnitField);
};
inline UBool
TimeUnit::operator!=(const UObject& other) const {
return !operator==(other);
}
U_NAMESPACE_END
#endif /* #if !UCONFIG_NO_FORMATTING */
#endif // __TMUNIT_H__
//eof
//
+168
View File
@@ -0,0 +1,168 @@
/*
*******************************************************************************
* Copyright (C) 2009, 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/measure.h"
#include "unicode/tmunit.h"
#if !UCONFIG_NO_FORMATTING
U_NAMESPACE_BEGIN
/**
* Express a duration as a time unit and number. Patterned after Currency.
* @see TimeUnitAmount
* @see TimeUnitFormat
* @draft 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.
* @draft 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.
* @draft ICU 4.2
*/
TimeUnitAmount(double amount, TimeUnit::UTimeUnitFields timeUnitField,
UErrorCode& status);
/**
* Copy constructor
* @draft ICU 4.2
*/
TimeUnitAmount(const TimeUnitAmount& other);
/**
* Assignment operator
* @draft 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().
* @draft ICU 4.2
*/
virtual UObject* clone() const;
/**
* Destructor
* @draft 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.
* @draft ICU 4.2
*/
virtual UBool 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.
* @draft ICU 4.2
*/
UBool 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.
* @draft ICU 4.2
*/
static UClassID U_EXPORT2 getStaticClassID(void);
/**
* 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.
* @draft ICU 4.2
*/
virtual UClassID getDynamicClassID(void) const;
/**
* Get the time unit.
* @return time unit object.
* @draft ICU 4.2
*/
const TimeUnit& getTimeUnit() const;
/**
* Get the time unit field value.
* @return time unit field value.
* @draft ICU 4.2
*/
TimeUnit::UTimeUnitFields getTimeUnitField() const;
};
inline UBool
TimeUnitAmount::operator!=(const UObject& other) const {
return !operator==(other);
}
U_NAMESPACE_END
#endif /* #if !UCONFIG_NO_FORMATTING */
#endif // __TMUTAMT_H__
//eof
//
+281
View File
@@ -0,0 +1,281 @@
/*
*******************************************************************************
* Copyright (C) 2008, 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 !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"
/**
* @internal ICU 4.2
*/
union UHashTok;
U_NAMESPACE_BEGIN
U_CDECL_BEGIN
/**
* @internal ICU 4.2
*/
static UBool U_CALLCONV hashTableValueComparator(UHashTok val1, UHashTok val2) ;
U_CDECL_END
class Hashtable;
/**
* 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
* @draft ICU 4.2
*/
class U_I18N_API TimeUnitFormat: public MeasureFormat {
public:
/**
* 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".
* @draft ICU 4.2
*/
enum EStyle {
kFull = 0,
kAbbreviate = 1,
kTotal = kAbbreviate + 1
};
/**
* Create TimeUnitFormat with default locale, and full name style.
* Use setLocale and/or setFormat to modify.
* @draft ICU 4.2
*/
TimeUnitFormat(UErrorCode& status);
/**
* Create TimeUnitFormat given locale, and full name style.
* @draft ICU 4.2
*/
TimeUnitFormat(const Locale& locale, UErrorCode& status);
/**
* Create TimeUnitFormat given locale and style.
* @draft ICU 4.2
*/
TimeUnitFormat(const Locale& locale, EStyle style, UErrorCode& status);
/**
* Copy constructor.
* @draft ICU 4.2
*/
TimeUnitFormat(const TimeUnitFormat&);
/**
* deconstructor
* @draft ICU 4.2
*/
virtual ~TimeUnitFormat();
/**
* Clone this Format object polymorphically. The caller owns the result and
* should delete it when done.
* @return A copy of the object.
* @draft ICU 4.2
*/
virtual Format* clone(void) const;
/**
* Assignment operator
* @draft ICU 4.2
*/
TimeUnitFormat& operator=(const TimeUnitFormat& other);
/**
* 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 true if the given Format objects are semantically equal.
* @draft ICU 4.2
*/
virtual UBool operator==(const Format& other) const;
/**
* Return true if the given Format objects are not semantically equal.
* Objects of different subclasses are considered unequal.
* @param other the object to be compared with.
* @return true if the given Format objects are not semantically equal.
* @draft ICU 4.2
*/
UBool operator!=(const Format& other) const;
/**
* 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
* @draft ICU 4.2
*/
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
* @draft ICU 4.2
*/
void setNumberFormat(const NumberFormat& format, UErrorCode& status);
/**
* Format a TimeUnitAmount.
* If the formattable object is not a time unit amount object,
* or the number in time unit amount is not a double type or long type
* numeric, it returns a failing status: U_ILLEGAL_ARGUMENT_ERROR.
* @see Format#format(const Formattable&, UnicodeString&, FieldPosition&, UErrorCode&) const
* @draft ICU 4.2
*/
virtual UnicodeString& format(const Formattable& obj,
UnicodeString& toAppendTo,
FieldPosition& pos,
UErrorCode& status) const;
/**
* Parse a TimeUnitAmount.
* @see Format#parseObject(const UnicodeString&, Formattable&, ParsePosition&) const;
* @draft ICU 4.2
*/
virtual void parseObject(const UnicodeString& source,
Formattable& result,
ParsePosition& pos) 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.
* @draft ICU 4.2
*/
static UClassID U_EXPORT2 getStaticClassID(void);
/**
* 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.
* @draft ICU 4.2
*/
virtual UClassID getDynamicClassID(void) const;
private:
NumberFormat* fNumberFormat;
Locale fLocale;
Hashtable* fTimeUnitToCountToPatterns[TimeUnit::UTIMEUNIT_FIELD_COUNT];
PluralRules* fPluralRules;
EStyle fStyle;
friend UBool U_CALLCONV hashTableValueComparator(UHashTok val1, UHashTok val2);
void create(const Locale& locale, EStyle 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(EStyle style, const char* key, UErrorCode& status);
// check completeness of fTimeUnitToCountToPatterns against all time units,
// and all plural rules, fill in fallback as necessary.
void checkConsistency(EStyle style, const char* key, UErrorCode& status);
// fill in fTimeUnitToCountToPatterns from locale fall-back chain
void searchInLocaleChain(EStyle style, const char* key,
TimeUnit::UTimeUnitFields field, const char*,
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);
};
inline UBool
TimeUnitFormat::operator!=(const Format& other) const {
return !operator==(other);
}
U_NAMESPACE_END
#endif /* #if !UCONFIG_NO_FORMATTING */
#endif // __TMUTFMT_H__
//eof
File diff suppressed because it is too large Load Diff
+828
View File
@@ -0,0 +1,828 @@
/*
*******************************************************************************
* 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 !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(void) 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 UBool 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 UBool 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(void) 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(void) 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(void) const;
/**
* 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 UBool 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 UBool operator!=(const TimeZoneRule& that) 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;
/**
* 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;
/**
* 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;
/**
* 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;
/**
* 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;
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(void);
/**
* 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(void) const;
};
/**
* <code>AnnualTimeZoneRule</code> is a class used for representing a time zone
* rule which takes effect annually. The calenday 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(void) const;
/**
* 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 UBool 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 UBool operator!=(const TimeZoneRule& that) const;
/**
* 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(void) 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(void) 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(void) 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;
/**
* 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;
/**
* 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;
/**
* 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;
/**
* 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;
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(void);
/**
* 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(void) const;
};
/**
* <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(void) const;
/**
* 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 UBool 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 UBool operator!=(const TimeZoneRule& that) const;
/**
* 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(void) 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(void) 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;
/**
* 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;
/**
* 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;
/**
* 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;
/**
* 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;
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(void);
/**
* 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(void) const;
};
U_NAMESPACE_END
#endif /* #if !UCONFIG_NO_FORMATTING */
#endif // TZRULE_H
//eof
+195
View File
@@ -0,0 +1,195 @@
/*
*******************************************************************************
* 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 !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(void) 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
*/
UBool 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
*/
UBool 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(void) 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(void) 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(void) 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(void);
/**
* 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(void) const;
};
U_NAMESPACE_END
#endif /* #if !UCONFIG_NO_FORMATTING */
#endif // TZTRANS_H
//eof
File diff suppressed because it is too large Load Diff
+481
View File
@@ -0,0 +1,481 @@
/*
******************************************************************************
* Copyright (C) 1996-2009, International Business Machines Corporation and others.
* All Rights Reserved.
******************************************************************************
*/
#ifndef UBRK_H
#define UBRK_H
#include "unicode/utypes.h"
#include "unicode/uloc.h"
#include "unicode/utext.h"
/**
* A text-break iterator.
* For usage in C programs.
*/
#ifndef UBRK_TYPEDEF_UBREAK_ITERATOR
# define UBRK_TYPEDEF_UBREAK_ITERATOR
/**
* Opaque type representing an ICU Break iterator object.
* @stable ICU 2.0
*/
typedef void UBreakIterator;
#endif
#if !UCONFIG_NO_BREAK_ITERATION
#include "unicode/parseerr.h"
/**
* \file
* \brief C API: BreakIterator
*
* <h2> BreakIterator C API </h2>
*
* The BreakIterator C API defines methods for finding the location
* of boundaries in text. Pointer to a UBreakIterator maintain a
* current position and scan over text returning the index of characters
* where boundaries occur.
* <p>
* Line boundary analysis determines where a text string can be broken
* when line-wrapping. The mechanism correctly handles punctuation and
* hyphenated words.
* <p>
* Sentence boundary analysis allows selection with correct
* interpretation of periods within numbers and abbreviations, and
* trailing punctuation marks such as quotation marks and parentheses.
* <p>
* Word boundary analysis is used by search and replace functions, as
* well as within text editing applications that allow the user to
* select words with a double click. Word selection provides correct
* interpretation of punctuation marks within and following
* words. Characters that are not part of a word, such as symbols or
* punctuation marks, have word-breaks on both sides.
* <p>
* Character boundary analysis identifies the boundaries of
* "Extended Grapheme Clusters", which are groupings of codepoints
* that should be treated as character-like units for many text operations.
* Please see Unicode Standard Annex #29, Unicode Text Segmentation,
* http://www.unicode.org/reports/tr29/ for additional information
* on grapheme clusters and guidelines on their use.
* <p>
* Title boundary analysis locates all positions,
* typically starts of words, that should be set to Title Case
* when title casing the text.
* <p>
* The text boundary positions are found according to the rules
* described in Unicode Standard Annex #29, Text Boundaries, and
* Unicode Standard Annex #14, Line Breaking Properties. These
* are available at http://www.unicode.org/reports/tr14/ and
* http://www.unicode.org/reports/tr29/.
* <p>
* In addition to the plain C API defined in this header file, an
* object oriented C++ API with equivalent functionality is defined in the
* file brkiter.h.
* <p>
* Code snippits illustrating the use of the Break Iterator APIs
* are available in the ICU User Guide,
* http://icu-project.org/userguide/boundaryAnalysis.html
* and in the sample program icu/source/samples/break/break.cpp"
*/
/** The possible types of text boundaries. @stable ICU 2.0 */
typedef enum UBreakIteratorType {
/** Character breaks @stable ICU 2.0 */
UBRK_CHARACTER = 0,
/** Word breaks @stable ICU 2.0 */
UBRK_WORD = 1,
/** Line breaks @stable ICU 2.0 */
UBRK_LINE = 2,
/** Sentence breaks @stable ICU 2.0 */
UBRK_SENTENCE = 3,
#ifndef U_HIDE_DEPRECATED_API
/**
* Title Case breaks
* The iterator created using this type locates title boundaries as described for
* Unicode 3.2 only. For Unicode 4.0 and above title boundary iteration,
* please use Word Boundary iterator.
*
* @deprecated ICU 2.8 Use the word break iterator for titlecasing for Unicode 4 and later.
*/
UBRK_TITLE = 4,
#endif /* U_HIDE_DEPRECATED_API */
UBRK_COUNT = 5
} UBreakIteratorType;
/** Value indicating all text boundaries have been returned.
* @stable ICU 2.0
*/
#define UBRK_DONE ((int32_t) -1)
/**
* Enum constants for the word break tags returned by
* getRuleStatus(). A range of values is defined for each category of
* word, to allow for further subdivisions of a category in future releases.
* Applications should check for tag values falling within the range, rather
* than for single individual values.
* @stable ICU 2.2
*/
typedef enum UWordBreak {
/** Tag value for "words" that do not fit into any of other categories.
* Includes spaces and most punctuation. */
UBRK_WORD_NONE = 0,
/** Upper bound for tags for uncategorized words. */
UBRK_WORD_NONE_LIMIT = 100,
/** Tag value for words that appear to be numbers, lower limit. */
UBRK_WORD_NUMBER = 100,
/** Tag value for words that appear to be numbers, upper limit. */
UBRK_WORD_NUMBER_LIMIT = 200,
/** Tag value for words that contain letters, excluding
* hiragana, katakana or ideographic characters, lower limit. */
UBRK_WORD_LETTER = 200,
/** Tag value for words containing letters, upper limit */
UBRK_WORD_LETTER_LIMIT = 300,
/** Tag value for words containing kana characters, lower limit */
UBRK_WORD_KANA = 300,
/** Tag value for words containing kana characters, upper limit */
UBRK_WORD_KANA_LIMIT = 400,
/** Tag value for words containing ideographic characters, lower limit */
UBRK_WORD_IDEO = 400,
/** Tag value for words containing ideographic characters, upper limit */
UBRK_WORD_IDEO_LIMIT = 500
} UWordBreak;
/**
* Enum constants for the line break tags returned by getRuleStatus().
* A range of values is defined for each category of
* word, to allow for further subdivisions of a category in future releases.
* Applications should check for tag values falling within the range, rather
* than for single individual values.
* @stable ICU 2.8
*/
typedef enum ULineBreakTag {
/** Tag value for soft line breaks, positions at which a line break
* is acceptable but not required */
UBRK_LINE_SOFT = 0,
/** Upper bound for soft line breaks. */
UBRK_LINE_SOFT_LIMIT = 100,
/** Tag value for a hard, or mandatory line break */
UBRK_LINE_HARD = 100,
/** Upper bound for hard line breaks. */
UBRK_LINE_HARD_LIMIT = 200
} ULineBreakTag;
/**
* Enum constants for the sentence break tags returned by getRuleStatus().
* A range of values is defined for each category of
* sentence, to allow for further subdivisions of a category in future releases.
* Applications should check for tag values falling within the range, rather
* than for single individual values.
* @stable ICU 2.8
*/
typedef enum USentenceBreakTag {
/** Tag value for for sentences ending with a sentence terminator
* ('.', '?', '!', etc.) character, possibly followed by a
* hard separator (CR, LF, PS, etc.)
*/
UBRK_SENTENCE_TERM = 0,
/** Upper bound for tags for sentences ended by sentence terminators. */
UBRK_SENTENCE_TERM_LIMIT = 100,
/** Tag value for for sentences that do not contain an ending
* sentence terminator ('.', '?', '!', etc.) character, but
* are ended only by a hard separator (CR, LF, PS, etc.) or end of input.
*/
UBRK_SENTENCE_SEP = 100,
/** Upper bound for tags for sentences ended by a separator. */
UBRK_SENTENCE_SEP_LIMIT = 200
/** Tag value for a hard, or mandatory line break */
} USentenceBreakTag;
/**
* Open a new UBreakIterator for locating text boundaries for a specified locale.
* A UBreakIterator may be used for detecting character, line, word,
* and sentence breaks in text.
* @param type The type of UBreakIterator to open: one of UBRK_CHARACTER, UBRK_WORD,
* UBRK_LINE, UBRK_SENTENCE
* @param locale The locale specifying the text-breaking conventions.
* @param text The text to be iterated over.
* @param textLength The number of characters in text, or -1 if null-terminated.
* @param status A UErrorCode to receive any errors.
* @return A UBreakIterator for the specified locale.
* @see ubrk_openRules
* @stable ICU 2.0
*/
U_STABLE UBreakIterator* U_EXPORT2
ubrk_open(UBreakIteratorType type,
const char *locale,
const UChar *text,
int32_t textLength,
UErrorCode *status);
/**
* Open a new UBreakIterator for locating text boundaries using specified breaking rules.
* The rule syntax is ... (TBD)
* @param rules A set of rules specifying the text breaking conventions.
* @param rulesLength The number of characters in rules, or -1 if null-terminated.
* @param text The text to be iterated over. May be null, in which case ubrk_setText() is
* used to specify the text to be iterated.
* @param textLength The number of characters in text, or -1 if null-terminated.
* @param parseErr Receives position and context information for any syntax errors
* detected while parsing the rules.
* @param status A UErrorCode to receive any errors.
* @return A UBreakIterator for the specified rules.
* @see ubrk_open
* @stable ICU 2.2
*/
U_STABLE UBreakIterator* U_EXPORT2
ubrk_openRules(const UChar *rules,
int32_t rulesLength,
const UChar *text,
int32_t textLength,
UParseError *parseErr,
UErrorCode *status);
/**
* Thread safe cloning operation
* @param bi iterator to be cloned
* @param stackBuffer user allocated space for the new clone. If NULL new memory will be allocated.
* If buffer is not large enough, new memory will be allocated.
* Clients can use the U_BRK_SAFECLONE_BUFFERSIZE. This will probably be enough to avoid memory allocations.
* @param pBufferSize pointer to size of allocated space.
* If *pBufferSize == 0, a sufficient size for use in cloning will
* be returned ('pre-flighting')
* If *pBufferSize is not enough for a stack-based safe clone,
* new memory will be allocated.
* @param status to indicate whether the operation went on smoothly or there were errors
* An informational status value, U_SAFECLONE_ALLOCATED_ERROR, is used if any allocations were necessary.
* @return pointer to the new clone
* @stable ICU 2.0
*/
U_STABLE UBreakIterator * U_EXPORT2
ubrk_safeClone(
const UBreakIterator *bi,
void *stackBuffer,
int32_t *pBufferSize,
UErrorCode *status);
/**
* A recommended size (in bytes) for the memory buffer to be passed to ubrk_saveClone().
* @stable ICU 2.0
*/
#define U_BRK_SAFECLONE_BUFFERSIZE 512
/**
* Close a UBreakIterator.
* Once closed, a UBreakIterator may no longer be used.
* @param bi The break iterator to close.
* @stable ICU 2.0
*/
U_STABLE void U_EXPORT2
ubrk_close(UBreakIterator *bi);
/**
* Sets an existing iterator to point to a new piece of text
* @param bi The iterator to use
* @param text The text to be set
* @param textLength The length of the text
* @param status The error code
* @stable ICU 2.0
*/
U_STABLE void U_EXPORT2
ubrk_setText(UBreakIterator* bi,
const UChar* text,
int32_t textLength,
UErrorCode* status);
/**
* Sets an existing iterator to point to a new piece of text
* @param bi The iterator to use
* @param text The text to be set.
* This function makes a shallow clone of the supplied UText. This means
* that the caller is free to immediately close or otherwise reuse the
* UText that was passed as a parameter, but that the underlying text itself
* must not be altered while being referenced by the break iterator.
* @param status The error code
* @stable ICU 3.4
*/
U_STABLE void U_EXPORT2
ubrk_setUText(UBreakIterator* bi,
UText* text,
UErrorCode* status);
/**
* Determine the most recently-returned text boundary.
*
* @param bi The break iterator to use.
* @return The character index most recently returned by \ref ubrk_next, \ref ubrk_previous,
* \ref ubrk_first, or \ref ubrk_last.
* @stable ICU 2.0
*/
U_STABLE int32_t U_EXPORT2
ubrk_current(const UBreakIterator *bi);
/**
* Determine the text boundary following the current text boundary.
*
* @param bi The break iterator to use.
* @return The character index of the next text boundary, or UBRK_DONE
* if all text boundaries have been returned.
* @see ubrk_previous
* @stable ICU 2.0
*/
U_STABLE int32_t U_EXPORT2
ubrk_next(UBreakIterator *bi);
/**
* Determine the text boundary preceding the current text boundary.
*
* @param bi The break iterator to use.
* @return The character index of the preceding text boundary, or UBRK_DONE
* if all text boundaries have been returned.
* @see ubrk_next
* @stable ICU 2.0
*/
U_STABLE int32_t U_EXPORT2
ubrk_previous(UBreakIterator *bi);
/**
* Determine the index of the first character in the text being scanned.
* This is not always the same as index 0 of the text.
* @param bi The break iterator to use.
* @return The character index of the first character in the text being scanned.
* @see ubrk_last
* @stable ICU 2.0
*/
U_STABLE int32_t U_EXPORT2
ubrk_first(UBreakIterator *bi);
/**
* Determine the index immediately <EM>beyond</EM> the last character in the text being
* scanned.
* This is not the same as the last character.
* @param bi The break iterator to use.
* @return The character offset immediately <EM>beyond</EM> the last character in the
* text being scanned.
* @see ubrk_first
* @stable ICU 2.0
*/
U_STABLE int32_t U_EXPORT2
ubrk_last(UBreakIterator *bi);
/**
* Determine the text boundary preceding the specified offset.
* The value returned is always smaller than offset, or UBRK_DONE.
* @param bi The break iterator to use.
* @param offset The offset to begin scanning.
* @return The text boundary preceding offset, or UBRK_DONE.
* @see ubrk_following
* @stable ICU 2.0
*/
U_STABLE int32_t U_EXPORT2
ubrk_preceding(UBreakIterator *bi,
int32_t offset);
/**
* Determine the text boundary following the specified offset.
* The value returned is always greater than offset, or UBRK_DONE.
* @param bi The break iterator to use.
* @param offset The offset to begin scanning.
* @return The text boundary following offset, or UBRK_DONE.
* @see ubrk_preceding
* @stable ICU 2.0
*/
U_STABLE int32_t U_EXPORT2
ubrk_following(UBreakIterator *bi,
int32_t offset);
/**
* Get a locale for which text breaking information is available.
* A UBreakIterator in a locale returned by this function will perform the correct
* text breaking for the locale.
* @param index The index of the desired locale.
* @return A locale for which number text breaking information is available, or 0 if none.
* @see ubrk_countAvailable
* @stable ICU 2.0
*/
U_STABLE const char* U_EXPORT2
ubrk_getAvailable(int32_t index);
/**
* Determine how many locales have text breaking information available.
* This function is most useful as determining the loop ending condition for
* calls to \ref ubrk_getAvailable.
* @return The number of locales for which text breaking information is available.
* @see ubrk_getAvailable
* @stable ICU 2.0
*/
U_STABLE int32_t U_EXPORT2
ubrk_countAvailable(void);
/**
* Returns true if the specfied position is a boundary position. As a side
* effect, leaves the iterator pointing to the first boundary position at
* or after "offset".
* @param bi The break iterator to use.
* @param offset the offset to check.
* @return True if "offset" is a boundary position.
* @stable ICU 2.0
*/
U_STABLE UBool U_EXPORT2
ubrk_isBoundary(UBreakIterator *bi, int32_t offset);
/**
* Return the status from the break rule that determined the most recently
* returned break position. The values appear in the rule source
* within brackets, {123}, for example. For rules that do not specify a
* status, a default value of 0 is returned.
* <p>
* For word break iterators, the possible values are defined in enum UWordBreak.
* @stable ICU 2.2
*/
U_STABLE int32_t U_EXPORT2
ubrk_getRuleStatus(UBreakIterator *bi);
/**
* Get the statuses from the break rules that determined the most recently
* returned break position. The values appear in the rule source
* within brackets, {123}, for example. The default status value for rules
* that do not explicitly provide one is zero.
* <p>
* For word break iterators, the possible values are defined in enum UWordBreak.
* @param bi The break iterator to use
* @param fillInVec an array to be filled in with the status values.
* @param capacity the length of the supplied vector. A length of zero causes
* the function to return the number of status values, in the
* normal way, without attemtping to store any values.
* @param status receives error codes.
* @return The number of rule status values from rules that determined
* the most recent boundary returned by the break iterator.
* @stable ICU 3.0
*/
U_STABLE int32_t U_EXPORT2
ubrk_getRuleStatusVec(UBreakIterator *bi, int32_t *fillInVec, int32_t capacity, UErrorCode *status);
/**
* Return the locale of the break iterator. You can choose between the valid and
* the actual locale.
* @param bi break iterator
* @param type locale type (valid or actual)
* @param status error code
* @return locale string
* @stable ICU 2.8
*/
U_STABLE const char* U_EXPORT2
ubrk_getLocaleByType(const UBreakIterator *bi, ULocDataLocaleType type, UErrorCode* status);
#endif /* #if !UCONFIG_NO_BREAK_ITERATION */
#endif
File diff suppressed because it is too large Load Diff
+401
View File
@@ -0,0 +1,401 @@
/*
*******************************************************************************
*
* Copyright (C) 2005-2009, International Business Machines
* Corporation and others. All Rights Reserved.
*
*******************************************************************************
* file name: ucasemap.h
* encoding: US-ASCII
* tab size: 8 (not used)
* indentation:4
*
* created on: 2005may06
* created by: Markus W. Scherer
*
* Case mapping service object and functions using it.
*/
#ifndef __UCASEMAP_H__
#define __UCASEMAP_H__
#include "unicode/utypes.h"
#include "unicode/ustring.h"
/**
* \file
* \brief C API: Unicode case mapping functions using a UCaseMap service object.
*
* The service object takes care of memory allocations, data loading, and setup
* for the attributes, as usual.
*
* Currently, the functionality provided here does not overlap with uchar.h
* and ustring.h, except for ucasemap_toTitle().
*
* ucasemap_utf8XYZ() functions operate directly on UTF-8 strings.
*/
/**
* UCaseMap is an opaque service object for newer ICU case mapping functions.
* Older functions did not use a service object.
* @stable ICU 3.4
*/
struct UCaseMap;
typedef struct UCaseMap UCaseMap; /**< C typedef for struct UCaseMap. @stable ICU 3.4 */
/**
* Open a UCaseMap service object for a locale and a set of options.
* The locale ID and options are preprocessed so that functions using the
* service object need not process them in each call.
*
* @param locale ICU locale ID, used for language-dependent
* upper-/lower-/title-casing according to the Unicode standard.
* Usual semantics: ""=root, NULL=default locale, etc.
* @param options Options bit set, used for case folding and string comparisons.
* Same flags as for u_foldCase(), u_strFoldCase(),
* u_strCaseCompare(), etc.
* Use 0 or U_FOLD_CASE_DEFAULT for default behavior.
* @param pErrorCode Must be a valid pointer to an error code value,
* which must not indicate a failure before the function call.
* @return Pointer to a UCaseMap service object, if successful.
*
* @see U_FOLD_CASE_DEFAULT
* @see U_FOLD_CASE_EXCLUDE_SPECIAL_I
* @see U_TITLECASE_NO_LOWERCASE
* @see U_TITLECASE_NO_BREAK_ADJUSTMENT
* @stable ICU 3.4
*/
U_STABLE UCaseMap * U_EXPORT2
ucasemap_open(const char *locale, uint32_t options, UErrorCode *pErrorCode);
/**
* Close a UCaseMap service object.
* @param csm Object to be closed.
* @stable ICU 3.4
*/
U_STABLE void U_EXPORT2
ucasemap_close(UCaseMap *csm);
/**
* Get the locale ID that is used for language-dependent case mappings.
* @param csm UCaseMap service object.
* @return locale ID
* @stable ICU 3.4
*/
U_STABLE const char * U_EXPORT2
ucasemap_getLocale(const UCaseMap *csm);
/**
* Get the options bit set that is used for case folding and string comparisons.
* @param csm UCaseMap service object.
* @return options bit set
* @stable ICU 3.4
*/
U_STABLE uint32_t U_EXPORT2
ucasemap_getOptions(const UCaseMap *csm);
/**
* Set the locale ID that is used for language-dependent case mappings.
*
* @param csm UCaseMap service object.
* @param locale Locale ID, see ucasemap_open().
* @param pErrorCode Must be a valid pointer to an error code value,
* which must not indicate a failure before the function call.
*
* @see ucasemap_open
* @stable ICU 3.4
*/
U_STABLE void U_EXPORT2
ucasemap_setLocale(UCaseMap *csm, const char *locale, UErrorCode *pErrorCode);
/**
* Set the options bit set that is used for case folding and string comparisons.
*
* @param csm UCaseMap service object.
* @param options Options bit set, see ucasemap_open().
* @param pErrorCode Must be a valid pointer to an error code value,
* which must not indicate a failure before the function call.
*
* @see ucasemap_open
* @stable ICU 3.4
*/
U_STABLE void U_EXPORT2
ucasemap_setOptions(UCaseMap *csm, uint32_t options, UErrorCode *pErrorCode);
/**
* Do not lowercase non-initial parts of words when titlecasing.
* Option bit for titlecasing APIs that take an options bit set.
*
* By default, titlecasing will titlecase the first cased character
* of a word and lowercase all other characters.
* With this option, the other characters will not be modified.
*
* @see ucasemap_setOptions
* @see ucasemap_toTitle
* @see ucasemap_utf8ToTitle
* @see UnicodeString::toTitle
* @stable ICU 3.8
*/
#define U_TITLECASE_NO_LOWERCASE 0x100
/**
* Do not adjust the titlecasing indexes from BreakIterator::next() indexes;
* titlecase exactly the characters at breaks from the iterator.
* Option bit for titlecasing APIs that take an options bit set.
*
* By default, titlecasing will take each break iterator index,
* adjust it by looking for the next cased character, and titlecase that one.
* Other characters are lowercased.
*
* This follows Unicode 4 & 5 section 3.13 Default Case Operations:
*
* R3 toTitlecase(X): Find the word boundaries based on Unicode Standard Annex
* #29, "Text Boundaries." Between each pair of word boundaries, find the first
* cased character F. If F exists, map F to default_title(F); then map each
* subsequent character C to default_lower(C).
*
* @see ucasemap_setOptions
* @see ucasemap_toTitle
* @see ucasemap_utf8ToTitle
* @see UnicodeString::toTitle
* @see U_TITLECASE_NO_LOWERCASE
* @stable ICU 3.8
*/
#define U_TITLECASE_NO_BREAK_ADJUSTMENT 0x200
#if !UCONFIG_NO_BREAK_ITERATION
/**
* Get the break iterator that is used for titlecasing.
* Do not modify the returned break iterator.
* @param csm UCaseMap service object.
* @return titlecasing break iterator
* @stable ICU 3.8
*/
U_DRAFT const UBreakIterator * U_EXPORT2
ucasemap_getBreakIterator(const UCaseMap *csm);
/**
* Set the break iterator that is used for titlecasing.
* The UCaseMap service object releases a previously set break iterator
* and "adopts" this new one, taking ownership of it.
* It will be released in a subsequent call to ucasemap_setBreakIterator()
* or ucasemap_close().
*
* Break iterator operations are not thread-safe. Therefore, titlecasing
* functions use non-const UCaseMap objects. It is not possible to titlecase
* strings concurrently using the same UCaseMap.
*
* @param csm UCaseMap service object.
* @param iterToAdopt Break iterator to be adopted for titlecasing.
* @param pErrorCode Must be a valid pointer to an error code value,
* which must not indicate a failure before the function call.
*
* @see ucasemap_toTitle
* @see ucasemap_utf8ToTitle
* @stable ICU 3.8
*/
U_DRAFT void U_EXPORT2
ucasemap_setBreakIterator(UCaseMap *csm, UBreakIterator *iterToAdopt, UErrorCode *pErrorCode);
/**
* Titlecase a UTF-16 string. This function is almost a duplicate of u_strToTitle(),
* except that it takes ucasemap_setOptions() into account and has performance
* advantages from being able to use a UCaseMap object for multiple case mapping
* operations, saving setup time.
*
* Casing is locale-dependent and context-sensitive.
* Titlecasing uses a break iterator to find the first characters of words
* that are to be titlecased. It titlecases those characters and lowercases
* all others. (This can be modified with ucasemap_setOptions().)
*
* Note: This function takes a non-const UCaseMap pointer because it will
* open a default break iterator if no break iterator was set yet,
* and effectively call ucasemap_setBreakIterator();
* also because the break iterator is stateful and will be modified during
* the iteration.
*
* The titlecase break iterator can be provided to customize for arbitrary
* styles, using rules and dictionaries beyond the standard iterators.
* The standard titlecase iterator for the root locale implements the
* algorithm of Unicode TR 21.
*
* This function uses only the setUText(), first(), next() and close() methods of the
* provided break iterator.
*
* The result may be longer or shorter than the original.
* The source string and the destination buffer must not overlap.
*
* @param csm UCaseMap service object. This pointer is non-const!
* See the note above for details.
* @param dest A buffer for the result string. The result will be NUL-terminated if
* the buffer is large enough.
* The contents is undefined in case of failure.
* @param destCapacity The size of the buffer (number of bytes). If it is 0, then
* dest may be NULL and the function will only return the length of the result
* without writing any of the result string.
* @param src The original string.
* @param srcLength The length of the original string. If -1, then src must be NUL-terminated.
* @param pErrorCode Must be a valid pointer to an error code value,
* which must not indicate a failure before the function call.
* @return The length of the result string, if successful - or in case of a buffer overflow,
* in which case it will be greater than destCapacity.
*
* @see u_strToTitle
* @stable ICU 3.8
*/
U_DRAFT int32_t U_EXPORT2
ucasemap_toTitle(UCaseMap *csm,
UChar *dest, int32_t destCapacity,
const UChar *src, int32_t srcLength,
UErrorCode *pErrorCode);
#endif
/**
* Lowercase the characters in a UTF-8 string.
* Casing is locale-dependent and context-sensitive.
* The result may be longer or shorter than the original.
* The source string and the destination buffer must not overlap.
*
* @param csm UCaseMap service object.
* @param dest A buffer for the result string. The result will be NUL-terminated if
* the buffer is large enough.
* The contents is undefined in case of failure.
* @param destCapacity The size of the buffer (number of bytes). If it is 0, then
* dest may be NULL and the function will only return the length of the result
* without writing any of the result string.
* @param src The original string.
* @param srcLength The length of the original string. If -1, then src must be NUL-terminated.
* @param pErrorCode Must be a valid pointer to an error code value,
* which must not indicate a failure before the function call.
* @return The length of the result string, if successful - or in case of a buffer overflow,
* in which case it will be greater than destCapacity.
*
* @see u_strToLower
* @stable ICU 3.4
*/
U_STABLE int32_t U_EXPORT2
ucasemap_utf8ToLower(const UCaseMap *csm,
char *dest, int32_t destCapacity,
const char *src, int32_t srcLength,
UErrorCode *pErrorCode);
/**
* Uppercase the characters in a UTF-8 string.
* Casing is locale-dependent and context-sensitive.
* The result may be longer or shorter than the original.
* The source string and the destination buffer must not overlap.
*
* @param csm UCaseMap service object.
* @param dest A buffer for the result string. The result will be NUL-terminated if
* the buffer is large enough.
* The contents is undefined in case of failure.
* @param destCapacity The size of the buffer (number of bytes). If it is 0, then
* dest may be NULL and the function will only return the length of the result
* without writing any of the result string.
* @param src The original string.
* @param srcLength The length of the original string. If -1, then src must be NUL-terminated.
* @param pErrorCode Must be a valid pointer to an error code value,
* which must not indicate a failure before the function call.
* @return The length of the result string, if successful - or in case of a buffer overflow,
* in which case it will be greater than destCapacity.
*
* @see u_strToUpper
* @stable ICU 3.4
*/
U_STABLE int32_t U_EXPORT2
ucasemap_utf8ToUpper(const UCaseMap *csm,
char *dest, int32_t destCapacity,
const char *src, int32_t srcLength,
UErrorCode *pErrorCode);
#if !UCONFIG_NO_BREAK_ITERATION
/**
* Titlecase a UTF-8 string.
* Casing is locale-dependent and context-sensitive.
* Titlecasing uses a break iterator to find the first characters of words
* that are to be titlecased. It titlecases those characters and lowercases
* all others. (This can be modified with ucasemap_setOptions().)
*
* Note: This function takes a non-const UCaseMap pointer because it will
* open a default break iterator if no break iterator was set yet,
* and effectively call ucasemap_setBreakIterator();
* also because the break iterator is stateful and will be modified during
* the iteration.
*
* The titlecase break iterator can be provided to customize for arbitrary
* styles, using rules and dictionaries beyond the standard iterators.
* The standard titlecase iterator for the root locale implements the
* algorithm of Unicode TR 21.
*
* This function uses only the setUText(), first(), next() and close() methods of the
* provided break iterator.
*
* The result may be longer or shorter than the original.
* The source string and the destination buffer must not overlap.
*
* @param csm UCaseMap service object. This pointer is non-const!
* See the note above for details.
* @param dest A buffer for the result string. The result will be NUL-terminated if
* the buffer is large enough.
* The contents is undefined in case of failure.
* @param destCapacity The size of the buffer (number of bytes). If it is 0, then
* dest may be NULL and the function will only return the length of the result
* without writing any of the result string.
* @param src The original string.
* @param srcLength The length of the original string. If -1, then src must be NUL-terminated.
* @param pErrorCode Must be a valid pointer to an error code value,
* which must not indicate a failure before the function call.
* @return The length of the result string, if successful - or in case of a buffer overflow,
* in which case it will be greater than destCapacity.
*
* @see u_strToTitle
* @see U_TITLECASE_NO_LOWERCASE
* @see U_TITLECASE_NO_BREAK_ADJUSTMENT
* @stable ICU 3.8
*/
U_DRAFT int32_t U_EXPORT2
ucasemap_utf8ToTitle(UCaseMap *csm,
char *dest, int32_t destCapacity,
const char *src, int32_t srcLength,
UErrorCode *pErrorCode);
#endif
/**
* Case-fold the characters in a UTF-8 string.
* Case-folding is locale-independent and not context-sensitive,
* but there is an option for whether to include or exclude mappings for dotted I
* and dotless i that are marked with 'I' in CaseFolding.txt.
* The result may be longer or shorter than the original.
* The source string and the destination buffer must not overlap.
*
* @param csm UCaseMap service object.
* @param dest A buffer for the result string. The result will be NUL-terminated if
* the buffer is large enough.
* The contents is undefined in case of failure.
* @param destCapacity The size of the buffer (number of bytes). If it is 0, then
* dest may be NULL and the function will only return the length of the result
* without writing any of the result string.
* @param src The original string.
* @param srcLength The length of the original string. If -1, then src must be NUL-terminated.
* @param pErrorCode Must be a valid pointer to an error code value,
* which must not indicate a failure before the function call.
* @return The length of the result string, if successful - or in case of a buffer overflow,
* in which case it will be greater than destCapacity.
*
* @see u_strFoldCase
* @see ucasemap_setOptions
* @see U_FOLD_CASE_DEFAULT
* @see U_FOLD_CASE_EXCLUDE_SPECIAL_I
* @stable ICU 3.8
*/
U_DRAFT int32_t U_EXPORT2
ucasemap_utf8FoldCase(const UCaseMap *csm,
char *dest, int32_t destCapacity,
const char *src, int32_t srcLength,
UErrorCode *pErrorCode);
#endif
+158
View File
@@ -0,0 +1,158 @@
/*
**********************************************************************
* Copyright (c) 2003-2004, International Business Machines
* Corporation and others. All Rights Reserved.
**********************************************************************
* Author: Alan Liu
* Created: March 19 2003
* Since: ICU 2.6
**********************************************************************
*/
#ifndef UCAT_H
#define UCAT_H
#include "unicode/utypes.h"
#include "unicode/ures.h"
/**
* \file
* \brief C API: Message Catalog Wrappers
*
* This C API provides look-alike functions that deliberately resemble
* the POSIX catopen, catclose, and catgets functions. The underlying
* implementation is in terms of ICU resource bundles, rather than
* POSIX message catalogs.
*
* The ICU resource bundles obey standard ICU inheritance policies.
* To facilitate this, sets and messages are flattened into one tier.
* This is done by creating resource bundle keys of the form
* &lt;set_num&gt;%&lt;msg_num&gt; where set_num is the set number and msg_num is
* the message number, formatted as decimal strings.
*
* Example: Consider a message catalog containing two sets:
*
* Set 1: Message 4 = "Good morning."
* Message 5 = "Good afternoon."
* Message 7 = "Good evening."
* Message 8 = "Good night."
* Set 4: Message 14 = "Please "
* Message 19 = "Thank you."
* Message 20 = "Sincerely,"
*
* The ICU resource bundle source file would, assuming it is named
* "greet.txt", would look like this:
*
* greet
* {
* 1%4 { "Good morning." }
* 1%5 { "Good afternoon." }
* 1%7 { "Good evening." }
* 1%8 { "Good night." }
*
* 4%14 { "Please " }
* 4%19 { "Thank you." }
* 4%20 { "Sincerely," }
* }
*
* The catgets function is commonly used in combination with functions
* like printf and strftime. ICU components like message format can
* be used instead, although they use a different format syntax.
* There is an ICU package, icuio, that provides some of
* the POSIX-style formatting API.
*/
U_CDECL_BEGIN
/**
* An ICU message catalog descriptor, analogous to nl_catd.
*
* @stable ICU 2.6
*/
typedef UResourceBundle* u_nl_catd;
/**
* Open and return an ICU message catalog descriptor. The descriptor
* may be passed to u_catgets() to retrieve localized strings.
*
* @param name string containing the full path pointing to the
* directory where the resources reside followed by the package name
* e.g. "/usr/resource/my_app/resources/guimessages" on a Unix system.
* If NULL, ICU default data files will be used.
*
* Unlike POSIX, environment variables are not interpolated within the
* name.
*
* @param locale the locale for which we want to open the resource. If
* NULL, the default ICU locale will be used (see uloc_getDefault). If
* strlen(locale) == 0, the root locale will be used.
*
* @param ec input/output error code. Upon output,
* U_USING_FALLBACK_WARNING indicates that a fallback locale was
* used. For example, 'de_CH' was requested, but nothing was found
* there, so 'de' was used. U_USING_DEFAULT_WARNING indicates that the
* default locale data or root locale data was used; neither the
* requested locale nor any of its fallback locales were found.
*
* @return a message catalog descriptor that may be passed to
* u_catgets(). If the ec parameter indicates success, then the caller
* is responsible for calling u_catclose() to close the message
* catalog. If the ec parameter indicates failure, then NULL will be
* returned.
*
* @stable ICU 2.6
*/
U_STABLE u_nl_catd U_EXPORT2
u_catopen(const char* name, const char* locale, UErrorCode* ec);
/**
* Close an ICU message catalog, given its descriptor.
*
* @param catd a message catalog descriptor to be closed. May be NULL,
* in which case no action is taken.
*
* @stable ICU 2.6
*/
U_STABLE void U_EXPORT2
u_catclose(u_nl_catd catd);
/**
* Retrieve a localized string from an ICU message catalog.
*
* @param catd a message catalog descriptor returned by u_catopen.
*
* @param set_num the message catalog set number. Sets need not be
* numbered consecutively.
*
* @param msg_num the message catalog message number within the
* set. Messages need not be numbered consecutively.
*
* @param s the default string. This is returned if the string
* specified by the set_num and msg_num is not found. It must be
* zero-terminated.
*
* @param len fill-in parameter to receive the length of the result.
* May be NULL, in which case it is ignored.
*
* @param ec input/output error code. May be U_USING_FALLBACK_WARNING
* or U_USING_DEFAULT_WARNING. U_MISSING_RESOURCE_ERROR indicates that
* the set_num/msg_num tuple does not specify a valid message string
* in this catalog.
*
* @return a pointer to a zero-terminated UChar array which lives in
* an internal buffer area, typically a memory mapped/DLL file. The
* caller must NOT delete this pointer. If the call is unsuccessful
* for any reason, then s is returned. This includes the situation in
* which ec indicates a failing error code upon entry to this
* function.
*
* @stable ICU 2.6
*/
U_STABLE const UChar* U_EXPORT2
u_catgets(u_nl_catd catd, int32_t set_num, int32_t msg_num,
const UChar* s,
int32_t* len, UErrorCode* ec);
U_CDECL_END
#endif /*UCAT_H*/
/*eof*/
File diff suppressed because it is too large Load Diff
+381
View File
@@ -0,0 +1,381 @@
/*
**********************************************************************
* Copyright (C) 1998-2005, International Business Machines
* Corporation and others. All Rights Reserved.
**********************************************************************
*/
#ifndef UCHRITER_H
#define UCHRITER_H
#include "unicode/utypes.h"
#include "unicode/chariter.h"
/**
* \file
* \brief C++ API: UChar Character Iterator
*/
U_NAMESPACE_BEGIN
/**
* A concrete subclass of CharacterIterator that iterates over the
* characters (code units or code points) in a UChar array.
* It's possible not only to create an
* iterator that iterates over an entire UChar array, but also to
* create one that iterates over only a subrange of a UChar array
* (iterators over different subranges of the same UChar array don't
* compare equal).
* @see CharacterIterator
* @see ForwardCharacterIterator
* @stable ICU 2.0
*/
class U_COMMON_API UCharCharacterIterator : public CharacterIterator {
public:
/**
* Create an iterator over the UChar array referred to by "textPtr".
* The iteration range is 0 to <code>length-1</code>.
* text is only aliased, not adopted (the
* destructor will not delete it).
* @param textPtr The UChar array to be iterated over
* @param length The length of the UChar array
* @stable ICU 2.0
*/
UCharCharacterIterator(const UChar* textPtr, int32_t length);
/**
* Create an iterator over the UChar array referred to by "textPtr".
* The iteration range is 0 to <code>length-1</code>.
* text is only aliased, not adopted (the
* destructor will not delete it).
* The starting
* position is specified by "position". If "position" is outside the valid
* iteration range, the behavior of this object is undefined.
* @param textPtr The UChar array to be iteratd over
* @param length The length of the UChar array
* @param position The starting position of the iteration
* @stable ICU 2.0
*/
UCharCharacterIterator(const UChar* textPtr, int32_t length,
int32_t position);
/**
* Create an iterator over the UChar array referred to by "textPtr".
* The iteration range is 0 to <code>end-1</code>.
* text is only aliased, not adopted (the
* destructor will not delete it).
* The starting
* position is specified by "position". If begin and end do not
* form a valid iteration range or "position" is outside the valid
* iteration range, the behavior of this object is undefined.
* @param textPtr The UChar array to be iterated over
* @param length The length of the UChar array
* @param textBegin The begin position of the iteration range
* @param textEnd The end position of the iteration range
* @param position The starting position of the iteration
* @stable ICU 2.0
*/
UCharCharacterIterator(const UChar* textPtr, int32_t length,
int32_t textBegin,
int32_t textEnd,
int32_t position);
/**
* Copy constructor. The new iterator iterates over the same range
* of the same string as "that", and its initial position is the
* same as "that"'s current position.
* @param that The UCharCharacterIterator to be copied
* @stable ICU 2.0
*/
UCharCharacterIterator(const UCharCharacterIterator& that);
/**
* Destructor.
* @stable ICU 2.0
*/
virtual ~UCharCharacterIterator();
/**
* Assignment operator. *this is altered to iterate over the sane
* range of the same string as "that", and refers to the same
* character within that string as "that" does.
* @param that The object to be copied
* @return the newly created object
* @stable ICU 2.0
*/
UCharCharacterIterator&
operator=(const UCharCharacterIterator& that);
/**
* Returns true if the iterators iterate over the same range of the
* same string and are pointing at the same character.
* @param that The ForwardCharacterIterator used to be compared for equality
* @return true if the iterators iterate over the same range of the
* same string and are pointing at the same character.
* @stable ICU 2.0
*/
virtual UBool operator==(const ForwardCharacterIterator& that) const;
/**
* Generates a hash code for this iterator.
* @return the hash code.
* @stable ICU 2.0
*/
virtual int32_t hashCode(void) const;
/**
* Returns a new UCharCharacterIterator referring to the same
* character in the same range of the same string as this one. The
* caller must delete the new iterator.
* @return the CharacterIterator newly created
* @stable ICU 2.0
*/
virtual CharacterIterator* clone(void) const;
/**
* Sets the iterator to refer to the first code unit in its
* iteration range, and returns that code unit.
* This can be used to begin an iteration with next().
* @return the first code unit in its iteration range.
* @stable ICU 2.0
*/
virtual UChar first(void);
/**
* Sets the iterator to refer to the first code unit in its
* iteration range, returns that code unit, and moves the position
* to the second code unit. This is an alternative to setToStart()
* for forward iteration with nextPostInc().
* @return the first code unit in its iteration range
* @stable ICU 2.0
*/
virtual UChar firstPostInc(void);
/**
* Sets the iterator to refer to the first code point in its
* iteration range, and returns that code unit,
* This can be used to begin an iteration with next32().
* Note that an iteration with next32PostInc(), beginning with,
* e.g., setToStart() or firstPostInc(), is more efficient.
* @return the first code point in its iteration range
* @stable ICU 2.0
*/
virtual UChar32 first32(void);
/**
* Sets the iterator to refer to the first code point in its
* iteration range, returns that code point, and moves the position
* to the second code point. This is an alternative to setToStart()
* for forward iteration with next32PostInc().
* @return the first code point in its iteration range.
* @stable ICU 2.0
*/
virtual UChar32 first32PostInc(void);
/**
* Sets the iterator to refer to the last code unit in its
* iteration range, and returns that code unit.
* This can be used to begin an iteration with previous().
* @return the last code unit in its iteration range.
* @stable ICU 2.0
*/
virtual UChar last(void);
/**
* Sets the iterator to refer to the last code point in its
* iteration range, and returns that code unit.
* This can be used to begin an iteration with previous32().
* @return the last code point in its iteration range.
* @stable ICU 2.0
*/
virtual UChar32 last32(void);
/**
* Sets the iterator to refer to the "position"-th code unit
* in the text-storage object the iterator refers to, and
* returns that code unit.
* @param position the position within the text-storage object
* @return the code unit
* @stable ICU 2.0
*/
virtual UChar setIndex(int32_t position);
/**
* Sets the iterator to refer to the beginning of the code point
* that contains the "position"-th code unit
* in the text-storage object the iterator refers to, and
* returns that code point.
* The current position is adjusted to the beginning of the code point
* (its first code unit).
* @param position the position within the text-storage object
* @return the code unit
* @stable ICU 2.0
*/
virtual UChar32 setIndex32(int32_t position);
/**
* Returns the code unit the iterator currently refers to.
* @return the code unit the iterator currently refers to.
* @stable ICU 2.0
*/
virtual UChar current(void) const;
/**
* Returns the code point the iterator currently refers to.
* @return the code point the iterator currently refers to.
* @stable ICU 2.0
*/
virtual UChar32 current32(void) const;
/**
* Advances to the next code unit in the iteration range (toward
* endIndex()), and returns that code unit. If there are no more
* code units to return, returns DONE.
* @return the next code unit in the iteration range.
* @stable ICU 2.0
*/
virtual UChar next(void);
/**
* Gets the current code unit for returning and advances to the next code unit
* in the iteration range
* (toward endIndex()). If there are
* no more code units to return, returns DONE.
* @return the current code unit.
* @stable ICU 2.0
*/
virtual UChar nextPostInc(void);
/**
* Advances to the next code point in the iteration range (toward
* endIndex()), and returns that code point. If there are no more
* code points to return, returns DONE.
* Note that iteration with "pre-increment" semantics is less
* efficient than iteration with "post-increment" semantics
* that is provided by next32PostInc().
* @return the next code point in the iteration range.
* @stable ICU 2.0
*/
virtual UChar32 next32(void);
/**
* Gets the current code point for returning and advances to the next code point
* in the iteration range
* (toward endIndex()). If there are
* no more code points to return, returns DONE.
* @return the current point.
* @stable ICU 2.0
*/
virtual UChar32 next32PostInc(void);
/**
* Returns FALSE if there are no more code units or code points
* at or after the current position in the iteration range.
* This is used with nextPostInc() or next32PostInc() in forward
* iteration.
* @return FALSE if there are no more code units or code points
* at or after the current position in the iteration range.
* @stable ICU 2.0
*/
virtual UBool hasNext();
/**
* Advances to the previous code unit in the iteration range (toward
* startIndex()), and returns that code unit. If there are no more
* code units to return, returns DONE.
* @return the previous code unit in the iteration range.
* @stable ICU 2.0
*/
virtual UChar previous(void);
/**
* Advances to the previous code point in the iteration range (toward
* startIndex()), and returns that code point. If there are no more
* code points to return, returns DONE.
* @return the previous code point in the iteration range.
* @stable ICU 2.0
*/
virtual UChar32 previous32(void);
/**
* Returns FALSE if there are no more code units or code points
* before the current position in the iteration range.
* This is used with previous() or previous32() in backward
* iteration.
* @return FALSE if there are no more code units or code points
* before the current position in the iteration range.
* @stable ICU 2.0
*/
virtual UBool hasPrevious();
/**
* Moves the current position relative to the start or end of the
* iteration range, or relative to the current position itself.
* The movement is expressed in numbers of code units forward
* or backward by specifying a positive or negative delta.
* @param delta the position relative to origin. A positive delta means forward;
* a negative delta means backward.
* @param origin Origin enumeration {kStart, kCurrent, kEnd}
* @return the new position
* @stable ICU 2.0
*/
virtual int32_t move(int32_t delta, EOrigin origin);
/**
* Moves the current position relative to the start or end of the
* iteration range, or relative to the current position itself.
* The movement is expressed in numbers of code points forward
* or backward by specifying a positive or negative delta.
* @param delta the position relative to origin. A positive delta means forward;
* a negative delta means backward.
* @param origin Origin enumeration {kStart, kCurrent, kEnd}
* @return the new position
* @stable ICU 2.0
*/
virtual int32_t move32(int32_t delta, EOrigin origin);
/**
* Sets the iterator to iterate over a new range of text
* @stable ICU 2.0
*/
void setText(const UChar* newText, int32_t newTextLength);
/**
* Copies the UChar array under iteration into the UnicodeString
* referred to by "result". Even if this iterator iterates across
* only a part of this string, the whole string is copied.
* @param result Receives a copy of the text under iteration.
* @stable ICU 2.0
*/
virtual void getText(UnicodeString& result);
/**
* Return a class ID for this class (not really public)
* @return a class ID for this class
* @stable ICU 2.0
*/
static UClassID U_EXPORT2 getStaticClassID(void);
/**
* Return a class ID for this object (not really public)
* @return a class ID for this object.
* @stable ICU 2.0
*/
virtual UClassID getDynamicClassID(void) const;
protected:
/**
* Protected constructor
* @stable ICU 2.0
*/
UCharCharacterIterator();
/**
* Protected member text
* @stable ICU 2.0
*/
const UChar* text;
};
U_NAMESPACE_END
#endif
+267
View File
@@ -0,0 +1,267 @@
/*
******************************************************************************
* *
* Copyright (C) 2001-2005, International Business Machines *
* Corporation and others. All Rights Reserved. *
* *
******************************************************************************
* file name: uclean.h
* encoding: US-ASCII
* tab size: 8 (not used)
* indentation:4
*
* created on: 2001July05
* created by: George Rhoten
*/
#ifndef __UCLEAN_H__
#define __UCLEAN_H__
#include "unicode/utypes.h"
/**
* \file
* \brief C API: Initialize and clean up ICU
*/
/**
* Initialize ICU. The description further below applies to ICU 2.6 to ICU 3.4.
* Starting with ICU 3.4, u_init() needs not be called any more for
* ensuring thread safety, but it can give an indication for whether ICU
* can load its data. In ICU 3.4, it will try to load the converter alias table
* (cnvalias.icu) and give an error code if that fails.
* This may change in the future.
* <p>
* For ensuring the availability of necessary data, an application should
* open the service objects (converters, collators, etc.) that it will use
* and check for error codes there.
* <p>
* Documentation for ICU 2.6 to ICU 3.4:
* <p>
* This function loads and initializes data items
* that are required internally by various ICU functions. Use of this explicit
* initialization is required in multi-threaded applications; in
* single threaded apps, use is optional, but incurs little additional
* cost, and is thus recommended.
* <p>
* In multi-threaded applications, u_init() should be called in the
* main thread before starting additional threads, or, alternatively
* it can be called in each individual thread once, before other ICU
* functions are called in that thread. In this second scenario, the
* application must guarantee that the first call to u_init() happen
* without contention, in a single thread only.
* <p>
* If <code>u_setMemoryFunctions()</code> or
* <code>u_setMutexFunctions</code> are needed (uncommon), they must be
* called _before_ <code>u_init()</code>.
* <p>
* Extra, repeated, or otherwise unneeded calls to u_init() do no harm,
* other than taking a small amount of time.
*
* @param status An ICU UErrorCode parameter. It must not be <code>NULL</code>.
* An Error will be returned if some required part of ICU data can not
* be loaded or initialized.
* The function returns immediately if the input error code indicates a
* failure, as usual.
*
* @stable ICU 2.6
*/
U_STABLE void U_EXPORT2
u_init(UErrorCode *status);
/**
* Clean up the system resources, such as allocated memory or open files,
* used in all ICU libraries. This will free/delete all memory owned by the
* ICU libraries, and return them to their original load state. All open ICU
* items (collators, resource bundles, converters, etc.) must be closed before
* calling this function, otherwise ICU may not free its allocated memory
* (e.g. close your converters and resource bundles before calling this
* function). Generally, this function should be called once just before
* an application exits. For applications that dynamically load and unload
* the ICU libraries (relatively uncommon), u_cleanup() should be called
* just before the library unload.
* <p>
* u_cleanup() also clears any ICU heap functions, mutex functions or
* trace functions that may have been set for the process.
* This has the effect of restoring ICU to its initial condition, before
* any of these override functions were installed. Refer to
* u_setMemoryFunctions(), u_setMutexFunctions and
* utrace_setFunctions(). If ICU is to be reinitialized after after
* calling u_cleanup(), these runtime override functions will need to
* be set up again if they are still required.
* <p>
* u_cleanup() is not thread safe. All other threads should stop using ICU
* before calling this function.
* <p>
* Any open ICU items will be left in an undefined state by u_cleanup(),
* and any subsequent attempt to use such an item will give unpredictable
* results.
* <p>
* After calling u_cleanup(), an application may continue to use ICU by
* calling u_init(). An application must invoke u_init() first from one single
* thread before allowing other threads call u_init(). All threads existing
* at the time of the first thread's call to u_init() must also call
* u_init() themselves before continuing with other ICU operations.
* <p>
* The use of u_cleanup() just before an application terminates is optional,
* but it should be called only once for performance reasons. The primary
* benefit is to eliminate reports of memory or resource leaks originating
* in ICU code from the results generated by heap analysis tools.
* <p>
* <strong>Use this function with great care!</strong>
* </p>
*
* @stable ICU 2.0
* @system
*/
U_STABLE void U_EXPORT2
u_cleanup(void);
/**
* An opaque pointer type that represents an ICU mutex.
* For user-implemented mutexes, the value will typically point to a
* struct or object that implements the mutex.
* @stable ICU 2.8
* @system
*/
typedef void *UMTX;
/**
* Function Pointer type for a user supplied mutex initialization function.
* The user-supplied function will be called by ICU whenever ICU needs to create a
* new mutex. The function implementation should create a mutex, and store a pointer
* to something that uniquely identifies the mutex into the UMTX that is supplied
* as a paramter.
* @param context user supplied value, obtained from from u_setMutexFunctions().
* @param mutex Receives a pointer that identifies the new mutex.
* The mutex init function must set the UMTX to a non-null value.
* Subsequent calls by ICU to lock, unlock, or destroy a mutex will
* identify the mutex by the UMTX value.
* @param status Error status. Report errors back to ICU by setting this variable
* with an error code.
* @stable ICU 2.8
* @system
*/
typedef void U_CALLCONV UMtxInitFn (const void *context, UMTX *mutex, UErrorCode* status);
/**
* Function Pointer type for a user supplied mutex functions.
* One of the user-supplied functions with this signature will be called by ICU
* whenever ICU needs to lock, unlock, or destroy a mutex.
* @param context user supplied value, obtained from from u_setMutexFunctions().
* @param mutex specify the mutex on which to operate.
* @stable ICU 2.8
* @system
*/
typedef void U_CALLCONV UMtxFn (const void *context, UMTX *mutex);
/**
* Set the functions that ICU will use for mutex operations
* Use of this function is optional; by default (without this function), ICU will
* directly access system functions for mutex operations
* This function can only be used when ICU is in an initial, unused state, before
* u_init() has been called.
* This function may be used even when ICU has been built without multi-threaded
* support (see ICU_USE_THREADS pre-processor variable, umutex.h)
* @param context This pointer value will be saved, and then (later) passed as
* a parameter to the user-supplied mutex functions each time they
* are called.
* @param init Pointer to a mutex initialization function. Must be non-null.
* @param destroy Pointer to the mutex destroy function. Must be non-null.
* @param lock pointer to the mutex lock function. Must be non-null.
* @param unlock Pointer to the mutex unlock function. Must be non-null.
* @param status Receives error values.
* @stable ICU 2.8
* @system
*/
U_STABLE void U_EXPORT2
u_setMutexFunctions(const void *context, UMtxInitFn *init, UMtxFn *destroy, UMtxFn *lock, UMtxFn *unlock,
UErrorCode *status);
/**
* Pointer type for a user supplied atomic increment or decrement function.
* @param context user supplied value, obtained from from u_setAtomicIncDecFunctions().
* @param p Pointer to a 32 bit int to be incremented or decremented
* @return The value of the variable after the inc or dec operation.
* @stable ICU 2.8
* @system
*/
typedef int32_t U_CALLCONV UMtxAtomicFn(const void *context, int32_t *p);
/**
* Set the functions that ICU will use for atomic increment and decrement of int32_t values.
* Use of this function is optional; by default (without this function), ICU will
* use its own internal implementation of atomic increment/decrement.
* This function can only be used when ICU is in an initial, unused state, before
* u_init() has been called.
* @param context This pointer value will be saved, and then (later) passed as
* a parameter to the increment and decrement functions each time they
* are called. This function can only be called
* @param inc Pointer to a function to do an atomic increment operation. Must be non-null.
* @param dec Pointer to a function to do an atomic decrement operation. Must be non-null.
* @param status Receives error values.
* @stable ICU 2.8
* @system
*/
U_STABLE void U_EXPORT2
u_setAtomicIncDecFunctions(const void *context, UMtxAtomicFn *inc, UMtxAtomicFn *dec,
UErrorCode *status);
/**
* Pointer type for a user supplied memory allocation function.
* @param context user supplied value, obtained from from u_setMemoryFunctions().
* @param size The number of bytes to be allocated
* @return Pointer to the newly allocated memory, or NULL if the allocation failed.
* @stable ICU 2.8
* @system
*/
typedef void *U_CALLCONV UMemAllocFn(const void *context, size_t size);
/**
* Pointer type for a user supplied memory re-allocation function.
* @param context user supplied value, obtained from from u_setMemoryFunctions().
* @param size The number of bytes to be allocated
* @return Pointer to the newly allocated memory, or NULL if the allocation failed.
* @stable ICU 2.8
* @system
*/
typedef void *U_CALLCONV UMemReallocFn(const void *context, void *mem, size_t size);
/**
* Pointer type for a user supplied memory free function. Behavior should be
* similar the standard C library free().
* @param context user supplied value, obtained from from u_setMemoryFunctions().
* @param mem Pointer to the memory block to be resized
* @param size The new size for the block
* @return Pointer to the resized memory block, or NULL if the resizing failed.
* @stable ICU 2.8
* @system
*/
typedef void U_CALLCONV UMemFreeFn (const void *context, void *mem);
/**
* Set the functions that ICU will use for memory allocation.
* Use of this function is optional; by default (without this function), ICU will
* use the standard C library malloc() and free() functions.
* This function can only be used when ICU is in an initial, unused state, before
* u_init() has been called.
* @param context This pointer value will be saved, and then (later) passed as
* a parameter to the memory functions each time they
* are called.
* @param a Pointer to a user-supplied malloc function.
* @param r Pointer to a user-supplied realloc function.
* @param f Pointer to a user-supplied free function.
* @param status Receives error values.
* @stable ICU 2.8
* @system
*/
U_STABLE void U_EXPORT2
u_setMemoryFunctions(const void *context, UMemAllocFn *a, UMemReallocFn *r, UMemFreeFn *f,
UErrorCode *status);
#endif
File diff suppressed because it is too large Load Diff
+162
View File
@@ -0,0 +1,162 @@
/*
**********************************************************************
* Copyright (C) 2000-2004, International Business Machines
* Corporation and others. All Rights Reserved.
**********************************************************************
* ucnv_cb.h:
* External APIs for the ICU's codeset conversion library
* Helena Shih
*
* Modification History:
*
* Date Name Description
*/
/**
* \file
* \brief C UConverter functions to aid the writers of callbacks
*
* <h2> Callback API for UConverter </h2>
*
* These functions are provided here for the convenience of the callback
* writer. If you are just looking for callback functions to use, please
* see ucnv_err.h. DO NOT call these functions directly when you are
* working with converters, unless your code has been called as a callback
* via ucnv_setFromUCallback or ucnv_setToUCallback !!
*
* A note about error codes and overflow. Unlike other ICU functions,
* these functions do not expect the error status to be U_ZERO_ERROR.
* Callbacks must be much more careful about their error codes.
* The error codes used here are in/out parameters, which should be passed
* back in the callback's error parameter.
*
* For example, if you call ucnv_cbfromUWriteBytes to write data out
* to the output codepage, it may return U_BUFFER_OVERFLOW_ERROR if
* the data did not fit in the target. But this isn't a failing error,
* in fact, ucnv_cbfromUWriteBytes may be called AGAIN with the error
* status still U_BUFFER_OVERFLOW_ERROR to attempt to write further bytes,
* which will also go into the internal overflow buffers.
*
* Concerning offsets, the 'offset' parameters here are relative to the start
* of SOURCE. For example, Suppose the string "ABCD" was being converted
* from Unicode into a codepage which doesn't have a mapping for 'B'.
* 'A' will be written out correctly, but
* The FromU Callback will be called on an unassigned character for 'B'.
* At this point, this is the state of the world:
* Target: A [..] [points after A]
* Source: A B [C] D [points to C - B has been consumed]
* 0 1 2 3
* codePoint = "B" [the unassigned codepoint]
*
* Now, suppose a callback wants to write the substitution character '?' to
* the target. It calls ucnv_cbFromUWriteBytes() to write the ?.
* It should pass ZERO as the offset, because the offset as far as the
* callback is concerned is relative to the SOURCE pointer [which points
* before 'C'.] If the callback goes into the args and consumes 'C' also,
* it would call FromUWriteBytes with an offset of 1 (and advance the source
* pointer).
*
*/
#ifndef UCNV_CB_H
#define UCNV_CB_H
#include "unicode/utypes.h"
#if !UCONFIG_NO_CONVERSION
#include "unicode/ucnv.h"
#include "unicode/ucnv_err.h"
/**
* ONLY used by FromU callback functions.
* Writes out the specified byte output bytes to the target byte buffer or to converter internal buffers.
*
* @param args callback fromUnicode arguments
* @param source source bytes to write
* @param length length of bytes to write
* @param offsetIndex the relative offset index from callback.
* @param err error status. If <TT>U_BUFFER_OVERFLOW</TT> is returned, then U_BUFFER_OVERFLOW <STRONG>must</STRONG>
* be returned to the user, because it means that not all data could be written into the target buffer, and some is
* in the converter error buffer.
* @see ucnv_cbFromUWriteSub
* @stable ICU 2.0
*/
U_STABLE void U_EXPORT2
ucnv_cbFromUWriteBytes (UConverterFromUnicodeArgs *args,
const char* source,
int32_t length,
int32_t offsetIndex,
UErrorCode * err);
/**
* ONLY used by FromU callback functions.
* This function will write out the correct substitution character sequence
* to the target.
*
* @param args callback fromUnicode arguments
* @param offsetIndex the relative offset index from the current source pointer to be used
* @param err error status. If <TT>U_BUFFER_OVERFLOW</TT> is returned, then U_BUFFER_OVERFLOW <STRONG>must</STRONG>
* be returned to the user, because it means that not all data could be written into the target buffer, and some is
* in the converter error buffer.
* @see ucnv_cbFromUWriteBytes
* @stable ICU 2.0
*/
U_STABLE void U_EXPORT2
ucnv_cbFromUWriteSub (UConverterFromUnicodeArgs *args,
int32_t offsetIndex,
UErrorCode * err);
/**
* ONLY used by fromU callback functions.
* This function will write out the error character(s) to the target UChar buffer.
*
* @param args callback fromUnicode arguments
* @param source pointer to pointer to first UChar to write [on exit: 1 after last UChar processed]
* @param sourceLimit pointer after last UChar to write
* @param offsetIndex the relative offset index from callback which will be set
* @param err error status <TT>U_BUFFER_OVERFLOW</TT>
* @see ucnv_cbToUWriteSub
* @stable ICU 2.0
*/
U_STABLE void U_EXPORT2 ucnv_cbFromUWriteUChars(UConverterFromUnicodeArgs *args,
const UChar** source,
const UChar* sourceLimit,
int32_t offsetIndex,
UErrorCode * err);
/**
* ONLY used by ToU callback functions.
* This function will write out the specified characters to the target
* UChar buffer.
*
* @param args callback toUnicode arguments
* @param source source string to write
* @param length the length of source string
* @param offsetIndex the relative offset index which will be written.
* @param err error status <TT>U_BUFFER_OVERFLOW</TT>
* @see ucnv_cbToUWriteSub
* @stable ICU 2.0
*/
U_STABLE void U_EXPORT2 ucnv_cbToUWriteUChars (UConverterToUnicodeArgs *args,
const UChar* source,
int32_t length,
int32_t offsetIndex,
UErrorCode * err);
/**
* ONLY used by ToU callback functions.
* This function will write out the Unicode substitution character (U+FFFD).
*
* @param args callback fromUnicode arguments
* @param offsetIndex the relative offset index from callback.
* @param err error status <TT>U_BUFFER_OVERFLOW</TT>
* @see ucnv_cbToUWriteUChars
* @stable ICU 2.0
*/
U_STABLE void U_EXPORT2 ucnv_cbToUWriteSub (UConverterToUnicodeArgs *args,
int32_t offsetIndex,
UErrorCode * err);
#endif
#endif
+463
View File
@@ -0,0 +1,463 @@
/*
**********************************************************************
* Copyright (C) 1999-2009, International Business Machines
* Corporation and others. All Rights Reserved.
**********************************************************************
*
*
* ucnv_err.h:
*/
/**
* \file
* \brief C UConverter predefined error callbacks
*
* <h2>Error Behaviour Functions</h2>
* Defines some error behaviour functions called by ucnv_{from,to}Unicode
* These are provided as part of ICU and many are stable, but they
* can also be considered only as an example of what can be done with
* callbacks. You may of course write your own.
*
* If you want to write your own, you may also find the functions from
* ucnv_cb.h useful when writing your own callbacks.
*
* These functions, although public, should NEVER be called directly.
* They should be used as parameters to the ucnv_setFromUCallback
* and ucnv_setToUCallback functions, to set the behaviour of a converter
* when it encounters ILLEGAL/UNMAPPED/INVALID sequences.
*
* usage example: 'STOP' doesn't need any context, but newContext
* could be set to something other than 'NULL' if needed. The available
* contexts in this header can modify the default behavior of the callback.
*
* \code
* UErrorCode err = U_ZERO_ERROR;
* UConverter *myConverter = ucnv_open("ibm-949", &err);
* const void *oldContext;
* UConverterFromUCallback oldAction;
*
*
* if (U_SUCCESS(err))
* {
* ucnv_setFromUCallBack(myConverter,
* UCNV_FROM_U_CALLBACK_STOP,
* NULL,
* &oldAction,
* &oldContext,
* &status);
* }
* \endcode
*
* The code above tells "myConverter" to stop when it encounters an
* ILLEGAL/TRUNCATED/INVALID sequences when it is used to convert from
* Unicode -> Codepage. The behavior from Codepage to Unicode is not changed,
* and ucnv_setToUCallBack would need to be called in order to change
* that behavior too.
*
* Here is an example with a context:
*
* \code
* UErrorCode err = U_ZERO_ERROR;
* UConverter *myConverter = ucnv_open("ibm-949", &err);
* const void *oldContext;
* UConverterFromUCallback oldAction;
*
*
* if (U_SUCCESS(err))
* {
* ucnv_setToUCallBack(myConverter,
* UCNV_TO_U_CALLBACK_SUBSTITUTE,
* UCNV_SUB_STOP_ON_ILLEGAL,
* &oldAction,
* &oldContext,
* &status);
* }
* \endcode
*
* The code above tells "myConverter" to stop when it encounters an
* ILLEGAL/TRUNCATED/INVALID sequences when it is used to convert from
* Codepage -> Unicode. Any unmapped and legal characters will be
* substituted to be the default substitution character.
*/
#ifndef UCNV_ERR_H
#define UCNV_ERR_H
#include "unicode/utypes.h"
#if !UCONFIG_NO_CONVERSION
/** Forward declaring the UConverter structure. @stable ICU 2.0 */
struct UConverter;
/** @stable ICU 2.0 */
typedef struct UConverter UConverter;
/**
* FROM_U, TO_U context options for sub callback
* @stable ICU 2.0
*/
#define UCNV_SUB_STOP_ON_ILLEGAL "i"
/**
* FROM_U, TO_U context options for skip callback
* @stable ICU 2.0
*/
#define UCNV_SKIP_STOP_ON_ILLEGAL "i"
/**
* FROM_U_CALLBACK_ESCAPE context option to escape the code unit according to ICU (%UXXXX)
* @stable ICU 2.0
*/
#define UCNV_ESCAPE_ICU NULL
/**
* FROM_U_CALLBACK_ESCAPE context option to escape the code unit according to JAVA (\\uXXXX)
* @stable ICU 2.0
*/
#define UCNV_ESCAPE_JAVA "J"
/**
* FROM_U_CALLBACK_ESCAPE context option to escape the code unit according to C (\\uXXXX \\UXXXXXXXX)
* TO_U_CALLBACK_ESCAPE option to escape the character value accoding to C (\\xXXXX)
* @stable ICU 2.0
*/
#define UCNV_ESCAPE_C "C"
/**
* FROM_U_CALLBACK_ESCAPE context option to escape the code unit according to XML Decimal escape \htmlonly(&amp;#DDDD;)\endhtmlonly
* TO_U_CALLBACK_ESCAPE context option to escape the character value accoding to XML Decimal escape \htmlonly(&amp;#DDDD;)\endhtmlonly
* @stable ICU 2.0
*/
#define UCNV_ESCAPE_XML_DEC "D"
/**
* FROM_U_CALLBACK_ESCAPE context option to escape the code unit according to XML Hex escape \htmlonly(&amp;#xXXXX;)\endhtmlonly
* TO_U_CALLBACK_ESCAPE context option to escape the character value accoding to XML Hex escape \htmlonly(&amp;#xXXXX;)\endhtmlonly
* @stable ICU 2.0
*/
#define UCNV_ESCAPE_XML_HEX "X"
/**
* FROM_U_CALLBACK_ESCAPE context option to escape the code unit according to Unicode (U+XXXXX)
* @stable ICU 2.0
*/
#define UCNV_ESCAPE_UNICODE "U"
/**
* FROM_U_CALLBACK_ESCAPE context option to escape the code unit according to CSS2 conventions (\\HH..H<space>, that is,
* a backslash, 1..6 hex digits, and a space)
* @stable ICU 4.0
*/
#define UCNV_ESCAPE_CSS2 "S"
/**
* The process condition code to be used with the callbacks.
* Codes which are greater than UCNV_IRREGULAR should be
* passed on to any chained callbacks.
* @stable ICU 2.0
*/
typedef enum {
UCNV_UNASSIGNED = 0, /**< The code point is unassigned.
The error code U_INVALID_CHAR_FOUND will be set. */
UCNV_ILLEGAL = 1, /**< The code point is illegal. For example,
\\x81\\x2E is illegal in SJIS because \\x2E
is not a valid trail byte for the \\x81
lead byte.
Also, starting with Unicode 3.0.1, non-shortest byte sequences
in UTF-8 (like \\xC1\\xA1 instead of \\x61 for U+0061)
are also illegal, not just irregular.
The error code U_ILLEGAL_CHAR_FOUND will be set. */
UCNV_IRREGULAR = 2, /**< The codepoint is not a regular sequence in
the encoding. For example, \\xED\\xA0\\x80..\\xED\\xBF\\xBF
are irregular UTF-8 byte sequences for single surrogate
code points.
The error code U_INVALID_CHAR_FOUND will be set. */
UCNV_RESET = 3, /**< The callback is called with this reason when a
'reset' has occured. Callback should reset all
state. */
UCNV_CLOSE = 4, /**< Called when the converter is closed. The
callback should release any allocated memory.*/
UCNV_CLONE = 5 /**< Called when ucnv_safeClone() is called on the
converter. the pointer available as the
'context' is an alias to the original converters'
context pointer. If the context must be owned
by the new converter, the callback must clone
the data and call ucnv_setFromUCallback
(or setToUCallback) with the correct pointer.
@stable ICU 2.2
*/
} UConverterCallbackReason;
/**
* The structure for the fromUnicode callback function parameter.
* @stable ICU 2.0
*/
typedef struct {
uint16_t size; /**< The size of this struct. @stable ICU 2.0 */
UBool flush; /**< The internal state of converter will be reset and data flushed if set to TRUE. @stable ICU 2.0 */
UConverter *converter; /**< Pointer to the converter that is opened and to which this struct is passed as an argument. @stable ICU 2.0 */
const UChar *source; /**< Pointer to the source source buffer. @stable ICU 2.0 */
const UChar *sourceLimit; /**< Pointer to the limit (end + 1) of source buffer. @stable ICU 2.0 */
char *target; /**< Pointer to the target buffer. @stable ICU 2.0 */
const char *targetLimit; /**< Pointer to the limit (end + 1) of target buffer. @stable ICU 2.0 */
int32_t *offsets; /**< Pointer to the buffer that recieves the offsets. *offset = blah ; offset++;. @stable ICU 2.0 */
} UConverterFromUnicodeArgs;
/**
* The structure for the toUnicode callback function parameter.
* @stable ICU 2.0
*/
typedef struct {
uint16_t size; /**< The size of this struct @stable ICU 2.0 */
UBool flush; /**< The internal state of converter will be reset and data flushed if set to TRUE. @stable ICU 2.0 */
UConverter *converter; /**< Pointer to the converter that is opened and to which this struct is passed as an argument. @stable ICU 2.0 */
const char *source; /**< Pointer to the source source buffer. @stable ICU 2.0 */
const char *sourceLimit; /**< Pointer to the limit (end + 1) of source buffer. @stable ICU 2.0 */
UChar *target; /**< Pointer to the target buffer. @stable ICU 2.0 */
const UChar *targetLimit; /**< Pointer to the limit (end + 1) of target buffer. @stable ICU 2.0 */
int32_t *offsets; /**< Pointer to the buffer that recieves the offsets. *offset = blah ; offset++;. @stable ICU 2.0 */
} UConverterToUnicodeArgs;
/**
* DO NOT CALL THIS FUNCTION DIRECTLY!
* This From Unicode callback STOPS at the ILLEGAL_SEQUENCE,
* returning the error code back to the caller immediately.
*
* @param context Pointer to the callback's private data
* @param fromUArgs Information about the conversion in progress
* @param codeUnits Points to 'length' UChars of the concerned Unicode sequence
* @param length Size (in bytes) of the concerned codepage sequence
* @param codePoint Single UChar32 (UTF-32) containing the concerend Unicode codepoint.
* @param reason Defines the reason the callback was invoked
* @param err This should always be set to a failure status prior to calling.
* @stable ICU 2.0
*/
U_STABLE void U_EXPORT2 UCNV_FROM_U_CALLBACK_STOP (
const void *context,
UConverterFromUnicodeArgs *fromUArgs,
const UChar* codeUnits,
int32_t length,
UChar32 codePoint,
UConverterCallbackReason reason,
UErrorCode * err);
/**
* DO NOT CALL THIS FUNCTION DIRECTLY!
* This To Unicode callback STOPS at the ILLEGAL_SEQUENCE,
* returning the error code back to the caller immediately.
*
* @param context Pointer to the callback's private data
* @param toUArgs Information about the conversion in progress
* @param codeUnits Points to 'length' bytes of the concerned codepage sequence
* @param length Size (in bytes) of the concerned codepage sequence
* @param reason Defines the reason the callback was invoked
* @param err This should always be set to a failure status prior to calling.
* @stable ICU 2.0
*/
U_STABLE void U_EXPORT2 UCNV_TO_U_CALLBACK_STOP (
const void *context,
UConverterToUnicodeArgs *toUArgs,
const char* codeUnits,
int32_t length,
UConverterCallbackReason reason,
UErrorCode * err);
/**
* DO NOT CALL THIS FUNCTION DIRECTLY!
* This From Unicode callback skips any ILLEGAL_SEQUENCE, or
* skips only UNASSINGED_SEQUENCE depending on the context parameter
* simply ignoring those characters.
*
* @param context The function currently recognizes the callback options:
* UCNV_SKIP_STOP_ON_ILLEGAL: STOPS at the ILLEGAL_SEQUENCE,
* returning the error code back to the caller immediately.
* NULL: Skips any ILLEGAL_SEQUENCE
* @param fromUArgs Information about the conversion in progress
* @param codeUnits Points to 'length' UChars of the concerned Unicode sequence
* @param length Size (in bytes) of the concerned codepage sequence
* @param codePoint Single UChar32 (UTF-32) containing the concerend Unicode codepoint.
* @param reason Defines the reason the callback was invoked
* @param err Return value will be set to success if the callback was handled,
* otherwise this value will be set to a failure status.
* @stable ICU 2.0
*/
U_STABLE void U_EXPORT2 UCNV_FROM_U_CALLBACK_SKIP (
const void *context,
UConverterFromUnicodeArgs *fromUArgs,
const UChar* codeUnits,
int32_t length,
UChar32 codePoint,
UConverterCallbackReason reason,
UErrorCode * err);
/**
* DO NOT CALL THIS FUNCTION DIRECTLY!
* This From Unicode callback will Substitute the ILLEGAL SEQUENCE, or
* UNASSIGNED_SEQUENCE depending on context parameter, with the
* current substitution string for the converter. This is the default
* callback.
*
* @param context The function currently recognizes the callback options:
* UCNV_SUB_STOP_ON_ILLEGAL: STOPS at the ILLEGAL_SEQUENCE,
* returning the error code back to the caller immediately.
* NULL: Substitutes any ILLEGAL_SEQUENCE
* @param fromUArgs Information about the conversion in progress
* @param codeUnits Points to 'length' UChars of the concerned Unicode sequence
* @param length Size (in bytes) of the concerned codepage sequence
* @param codePoint Single UChar32 (UTF-32) containing the concerend Unicode codepoint.
* @param reason Defines the reason the callback was invoked
* @param err Return value will be set to success if the callback was handled,
* otherwise this value will be set to a failure status.
* @see ucnv_setSubstChars
* @stable ICU 2.0
*/
U_STABLE void U_EXPORT2 UCNV_FROM_U_CALLBACK_SUBSTITUTE (
const void *context,
UConverterFromUnicodeArgs *fromUArgs,
const UChar* codeUnits,
int32_t length,
UChar32 codePoint,
UConverterCallbackReason reason,
UErrorCode * err);
/**
* DO NOT CALL THIS FUNCTION DIRECTLY!
* This From Unicode callback will Substitute the ILLEGAL SEQUENCE with the
* hexadecimal representation of the illegal codepoints
*
* @param context The function currently recognizes the callback options:
* <ul>
* <li>UCNV_ESCAPE_ICU: Substitues the ILLEGAL SEQUENCE with the hexadecimal
* representation in the format %UXXXX, e.g. "%uFFFE%u00AC%uC8FE").
* In the Event the converter doesn't support the characters {%,U}[A-F][0-9],
* it will substitute the illegal sequence with the substitution characters.
* Note that codeUnit(32bit int eg: unit of a surrogate pair) is represented as
* %UD84D%UDC56</li>
* <li>UCNV_ESCAPE_JAVA: Substitues the ILLEGAL SEQUENCE with the hexadecimal
* representation in the format \\uXXXX, e.g. "\\uFFFE\\u00AC\\uC8FE").
* In the Event the converter doesn't support the characters {\,u}[A-F][0-9],
* it will substitute the illegal sequence with the substitution characters.
* Note that codeUnit(32bit int eg: unit of a surrogate pair) is represented as
* \\uD84D\\uDC56</li>
* <li>UCNV_ESCAPE_C: Substitues the ILLEGAL SEQUENCE with the hexadecimal
* representation in the format \\uXXXX, e.g. "\\uFFFE\\u00AC\\uC8FE").
* In the Event the converter doesn't support the characters {\,u,U}[A-F][0-9],
* it will substitute the illegal sequence with the substitution characters.
* Note that codeUnit(32bit int eg: unit of a surrogate pair) is represented as
* \\U00023456</li>
* <li>UCNV_ESCAPE_XML_DEC: Substitues the ILLEGAL SEQUENCE with the decimal
* representation in the format \htmlonly&amp;#DDDDDDDD;, e.g. "&amp;#65534;&amp;#172;&amp;#51454;")\endhtmlonly.
* In the Event the converter doesn't support the characters {&amp;,#}[0-9],
* it will substitute the illegal sequence with the substitution characters.
* Note that codeUnit(32bit int eg: unit of a surrogate pair) is represented as
* &amp;#144470; and Zero padding is ignored.</li>
* <li>UCNV_ESCAPE_XML_HEX:Substitues the ILLEGAL SEQUENCE with the decimal
* representation in the format \htmlonly&amp;#xXXXX; e.g. "&amp;#xFFFE;&amp;#x00AC;&amp;#xC8FE;")\endhtmlonly.
* In the Event the converter doesn't support the characters {&,#,x}[0-9],
* it will substitute the illegal sequence with the substitution characters.
* Note that codeUnit(32bit int eg: unit of a surrogate pair) is represented as
* \htmlonly&amp;#x23456;\endhtmlonly</li>
* </ul>
* @param fromUArgs Information about the conversion in progress
* @param codeUnits Points to 'length' UChars of the concerned Unicode sequence
* @param length Size (in bytes) of the concerned codepage sequence
* @param codePoint Single UChar32 (UTF-32) containing the concerend Unicode codepoint.
* @param reason Defines the reason the callback was invoked
* @param err Return value will be set to success if the callback was handled,
* otherwise this value will be set to a failure status.
* @stable ICU 2.0
*/
U_STABLE void U_EXPORT2 UCNV_FROM_U_CALLBACK_ESCAPE (
const void *context,
UConverterFromUnicodeArgs *fromUArgs,
const UChar* codeUnits,
int32_t length,
UChar32 codePoint,
UConverterCallbackReason reason,
UErrorCode * err);
/**
* DO NOT CALL THIS FUNCTION DIRECTLY!
* This To Unicode callback skips any ILLEGAL_SEQUENCE, or
* skips only UNASSINGED_SEQUENCE depending on the context parameter
* simply ignoring those characters.
*
* @param context The function currently recognizes the callback options:
* UCNV_SKIP_STOP_ON_ILLEGAL: STOPS at the ILLEGAL_SEQUENCE,
* returning the error code back to the caller immediately.
* NULL: Skips any ILLEGAL_SEQUENCE
* @param toUArgs Information about the conversion in progress
* @param codeUnits Points to 'length' bytes of the concerned codepage sequence
* @param length Size (in bytes) of the concerned codepage sequence
* @param reason Defines the reason the callback was invoked
* @param err Return value will be set to success if the callback was handled,
* otherwise this value will be set to a failure status.
* @stable ICU 2.0
*/
U_STABLE void U_EXPORT2 UCNV_TO_U_CALLBACK_SKIP (
const void *context,
UConverterToUnicodeArgs *toUArgs,
const char* codeUnits,
int32_t length,
UConverterCallbackReason reason,
UErrorCode * err);
/**
* DO NOT CALL THIS FUNCTION DIRECTLY!
* This To Unicode callback will Substitute the ILLEGAL SEQUENCE,or
* UNASSIGNED_SEQUENCE depending on context parameter, with the
* Unicode substitution character, U+FFFD.
*
* @param context The function currently recognizes the callback options:
* UCNV_SUB_STOP_ON_ILLEGAL: STOPS at the ILLEGAL_SEQUENCE,
* returning the error code back to the caller immediately.
* NULL: Substitutes any ILLEGAL_SEQUENCE
* @param toUArgs Information about the conversion in progress
* @param codeUnits Points to 'length' bytes of the concerned codepage sequence
* @param length Size (in bytes) of the concerned codepage sequence
* @param reason Defines the reason the callback was invoked
* @param err Return value will be set to success if the callback was handled,
* otherwise this value will be set to a failure status.
* @stable ICU 2.0
*/
U_STABLE void U_EXPORT2 UCNV_TO_U_CALLBACK_SUBSTITUTE (
const void *context,
UConverterToUnicodeArgs *toUArgs,
const char* codeUnits,
int32_t length,
UConverterCallbackReason reason,
UErrorCode * err);
/**
* DO NOT CALL THIS FUNCTION DIRECTLY!
* This To Unicode callback will Substitute the ILLEGAL SEQUENCE with the
* hexadecimal representation of the illegal bytes
* (in the format %XNN, e.g. "%XFF%X0A%XC8%X03").
*
* @param context This function currently recognizes the callback options:
* UCNV_ESCAPE_ICU, UCNV_ESCAPE_JAVA, UCNV_ESCAPE_C, UCNV_ESCAPE_XML_DEC,
* UCNV_ESCAPE_XML_HEX and UCNV_ESCAPE_UNICODE.
* @param toUArgs Information about the conversion in progress
* @param codeUnits Points to 'length' bytes of the concerned codepage sequence
* @param length Size (in bytes) of the concerned codepage sequence
* @param reason Defines the reason the callback was invoked
* @param err Return value will be set to success if the callback was handled,
* otherwise this value will be set to a failure status.
* @stable ICU 2.0
*/
U_STABLE void U_EXPORT2 UCNV_TO_U_CALLBACK_ESCAPE (
const void *context,
UConverterToUnicodeArgs *toUArgs,
const char* codeUnits,
int32_t length,
UConverterCallbackReason reason,
UErrorCode * err);
#endif
#endif
/*UCNV_ERR_H*/
+162
View File
@@ -0,0 +1,162 @@
/*
*******************************************************************************
*
* Copyright (C) 2008, International Business Machines
* Corporation, Google and others. All Rights Reserved.
*
*******************************************************************************
*/
/*
* Author : [email protected] (Mohamed Eldawy)
* ucnvsel.h
*
* Purpose: To generate a list of encodings capable of handling
* a given Unicode text
*
* Started 09-April-2008
*/
#ifndef __ICU_UCNV_SEL_H__
#define __ICU_UCNV_SEL_H__
#include "unicode/uset.h"
#include "unicode/utypes.h"
#include "unicode/utf16.h"
#include "unicode/uenum.h"
#include "unicode/ucnv.h"
/**
* \file
*
* A converter selector is built with a set of encoding/charset names
* and given an input string returns the set of names of the
* corresponding converters which can convert the string.
*
* A converter selector can be serialized into a buffer and reopened
* from the serialized form.
*/
/**
* @{
* The selector data structure
*/
struct UConverterSelector;
typedef struct UConverterSelector UConverterSelector;
/** @} */
/**
* Open a selector.
* If converterListSize is 0, build for all available converters.
* If excludedCodePoints is NULL, don't exclude any code points.
*
* @param converterList a pointer to encoding names needed to be involved.
* Can be NULL if converterListSize==0.
* The list and the names will be cloned, and the caller
* retains ownership of the original.
* @param converterListSize number of encodings in above list.
* If 0, builds a selector for all available converters.
* @param excludedCodePoints a set of code points to be excluded from consideration.
* That is, excluded code points in a string do not change
* the selection result. (They might be handled by a callback.)
* Use NULL to exclude nothing.
* @param whichSet what converter set to use? Use this to determine whether
* to consider only roundtrip mappings or also fallbacks.
* @param status an in/out ICU UErrorCode
* @return the new selector
*
* @draft ICU 4.2
*/
U_CAPI UConverterSelector* U_EXPORT2
ucnvsel_open(const char* const* converterList, int32_t converterListSize,
const USet* excludedCodePoints,
const UConverterUnicodeSet whichSet, UErrorCode* status);
/**
* Closes a selector.
* If any Enumerations were returned by ucnv_select*, they become invalid.
* They can be closed before or after calling ucnv_closeSelector,
* but should never be used after the selector is closed.
*
* @see ucnv_selectForString
* @see ucnv_selectForUTF8
*
* @param sel selector to close
*
* @draft ICU 4.2
*/
U_CAPI void U_EXPORT2
ucnvsel_close(UConverterSelector *sel);
/**
* Open a selector from its serialized form.
* The buffer must remain valid and unchanged for the lifetime of the selector.
* This is much faster than creating a selector from scratch.
* Using a serialized form from a different machine (endianness/charset) is supported.
*
* @param buffer pointer to the serialized form of a converter selector;
* must be 32-bit-aligned
* @param length the capacity of this buffer (can be equal to or larger than
* the actual data length)
* @param status an in/out ICU UErrorCode
* @return the new selector
*
* @draft ICU 4.2
*/
U_CAPI UConverterSelector* U_EXPORT2
ucnvsel_openFromSerialized(const void* buffer, int32_t length, UErrorCode* status);
/**
* Serialize a selector into a linear buffer.
* The serialized form is portable to different machines.
*
* @param sel selector to consider
* @param buffer pointer to 32-bit-aligned memory to be filled with the
* serialized form of this converter selector
* @param bufferCapacity the capacity of this buffer
* @param status an in/out ICU UErrorCode
* @return the required buffer capacity to hold serialize data (even if the call fails
* with a U_BUFFER_OVERFLOW_ERROR, it will return the required capacity)
*
* @draft ICU 4.2
*/
U_CAPI int32_t U_EXPORT2
ucnvsel_serialize(const UConverterSelector* sel,
void* buffer, int32_t bufferCapacity, UErrorCode* status);
/**
* Select converters that can map all characters in a UTF-16 string,
* ignoring the excluded code points.
*
* @param sel a selector
* @param s UTF-16 string
* @param length length of the string, or -1 if NUL-terminated
* @param status an in/out ICU UErrorCode
* @return an enumeration containing encoding names.
* The returned encoding names and their order will be the same as
* supplied when building the selector.
*
* @draft ICU 4.2
*/
U_CAPI UEnumeration * U_EXPORT2
ucnvsel_selectForString(const UConverterSelector* sel,
const UChar *s, int32_t length, UErrorCode *status);
/**
* Select converters that can map all characters in a UTF-8 string,
* ignoring the excluded code points.
*
* @param sel a selector
* @param s UTF-8 string
* @param length length of the string, or -1 if NUL-terminated
* @param status an in/out ICU UErrorCode
* @return an enumeration containing encoding names.
* The returned encoding names and their order will be the same as
* supplied when building the selector.
*
* @draft ICU 4.2
*/
U_CAPI UEnumeration * U_EXPORT2
ucnvsel_selectForUTF8(const UConverterSelector* sel,
const char *s, int32_t length, UErrorCode *status);
#endif /* __ICU_UCNV_SEL_H__ */
File diff suppressed because it is too large Load Diff
+330
View File
@@ -0,0 +1,330 @@
/*
*******************************************************************************
* Copyright (C) 2001-2009, International Business Machines
* Corporation and others. All Rights Reserved.
*******************************************************************************
*
* File ucoleitr.cpp
*
* 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 occured during processing or if no more CEs is
* to be returned.
* @stable ICU 2.0
*/
#define UCOL_NULLORDER ((int32_t)0xFFFFFFFF)
/**
* This indicates an error has occured during processing or there are no more CEs
* to be returned.
*
* @internal
*/
#define UCOL_PROCESSED_NULLORDER ((int64_t)U_INT64_MAX)
#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 Spanish:
* <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,
* <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;
* . s=(UChar*)malloc(sizeof(UChar) * (strlen("This is a test")+1) );
* . u_uastrcpy(s, "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(s);
* . 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 UCOL_IGNORABLE 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>t_int32</strong>.
*
* @see UCollator
*/
/**
* Open the collation elements for a string.
*
* @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 an UErrorCode to receive any errors.
* @return a struct containing collation element information
* @stable ICU 2.0
*/
U_STABLE 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_STABLE 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_STABLE 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_STABLE void U_EXPORT2
ucol_reset(UCollationElements *elems);
/**
* Set the collation elements to use implicit ordering for Han
* even if they've been tailored. This will also force Hangul
* syllables to be ordered by decomposing them to their component
* Jamo.
*
* @param elems The UCollationElements containing the text.
* @param status A pointer to a UErrorCode to reveive any errors.
*
* @internal
*/
U_INTERNAL void U_EXPORT2
ucol_forceHanImplicit(UCollationElements *elems, UErrorCode *status);
/**
* 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 an UErrorCode to receive any errors.
* @return The next collation elements ordering, otherwise returns NULLORDER
* if an error has occured or if the end of string has been reached
* @stable ICU 2.0
*/
U_STABLE 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.
* It is very rare that the stack will overflow, however if such a case is
* encountered, the problem can be solved by increasing the size
* UCOL_EXPAND_CE_BUFFER_SIZE in ucol_imp.h.
* @param elems The UCollationElements containing the text.
* @param status A pointer to an UErrorCode to receive any errors. Noteably
* a U_BUFFER_OVERFLOW_ERROR is returned if the internal stack
* buffer has been exhausted.
* @return The previous collation elements ordering, otherwise returns
* NULLORDER if an error has occured or if the start of string has
* been reached.
* @stable ICU 2.0
*/
U_STABLE int32_t U_EXPORT2
ucol_previous(UCollationElements *elems, UErrorCode *status);
/**
* Get the processed 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 ixLow a pointer to an int32_t to receive the iterator index before fetching the CE.
* @param ixHigh a pointer to an int32_t to receive the iterator index after fetching the CE.
* @param status A pointer to an UErrorCode to receive any errors.
* @return The next collation elements ordering, otherwise returns UCOL_PROCESSED_NULLORDER
* if an error has occured or if the end of string has been reached
*
* @internal
*/
U_INTERNAL int64_t U_EXPORT2
ucol_nextProcessed(UCollationElements *elems, int32_t *ixLow, int32_t *ixHigh, UErrorCode *status);
/**
* Get the processed 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.
* It is very rare that the stack will overflow, however if such a case is
* encountered, the problem can be solved by increasing the size
* UCOL_EXPAND_CE_BUFFER_SIZE in ucol_imp.h.
*
* @param elems The UCollationElements containing the text.
* @param ixLow A pointer to an int32_t to receive the iterator index after fetching the CE
* @param ixHigh A pointer to an int32_t to receiver the iterator index before fetching the CE
* @param status A pointer to an UErrorCode to receive any errors. Noteably
* a U_BUFFER_OVERFLOW_ERROR is returned if the internal stack
* buffer has been exhausted.
* @return The previous collation elements ordering, otherwise returns
* UCOL_PROCESSED_NULLORDER if an error has occured or if the start of
* string has been reached.
*
* @internal
*/
U_INTERNAL int64_t U_EXPORT2
ucol_previousProcessed(UCollationElements *elems, int32_t *ixLow, int32_t *ixHigh, 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_STABLE 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.
* @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 an UErrorCode to receive any errors.
* @see ucol_getText
* @stable ICU 2.0
*/
U_STABLE 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_STABLE 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 an UErrorCode to receive any errors.
* @see ucol_getOffset
* @stable ICU 2.0
*/
U_STABLE 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_STABLE 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_STABLE 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_STABLE int32_t U_EXPORT2
ucol_tertiaryOrder (int32_t order);
#endif /* #if !UCONFIG_NO_COLLATION */
#endif
+231
View File
@@ -0,0 +1,231 @@
/*
**********************************************************************
* Copyright (C) 2002-2009, International Business Machines
* Corporation and others. All Rights Reserved.
**********************************************************************
* file name: uconfig.h
* encoding: US-ASCII
* tab size: 8 (not used)
* indentation:4
*
* created on: 2002sep19
* created by: Markus W. Scherer
*/
#ifndef __UCONFIG_H__
#define __UCONFIG_H__
/*!
* \file
* \brief Switches for excluding parts of ICU library code modules.
*
* Allows to build partial, smaller libraries for special purposes.
* By default, all modules are built.
* The switches are fairly coarse, controlling large modules.
* Basic services cannot be turned off.
*
* Building with any of these options does not guarantee that the
* ICU build process will completely work. It is recommended that
* the ICU libraries and data be built using the normal build.
* At that time you should remove the data used by those services.
* After building the ICU data library, you should rebuild the ICU
* libraries with these switches customized to your needs.
*
* @stable ICU 2.4
*/
/**
* If this switch is defined, ICU will attempt to load a header file named "uconfig_local.h"
* prior to determining default settings for uconfig variables.
*
* @internal ICU 4.0
*
*/
#if defined(UCONFIG_USE_LOCAL)
#include "uconfig_local.h"
#endif
/**
* \def UCONFIG_ONLY_COLLATION
* This switch turns off modules that are not needed for collation.
*
* It does not turn off legacy conversion because that is necessary
* for ICU to work on EBCDIC platforms (for the default converter).
* If you want "only collation" and do not build for EBCDIC,
* then you can define UCONFIG_NO_LEGACY_CONVERSION 1 as well.
*
* @stable ICU 2.4
*/
#ifndef UCONFIG_ONLY_COLLATION
# define UCONFIG_ONLY_COLLATION 0
#endif
#if UCONFIG_ONLY_COLLATION
/* common library */
# define UCONFIG_NO_BREAK_ITERATION 1
# define UCONFIG_NO_IDNA 1
/* i18n library */
# if UCONFIG_NO_COLLATION
# error Contradictory collation switches in uconfig.h.
# endif
# define UCONFIG_NO_FORMATTING 1
# define UCONFIG_NO_TRANSLITERATION 1
# define UCONFIG_NO_REGULAR_EXPRESSIONS 1
#endif
/* common library switches -------------------------------------------------- */
/**
* \def UCONFIG_NO_FILE_IO
* This switch turns off all file access in the common library
* where file access is only used for data loading.
* ICU data must then be provided in the form of a data DLL (or with an
* equivalent way to link to the data residing in an executable,
* as in building a combined library with both the common library's code and
* the data), or via udata_setCommonData().
* Application data must be provided via udata_setAppData() or by using
* "open" functions that take pointers to data, for example ucol_openBinary().
*
* File access is not used at all in the i18n library.
*
* File access cannot be turned off for the icuio library or for the ICU
* test suites and ICU tools.
*
* @stable ICU 3.6
*/
#ifndef UCONFIG_NO_FILE_IO
# define UCONFIG_NO_FILE_IO 0
#endif
/**
* \def UCONFIG_NO_CONVERSION
* ICU will not completely build with this switch turned on.
* This switch turns off all converters.
*
* You may want to use this together with U_CHARSET_IS_UTF8 defined to 1
* in utypes.h if char* strings in your environment are always in UTF-8.
*
* @stable ICU 3.2
* @see U_CHARSET_IS_UTF8
*/
#ifndef UCONFIG_NO_CONVERSION
# define UCONFIG_NO_CONVERSION 0
#endif
#if UCONFIG_NO_CONVERSION
# define UCONFIG_NO_LEGACY_CONVERSION 1
#endif
/**
* \def UCONFIG_NO_LEGACY_CONVERSION
* This switch turns off all converters except for
* - Unicode charsets (UTF-7/8/16/32, CESU-8, SCSU, BOCU-1)
* - US-ASCII
* - ISO-8859-1
*
* Turning off legacy conversion is not possible on EBCDIC platforms
* because they need ibm-37 or ibm-1047 default converters.
*
* @stable ICU 2.4
*/
#ifndef UCONFIG_NO_LEGACY_CONVERSION
# define UCONFIG_NO_LEGACY_CONVERSION 0
#endif
/**
* \def UCONFIG_NO_NORMALIZATION
* This switch turns off normalization.
* It implies turning off several other services as well, for example
* collation and IDNA.
*
* @stable ICU 2.6
*/
#ifndef UCONFIG_NO_NORMALIZATION
# define UCONFIG_NO_NORMALIZATION 0
#elif UCONFIG_NO_NORMALIZATION
/* common library */
# define UCONFIG_NO_IDNA 1
/* i18n library */
# if UCONFIG_ONLY_COLLATION
# error Contradictory collation switches in uconfig.h.
# endif
# define UCONFIG_NO_COLLATION 1
# define UCONFIG_NO_TRANSLITERATION 1
#endif
/**
* \def UCONFIG_NO_BREAK_ITERATION
* This switch turns off break iteration.
*
* @stable ICU 2.4
*/
#ifndef UCONFIG_NO_BREAK_ITERATION
# define UCONFIG_NO_BREAK_ITERATION 0
#endif
/**
* \def UCONFIG_NO_IDNA
* This switch turns off IDNA.
*
* @stable ICU 2.6
*/
#ifndef UCONFIG_NO_IDNA
# define UCONFIG_NO_IDNA 0
#endif
/* i18n library switches ---------------------------------------------------- */
/**
* \def UCONFIG_NO_COLLATION
* This switch turns off collation and collation-based string search.
*
* @stable ICU 2.4
*/
#ifndef UCONFIG_NO_COLLATION
# define UCONFIG_NO_COLLATION 0
#endif
/**
* \def UCONFIG_NO_FORMATTING
* This switch turns off formatting and calendar/timezone services.
*
* @stable ICU 2.4
*/
#ifndef UCONFIG_NO_FORMATTING
# define UCONFIG_NO_FORMATTING 0
#endif
/**
* \def UCONFIG_NO_TRANSLITERATION
* This switch turns off transliteration.
*
* @stable ICU 2.4
*/
#ifndef UCONFIG_NO_TRANSLITERATION
# define UCONFIG_NO_TRANSLITERATION 0
#endif
/**
* \def UCONFIG_NO_REGULAR_EXPRESSIONS
* This switch turns off regular expressions.
*
* @stable ICU 2.4
*/
#ifndef UCONFIG_NO_REGULAR_EXPRESSIONS
# define UCONFIG_NO_REGULAR_EXPRESSIONS 0
#endif
/**
* \def UCONFIG_NO_SERVICE
* This switch turns off service registration.
*
* @stable ICU 3.2
*/
#ifndef UCONFIG_NO_SERVICE
# define UCONFIG_NO_SERVICE 0
#endif
#endif
+349
View File
@@ -0,0 +1,349 @@
/*
**********************************************************************
* Copyright (C) 2005-2007, International Business Machines
* Corporation and others. All Rights Reserved.
**********************************************************************
* file name: ucsdet.h
* encoding: US-ASCII
* 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"
/**
* \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.
*/
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_STABLE 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_STABLE void U_EXPORT2
ucsdet_close(UCharsetDetector *ucsd);
/**
* 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_STABLE 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_STABLE 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_STABLE 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_STABLE 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_STABLE 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_STABLE 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_STABLE 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_STABLE 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.
*
* 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.
*
* @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_STABLE 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_STABLE 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_STABLE UBool U_EXPORT2
ucsdet_enableInputFilter(UCharsetDetector *ucsd, UBool filter);
#endif
#endif /* __UCSDET_H */
+316
View File
@@ -0,0 +1,316 @@
/*
**********************************************************************
* Copyright (c) 2002-2009, International Business Machines
* Corporation and others. All Rights Reserved.
**********************************************************************
*/
#ifndef _UCURR_H_
#define _UCURR_H_
#include "unicode/utypes.h"
#include "unicode/uenum.h"
/**
* \file
* \brief C API: Encapsulates information about a currency.
*/
#if !UCONFIG_NO_FORMATTING
/**
* The ucurr API encapsulates information about a currency, as defined by
* ISO 4217. A currency is represented by a 3-character string
* containing its ISO 4217 code. This API can return various data
* necessary the proper display of a currency:
*
* <ul><li>A display symbol, for a specific locale
* <li>The number of fraction digits to display
* <li>A rounding increment
* </ul>
*
* The <tt>DecimalFormat</tt> class uses these data to display
* currencies.
* @author Alan Liu
* @since ICU 2.2
*/
/**
* Finds a currency code for the given locale.
* @param locale the locale for which to retrieve a currency code.
* Currency can be specified by the "currency" keyword
* in which case it overrides the default currency code
* @param buff fill in buffer. Can be NULL for preflighting.
* @param buffCapacity capacity of the fill in buffer. Can be 0 for
* preflighting. If it is non-zero, the buff parameter
* must not be NULL.
* @param ec error code
* @return length of the currency string. It should always be 3. If 0,
* currency couldn't be found or the input values are
* invalid.
* @stable ICU 2.8
*/
U_STABLE int32_t U_EXPORT2
ucurr_forLocale(const char* locale,
UChar* buff,
int32_t buffCapacity,
UErrorCode* ec);
/**
* Selector constants for ucurr_getName().
*
* @see ucurr_getName
* @stable ICU 2.6
*/
typedef enum UCurrNameStyle {
/**
* Selector for ucurr_getName indicating a symbolic name for a
* currency, such as "$" for USD.
* @stable ICU 2.6
*/
UCURR_SYMBOL_NAME,
/**
* Selector for ucurr_getName indicating the long name for a
* currency, such as "US Dollar" for USD.
* @stable ICU 2.6
*/
UCURR_LONG_NAME
} UCurrNameStyle;
#if !UCONFIG_NO_SERVICE
/**
* @stable ICU 2.6
*/
typedef const void* UCurrRegistryKey;
/**
* Register an (existing) ISO 4217 currency code for the given locale.
* Only the country code and the two variants EURO and PRE_EURO are
* recognized.
* @param isoCode the three-letter ISO 4217 currency code
* @param locale the locale for which to register this currency code
* @param status the in/out status code
* @return a registry key that can be used to unregister this currency code, or NULL
* if there was an error.
* @stable ICU 2.6
*/
U_STABLE UCurrRegistryKey U_EXPORT2
ucurr_register(const UChar* isoCode,
const char* locale,
UErrorCode* status);
/**
* Unregister the previously-registered currency definitions using the
* URegistryKey returned from ucurr_register. Key becomes invalid after
* a successful call and should not be used again. Any currency
* that might have been hidden by the original ucurr_register call is
* restored.
* @param key the registry key returned by a previous call to ucurr_register
* @param status the in/out status code, no special meanings are assigned
* @return TRUE if the currency for this key was successfully unregistered
* @stable ICU 2.6
*/
U_STABLE UBool U_EXPORT2
ucurr_unregister(UCurrRegistryKey key, UErrorCode* status);
#endif /* UCONFIG_NO_SERVICE */
/**
* Returns the display name for the given currency in the
* given locale. For example, the display name for the USD
* currency object in the en_US locale is "$".
* @param currency null-terminated 3-letter ISO 4217 code
* @param locale locale in which to display currency
* @param nameStyle selector for which kind of name to return
* @param isChoiceFormat fill-in set to TRUE if the returned value
* is a ChoiceFormat pattern; otherwise it is a static string
* @param len fill-in parameter to receive length of result
* @param ec error code
* @return pointer to display string of 'len' UChars. If the resource
* data contains no entry for 'currency', then 'currency' itself is
* returned. If *isChoiceFormat is TRUE, then the result is a
* ChoiceFormat pattern. Otherwise it is a static string.
* @stable ICU 2.6
*/
U_STABLE const UChar* U_EXPORT2
ucurr_getName(const UChar* currency,
const char* locale,
UCurrNameStyle nameStyle,
UBool* isChoiceFormat,
int32_t* len,
UErrorCode* ec);
/**
* Returns the plural name for the given currency in the
* given locale. For example, the plural name for the USD
* currency object in the en_US locale is "US dollar" or "US dollars".
* @param currency null-terminated 3-letter ISO 4217 code
* @param locale locale in which to display currency
* @param isChoiceFormat fill-in set to TRUE if the returned value
* is a ChoiceFormat pattern; otherwise it is a static string
* @param pluralCount plural count
* @param len fill-in parameter to receive length of result
* @param ec error code
* @return pointer to display string of 'len' UChars. If the resource
* data contains no entry for 'currency', then 'currency' itself is
* returned.
* @draft ICU 4.2
*/
U_STABLE const UChar* U_EXPORT2
ucurr_getPluralName(const UChar* currency,
const char* locale,
UBool* isChoiceFormat,
const char* pluralCount,
int32_t* len,
UErrorCode* ec);
/**
* Returns the number of the number of fraction digits that should
* be displayed for the given currency.
* @param currency null-terminated 3-letter ISO 4217 code
* @param ec input-output error code
* @return a non-negative number of fraction digits to be
* displayed, or 0 if there is an error
* @stable ICU 3.0
*/
U_STABLE int32_t U_EXPORT2
ucurr_getDefaultFractionDigits(const UChar* currency,
UErrorCode* ec);
/**
* Returns the rounding increment for the given currency, or 0.0 if no
* rounding is done by the currency.
* @param currency null-terminated 3-letter ISO 4217 code
* @param ec input-output error code
* @return the non-negative rounding increment, or 0.0 if none,
* or 0.0 if there is an error
* @stable ICU 3.0
*/
U_STABLE double U_EXPORT2
ucurr_getRoundingIncrement(const UChar* currency,
UErrorCode* ec);
/**
* Selector constants for ucurr_openCurrencies().
*
* @see ucurr_openCurrencies
* @stable ICU 3.2
*/
typedef enum UCurrCurrencyType {
/**
* Select all ISO-4217 currency codes.
* @stable ICU 3.2
*/
UCURR_ALL = INT32_MAX,
/**
* Select only ISO-4217 commonly used currency codes.
* These currencies can be found in common use, and they usually have
* bank notes or coins associated with the currency code.
* This does not include fund codes, precious metals and other
* various ISO-4217 codes limited to special financial products.
* @stable ICU 3.2
*/
UCURR_COMMON = 1,
/**
* Select ISO-4217 uncommon currency codes.
* These codes respresent fund codes, precious metals and other
* various ISO-4217 codes limited to special financial products.
* A fund code is a monetary resource associated with a currency.
* @stable ICU 3.2
*/
UCURR_UNCOMMON = 2,
/**
* Select only deprecated ISO-4217 codes.
* These codes are no longer in general public use.
* @stable ICU 3.2
*/
UCURR_DEPRECATED = 4,
/**
* Select only non-deprecated ISO-4217 codes.
* These codes are in general public use.
* @stable ICU 3.2
*/
UCURR_NON_DEPRECATED = 8
} UCurrCurrencyType;
/**
* Provides a UEnumeration object for listing ISO-4217 codes.
* @param currType You can use one of several UCurrCurrencyType values for this
* variable. You can also | (or) them together to get a specific list of
* currencies. Most people will want to use the (UCURR_CURRENCY|UCURR_NON_DEPRECATED) value to
* get a list of current currencies.
* @param pErrorCode Error code
* @stable ICU 3.2
*/
U_STABLE UEnumeration * U_EXPORT2
ucurr_openISOCurrencies(uint32_t currType, UErrorCode *pErrorCode);
/**
* Finds the number of valid currency codes for the
* given locale and date.
* @param locale the locale for which to retrieve the
* currency count.
* @param date the date for which to retrieve the
* currency count for the given locale.
* @param ec error code
* @return the number of currency codes for the
* given locale and date. If 0, currency
* codes couldn't be found for the input
* values are invalid.
* @stable ICU 4.0
*/
U_DRAFT int32_t U_EXPORT2
ucurr_countCurrencies(const char* locale,
UDate date,
UErrorCode* ec);
/**
* Finds a currency code for the given locale and date
* @param locale the locale for which to retrieve a currency code.
* Currency can be specified by the "currency" keyword
* in which case it overrides the default currency code
* @param date the date for which to retrieve a currency code for
* the given locale.
* @param index the index within the available list of currency codes
* for the given locale on the given date.
* @param buff fill in buffer. Can be NULL for preflighting.
* @param buffCapacity capacity of the fill in buffer. Can be 0 for
* preflighting. If it is non-zero, the buff parameter
* must not be NULL.
* @param ec error code
* @return length of the currency string. It should always be 3.
* If 0, currency couldn't be found or the input values are
* invalid.
* @stable ICU 4.0
*/
U_DRAFT int32_t U_EXPORT2
ucurr_forLocaleAndDate(const char* locale,
UDate date,
int32_t index,
UChar* buff,
int32_t buffCapacity,
UErrorCode* ec);
/**
* Given a key and a locale, returns an array of string values in a preferred
* order that would make a difference. These are all and only those values where
* the open (creation) of the service with the locale formed from the input locale
* plus input keyword and that value has different behavior than creation with the
* input locale alone.
* @param key one of the keys supported by this service. For now, only
* "currency" is supported.
* @param locale the locale
* @param commonlyUsed if set to true it will return only commonly used values
* with the given locale in preferred order. Otherwise,
* it will return all the available values for the locale.
* @param status error status
* @return a string enumeration over keyword values for the given key and the locale.
* @draft ICU 4.2
*/
U_DRAFT UEnumeration* U_EXPORT2
ucurr_getKeywordValuesForLocale(const char* key,
const char* locale,
UBool commonlyUsed,
UErrorCode* status);
#endif /* #if !UCONFIG_NO_FORMATTING */
#endif
+962
View File
@@ -0,0 +1,962 @@
/*
*******************************************************************************
* Copyright (C) 1996-2009, International Business Machines
* Corporation and others. All Rights Reserved.
*******************************************************************************
*/
#ifndef UDAT_H
#define UDAT_H
#include "unicode/utypes.h"
#if !UCONFIG_NO_FORMATTING
#include "unicode/ucal.h"
#include "unicode/unum.h"
/**
* \file
* \brief C API: DateFormat
*
* <h2> Date Format C API</h2>
*
* Date Format C API consists of functions 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
* structure UDateFormat, which can handle pretty much all normal
* date formatting and parsing actions.
* <P>
* Date Format 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 with default time and date style,
* use one of the static factory methods:
* <pre>
* \code
* UErrorCode status = U_ZERO_ERROR;
* UChar *myString;
* int32_t myStrlen = 0;
* UDateFormat* dfmt = udat_open(UDAT_DEFAULT, UDAT_DEFAULT, NULL, NULL, -1, NULL, -1, &status);
* myStrlen = udat_format(dfmt, myDate, NULL, myStrlen, NULL, &status);
* if (status==U_BUFFER_OVERFLOW_ERROR){
* status=U_ZERO_ERROR;
* myString=(UChar*)malloc(sizeof(UChar) * (myStrlen+1) );
* udat_format(dfmt, myDate, myString, myStrlen+1, NULL, &status);
* }
* \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
* UErrorCode status = U_ZERO_ERROR;
* int32_t i, myStrlen = 0;
* UChar* myString;
* char buffer[1024];
* UDate myDateArr[] = { 0.0, 100000000.0, 2000000000.0 }; // test values
* UDateFormat* df = udat_open(UDAT_DEFAULT, UDAT_DEFAULT, NULL, NULL, -1, NULL, 0, &status);
* for (i = 0; i < 3; i++) {
* myStrlen = udat_format(df, myDateArr[i], NULL, myStrlen, NULL, &status);
* if(status == U_BUFFER_OVERFLOW_ERROR){
* status = U_ZERO_ERROR;
* myString = (UChar*)malloc(sizeof(UChar) * (myStrlen+1) );
* udat_format(df, myDateArr[i], myString, myStrlen+1, NULL, &status);
* printf("%s\n", u_austrcpy(buffer, myString) );
* free(myString);
* }
* }
* \endcode
* </pre>
* To get specific fields of a date, you can use UFieldPosition to
* get specific fields.
* <pre>
* \code
* UErrorCode status = U_ZERO_ERROR;
* UFieldPosition pos;
* UChar *myString;
* int32_t myStrlen = 0;
* char buffer[1024];
*
* pos.field = 1; // Same as the DateFormat::EField enum
* UDateFormat* dfmt = udat_open(UDAT_DEFAULT, UDAT_DEFAULT, NULL, -1, NULL, 0, &status);
* myStrlen = udat_format(dfmt, myDate, NULL, myStrlen, &pos, &status);
* if (status==U_BUFFER_OVERFLOW_ERROR){
* status=U_ZERO_ERROR;
* myString=(UChar*)malloc(sizeof(UChar) * (myStrlen+1) );
* udat_format(dfmt, myDate, myString, myStrlen+1, &pos, &status);
* }
* printf("date format: %s\n", u_austrcpy(buffer, myString));
* buffer[pos.endIndex] = 0; // NULL terminate the string.
* printf("UFieldPosition position equals %s\n", &buffer[pos.beginIndex]);
* \endcode
* </pre>
* To format a date for a different Locale, specify it in the call to
* udat_open()
* <pre>
* \code
* UDateFormat* df = udat_open(UDAT_SHORT, UDAT_SHORT, "fr_FR", NULL, -1, NULL, 0, &status);
* \endcode
* </pre>
* You can use a DateFormat API udat_parse() to parse.
* <pre>
* \code
* UErrorCode status = U_ZERO_ERROR;
* int32_t parsepos=0;
* UDate myDate = udat_parse(df, myString, u_strlen(myString), &parsepos, &status);
* \endcode
* </pre>
* You can pass in different options for the arguments for date and time style
* to control the length of the result; from SHORT to MEDIUM to LONG to FULL.
* The exact result depends on the locale, but generally:
* see UDateFormatStyle for more details
* <ul type=round>
* <li> UDAT_SHORT is completely numeric, such as 12/13/52 or 3:30pm
* <li> UDAT_MEDIUM is longer, such as Jan 12, 1952
* <li> UDAT_LONG is longer, such as January 12, 1952 or 3:30:32pm
* <li> UDAT_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.
* <P>
* You can also use forms of the parse and format methods with Parse Position and
* UFieldPosition 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>
*/
/** A date formatter.
* For usage in C programs.
* @stable ICU 2.6
*/
typedef void* UDateFormat;
/** The possible date/time format styles
* @stable ICU 2.6
*/
typedef enum UDateFormatStyle {
/** Full style */
UDAT_FULL,
/** Long style */
UDAT_LONG,
/** Medium style */
UDAT_MEDIUM,
/** Short style */
UDAT_SHORT,
/** Default style */
UDAT_DEFAULT = UDAT_MEDIUM,
/** Bitfield for relative date */
UDAT_RELATIVE = (1 << 7),
UDAT_FULL_RELATIVE = UDAT_FULL | UDAT_RELATIVE,
UDAT_LONG_RELATIVE = UDAT_LONG | UDAT_RELATIVE,
UDAT_MEDIUM_RELATIVE = UDAT_MEDIUM | UDAT_RELATIVE,
UDAT_SHORT_RELATIVE = UDAT_SHORT | UDAT_RELATIVE,
/** No style */
UDAT_NONE = -1,
/** for internal API use only */
UDAT_IGNORE = -2
} UDateFormatStyle;
/**
* @{
* Below are a set of pre-defined skeletons.
*
* <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>
* <li>
* hides the order of fields.
* </li>
* <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.
* </li>
* </ol>
*
* @stable ICU 4.0
*/
#define UDAT_MINUTE_SECOND "ms"
#define UDAT_HOUR24_MINUTE "Hm"
#define UDAT_HOUR24_MINUTE_SECOND "Hms"
#define UDAT_HOUR_MINUTE_SECOND "hms"
#define UDAT_STANDALONE_MONTH "LLLL"
#define UDAT_ABBR_STANDALONE_MONTH "LLL"
#define UDAT_YEAR_QUARTER "yQQQ"
#define UDAT_YEAR_ABBR_QUARTER "yQ"
/** @} */
/**
* @{
* Below are a set of pre-defined skeletons that
* have pre-defined interval patterns in resource files.
* Users are encouraged to use them in date interval format factory methods.
*
*/
#define UDAT_HOUR_MINUTE "hm"
#define UDAT_YEAR "y"
#define UDAT_DAY "d"
#define UDAT_NUM_MONTH_WEEKDAY_DAY "MEd"
#define UDAT_YEAR_NUM_MONTH "yM"
#define UDAT_NUM_MONTH_DAY "Md"
#define UDAT_YEAR_NUM_MONTH_WEEKDAY_DAY "yMEd"
#define UDAT_ABBR_MONTH_WEEKDAY_DAY "MMMEd"
#define UDAT_YEAR_MONTH "yMMMM"
#define UDAT_YEAR_ABBR_MONTH "yMMM"
#define UDAT_MONTH_DAY "MMMMd"
#define UDAT_ABBR_MONTH_DAY "MMMd"
#define UDAT_MONTH_WEEKDAY_DAY "MMMMEEEEd"
#define UDAT_YEAR_ABBR_MONTH_WEEKDAY_DAY "yMMMEd"
#define UDAT_YEAR_MONTH_WEEKDAY_DAY "yMMMMEEEEd"
#define UDAT_YEAR_MONTH_DAY "yMMMMd"
#define UDAT_YEAR_ABBR_MONTH_DAY "yMMMd"
#define UDAT_YEAR_NUM_MONTH_DAY "yMd"
#define UDAT_NUM_MONTH "M"
#define UDAT_ABBR_MONTH "MMM"
#define UDAT_MONTH "MMMM"
#define UDAT_HOUR_MINUTE_GENERIC_TZ "hmv"
#define UDAT_HOUR_MINUTE_TZ "hmz"
#define UDAT_HOUR "h"
#define UDAT_HOUR_GENERIC_TZ "hv"
#define UDAT_HOUR_TZ "hz"
/** @} */
/**
* FieldPosition and UFieldPosition selectors for format fields
* defined by DateFormat and UDateFormat.
* @stable ICU 3.0
*/
typedef enum UDateFormatField {
/**
* FieldPosition and UFieldPosition selector for 'G' field alignment,
* corresponding to the UCAL_ERA field.
* @stable ICU 3.0
*/
UDAT_ERA_FIELD = 0,
/**
* FieldPosition and UFieldPosition selector for 'y' field alignment,
* corresponding to the UCAL_YEAR field.
* @stable ICU 3.0
*/
UDAT_YEAR_FIELD = 1,
/**
* FieldPosition and UFieldPosition selector for 'M' field alignment,
* corresponding to the UCAL_MONTH field.
* @stable ICU 3.0
*/
UDAT_MONTH_FIELD = 2,
/**
* FieldPosition and UFieldPosition selector for 'd' field alignment,
* corresponding to the UCAL_DATE field.
* @stable ICU 3.0
*/
UDAT_DATE_FIELD = 3,
/**
* FieldPosition and UFieldPosition selector for 'k' field alignment,
* corresponding to the UCAL_HOUR_OF_DAY field.
* UDAT_HOUR_OF_DAY1_FIELD is used for the one-based 24-hour clock.
* For example, 23:59 + 01:00 results in 24:59.
* @stable ICU 3.0
*/
UDAT_HOUR_OF_DAY1_FIELD = 4,
/**
* FieldPosition and UFieldPosition selector for 'H' field alignment,
* corresponding to the UCAL_HOUR_OF_DAY field.
* UDAT_HOUR_OF_DAY0_FIELD is used for the zero-based 24-hour clock.
* For example, 23:59 + 01:00 results in 00:59.
* @stable ICU 3.0
*/
UDAT_HOUR_OF_DAY0_FIELD = 5,
/**
* FieldPosition and UFieldPosition selector for 'm' field alignment,
* corresponding to the UCAL_MINUTE field.
* @stable ICU 3.0
*/
UDAT_MINUTE_FIELD = 6,
/**
* FieldPosition and UFieldPosition selector for 's' field alignment,
* corresponding to the UCAL_SECOND field.
* @stable ICU 3.0
*/
UDAT_SECOND_FIELD = 7,
/**
* FieldPosition and UFieldPosition selector for 'S' field alignment,
* corresponding to the UCAL_MILLISECOND field.
* @stable ICU 3.0
*/
UDAT_FRACTIONAL_SECOND_FIELD = 8,
/**
* FieldPosition and UFieldPosition selector for 'E' field alignment,
* corresponding to the UCAL_DAY_OF_WEEK field.
* @stable ICU 3.0
*/
UDAT_DAY_OF_WEEK_FIELD = 9,
/**
* FieldPosition and UFieldPosition selector for 'D' field alignment,
* corresponding to the UCAL_DAY_OF_YEAR field.
* @stable ICU 3.0
*/
UDAT_DAY_OF_YEAR_FIELD = 10,
/**
* FieldPosition and UFieldPosition selector for 'F' field alignment,
* corresponding to the UCAL_DAY_OF_WEEK_IN_MONTH field.
* @stable ICU 3.0
*/
UDAT_DAY_OF_WEEK_IN_MONTH_FIELD = 11,
/**
* FieldPosition and UFieldPosition selector for 'w' field alignment,
* corresponding to the UCAL_WEEK_OF_YEAR field.
* @stable ICU 3.0
*/
UDAT_WEEK_OF_YEAR_FIELD = 12,
/**
* FieldPosition and UFieldPosition selector for 'W' field alignment,
* corresponding to the UCAL_WEEK_OF_MONTH field.
* @stable ICU 3.0
*/
UDAT_WEEK_OF_MONTH_FIELD = 13,
/**
* FieldPosition and UFieldPosition selector for 'a' field alignment,
* corresponding to the UCAL_AM_PM field.
* @stable ICU 3.0
*/
UDAT_AM_PM_FIELD = 14,
/**
* FieldPosition and UFieldPosition selector for 'h' field alignment,
* corresponding to the UCAL_HOUR field.
* UDAT_HOUR1_FIELD is used for the one-based 12-hour clock.
* For example, 11:30 PM + 1 hour results in 12:30 AM.
* @stable ICU 3.0
*/
UDAT_HOUR1_FIELD = 15,
/**
* FieldPosition and UFieldPosition selector for 'K' field alignment,
* corresponding to the UCAL_HOUR field.
* UDAT_HOUR0_FIELD is used for the zero-based 12-hour clock.
* For example, 11:30 PM + 1 hour results in 00:30 AM.
* @stable ICU 3.0
*/
UDAT_HOUR0_FIELD = 16,
/**
* FieldPosition and UFieldPosition selector for 'z' field alignment,
* corresponding to the UCAL_ZONE_OFFSET and
* UCAL_DST_OFFSET fields.
* @stable ICU 3.0
*/
UDAT_TIMEZONE_FIELD = 17,
/**
* FieldPosition and UFieldPosition selector for 'Y' field alignment,
* corresponding to the UCAL_YEAR_WOY field.
* @stable ICU 3.0
*/
UDAT_YEAR_WOY_FIELD = 18,
/**
* FieldPosition and UFieldPosition selector for 'e' field alignment,
* corresponding to the UCAL_DOW_LOCAL field.
* @stable ICU 3.0
*/
UDAT_DOW_LOCAL_FIELD = 19,
/**
* FieldPosition and UFieldPosition selector for 'u' field alignment,
* corresponding to the UCAL_EXTENDED_YEAR field.
* @stable ICU 3.0
*/
UDAT_EXTENDED_YEAR_FIELD = 20,
/**
* FieldPosition and UFieldPosition selector for 'g' field alignment,
* corresponding to the UCAL_JULIAN_DAY field.
* @stable ICU 3.0
*/
UDAT_JULIAN_DAY_FIELD = 21,
/**
* FieldPosition and UFieldPosition selector for 'A' field alignment,
* corresponding to the UCAL_MILLISECONDS_IN_DAY field.
* @stable ICU 3.0
*/
UDAT_MILLISECONDS_IN_DAY_FIELD = 22,
/**
* FieldPosition and UFieldPosition selector for 'Z' field alignment,
* corresponding to the UCAL_ZONE_OFFSET and
* UCAL_DST_OFFSET fields.
* @stable ICU 3.0
*/
UDAT_TIMEZONE_RFC_FIELD = 23,
/**
* FieldPosition and UFieldPosition selector for 'v' field alignment,
* corresponding to the UCAL_ZONE_OFFSET field.
* @stable ICU 3.4
*/
UDAT_TIMEZONE_GENERIC_FIELD = 24,
/**
* FieldPosition selector for 'c' field alignment,
* corresponding to the {@link #UCAL_DATE} field.
* This displays the stand alone day name, if available.
* @stable ICU 3.4
*/
UDAT_STANDALONE_DAY_FIELD = 25,
/**
* FieldPosition selector for 'L' field alignment,
* corresponding to the {@link #UCAL_MONTH} field.
* This displays the stand alone month name, if available.
* @stable ICU 3.4
*/
UDAT_STANDALONE_MONTH_FIELD = 26,
/**
* FieldPosition selector for "Q" field alignment,
* corresponding to quarters. This is implemented
* using the {@link #UCAL_MONTH} field. This
* displays the quarter.
* @stable ICU 3.6
*/
UDAT_QUARTER_FIELD = 27,
/**
* FieldPosition selector for the "q" field alignment,
* corresponding to stand-alone quarters. This is
* implemented using the {@link #UCAL_MONTH} field.
* This displays the stand-alone quarter.
* @stable ICU 3.6
*/
UDAT_STANDALONE_QUARTER_FIELD = 28,
/**
* FieldPosition and UFieldPosition selector for 'V' field alignment,
* corresponding to the UCAL_ZONE_OFFSET field.
* @stable ICU 3.8
*/
UDAT_TIMEZONE_SPECIAL_FIELD = 29,
/**
* Number of FieldPosition and UFieldPosition selectors for
* DateFormat and UDateFormat.
* Valid selectors range from 0 to UDAT_FIELD_COUNT-1.
* This value is subject to change if new fields are defined
* in the future.
* @stable ICU 3.0
*/
UDAT_FIELD_COUNT = 30
} UDateFormatField;
/**
* Open a new UDateFormat for formatting and parsing dates and times.
* A UDateFormat may be used to format dates in calls to {@link #udat_format },
* and to parse dates in calls to {@link #udat_parse }.
* @param timeStyle The style used to format times; one of UDAT_FULL, UDAT_LONG,
* UDAT_MEDIUM, UDAT_SHORT, UDAT_DEFAULT, or UDAT_NONE (relative time styles
* are not currently supported)
* @param dateStyle The style used to format dates; one of UDAT_FULL, UDAT_LONG,
* UDAT_MEDIUM, UDAT_SHORT, UDAT_DEFAULT, UDAT_FULL_RELATIVE, UDAT_LONG_RELATIVE,
* UDAT_MEDIUM_RELATIVE, UDAT_SHORT_RELATIVE, or UDAT_NONE
* @param locale The locale specifying the formatting conventions
* @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.
* @param pattern A pattern specifying the format to use.
* @param patternLength The number of characters in the pattern, or -1 if null-terminated.
* @param status A pointer to an UErrorCode to receive any errors
* @return A pointer to a UDateFormat to use for formatting dates and times, or 0 if
* an error occurred.
* @stable ICU 2.0
*/
U_STABLE UDateFormat* U_EXPORT2
udat_open(UDateFormatStyle timeStyle,
UDateFormatStyle dateStyle,
const char *locale,
const UChar *tzID,
int32_t tzIDLength,
const UChar *pattern,
int32_t patternLength,
UErrorCode *status);
/**
* Close a UDateFormat.
* Once closed, a UDateFormat may no longer be used.
* @param format The formatter to close.
* @stable ICU 2.0
*/
U_STABLE void U_EXPORT2
udat_close(UDateFormat* format);
/**
* Open a copy of a UDateFormat.
* This function performs a deep copy.
* @param fmt The format 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_STABLE UDateFormat* U_EXPORT2
udat_clone(const UDateFormat *fmt,
UErrorCode *status);
/**
* Format a date using an UDateFormat.
* The date will be formatted using the conventions specified in {@link #udat_open }
* @param format The formatter to use
* @param dateToFormat The date to format
* @param result A pointer to a buffer to receive the formatted number.
* @param resultLength 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.
* @param status A pointer to an UErrorCode to receive any errors
* @return The total buffer size needed; if greater than resultLength, the output was truncated.
* @see udat_parse
* @see UFieldPosition
* @stable ICU 2.0
*/
U_STABLE int32_t U_EXPORT2
udat_format( const UDateFormat* format,
UDate dateToFormat,
UChar* result,
int32_t resultLength,
UFieldPosition* position,
UErrorCode* status);
/**
* Parse a string into an date/time using a UDateFormat.
* The date will be parsed using the conventions specified in {@link #udat_open }
* @param format The formatter to use.
* @param text The text to parse.
* @param textLength The length of text, or -1 if null-terminated.
* @param parsePos If not 0, on input a pointer to an integer specifying the offset at which
* to begin parsing. If not 0, on output the offset at which parsing ended.
* @param status A pointer to an UErrorCode to receive any errors
* @return The value of the parsed date/time
* @see udat_format
* @stable ICU 2.0
*/
U_STABLE UDate U_EXPORT2
udat_parse( const UDateFormat* format,
const UChar* text,
int32_t textLength,
int32_t *parsePos,
UErrorCode *status);
/**
* Parse a string into an date/time using a UDateFormat.
* The date will be parsed using the conventions specified in {@link #udat_open }
* @param format The formatter to use.
* @param calendar The calendar in which to store the parsed data.
* @param text The text to parse.
* @param textLength The length of text, or -1 if null-terminated.
* @param parsePos If not 0, on input a pointer to an integer specifying the offset at which
* to begin parsing. If not 0, on output the offset at which parsing ended.
* @param status A pointer to an UErrorCode to receive any errors
* @see udat_format
* @stable ICU 2.0
*/
U_STABLE void U_EXPORT2
udat_parseCalendar(const UDateFormat* format,
UCalendar* calendar,
const UChar* text,
int32_t textLength,
int32_t *parsePos,
UErrorCode *status);
/**
* Determine if an UDateFormat will perform lenient parsing.
* With lenient parsing, the parser may use heuristics to interpret inputs that do not
* precisely match the pattern. With strict parsing, inputs must match the pattern.
* @param fmt The formatter to query
* @return TRUE if fmt is set to perform lenient parsing, FALSE otherwise.
* @see udat_setLenient
* @stable ICU 2.0
*/
U_STABLE UBool U_EXPORT2
udat_isLenient(const UDateFormat* fmt);
/**
* Specify whether an UDateFormat will perform lenient parsing.
* With lenient parsing, the parser may use heuristics to interpret inputs that do not
* precisely match the pattern. With strict parsing, inputs must match the pattern.
* @param fmt The formatter to set
* @param isLenient TRUE if fmt should perform lenient parsing, FALSE otherwise.
* @see dat_isLenient
* @stable ICU 2.0
*/
U_STABLE void U_EXPORT2
udat_setLenient( UDateFormat* fmt,
UBool isLenient);
/**
* Get the UCalendar associated with an UDateFormat.
* A UDateFormat uses a UCalendar to convert a raw value to, for example,
* the day of the week.
* @param fmt The formatter to query.
* @return A pointer to the UCalendar used by fmt.
* @see udat_setCalendar
* @stable ICU 2.0
*/
U_STABLE const UCalendar* U_EXPORT2
udat_getCalendar(const UDateFormat* fmt);
/**
* Set the UCalendar associated with an UDateFormat.
* A UDateFormat uses a UCalendar to convert a raw value to, for example,
* the day of the week.
* @param fmt The formatter to set.
* @param calendarToSet A pointer to an UCalendar to be used by fmt.
* @see udat_setCalendar
* @stable ICU 2.0
*/
U_STABLE void U_EXPORT2
udat_setCalendar( UDateFormat* fmt,
const UCalendar* calendarToSet);
/**
* Get the UNumberFormat associated with an UDateFormat.
* A UDateFormat uses a UNumberFormat to format numbers within a date,
* for example the day number.
* @param fmt The formatter to query.
* @return A pointer to the UNumberFormat used by fmt to format numbers.
* @see udat_setNumberFormat
* @stable ICU 2.0
*/
U_STABLE const UNumberFormat* U_EXPORT2
udat_getNumberFormat(const UDateFormat* fmt);
/**
* Set the UNumberFormat associated with an UDateFormat.
* A UDateFormat uses a UNumberFormat to format numbers within a date,
* for example the day number.
* @param fmt The formatter to set.
* @param numberFormatToSet A pointer to the UNumberFormat to be used by fmt to format numbers.
* @see udat_getNumberFormat
* @stable ICU 2.0
*/
U_STABLE void U_EXPORT2
udat_setNumberFormat( UDateFormat* fmt,
const UNumberFormat* numberFormatToSet);
/**
* Get a locale for which date/time formatting patterns are available.
* A UDateFormat in a locale returned by this function will perform the correct
* formatting and parsing for the locale.
* @param localeIndex The index of the desired locale.
* @return A locale for which date/time formatting patterns are available, or 0 if none.
* @see udat_countAvailable
* @stable ICU 2.0
*/
U_STABLE const char* U_EXPORT2
udat_getAvailable(int32_t localeIndex);
/**
* Determine how many locales have date/time formatting patterns available.
* This function is most useful as determining the loop ending condition for
* calls to {@link #udat_getAvailable }.
* @return The number of locales for which date/time formatting patterns are available.
* @see udat_getAvailable
* @stable ICU 2.0
*/
U_STABLE int32_t U_EXPORT2
udat_countAvailable(void);
/**
* Get the year relative to which all 2-digit years are interpreted.
* For example, if the 2-digit start year is 2100, the year 99 will be
* interpreted as 2199.
* @param fmt The formatter to query.
* @param status A pointer to an UErrorCode to receive any errors
* @return The year relative to which all 2-digit years are interpreted.
* @see udat_Set2DigitYearStart
* @stable ICU 2.0
*/
U_STABLE UDate U_EXPORT2
udat_get2DigitYearStart( const UDateFormat *fmt,
UErrorCode *status);
/**
* Set the year relative to which all 2-digit years will be interpreted.
* For example, if the 2-digit start year is 2100, the year 99 will be
* interpreted as 2199.
* @param fmt The formatter to set.
* @param d The year relative to which all 2-digit years will be interpreted.
* @param status A pointer to an UErrorCode to receive any errors
* @see udat_Set2DigitYearStart
* @stable ICU 2.0
*/
U_STABLE void U_EXPORT2
udat_set2DigitYearStart( UDateFormat *fmt,
UDate d,
UErrorCode *status);
/**
* Extract the pattern from a UDateFormat.
* The pattern will follow the pattern syntax rules.
* @param fmt The formatter to query.
* @param localized TRUE if the pattern should be localized, FALSE otherwise.
* @param result A pointer to a buffer to receive the pattern.
* @param resultLength The maximum size of result.
* @param status A pointer to an UErrorCode to receive any errors
* @return The total buffer size needed; if greater than resultLength, the output was truncated.
* @see udat_applyPattern
* @stable ICU 2.0
*/
U_STABLE int32_t U_EXPORT2
udat_toPattern( const UDateFormat *fmt,
UBool localized,
UChar *result,
int32_t resultLength,
UErrorCode *status);
/**
* Set the pattern used by an UDateFormat.
* The pattern should follow the pattern syntax rules.
* @param format The formatter to set.
* @param localized TRUE if the pattern is localized, FALSE otherwise.
* @param pattern The new pattern
* @param patternLength The length of pattern, or -1 if null-terminated.
* @see udat_toPattern
* @stable ICU 2.0
*/
U_STABLE void U_EXPORT2
udat_applyPattern( UDateFormat *format,
UBool localized,
const UChar *pattern,
int32_t patternLength);
/**
* The possible types of date format symbols
* @stable ICU 2.6
*/
typedef enum UDateFormatSymbolType {
/** The era names, for example AD */
UDAT_ERAS,
/** The month names, for example February */
UDAT_MONTHS,
/** The short month names, for example Feb. */
UDAT_SHORT_MONTHS,
/** The weekday names, for example Monday */
UDAT_WEEKDAYS,
/** The short weekday names, for example Mon. */
UDAT_SHORT_WEEKDAYS,
/** The AM/PM names, for example AM */
UDAT_AM_PMS,
/** The localized characters */
UDAT_LOCALIZED_CHARS,
/** The long era names, for example Anno Domini */
UDAT_ERA_NAMES,
/** The narrow month names, for example F */
UDAT_NARROW_MONTHS,
/** The narrow weekday names, for example N */
UDAT_NARROW_WEEKDAYS,
/** Standalone context versions of months */
UDAT_STANDALONE_MONTHS,
UDAT_STANDALONE_SHORT_MONTHS,
UDAT_STANDALONE_NARROW_MONTHS,
/** Standalone context versions of weekdays */
UDAT_STANDALONE_WEEKDAYS,
UDAT_STANDALONE_SHORT_WEEKDAYS,
UDAT_STANDALONE_NARROW_WEEKDAYS,
/** The quarters, for example 1st Quarter */
UDAT_QUARTERS,
/** The short quarter names, for example Q1 */
UDAT_SHORT_QUARTERS,
/** Standalone context versions of quarters */
UDAT_STANDALONE_QUARTERS,
UDAT_STANDALONE_SHORT_QUARTERS
} UDateFormatSymbolType;
struct UDateFormatSymbols;
/** Date format symbols.
* For usage in C programs.
* @stable ICU 2.6
*/
typedef struct UDateFormatSymbols UDateFormatSymbols;
/**
* Get the symbols associated with an UDateFormat.
* The symbols are what a UDateFormat uses to represent locale-specific data,
* for example month or day names.
* @param fmt The formatter to query.
* @param type The type of symbols to get. One of UDAT_ERAS, UDAT_MONTHS, UDAT_SHORT_MONTHS,
* UDAT_WEEKDAYS, UDAT_SHORT_WEEKDAYS, UDAT_AM_PMS, or UDAT_LOCALIZED_CHARS
* @param symbolIndex The desired symbol of type type.
* @param result A pointer to a buffer to receive the pattern.
* @param resultLength The maximum size of result.
* @param status A pointer to an UErrorCode to receive any errors
* @return The total buffer size needed; if greater than resultLength, the output was truncated.
* @see udat_countSymbols
* @see udat_setSymbols
* @stable ICU 2.0
*/
U_STABLE int32_t U_EXPORT2
udat_getSymbols(const UDateFormat *fmt,
UDateFormatSymbolType type,
int32_t symbolIndex,
UChar *result,
int32_t resultLength,
UErrorCode *status);
/**
* Count the number of particular symbols for an UDateFormat.
* This function is most useful as for detemining the loop termination condition
* for calls to {@link #udat_getSymbols }.
* @param fmt The formatter to query.
* @param type The type of symbols to count. One of UDAT_ERAS, UDAT_MONTHS, UDAT_SHORT_MONTHS,
* UDAT_WEEKDAYS, UDAT_SHORT_WEEKDAYS, UDAT_AM_PMS, or UDAT_LOCALIZED_CHARS
* @return The number of symbols of type type.
* @see udat_getSymbols
* @see udat_setSymbols
* @stable ICU 2.0
*/
U_STABLE int32_t U_EXPORT2
udat_countSymbols( const UDateFormat *fmt,
UDateFormatSymbolType type);
/**
* Set the symbols associated with an UDateFormat.
* The symbols are what a UDateFormat uses to represent locale-specific data,
* for example month or day names.
* @param format The formatter to set
* @param type The type of symbols to set. One of UDAT_ERAS, UDAT_MONTHS, UDAT_SHORT_MONTHS,
* UDAT_WEEKDAYS, UDAT_SHORT_WEEKDAYS, UDAT_AM_PMS, or UDAT_LOCALIZED_CHARS
* @param symbolIndex The index of the symbol to set of type type.
* @param value The new value
* @param valueLength The length of value, or -1 if null-terminated
* @param status A pointer to an UErrorCode to receive any errors
* @see udat_getSymbols
* @see udat_countSymbols
* @stable ICU 2.0
*/
U_STABLE void U_EXPORT2
udat_setSymbols( UDateFormat *format,
UDateFormatSymbolType type,
int32_t symbolIndex,
UChar *value,
int32_t valueLength,
UErrorCode *status);
/**
* Get the locale for this date format object.
* You can choose between valid and actual locale.
* @param fmt The formatter to get the locale from
* @param type type of the locale we're looking for (valid or actual)
* @param status error code for the operation
* @return the locale name
* @stable ICU 2.8
*/
U_STABLE const char* U_EXPORT2
udat_getLocaleByType(const UDateFormat *fmt,
ULocDataLocaleType type,
UErrorCode* status);
/**
* Extract the date pattern from a UDateFormat set for relative date formatting.
* The pattern will follow the pattern syntax rules.
* @param fmt The formatter to query.
* @param result A pointer to a buffer to receive the pattern.
* @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.
* @see udat_applyPatternRelative
* @internal ICU 4.2 technology preview
*/
U_INTERNAL int32_t U_EXPORT2
udat_toPatternRelativeDate(const UDateFormat *fmt,
UChar *result,
int32_t resultLength,
UErrorCode *status);
/**
* Extract the time pattern from a UDateFormat set for relative date formatting.
* The pattern will follow the pattern syntax rules.
* @param fmt The formatter to query.
* @param result A pointer to a buffer to receive the pattern.
* @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.
* @see udat_applyPatternRelative
* @internal ICU 4.2 technology preview
*/
U_INTERNAL int32_t U_EXPORT2
udat_toPatternRelativeTime(const UDateFormat *fmt,
UChar *result,
int32_t resultLength,
UErrorCode *status);
/**
* Set the date & time patterns used by a UDateFormat set for relative date formatting.
* The patterns should follow the pattern syntax rules.
* @param format The formatter to set.
* @param datePattern The new date pattern
* @param datePatternLength The length of datePattern, or -1 if null-terminated.
* @param timePattern The new time pattern
* @param timePatternLength The length of timePattern, or -1 if null-terminated.
* @param status A pointer to a UErrorCode to receive any errors
* @see udat_toPatternRelativeDate, udat_toPatternRelativeTime
* @internal ICU 4.2 technology preview
*/
U_INTERNAL void U_EXPORT2
udat_applyPatternRelative(UDateFormat *format,
const UChar *datePattern,
int32_t datePatternLength,
const UChar *timePattern,
int32_t timePatternLength,
UErrorCode *status);
#endif /* #if !UCONFIG_NO_FORMATTING */
#endif
+389
View File
@@ -0,0 +1,389 @@
/*
******************************************************************************
*
* Copyright (C) 1999-2008, International Business Machines
* Corporation and others. All Rights Reserved.
*
******************************************************************************
* file name: udata.h
* encoding: US-ASCII
* tab size: 8 (not used)
* indentation:4
*
* created on: 1999oct25
* created by: Markus W. Scherer
*/
#ifndef __UDATA_H__
#define __UDATA_H__
#include "unicode/utypes.h"
U_CDECL_BEGIN
/**
* \file
* \brief C API: Data loading interface
*
* <h2>Information about data loading interface</h2>
*
* This API is used to find and efficiently load data for ICU and applications
* using ICU. It provides an abstract interface that specifies a data type and
* name to find and load the data. Normally this API is used by other ICU APIs
* to load required data out of the ICU data library, but it can be used to
* load data out of other places.
*
* See the User Guide Data Management chapter.
*/
#ifndef U_HIDE_INTERNAL_API
/**
* Character used to separate package names from tree names
* @internal ICU 3.0
*/
#define U_TREE_SEPARATOR '-'
/**
* String used to separate package names from tree names
* @internal ICU 3.0
*/
#define U_TREE_SEPARATOR_STRING "-"
/**
* Character used to separate parts of entry names
* @internal ICU 3.0
*/
#define U_TREE_ENTRY_SEP_CHAR '/'
/**
* String used to separate parts of entry names
* @internal ICU 3.0
*/
#define U_TREE_ENTRY_SEP_STRING "/"
/**
* Alias for standard ICU data
* @internal ICU 3.0
*/
#define U_ICUDATA_ALIAS "ICUDATA"
#endif /* U_HIDE_INTERNAL_API */
/**
* UDataInfo contains the properties about the requested data.
* This is meta data.
*
* <p>This structure may grow in the future, indicated by the
* <code>size</code> field.</p>
*
* <p>The platform data property fields help determine if a data
* file can be efficiently used on a given machine.
* The particular fields are of importance only if the data
* is affected by the properties - if there is integer data
* with word sizes > 1 byte, char* text, or UChar* text.</p>
*
* <p>The implementation for the <code>udata_open[Choice]()</code>
* functions may reject data based on the value in <code>isBigEndian</code>.
* No other field is used by the <code>udata</code> API implementation.</p>
*
* <p>The <code>dataFormat</code> may be used to identify
* the kind of data, e.g. a converter table.</p>
*
* <p>The <code>formatVersion</code> field should be used to
* make sure that the format can be interpreted.
* I may be a good idea to check only for the one or two highest
* of the version elements to allow the data memory to
* get more or somewhat rearranged contents, for as long
* as the using code can still interpret the older contents.</p>
*
* <p>The <code>dataVersion</code> field is intended to be a
* common place to store the source version of the data;
* for data from the Unicode character database, this could
* reflect the Unicode version.</p>
* @stable ICU 2.0
*/
typedef struct {
/** sizeof(UDataInfo)
* @stable ICU 2.0 */
uint16_t size;
/** unused, set to 0
* @stable ICU 2.0*/
uint16_t reservedWord;
/* platform data properties */
/** 0 for little-endian machine, 1 for big-endian
* @stable ICU 2.0 */
uint8_t isBigEndian;
/** see U_CHARSET_FAMILY values in utypes.h
* @stable ICU 2.0*/
uint8_t charsetFamily;
/** sizeof(UChar), one of { 1, 2, 4 }
* @stable ICU 2.0*/
uint8_t sizeofUChar;
/** unused, set to 0
* @stable ICU 2.0*/
uint8_t reservedByte;
/** data format identifier
* @stable ICU 2.0*/
uint8_t dataFormat[4];
/** versions: [0] major [1] minor [2] milli [3] micro
* @stable ICU 2.0*/
uint8_t formatVersion[4];
/** versions: [0] major [1] minor [2] milli [3] micro
* @stable ICU 2.0*/
uint8_t dataVersion[4];
} UDataInfo;
/* API for reading data -----------------------------------------------------*/
/**
* Forward declaration of the data memory type.
* @stable ICU 2.0
*/
typedef struct UDataMemory UDataMemory;
/**
* Callback function for udata_openChoice().
* @param context parameter passed into <code>udata_openChoice()</code>.
* @param type The type of the data as passed into <code>udata_openChoice()</code>.
* It may be <code>NULL</code>.
* @param name The name of the data as passed into <code>udata_openChoice()</code>.
* @param pInfo A pointer to the <code>UDataInfo</code> structure
* of data that has been loaded and will be returned
* by <code>udata_openChoice()</code> if this function
* returns <code>TRUE</code>.
* @return TRUE if the current data memory is acceptable
* @stable ICU 2.0
*/
typedef UBool U_CALLCONV
UDataMemoryIsAcceptable(void *context,
const char *type, const char *name,
const UDataInfo *pInfo);
/**
* Convenience function.
* This function works the same as <code>udata_openChoice</code>
* except that any data that matches the type and name
* is assumed to be acceptable.
* @param path Specifies an absolute path and/or a basename for the
* finding of the data in the file system.
* <code>NULL</code> for ICU data.
* @param type A string that specifies the type of data to be loaded.
* For example, resource bundles are loaded with type "res",
* conversion tables with type "cnv".
* This may be <code>NULL</code> or empty.
* @param name A string that specifies the name of the data.
* @param pErrorCode An ICU UErrorCode parameter. It must not be <code>NULL</code>.
* @return A pointer (handle) to a data memory object, or <code>NULL</code>
* if an error occurs. Call <code>udata_getMemory()</code>
* to get a pointer to the actual data.
*
* @see udata_openChoice
* @stable ICU 2.0
*/
U_STABLE UDataMemory * U_EXPORT2
udata_open(const char *path, const char *type, const char *name,
UErrorCode *pErrorCode);
/**
* Data loading function.
* This function is used to find and load efficiently data for
* ICU and applications using ICU.
* It provides an abstract interface that allows to specify a data
* type and name to find and load the data.
*
* <p>The implementation depends on platform properties and user preferences
* and may involve loading shared libraries (DLLs), mapping
* files into memory, or fopen()/fread() files.
* It may also involve using static memory or database queries etc.
* Several or all data items may be combined into one entity
* (DLL, memory-mappable file).</p>
*
* <p>The data is always preceded by a header that includes
* a <code>UDataInfo</code> structure.
* The caller's <code>isAcceptable()</code> function is called to make
* sure that the data is useful. It may be called several times if it
* rejects the data and there is more than one location with data
* matching the type and name.</p>
*
* <p>If <code>path==NULL</code>, then ICU data is loaded.
* Otherwise, it is separated into a basename and a basename-less directory string.
* The basename is used as the data package name, and the directory is
* logically prepended to the ICU data directory string.</p>
*
* <p>For details about ICU data loading see the User Guide
* Data Management chapter. (http://icu-project.org/userguide/icudata.html)</p>
*
* @param path Specifies an absolute path and/or a basename for the
* finding of the data in the file system.
* <code>NULL</code> for ICU data.
* @param type A string that specifies the type of data to be loaded.
* For example, resource bundles are loaded with type "res",
* conversion tables with type "cnv".
* This may be <code>NULL</code> or empty.
* @param name A string that specifies the name of the data.
* @param isAcceptable This function is called to verify that loaded data
* is useful for the client code. If it returns FALSE
* for all data items, then <code>udata_openChoice()</code>
* will return with an error.
* @param context Arbitrary parameter to be passed into isAcceptable.
* @param pErrorCode An ICU UErrorCode parameter. It must not be <code>NULL</code>.
* @return A pointer (handle) to a data memory object, or <code>NULL</code>
* if an error occurs. Call <code>udata_getMemory()</code>
* to get a pointer to the actual data.
* @stable ICU 2.0
*/
U_STABLE UDataMemory * U_EXPORT2
udata_openChoice(const char *path, const char *type, const char *name,
UDataMemoryIsAcceptable *isAcceptable, void *context,
UErrorCode *pErrorCode);
/**
* Close the data memory.
* This function must be called to allow the system to
* release resources associated with this data memory.
* @param pData The pointer to data memory object
* @stable ICU 2.0
*/
U_STABLE void U_EXPORT2
udata_close(UDataMemory *pData);
/**
* Get the pointer to the actual data inside the data memory.
* The data is read-only.
* @param pData The pointer to data memory object
* @stable ICU 2.0
*/
U_STABLE const void * U_EXPORT2
udata_getMemory(UDataMemory *pData);
/**
* Get the information from the data memory header.
* This allows to get access to the header containing
* platform data properties etc. which is not part of
* the data itself and can therefore not be accessed
* via the pointer that <code>udata_getMemory()</code> returns.
*
* @param pData pointer to the data memory object
* @param pInfo pointer to a UDataInfo object;
* its <code>size</code> field must be set correctly,
* typically to <code>sizeof(UDataInfo)</code>.
*
* <code>*pInfo</code> will be filled with the UDataInfo structure
* in the data memory object. If this structure is smaller than
* <code>pInfo->size</code>, then the <code>size</code> will be
* adjusted and only part of the structure will be filled.
* @stable ICU 2.0
*/
U_STABLE void U_EXPORT2
udata_getInfo(UDataMemory *pData, UDataInfo *pInfo);
/**
* This function bypasses the normal ICU data loading process and
* allows you to force ICU's system data to come out of a user-specified
* area in memory.
*
* The format of this data is that of the icu common data file, as is
* generated by the pkgdata tool with mode=common or mode=dll.
* You can read in a whole common mode file and pass the address to the start of the
* data, or (with the appropriate link options) pass in the pointer to
* the data that has been loaded from a dll by the operating system,
* as shown in this code:
*
* extern const char U_IMPORT U_ICUDATA_ENTRY_POINT [];
* // U_ICUDATA_ENTRY_POINT is same as entry point specified to pkgdata tool
* UErrorCode status = U_ZERO_ERROR;
*
* udata_setCommonData(&U_ICUDATA_ENTRY_POINT, &status);
*
* Warning: ICU must NOT have even attempted to access its data yet
* when this call is made, or U_USING_DEFAULT_WARNING code will
* be returned. Be careful of UnicodeStrings in static initialization which
* may attempt to load a converter (use the UNICODE_STRING(x) macro instead).
*
* Also note that it is important that the declaration be as above. The entry point
* must not be declared as an extern void*.
*
* This function has no effect on application (non ICU) data. See udata_setAppData()
* for similar functionality for application data.
*
* @param data pointer to ICU common data
* @param err outgoing error status <code>U_USING_DEFAULT_WARNING, U_UNSUPPORTED_ERROR</code>
* @stable ICU 2.0
*/
U_STABLE void U_EXPORT2
udata_setCommonData(const void *data, UErrorCode *err);
/**
* This function bypasses the normal ICU data loading process for application-specific
* data and allows you to force the it to come out of a user-specified
* pointer.
*
* The format of this data is that of the icu common data file, like 'icudt26l.dat'
* or the corresponding shared library (DLL) file.
* The application must read in or otherwise construct an image of the data and then
* pass the address of it to this function.
*
*
* Warning: setAppData will set a U_USING_DEFAULT_WARNING code if
* data with the specifed path that has already been opened, or
* if setAppData with the same path has already been called.
* Any such calls to setAppData will have no effect.
*
*
* @param packageName the package name by which the application will refer
* to (open) this data
* @param data pointer to the data
* @param err outgoing error status <code>U_USING_DEFAULT_WARNING, U_UNSUPPORTED_ERROR</code>
* @see udata_setCommonData
* @stable ICU 2.0
*/
U_STABLE void U_EXPORT2
udata_setAppData(const char *packageName, const void *data, UErrorCode *err);
/**
* Possible settings for udata_setFileAccess()
* @see udata_setFileAccess
* @stable ICU 3.4
*/
typedef enum UDataFileAccess {
/** ICU looks for data in single files first, then in packages. (default) */
UDATA_FILES_FIRST,
/** ICU only loads data from packages, not from single files. */
UDATA_ONLY_PACKAGES,
/** ICU loads data from packages first, and only from single files
if the data cannot be found in a package. */
UDATA_PACKAGES_FIRST,
/** ICU does not access the file system for data loading. */
UDATA_NO_FILES,
/** An alias for the default access mode. */
UDATA_DEFAULT_ACCESS = UDATA_FILES_FIRST,
UDATA_FILE_ACCESS_COUNT
} UDataFileAccess;
/**
* This function may be called to control how ICU loads data. It must be called
* before any ICU data is loaded, including application data loaded with ures/ResourceBundle or
* udata APIs. It should be called before u_init. This function is not multithread safe.
* The results of calling it while other threads are loading data are undefined.
* @param access The type of file access to be used
* @param status Error code.
* @see UDataFileAccess
* @stable ICU 3.4
*/
U_STABLE void U_EXPORT2
udata_setFileAccess(UDataFileAccess access, UErrorCode *status);
U_CDECL_END
#endif
+471
View File
@@ -0,0 +1,471 @@
/*
*******************************************************************************
*
* Copyright (C) 2007-2009, International Business Machines
* Corporation and others. All Rights Reserved.
*
*******************************************************************************
* file name: udatpg.h
* encoding: US-ASCII
* 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/uenum.h"
/**
* \file
* \brief C API: Wrapper for 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,
/** @stable ICU 3.8 */
UDATPG_FIELD_COUNT
} UDateTimePatternField;
/**
* 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,
/** @stable ICU 3.8 */
UDATPG_CONFLICT_COUNT
} 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_DRAFT 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_DRAFT UDateTimePatternGenerator * U_EXPORT2
udatpg_openEmpty(UErrorCode *pErrorCode);
/**
* Close a generator.
* @param dtpg a pointer to UDateTimePatternGenerator.
* @stable ICU 3.8
*/
U_DRAFT void U_EXPORT2
udatpg_close(UDateTimePatternGenerator *dtpg);
/**
* 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_DRAFT 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_DRAFT int32_t U_EXPORT2
udatpg_getBestPattern(UDateTimePatternGenerator *dtpg,
const UChar *skeleton, int32_t length,
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 dtpg a pointer to UDateTimePatternGenerator.
* @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_DRAFT int32_t U_EXPORT2
udatpg_getSkeleton(UDateTimePatternGenerator *dtpg,
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 dtpg a pointer to UDateTimePatternGenerator.
* @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_DRAFT int32_t U_EXPORT2
udatpg_getBaseSkeleton(UDateTimePatternGenerator *dtpg,
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 overriden. 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_DRAFT 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_DRAFT 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_DRAFT 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_DRAFT 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.
*
* @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
* @stable ICU 3.8
*/
U_DRAFT const UChar * U_EXPORT2
udatpg_getAppendItemName(const UDateTimePatternGenerator *dtpg,
UDateTimePatternField field,
int32_t *pLength);
/**
* The date time format is a message format pattern used to compose date and
* time patterns. The default value is "{0} {1}", where {0} will be replaced
* by the date pattern and {1} will be replaced by the time pattern.
* <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 "{0} {1}". 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".
*
* @param dtpg a pointer to UDateTimePatternGenerator.
* @param dtFormat
* message format pattern, here {0} will be replaced by the date
* pattern and {1} will be replaced by the time pattern.
* @param length the length of dtFormat.
* @stable ICU 3.8
*/
U_DRAFT void U_EXPORT2
udatpg_setDateTimeFormat(const UDateTimePatternGenerator *dtpg,
const UChar *dtFormat, int32_t length);
/**
* Getter corresponding to setDateTimeFormat.
* @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_DRAFT const UChar * U_EXPORT2
udatpg_getDateTimeFormat(const UDateTimePatternGenerator *dtpg,
int32_t *pLength);
/**
* 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_DRAFT 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_DRAFT 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_DRAFT 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);
/**
* 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_DRAFT 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_DRAFT 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_DRAFT const UChar * U_EXPORT2
udatpg_getPatternForSkeleton(const UDateTimePatternGenerator *dtpg,
const UChar *skeleton, int32_t skeletonLength,
int32_t *pLength);
#endif
+50
View File
@@ -0,0 +1,50 @@
/*
*******************************************************************************
* Copyright (C) 2004-2009, International Business Machines
* Corporation and others. All Rights Reserved.
*******************************************************************************
*
* file name:
* encoding: US-ASCII
* tab size: 8 (not used)
* indentation:4
*
* Created by: genheaders.pl, a perl script written by Ram Viswanadha
*
* Contains data for commenting out APIs.
* Gets included by umachine.h
*
* THIS FILE IS MACHINE-GENERATED, DON'T PLAY WITH IT IF YOU DON'T KNOW WHAT
* YOU ARE DOING, OTHERWISE VERY BAD THINGS WILL HAPPEN!
*/
#ifndef UDEPRCTD_H
#define UDEPRCTD_H
#ifdef U_HIDE_DEPRECATED_API
# if U_DISABLE_RENAMING
# define ucol_getContractions ucol_getContractions_DEPRECATED_API_DO_NOT_USE
# define ucol_getLocale ucol_getLocale_DEPRECATED_API_DO_NOT_USE
# define ures_countArrayItems ures_countArrayItems_DEPRECATED_API_DO_NOT_USE
# define ures_getLocale ures_getLocale_DEPRECATED_API_DO_NOT_USE
# define ures_getVersionNumber ures_getVersionNumber_DEPRECATED_API_DO_NOT_USE
# define utrans_getAvailableID utrans_getAvailableID_DEPRECATED_API_DO_NOT_USE
# define utrans_getID utrans_getID_DEPRECATED_API_DO_NOT_USE
# define utrans_open utrans_open_DEPRECATED_API_DO_NOT_USE
# define utrans_unregister utrans_unregister_DEPRECATED_API_DO_NOT_USE
# else
# define ucol_getContractions_4_2 ucol_getContractions_DEPRECATED_API_DO_NOT_USE
# define ucol_getLocale_4_2 ucol_getLocale_DEPRECATED_API_DO_NOT_USE
# define ures_countArrayItems_4_2 ures_countArrayItems_DEPRECATED_API_DO_NOT_USE
# define ures_getLocale_4_2 ures_getLocale_DEPRECATED_API_DO_NOT_USE
# define ures_getVersionNumber_4_2 ures_getVersionNumber_DEPRECATED_API_DO_NOT_USE
# define utrans_getAvailableID_4_2 utrans_getAvailableID_DEPRECATED_API_DO_NOT_USE
# define utrans_getID_4_2 utrans_getID_DEPRECATED_API_DO_NOT_USE
# define utrans_open_4_2 utrans_open_DEPRECATED_API_DO_NOT_USE
# define utrans_unregister_4_2 utrans_unregister_DEPRECATED_API_DO_NOT_USE
# endif /* U_DISABLE_RENAMING */
#endif /* U_HIDE_DEPRECATED_API */
#endif /* UDEPRCTD_H */
+116
View File
@@ -0,0 +1,116 @@
/*
*******************************************************************************
* Copyright (C) 2004-2009, International Business Machines
* Corporation and others. All Rights Reserved.
*******************************************************************************
*
* file name:
* encoding: US-ASCII
* tab size: 8 (not used)
* indentation:4
*
* Created by: genheaders.pl, a perl script written by Ram Viswanadha
*
* Contains data for commenting out APIs.
* Gets included by umachine.h
*
* THIS FILE IS MACHINE-GENERATED, DON'T PLAY WITH IT IF YOU DON'T KNOW WHAT
* YOU ARE DOING, OTHERWISE VERY BAD THINGS WILL HAPPEN!
*/
#ifndef UDRAFT_H
#define UDRAFT_H
#ifdef U_HIDE_DRAFT_API
# if U_DISABLE_RENAMING
# define u_compareVersions u_compareVersions_DRAFT_API_DO_NOT_USE
# define u_strFromUTF32WithSub u_strFromUTF32WithSub_DRAFT_API_DO_NOT_USE
# define u_strToUTF32WithSub u_strToUTF32WithSub_DRAFT_API_DO_NOT_USE
# define u_versionFromUString u_versionFromUString_DRAFT_API_DO_NOT_USE
# define ucal_getKeywordValuesForLocale ucal_getKeywordValuesForLocale_DRAFT_API_DO_NOT_USE
# define ucal_getType ucal_getType_DRAFT_API_DO_NOT_USE
# define ucnvsel_close ucnvsel_close_DRAFT_API_DO_NOT_USE
# define ucnvsel_open ucnvsel_open_DRAFT_API_DO_NOT_USE
# define ucnvsel_openFromSerialized ucnvsel_openFromSerialized_DRAFT_API_DO_NOT_USE
# define ucnvsel_selectForString ucnvsel_selectForString_DRAFT_API_DO_NOT_USE
# define ucnvsel_selectForUTF8 ucnvsel_selectForUTF8_DRAFT_API_DO_NOT_USE
# define ucnvsel_serialize ucnvsel_serialize_DRAFT_API_DO_NOT_USE
# define ucol_getKeywordValuesForLocale ucol_getKeywordValuesForLocale_DRAFT_API_DO_NOT_USE
# define ucurr_getKeywordValuesForLocale ucurr_getKeywordValuesForLocale_DRAFT_API_DO_NOT_USE
# define ucurr_getPluralName ucurr_getPluralName_DRAFT_API_DO_NOT_USE
# define uloc_forLanguageTag uloc_forLanguageTag_DRAFT_API_DO_NOT_USE
# define uloc_toLanguageTag uloc_toLanguageTag_DRAFT_API_DO_NOT_USE
# define ulocdata_getCLDRVersion ulocdata_getCLDRVersion_DRAFT_API_DO_NOT_USE
# define ulocdata_getLocaleDisplayPattern ulocdata_getLocaleDisplayPattern_DRAFT_API_DO_NOT_USE
# define ulocdata_getLocaleSeparator ulocdata_getLocaleSeparator_DRAFT_API_DO_NOT_USE
# define uset_closeOver uset_closeOver_DRAFT_API_DO_NOT_USE
# define uset_openEmpty uset_openEmpty_DRAFT_API_DO_NOT_USE
# define uset_removeAllStrings uset_removeAllStrings_DRAFT_API_DO_NOT_USE
# define uspoof_areConfusable uspoof_areConfusable_DRAFT_API_DO_NOT_USE
# define uspoof_areConfusableUTF8 uspoof_areConfusableUTF8_DRAFT_API_DO_NOT_USE
# define uspoof_check uspoof_check_DRAFT_API_DO_NOT_USE
# define uspoof_checkUTF8 uspoof_checkUTF8_DRAFT_API_DO_NOT_USE
# define uspoof_clone uspoof_clone_DRAFT_API_DO_NOT_USE
# define uspoof_close uspoof_close_DRAFT_API_DO_NOT_USE
# define uspoof_getAllowedChars uspoof_getAllowedChars_DRAFT_API_DO_NOT_USE
# define uspoof_getAllowedLocales uspoof_getAllowedLocales_DRAFT_API_DO_NOT_USE
# define uspoof_getChecks uspoof_getChecks_DRAFT_API_DO_NOT_USE
# define uspoof_getSkeleton uspoof_getSkeleton_DRAFT_API_DO_NOT_USE
# define uspoof_getSkeletonUTF8 uspoof_getSkeletonUTF8_DRAFT_API_DO_NOT_USE
# define uspoof_open uspoof_open_DRAFT_API_DO_NOT_USE
# define uspoof_openFromSerialized uspoof_openFromSerialized_DRAFT_API_DO_NOT_USE
# define uspoof_openFromSource uspoof_openFromSource_DRAFT_API_DO_NOT_USE
# define uspoof_serialize uspoof_serialize_DRAFT_API_DO_NOT_USE
# define uspoof_setAllowedChars uspoof_setAllowedChars_DRAFT_API_DO_NOT_USE
# define uspoof_setAllowedLocales uspoof_setAllowedLocales_DRAFT_API_DO_NOT_USE
# define uspoof_setChecks uspoof_setChecks_DRAFT_API_DO_NOT_USE
# define usprep_openByType usprep_openByType_DRAFT_API_DO_NOT_USE
# else
# define u_compareVersions_4_2 u_compareVersions_DRAFT_API_DO_NOT_USE
# define u_strFromUTF32WithSub_4_2 u_strFromUTF32WithSub_DRAFT_API_DO_NOT_USE
# define u_strToUTF32WithSub_4_2 u_strToUTF32WithSub_DRAFT_API_DO_NOT_USE
# define u_versionFromUString_4_2 u_versionFromUString_DRAFT_API_DO_NOT_USE
# define ucal_getKeywordValuesForLocale_4_2 ucal_getKeywordValuesForLocale_DRAFT_API_DO_NOT_USE
# define ucal_getType_4_2 ucal_getType_DRAFT_API_DO_NOT_USE
# define ucnvsel_close_4_2 ucnvsel_close_DRAFT_API_DO_NOT_USE
# define ucnvsel_openFromSerialized_4_2 ucnvsel_openFromSerialized_DRAFT_API_DO_NOT_USE
# define ucnvsel_open_4_2 ucnvsel_open_DRAFT_API_DO_NOT_USE
# define ucnvsel_selectForString_4_2 ucnvsel_selectForString_DRAFT_API_DO_NOT_USE
# define ucnvsel_selectForUTF8_4_2 ucnvsel_selectForUTF8_DRAFT_API_DO_NOT_USE
# define ucnvsel_serialize_4_2 ucnvsel_serialize_DRAFT_API_DO_NOT_USE
# define ucol_getKeywordValuesForLocale_4_2 ucol_getKeywordValuesForLocale_DRAFT_API_DO_NOT_USE
# define ucurr_getKeywordValuesForLocale_4_2 ucurr_getKeywordValuesForLocale_DRAFT_API_DO_NOT_USE
# define ucurr_getPluralName_4_2 ucurr_getPluralName_DRAFT_API_DO_NOT_USE
# define uloc_forLanguageTag_4_2 uloc_forLanguageTag_DRAFT_API_DO_NOT_USE
# define uloc_toLanguageTag_4_2 uloc_toLanguageTag_DRAFT_API_DO_NOT_USE
# define ulocdata_getCLDRVersion_4_2 ulocdata_getCLDRVersion_DRAFT_API_DO_NOT_USE
# define ulocdata_getLocaleDisplayPattern_4_2 ulocdata_getLocaleDisplayPattern_DRAFT_API_DO_NOT_USE
# define ulocdata_getLocaleSeparator_4_2 ulocdata_getLocaleSeparator_DRAFT_API_DO_NOT_USE
# define uset_closeOver_4_2 uset_closeOver_DRAFT_API_DO_NOT_USE
# define uset_openEmpty_4_2 uset_openEmpty_DRAFT_API_DO_NOT_USE
# define uset_removeAllStrings_4_2 uset_removeAllStrings_DRAFT_API_DO_NOT_USE
# define uspoof_areConfusableUTF8_4_2 uspoof_areConfusableUTF8_DRAFT_API_DO_NOT_USE
# define uspoof_areConfusable_4_2 uspoof_areConfusable_DRAFT_API_DO_NOT_USE
# define uspoof_checkUTF8_4_2 uspoof_checkUTF8_DRAFT_API_DO_NOT_USE
# define uspoof_check_4_2 uspoof_check_DRAFT_API_DO_NOT_USE
# define uspoof_clone_4_2 uspoof_clone_DRAFT_API_DO_NOT_USE
# define uspoof_close_4_2 uspoof_close_DRAFT_API_DO_NOT_USE
# define uspoof_getAllowedChars_4_2 uspoof_getAllowedChars_DRAFT_API_DO_NOT_USE
# define uspoof_getAllowedLocales_4_2 uspoof_getAllowedLocales_DRAFT_API_DO_NOT_USE
# define uspoof_getChecks_4_2 uspoof_getChecks_DRAFT_API_DO_NOT_USE
# define uspoof_getSkeletonUTF8_4_2 uspoof_getSkeletonUTF8_DRAFT_API_DO_NOT_USE
# define uspoof_getSkeleton_4_2 uspoof_getSkeleton_DRAFT_API_DO_NOT_USE
# define uspoof_openFromSerialized_4_2 uspoof_openFromSerialized_DRAFT_API_DO_NOT_USE
# define uspoof_openFromSource_4_2 uspoof_openFromSource_DRAFT_API_DO_NOT_USE
# define uspoof_open_4_2 uspoof_open_DRAFT_API_DO_NOT_USE
# define uspoof_serialize_4_2 uspoof_serialize_DRAFT_API_DO_NOT_USE
# define uspoof_setAllowedChars_4_2 uspoof_setAllowedChars_DRAFT_API_DO_NOT_USE
# define uspoof_setAllowedLocales_4_2 uspoof_setAllowedLocales_DRAFT_API_DO_NOT_USE
# define uspoof_setChecks_4_2 uspoof_setChecks_DRAFT_API_DO_NOT_USE
# define usprep_openByType_4_2 usprep_openByType_DRAFT_API_DO_NOT_USE
# endif /* U_DISABLE_RENAMING */
#endif /* U_HIDE_DRAFT_API */
#endif /* UDRAFT_H */
+154
View File
@@ -0,0 +1,154 @@
/*
*******************************************************************************
*
* Copyright (C) 2002-2009, International Business Machines
* Corporation and others. All Rights Reserved.
*
*******************************************************************************
* file name: uenum.h
* encoding: US-ASCII
* tab size: 8 (not used)
* indentation:2
*
* created on: 2002jul08
* created by: Vladimir Weinstein
*/
#ifndef __UENUM_H
#define __UENUM_H
#include "unicode/utypes.h"
#ifdef XP_CPLUSPLUS
#include "unicode/strenum.h"
#endif
/**
* \file
* \brief C API: String Enumeration
*/
/**
* An enumeration object.
* For usage in C programs.
* @stable ICU 2.2
*/
struct UEnumeration;
/** structure representing an enumeration object instance @stable ICU 2.2 */
typedef struct UEnumeration UEnumeration;
/**
* Disposes of resources in use by the iterator. If en is NULL,
* does nothing. After this call, any char* or UChar* pointer
* returned by uenum_unext() or uenum_next() is invalid.
* @param en UEnumeration structure pointer
* @stable ICU 2.2
*/
U_STABLE void U_EXPORT2
uenum_close(UEnumeration* en);
/**
* Returns the number of elements that the iterator traverses. If
* the iterator is out-of-sync with its service, status is set to
* U_ENUM_OUT_OF_SYNC_ERROR.
* This is a convenience function. It can end up being very
* expensive as all the items might have to be pre-fetched (depending
* on the type of data being traversed). Use with caution and only
* when necessary.
* @param en UEnumeration structure pointer
* @param status error code, can be U_ENUM_OUT_OF_SYNC_ERROR if the
* iterator is out of sync.
* @return number of elements in the iterator
* @stable ICU 2.2
*/
U_STABLE int32_t U_EXPORT2
uenum_count(UEnumeration* en, UErrorCode* status);
/**
* Returns the next element in the iterator's list. If there are
* no more elements, returns NULL. If the iterator is out-of-sync
* with its service, status is set to U_ENUM_OUT_OF_SYNC_ERROR and
* NULL is returned. If the native service string is a char* string,
* it is converted to UChar* with the invariant converter.
* The result is terminated by (UChar)0.
* @param en the iterator object
* @param resultLength pointer to receive the length of the result
* (not including the terminating \\0).
* If the pointer is NULL it is ignored.
* @param status the error code, set to U_ENUM_OUT_OF_SYNC_ERROR if
* the iterator is out of sync with its service.
* @return a pointer to the string. The string will be
* zero-terminated. The return pointer is owned by this iterator
* and must not be deleted by the caller. The pointer is valid
* until the next call to any uenum_... method, including
* uenum_next() or uenum_unext(). When all strings have been
* traversed, returns NULL.
* @stable ICU 2.2
*/
U_STABLE const UChar* U_EXPORT2
uenum_unext(UEnumeration* en,
int32_t* resultLength,
UErrorCode* status);
/**
* Returns the next element in the iterator's list. If there are
* no more elements, returns NULL. If the iterator is out-of-sync
* with its service, status is set to U_ENUM_OUT_OF_SYNC_ERROR and
* NULL is returned. If the native service string is a UChar*
* string, it is converted to char* with the invariant converter.
* The result is terminated by (char)0. If the conversion fails
* (because a character cannot be converted) then status is set to
* U_INVARIANT_CONVERSION_ERROR and the return value is undefined
* (but non-NULL).
* @param en the iterator object
* @param resultLength pointer to receive the length of the result
* (not including the terminating \\0).
* If the pointer is NULL it is ignored.
* @param status the error code, set to U_ENUM_OUT_OF_SYNC_ERROR if
* the iterator is out of sync with its service. Set to
* U_INVARIANT_CONVERSION_ERROR if the underlying native string is
* UChar* and conversion to char* with the invariant converter
* fails. This error pertains only to current string, so iteration
* might be able to continue successfully.
* @return a pointer to the string. The string will be
* zero-terminated. The return pointer is owned by this iterator
* and must not be deleted by the caller. The pointer is valid
* until the next call to any uenum_... method, including
* uenum_next() or uenum_unext(). When all strings have been
* traversed, returns NULL.
* @stable ICU 2.2
*/
U_STABLE const char* U_EXPORT2
uenum_next(UEnumeration* en,
int32_t* resultLength,
UErrorCode* status);
/**
* Resets the iterator to the current list of service IDs. This
* re-establishes sync with the service and rewinds the iterator
* to start at the first element.
* @param en the iterator object
* @param status the error code, set to U_ENUM_OUT_OF_SYNC_ERROR if
* the iterator is out of sync with its service.
* @stable ICU 2.2
*/
U_STABLE void U_EXPORT2
uenum_reset(UEnumeration* en, UErrorCode* status);
#ifdef XP_CPLUSPLUS
/**
* Given a StringEnumeration, wrap it in a UEnumeration. The
* StringEnumeration is adopted; after this call, the caller must not
* delete it (regardless of error status).
* @param adopted the C++ StringEnumeration to be wrapped in a UEnumeration.
* @param ec the error code.
* @return a UEnumeration wrapping the adopted StringEnumeration.
* @draft ICU 4.2
*/
U_CAPI UEnumeration* U_EXPORT2
uenum_openFromStringEnumeration(U_NAMESPACE_QUALIFIER StringEnumeration* adopted, UErrorCode* ec);
#endif
#endif

Some files were not shown because too many files have changed in this diff Show More