ICU-13597 Adding initial C API for NumberFormatter. Not yet fully featured.

X-SVN-Rev: 41156
This commit is contained in:
Shane Carr 2018-03-27 01:58:26 +00:00
parent 3574a63853
commit 3a55650b8c
13 changed files with 1109 additions and 504 deletions

View File

@ -108,7 +108,7 @@ double-conversion-cached-powers.o double-conversion-diy-fp.o double-conversion-f
numparse_stringsegment.o numparse_unisets.o numparse_parsednumber.o \
numparse_impl.o numparse_symbols.o numparse_decimal.o numparse_scientific.o \
numparse_currency.o numparse_affixes.o numparse_compositions.o numparse_validators.o \
number_mapper.o number_multiplier.o number_currencysymbols.o number_skeletons.o
number_mapper.o number_multiplier.o number_currencysymbols.o number_skeletons.o number_capi.o \
## Header files to install

View File

@ -0,0 +1,197 @@
// © 2018 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
#include "unicode/utypes.h"
#if !UCONFIG_NO_FORMATTING && !UPRV_INCOMPLETE_CPP11_SUPPORT
// Allow implicit conversion from char16_t* to UnicodeString for this file:
// Helpful in toString methods and elsewhere.
#define UNISTR_FROM_STRING_EXPLICIT
#include "numparse_types.h"
#include "number_utypes.h"
#include "unicode/numberformatter.h"
#include "unicode/unumberformatter.h"
using namespace icu;
using namespace icu::number;
using namespace icu::number::impl;
//////////////////////////////////
/// C API CONVERSION FUNCTIONS ///
//////////////////////////////////
UNumberFormatterData* UNumberFormatterData::validate(UNumberFormatter* input, UErrorCode& status) {
auto* constInput = static_cast<const UNumberFormatter*>(input);
auto* validated = validate(constInput, status);
return const_cast<UNumberFormatterData*>(validated);
}
const UNumberFormatterData*
UNumberFormatterData::validate(const UNumberFormatter* input, UErrorCode& status) {
if (U_FAILURE(status)) {
return nullptr;
}
if (input == nullptr) {
status = U_ILLEGAL_ARGUMENT_ERROR;
return nullptr;
}
auto* impl = reinterpret_cast<const UNumberFormatterData*>(input);
if (impl->fMagic != UNumberFormatterData::kMagic) {
status = U_INVALID_FORMAT_ERROR;
return nullptr;
}
return impl;
}
UNumberFormatter* UNumberFormatterData::exportForC() {
return reinterpret_cast<UNumberFormatter*>(this);
}
UFormattedNumberData* UFormattedNumberData::validate(UFormattedNumber* input, UErrorCode& status) {
auto* constInput = static_cast<const UFormattedNumber*>(input);
auto* validated = validate(constInput, status);
return const_cast<UFormattedNumberData*>(validated);
}
const UFormattedNumberData*
UFormattedNumberData::validate(const UFormattedNumber* input, UErrorCode& status) {
if (U_FAILURE(status)) {
return nullptr;
}
if (input == nullptr) {
status = U_ILLEGAL_ARGUMENT_ERROR;
return nullptr;
}
auto* impl = reinterpret_cast<const UFormattedNumberData*>(input);
if (impl->fMagic != UFormattedNumberData::kMagic) {
status = U_INVALID_FORMAT_ERROR;
return nullptr;
}
return impl;
}
UFormattedNumber* UFormattedNumberData::exportForC() {
return reinterpret_cast<UFormattedNumber*>(this);
}
/////////////////////////////////////
/// END CAPI CONVERSION FUNCTIONS ///
/////////////////////////////////////
U_CAPI UNumberFormatter* U_EXPORT2
unumf_openFromSkeletonAndLocale(const UChar* skeleton, int32_t skeletonLen, const char* locale,
UErrorCode* ec) {
auto* impl = new UNumberFormatterData();
if (impl == nullptr) {
*ec = U_MEMORY_ALLOCATION_ERROR;
return nullptr;
}
// Readonly-alias constructor (first argument is whether we are NUL-terminated)
UnicodeString skeletonString(skeletonLen == -1, skeleton, skeletonLen);
impl->fFormatter = NumberFormatter::fromSkeleton(skeletonString, *ec).locale(locale);
return impl->exportForC();
}
U_CAPI UFormattedNumber* U_EXPORT2
unumf_openResult(UErrorCode* ec) {
auto* impl = new UFormattedNumberData();
if (impl == nullptr) {
*ec = U_MEMORY_ALLOCATION_ERROR;
return nullptr;
}
return impl->exportForC();
}
U_CAPI void U_EXPORT2
unumf_formatInt(const UNumberFormatter* uformatter, int64_t value, UFormattedNumber* uresult,
UErrorCode* ec) {
const UNumberFormatterData* formatter = UNumberFormatterData::validate(uformatter, *ec);
UFormattedNumberData* result = UFormattedNumberData::validate(uresult, *ec);
if (U_FAILURE(*ec)) { return; }
result->string.clear();
result->quantity.setToLong(value);
formatter->fFormatter.formatImpl(result, *ec);
}
U_CAPI void U_EXPORT2
unumf_formatDouble(const UNumberFormatter* uformatter, double value, UFormattedNumber* uresult,
UErrorCode* ec) {
const UNumberFormatterData* formatter = UNumberFormatterData::validate(uformatter, *ec);
UFormattedNumberData* result = UFormattedNumberData::validate(uresult, *ec);
if (U_FAILURE(*ec)) { return; }
result->string.clear();
result->quantity.setToDouble(value);
formatter->fFormatter.formatImpl(result, *ec);
}
U_CAPI void U_EXPORT2
unumf_formatDecimal(const UNumberFormatter* uformatter, const char* value, int32_t valueLen,
UFormattedNumber* uresult, UErrorCode* ec) {
const UNumberFormatterData* formatter = UNumberFormatterData::validate(uformatter, *ec);
UFormattedNumberData* result = UFormattedNumberData::validate(uresult, *ec);
if (U_FAILURE(*ec)) { return; }
result->string.clear();
result->quantity.setToDecNumber({value, valueLen}, *ec);
if (U_FAILURE(*ec)) { return; }
formatter->fFormatter.formatImpl(result, *ec);
}
U_CAPI int32_t U_EXPORT2
unumf_resultToString(const UFormattedNumber* uresult, UChar* buffer, int32_t bufferCapacity,
UErrorCode* ec) {
const UFormattedNumberData* result = UFormattedNumberData::validate(uresult, *ec);
if (U_FAILURE(*ec)) { return 0; }
return result->string.toUnicodeString().extract(buffer, bufferCapacity, *ec);
}
U_CAPI void U_EXPORT2
unumf_closeResult(const UFormattedNumber* uresult, UErrorCode* ec) {
const UFormattedNumberData* impl = UFormattedNumberData::validate(uresult, *ec);
if (U_FAILURE(*ec)) { return; }
delete impl;
}
U_CAPI void U_EXPORT2
unumf_close(UNumberFormatter* f, UErrorCode* ec) {
const UNumberFormatterData* impl = UNumberFormatterData::validate(f, *ec);
if (U_FAILURE(*ec)) { return; }
delete impl;
}
#endif /* #if !UCONFIG_NO_FORMATTING */

View File

@ -12,13 +12,14 @@
#include "number_formatimpl.h"
#include "umutex.h"
#include "number_skeletons.h"
#include "number_utypes.h"
using namespace icu;
using namespace icu::number;
using namespace icu::number::impl;
template<typename Derived>
Derived NumberFormatterSettings<Derived>::notation(const Notation& notation) const & {
Derived NumberFormatterSettings<Derived>::notation(const Notation& notation) const& {
Derived copy(*this);
// NOTE: Slicing is OK.
copy.fMacros.notation = notation;
@ -26,7 +27,7 @@ Derived NumberFormatterSettings<Derived>::notation(const Notation& notation) con
}
template<typename Derived>
Derived NumberFormatterSettings<Derived>::notation(const Notation& notation) && {
Derived NumberFormatterSettings<Derived>::notation(const Notation& notation)&& {
Derived move(std::move(*this));
// NOTE: Slicing is OK.
move.fMacros.notation = notation;
@ -34,7 +35,7 @@ Derived NumberFormatterSettings<Derived>::notation(const Notation& notation) &&
}
template<typename Derived>
Derived NumberFormatterSettings<Derived>::unit(const icu::MeasureUnit& unit) const & {
Derived NumberFormatterSettings<Derived>::unit(const icu::MeasureUnit& unit) const& {
Derived copy(*this);
// NOTE: Slicing occurs here. However, CurrencyUnit can be restored from MeasureUnit.
// TimeUnit may be affected, but TimeUnit is not as relevant to number formatting.
@ -43,7 +44,7 @@ Derived NumberFormatterSettings<Derived>::unit(const icu::MeasureUnit& unit) con
}
template<typename Derived>
Derived NumberFormatterSettings<Derived>::unit(const icu::MeasureUnit& unit) && {
Derived NumberFormatterSettings<Derived>::unit(const icu::MeasureUnit& unit)&& {
Derived move(std::move(*this));
// See comments above about slicing.
move.fMacros.unit = unit;
@ -51,7 +52,7 @@ Derived NumberFormatterSettings<Derived>::unit(const icu::MeasureUnit& unit) &&
}
template<typename Derived>
Derived NumberFormatterSettings<Derived>::adoptUnit(icu::MeasureUnit* unit) const & {
Derived NumberFormatterSettings<Derived>::adoptUnit(icu::MeasureUnit* unit) const& {
Derived copy(*this);
// Just move the unit into the MacroProps by value, and delete it since we have ownership.
// NOTE: Slicing occurs here. However, CurrencyUnit can be restored from MeasureUnit.
@ -65,7 +66,7 @@ Derived NumberFormatterSettings<Derived>::adoptUnit(icu::MeasureUnit* unit) cons
}
template<typename Derived>
Derived NumberFormatterSettings<Derived>::adoptUnit(icu::MeasureUnit* unit) && {
Derived NumberFormatterSettings<Derived>::adoptUnit(icu::MeasureUnit* unit)&& {
Derived move(std::move(*this));
// See comments above about slicing and ownership.
if (unit != nullptr) {
@ -77,7 +78,7 @@ Derived NumberFormatterSettings<Derived>::adoptUnit(icu::MeasureUnit* unit) && {
}
template<typename Derived>
Derived NumberFormatterSettings<Derived>::perUnit(const icu::MeasureUnit& perUnit) const & {
Derived NumberFormatterSettings<Derived>::perUnit(const icu::MeasureUnit& perUnit) const& {
Derived copy(*this);
// See comments above about slicing.
copy.fMacros.perUnit = perUnit;
@ -85,7 +86,7 @@ Derived NumberFormatterSettings<Derived>::perUnit(const icu::MeasureUnit& perUni
}
template<typename Derived>
Derived NumberFormatterSettings<Derived>::perUnit(const icu::MeasureUnit& perUnit) && {
Derived NumberFormatterSettings<Derived>::perUnit(const icu::MeasureUnit& perUnit)&& {
Derived copy(*this);
// See comments above about slicing.
copy.fMacros.perUnit = perUnit;
@ -93,7 +94,7 @@ Derived NumberFormatterSettings<Derived>::perUnit(const icu::MeasureUnit& perUni
}
template<typename Derived>
Derived NumberFormatterSettings<Derived>::adoptPerUnit(icu::MeasureUnit* perUnit) const & {
Derived NumberFormatterSettings<Derived>::adoptPerUnit(icu::MeasureUnit* perUnit) const& {
Derived move(std::move(*this));
// See comments above about slicing and ownership.
if (perUnit != nullptr) {
@ -105,7 +106,7 @@ Derived NumberFormatterSettings<Derived>::adoptPerUnit(icu::MeasureUnit* perUnit
}
template<typename Derived>
Derived NumberFormatterSettings<Derived>::adoptPerUnit(icu::MeasureUnit* perUnit) && {
Derived NumberFormatterSettings<Derived>::adoptPerUnit(icu::MeasureUnit* perUnit)&& {
Derived copy(*this);
// See comments above about slicing and ownership.
if (perUnit != nullptr) {
@ -117,7 +118,7 @@ Derived NumberFormatterSettings<Derived>::adoptPerUnit(icu::MeasureUnit* perUnit
}
template<typename Derived>
Derived NumberFormatterSettings<Derived>::rounding(const Rounder& rounder) const & {
Derived NumberFormatterSettings<Derived>::rounding(const Rounder& rounder) const& {
Derived copy(*this);
// NOTE: Slicing is OK.
copy.fMacros.rounder = rounder;
@ -125,7 +126,7 @@ Derived NumberFormatterSettings<Derived>::rounding(const Rounder& rounder) const
}
template<typename Derived>
Derived NumberFormatterSettings<Derived>::rounding(const Rounder& rounder) && {
Derived NumberFormatterSettings<Derived>::rounding(const Rounder& rounder)&& {
Derived move(std::move(*this));
// NOTE: Slicing is OK.
move.fMacros.rounder = rounder;
@ -133,7 +134,7 @@ Derived NumberFormatterSettings<Derived>::rounding(const Rounder& rounder) && {
}
template<typename Derived>
Derived NumberFormatterSettings<Derived>::grouping(const UGroupingStrategy& strategy) const & {
Derived NumberFormatterSettings<Derived>::grouping(const UGroupingStrategy& strategy) const& {
Derived copy(*this);
// NOTE: This is slightly different than how the setting is stored in Java
// because we want to put it on the stack.
@ -142,147 +143,147 @@ Derived NumberFormatterSettings<Derived>::grouping(const UGroupingStrategy& stra
}
template<typename Derived>
Derived NumberFormatterSettings<Derived>::grouping(const UGroupingStrategy& strategy) && {
Derived NumberFormatterSettings<Derived>::grouping(const UGroupingStrategy& strategy)&& {
Derived move(std::move(*this));
move.fMacros.grouper = Grouper::forStrategy(strategy);
return move;
}
template<typename Derived>
Derived NumberFormatterSettings<Derived>::integerWidth(const IntegerWidth& style) const & {
Derived NumberFormatterSettings<Derived>::integerWidth(const IntegerWidth& style) const& {
Derived copy(*this);
copy.fMacros.integerWidth = style;
return copy;
}
template<typename Derived>
Derived NumberFormatterSettings<Derived>::integerWidth(const IntegerWidth& style) && {
Derived NumberFormatterSettings<Derived>::integerWidth(const IntegerWidth& style)&& {
Derived move(std::move(*this));
move.fMacros.integerWidth = style;
return move;
}
template<typename Derived>
Derived NumberFormatterSettings<Derived>::symbols(const DecimalFormatSymbols& symbols) const & {
Derived NumberFormatterSettings<Derived>::symbols(const DecimalFormatSymbols& symbols) const& {
Derived copy(*this);
copy.fMacros.symbols.setTo(symbols);
return copy;
}
template<typename Derived>
Derived NumberFormatterSettings<Derived>::symbols(const DecimalFormatSymbols& symbols) && {
Derived NumberFormatterSettings<Derived>::symbols(const DecimalFormatSymbols& symbols)&& {
Derived move(std::move(*this));
move.fMacros.symbols.setTo(symbols);
return move;
}
template<typename Derived>
Derived NumberFormatterSettings<Derived>::adoptSymbols(NumberingSystem* ns) const & {
Derived NumberFormatterSettings<Derived>::adoptSymbols(NumberingSystem* ns) const& {
Derived copy(*this);
copy.fMacros.symbols.setTo(ns);
return copy;
}
template<typename Derived>
Derived NumberFormatterSettings<Derived>::adoptSymbols(NumberingSystem* ns) && {
Derived NumberFormatterSettings<Derived>::adoptSymbols(NumberingSystem* ns)&& {
Derived move(std::move(*this));
move.fMacros.symbols.setTo(ns);
return move;
}
template<typename Derived>
Derived NumberFormatterSettings<Derived>::unitWidth(const UNumberUnitWidth& width) const & {
Derived NumberFormatterSettings<Derived>::unitWidth(const UNumberUnitWidth& width) const& {
Derived copy(*this);
copy.fMacros.unitWidth = width;
return copy;
}
template<typename Derived>
Derived NumberFormatterSettings<Derived>::unitWidth(const UNumberUnitWidth& width) && {
Derived NumberFormatterSettings<Derived>::unitWidth(const UNumberUnitWidth& width)&& {
Derived move(std::move(*this));
move.fMacros.unitWidth = width;
return move;
}
template<typename Derived>
Derived NumberFormatterSettings<Derived>::sign(const UNumberSignDisplay& style) const & {
Derived NumberFormatterSettings<Derived>::sign(const UNumberSignDisplay& style) const& {
Derived copy(*this);
copy.fMacros.sign = style;
return copy;
}
template<typename Derived>
Derived NumberFormatterSettings<Derived>::sign(const UNumberSignDisplay& style) && {
Derived NumberFormatterSettings<Derived>::sign(const UNumberSignDisplay& style)&& {
Derived move(std::move(*this));
move.fMacros.sign = style;
return move;
}
template<typename Derived>
Derived NumberFormatterSettings<Derived>::decimal(const UNumberDecimalSeparatorDisplay& style) const & {
Derived NumberFormatterSettings<Derived>::decimal(const UNumberDecimalSeparatorDisplay& style) const& {
Derived copy(*this);
copy.fMacros.decimal = style;
return copy;
}
template<typename Derived>
Derived NumberFormatterSettings<Derived>::decimal(const UNumberDecimalSeparatorDisplay& style) && {
Derived NumberFormatterSettings<Derived>::decimal(const UNumberDecimalSeparatorDisplay& style)&& {
Derived move(std::move(*this));
move.fMacros.decimal = style;
return move;
}
template<typename Derived>
Derived NumberFormatterSettings<Derived>::padding(const Padder& padder) const & {
Derived NumberFormatterSettings<Derived>::padding(const Padder& padder) const& {
Derived copy(*this);
copy.fMacros.padder = padder;
return copy;
}
template<typename Derived>
Derived NumberFormatterSettings<Derived>::padding(const Padder& padder) && {
Derived NumberFormatterSettings<Derived>::padding(const Padder& padder)&& {
Derived move(std::move(*this));
move.fMacros.padder = padder;
return move;
}
template<typename Derived>
Derived NumberFormatterSettings<Derived>::threshold(int32_t threshold) const & {
Derived NumberFormatterSettings<Derived>::threshold(int32_t threshold) const& {
Derived copy(*this);
copy.fMacros.threshold = threshold;
return copy;
}
template<typename Derived>
Derived NumberFormatterSettings<Derived>::threshold(int32_t threshold) && {
Derived NumberFormatterSettings<Derived>::threshold(int32_t threshold)&& {
Derived move(std::move(*this));
move.fMacros.threshold = threshold;
return move;
}
template<typename Derived>
Derived NumberFormatterSettings<Derived>::macros(const impl::MacroProps& macros) const & {
Derived NumberFormatterSettings<Derived>::macros(const impl::MacroProps& macros) const& {
Derived copy(*this);
copy.fMacros = macros;
return copy;
}
template<typename Derived>
Derived NumberFormatterSettings<Derived>::macros(const impl::MacroProps& macros) && {
Derived NumberFormatterSettings<Derived>::macros(const impl::MacroProps& macros)&& {
Derived move(std::move(*this));
move.fMacros = macros;
return move;
}
template<typename Derived>
Derived NumberFormatterSettings<Derived>::macros(impl::MacroProps&& macros) const & {
Derived NumberFormatterSettings<Derived>::macros(impl::MacroProps&& macros) const& {
Derived copy(*this);
copy.fMacros = std::move(macros);
return copy;
}
template<typename Derived>
Derived NumberFormatterSettings<Derived>::macros(impl::MacroProps&& macros) && {
Derived NumberFormatterSettings<Derived>::macros(impl::MacroProps&& macros)&& {
Derived move(std::move(*this));
move.fMacros = std::move(macros);
return move;
@ -316,8 +317,7 @@ NumberFormatter::fromSkeleton(const UnicodeString& skeleton, UErrorCode& status)
}
template<typename T>
using NFS = NumberFormatterSettings<T>;
template<typename T> using NFS = NumberFormatterSettings<T>;
using LNF = LocalizedNumberFormatter;
using UNF = UnlocalizedNumberFormatter;
@ -403,11 +403,11 @@ LocalizedNumberFormatter::LocalizedNumberFormatter(MacroProps&& macros, const Lo
fMacros.locale = locale;
}
LocalizedNumberFormatter UnlocalizedNumberFormatter::locale(const Locale& locale) const & {
LocalizedNumberFormatter UnlocalizedNumberFormatter::locale(const Locale& locale) const& {
return LocalizedNumberFormatter(fMacros, locale);
}
LocalizedNumberFormatter UnlocalizedNumberFormatter::locale(const Locale& locale) && {
LocalizedNumberFormatter UnlocalizedNumberFormatter::locale(const Locale& locale)&& {
return LocalizedNumberFormatter(std::move(fMacros), locale);
}
@ -547,51 +547,82 @@ FormattedNumber& FormattedNumber::operator=(FormattedNumber&& src) U_NOEXCEPT {
FormattedNumber LocalizedNumberFormatter::formatInt(int64_t value, UErrorCode& status) const {
if (U_FAILURE(status)) { return FormattedNumber(U_ILLEGAL_ARGUMENT_ERROR); }
auto results = new NumberFormatterResults();
auto results = new UFormattedNumberData();
if (results == nullptr) {
status = U_MEMORY_ALLOCATION_ERROR;
return FormattedNumber(status);
}
results->quantity.setToLong(value);
return formatImpl(results, status);
formatImpl(results, status);
// Do not save the results object if we encountered a failure.
if (U_SUCCESS(status)) {
return FormattedNumber(results);
} else {
delete results;
return FormattedNumber(status);
}
}
FormattedNumber LocalizedNumberFormatter::formatDouble(double value, UErrorCode& status) const {
if (U_FAILURE(status)) { return FormattedNumber(U_ILLEGAL_ARGUMENT_ERROR); }
auto results = new NumberFormatterResults();
auto results = new UFormattedNumberData();
if (results == nullptr) {
status = U_MEMORY_ALLOCATION_ERROR;
return FormattedNumber(status);
}
results->quantity.setToDouble(value);
return formatImpl(results, status);
formatImpl(results, status);
// Do not save the results object if we encountered a failure.
if (U_SUCCESS(status)) {
return FormattedNumber(results);
} else {
delete results;
return FormattedNumber(status);
}
}
FormattedNumber LocalizedNumberFormatter::formatDecimal(StringPiece value, UErrorCode& status) const {
if (U_FAILURE(status)) { return FormattedNumber(U_ILLEGAL_ARGUMENT_ERROR); }
auto results = new NumberFormatterResults();
auto results = new UFormattedNumberData();
if (results == nullptr) {
status = U_MEMORY_ALLOCATION_ERROR;
return FormattedNumber(status);
}
results->quantity.setToDecNumber(value, status);
return formatImpl(results, status);
formatImpl(results, status);
// Do not save the results object if we encountered a failure.
if (U_SUCCESS(status)) {
return FormattedNumber(results);
} else {
delete results;
return FormattedNumber(status);
}
}
FormattedNumber
LocalizedNumberFormatter::formatDecimalQuantity(const DecimalQuantity& dq, UErrorCode& status) const {
if (U_FAILURE(status)) { return FormattedNumber(U_ILLEGAL_ARGUMENT_ERROR); }
auto results = new NumberFormatterResults();
auto results = new UFormattedNumberData();
if (results == nullptr) {
status = U_MEMORY_ALLOCATION_ERROR;
return FormattedNumber(status);
}
results->quantity = dq;
return formatImpl(results, status);
formatImpl(results, status);
// Do not save the results object if we encountered a failure.
if (U_SUCCESS(status)) {
return FormattedNumber(results);
} else {
delete results;
return FormattedNumber(status);
}
}
FormattedNumber
LocalizedNumberFormatter::formatImpl(impl::NumberFormatterResults* results, UErrorCode& status) const {
void LocalizedNumberFormatter::formatImpl(impl::UFormattedNumberData* results, UErrorCode& status) const {
// fUnsafeCallCount contains memory to be interpreted as an atomic int, most commonly
// std::atomic<int32_t>. Since the type of atomic int is platform-dependent, we cast the
// bytes in fUnsafeCallCount to u_atomic_int32_t, a typedef for the platform-dependent
@ -627,14 +658,6 @@ LocalizedNumberFormatter::formatImpl(impl::NumberFormatterResults* results, UErr
// Format the number without building the data structure (slow path).
NumberFormatterImpl::applyStatic(fMacros, results->quantity, results->string, status);
}
// Do not save the results object if we encountered a failure.
if (U_SUCCESS(status)) {
return FormattedNumber(results);
} else {
delete results;
return FormattedNumber(status);
}
}
const impl::NumberFormatterImpl* LocalizedNumberFormatter::getCompiled() const {

View File

@ -334,7 +334,8 @@ int32_t NumberStringBuilder::remove(int32_t index, int32_t count) {
}
UnicodeString NumberStringBuilder::toUnicodeString() const {
return UnicodeString(getCharPtr() + fZero, fLength);
// Readonly-alias constructor:
return UnicodeString(FALSE, getCharPtr() + fZero, fLength);
}
UnicodeString NumberStringBuilder::toDebugString() const {

View File

@ -102,17 +102,6 @@ struct MicroProps : public MicroPropsGenerator {
bool exhausted = false;
};
/**
* This struct provides the result of the number formatting pipeline to FormattedNumber.
*
* The DecimalQuantity is not currently being used by FormattedNumber, but at some point it could be used
* to add a toDecNumber() or similar method.
*/
struct NumberFormatterResults : public UMemory {
DecimalQuantity quantity;
NumberStringBuilder string;
};
inline int32_t insertDigitFromSymbols(NumberStringBuilder& output, int32_t index, int8_t digit,
const DecimalFormatSymbols& symbols, Field field,
UErrorCode& status) {

View File

@ -0,0 +1,79 @@
// © 2018 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
#include "unicode/utypes.h"
#if !UCONFIG_NO_FORMATTING && !UPRV_INCOMPLETE_CPP11_SUPPORT
#ifndef __SOURCE_NUMBER_UTYPES_H__
#define __SOURCE_NUMBER_UTYPES_H__
#include "unicode/numberformatter.h"
#include "number_types.h"
#include "number_decimalquantity.h"
#include "number_stringbuilder.h"
U_NAMESPACE_BEGIN namespace number {
namespace impl {
/**
* Implementation class for UNumberFormatter with a magic number for safety.
*
* Wraps a LocalizedNumberFormatter by value.
*/
struct UNumberFormatterData : public UMemory {
// The magic number to identify incoming objects.
// Reads in ASCII as "NFR" (NumberFormatteR with room at the end)
static constexpr int32_t kMagic = 0x4E465200;
// Data members:
int32_t fMagic = kMagic;
LocalizedNumberFormatter fFormatter;
/** Convert from UNumberFormatter -> UNumberFormatterData. */
static UNumberFormatterData* validate(UNumberFormatter* input, UErrorCode& status);
/** Convert from UNumberFormatter -> UNumberFormatterData (const version). */
static const UNumberFormatterData* validate(const UNumberFormatter* input, UErrorCode& status);
/** Convert from UNumberFormatterData -> UNumberFormatter. */
UNumberFormatter* exportForC();
};
/**
* Implementation class for UFormattedNumber with magic number for safety.
*
* This struct is also held internally by the C++ version FormattedNumber since the member types are not
* declared in the public header file.
*
* The DecimalQuantity is not currently being used by FormattedNumber, but at some point it could be used
* to add a toDecNumber() or similar method.
*/
struct UFormattedNumberData : public UMemory {
// The magic number to identify incoming objects.
// Reads in ASCII as "FDN" (FormatteDNumber with room at the end)
static constexpr int32_t kMagic = 0x46444E00;
// Data members:
int32_t fMagic = kMagic;
DecimalQuantity quantity;
NumberStringBuilder string;
/** Convert from UFormattedNumber -> UFormattedNumberData. */
static UFormattedNumberData* validate(UFormattedNumber* input, UErrorCode& status);
/** Convert from UFormattedNumber -> UFormattedNumberData (const version). */
static const UFormattedNumberData* validate(const UFormattedNumber* input, UErrorCode& status);
/** Convert from UFormattedNumberData -> UFormattedNumber. */
UFormattedNumber* exportForC();
};
} // namespace impl
} // namespace number
U_NAMESPACE_END
#endif //__SOURCE_NUMBER_UTYPES_H__
#endif /* #if !UCONFIG_NO_FORMATTING */

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,517 @@
// © 2018 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
#include "unicode/utypes.h"
#if !UCONFIG_NO_FORMATTING && !UPRV_INCOMPLETE_CPP11_SUPPORT
#ifndef __UNUMBERFORMATTER_H__
#define __UNUMBERFORMATTER_H__
/**
* \file
* \brief C-compatible API for localized number formatting; not recommended for C++.
*
* This is the C-compatible version of the NumberFormatter API introduced in ICU 60. C++ users should
* include unicode/numberformatter.h and use the proper C++ APIs.
*/
/**
* An enum declaring how to render units, including currencies. Example outputs when formatting 123 USD and 123
* meters in <em>en-CA</em>:
*
* <p>
* <ul>
* <li>NARROW*: "$123.00" and "123 m"
* <li>SHORT: "US$ 123.00" and "123 m"
* <li>FULL_NAME: "123.00 US dollars" and "123 meters"
* <li>ISO_CODE: "USD 123.00" and undefined behavior
* <li>HIDDEN: "123.00" and "123"
* </ul>
*
* <p>
* This enum is similar to {@link com.ibm.icu.text.MeasureFormat.FormatWidth}.
*
* @draft ICU 60
*/
typedef enum UNumberUnitWidth {
/**
* Print an abbreviated version of the unit name. Similar to SHORT, but always use the shortest available
* abbreviation or symbol. This option can be used when the context hints at the identity of the unit. For more
* information on the difference between NARROW and SHORT, see SHORT.
*
* <p>
* In CLDR, this option corresponds to the "Narrow" format for measure units and the "¤¤¤¤¤" placeholder for
* currencies.
*
* @draft ICU 60
*/
UNUM_UNIT_WIDTH_NARROW,
/**
* Print an abbreviated version of the unit name. Similar to NARROW, but use a slightly wider abbreviation or
* symbol when there may be ambiguity. This is the default behavior.
*
* <p>
* For example, in <em>es-US</em>, the SHORT form for Fahrenheit is "{0} °F", but the NARROW form is "{0}°",
* since Fahrenheit is the customary unit for temperature in that locale.
*
* <p>
* In CLDR, this option corresponds to the "Short" format for measure units and the "¤" placeholder for
* currencies.
*
* @draft ICU 60
*/
UNUM_UNIT_WIDTH_SHORT,
/**
* Print the full name of the unit, without any abbreviations.
*
* <p>
* In CLDR, this option corresponds to the default format for measure units and the "¤¤¤" placeholder for
* currencies.
*
* @draft ICU 60
*/
UNUM_UNIT_WIDTH_FULL_NAME,
/**
* Use the three-digit ISO XXX code in place of the symbol for displaying currencies. The behavior of this
* option is currently undefined for use with measure units.
*
* <p>
* In CLDR, this option corresponds to the "¤¤" placeholder for currencies.
*
* @draft ICU 60
*/
UNUM_UNIT_WIDTH_ISO_CODE,
/**
* Format the number according to the specified unit, but do not display the unit. For currencies, apply
* monetary symbols and formats as with SHORT, but omit the currency symbol. For measure units, the behavior is
* equivalent to not specifying the unit at all.
*
* @draft ICU 60
*/
UNUM_UNIT_WIDTH_HIDDEN,
/**
* One more than the highest UNumberUnitWidth value.
*
* @internal ICU 60: The numeric value may change over time; see ICU ticket #12420.
*/
UNUM_UNIT_WIDTH_COUNT
} UNumberUnitWidth;
/**
* An enum declaring the strategy for when and how to display grouping separators (i.e., the
* separator, often a comma or period, after every 2-3 powers of ten). The choices are several
* pre-built strategies for different use cases that employ locale data whenever possible. Example
* outputs for 1234 and 1234567 in <em>en-IN</em>:
*
* <ul>
* <li>OFF: 1234 and 12345
* <li>MIN2: 1234 and 12,34,567
* <li>AUTO: 1,234 and 12,34,567
* <li>ON_ALIGNED: 1,234 and 12,34,567
* <li>THOUSANDS: 1,234 and 1,234,567
* </ul>
*
* <p>
* The default is AUTO, which displays grouping separators unless the locale data says that grouping
* is not customary. To force grouping for all numbers greater than 1000 consistently across locales,
* use ON_ALIGNED. On the other hand, to display grouping less frequently than the default, use MIN2
* or OFF. See the docs of each option for details.
*
* <p>
* Note: This enum specifies the strategy for grouping sizes. To set which character to use as the
* grouping separator, use the "symbols" setter.
*
* @draft ICU 61 -- TODO: This should be renamed to UNumberGroupingStrategy before promoting to stable,
* for consistency with the other enums.
*/
typedef enum UGroupingStrategy {
/**
* Do not display grouping separators in any locale.
*
* @draft ICU 61
*/
UNUM_GROUPING_OFF,
/**
* Display grouping using locale defaults, except do not show grouping on values smaller than
* 10000 (such that there is a <em>minimum of two digits</em> before the first separator).
*
* <p>
* Note that locales may restrict grouping separators to be displayed only on 1 million or
* greater (for example, ee and hu) or disable grouping altogether (for example, bg currency).
*
* <p>
* Locale data is used to determine whether to separate larger numbers into groups of 2
* (customary in South Asia) or groups of 3 (customary in Europe and the Americas).
*
* @draft ICU 61
*/
UNUM_GROUPING_MIN2,
/**
* Display grouping using the default strategy for all locales. This is the default behavior.
*
* <p>
* Note that locales may restrict grouping separators to be displayed only on 1 million or
* greater (for example, ee and hu) or disable grouping altogether (for example, bg currency).
*
* <p>
* Locale data is used to determine whether to separate larger numbers into groups of 2
* (customary in South Asia) or groups of 3 (customary in Europe and the Americas).
*
* @draft ICU 61
*/
UNUM_GROUPING_AUTO,
/**
* Always display the grouping separator on values of at least 1000.
*
* <p>
* This option ignores the locale data that restricts or disables grouping, described in MIN2 and
* AUTO. This option may be useful to normalize the alignment of numbers, such as in a
* spreadsheet.
*
* <p>
* Locale data is used to determine whether to separate larger numbers into groups of 2
* (customary in South Asia) or groups of 3 (customary in Europe and the Americas).
*
* @draft ICU 61
*/
UNUM_GROUPING_ON_ALIGNED,
/**
* Use the Western defaults: groups of 3 and enabled for all numbers 1000 or greater. Do not use
* locale data for determining the grouping strategy.
*
* @draft ICU 61
*/
UNUM_GROUPING_THOUSANDS,
/**
* One more than the highest UNumberSignDisplay value.
*
* @internal ICU 62: The numeric value may change over time; see ICU ticket #12420.
*/
UNUM_GROUPING_COUNT
} UGroupingStrategy;
/**
* An enum declaring how to denote positive and negative numbers. Example outputs when formatting
* 123, 0, and -123 in <em>en-US</em>:
*
* <ul>
* <li>AUTO: "123", "0", and "-123"
* <li>ALWAYS: "+123", "+0", and "-123"
* <li>NEVER: "123", "0", and "123"
* <li>ACCOUNTING: "$123", "$0", and "($123)"
* <li>ACCOUNTING_ALWAYS: "+$123", "+$0", and "($123)"
* <li>EXCEPT_ZERO: "+123", "0", and "-123"
* <li>ACCOUNTING_EXCEPT_ZERO: "+$123", "$0", and "($123)"
* </ul>
*
* <p>
* The exact format, including the position and the code point of the sign, differ by locale.
*
* @draft ICU 60
*/
typedef enum UNumberSignDisplay {
/**
* Show the minus sign on negative numbers, and do not show the sign on positive numbers. This is the default
* behavior.
*
* @draft ICU 60
*/
UNUM_SIGN_AUTO,
/**
* Show the minus sign on negative numbers and the plus sign on positive numbers, including zero.
* To hide the sign on zero, see {@link UNUM_SIGN_EXCEPT_ZERO}.
*
* @draft ICU 60
*/
UNUM_SIGN_ALWAYS,
/**
* Do not show the sign on positive or negative numbers.
*
* @draft ICU 60
*/
UNUM_SIGN_NEVER,
/**
* Use the locale-dependent accounting format on negative numbers, and do not show the sign on positive numbers.
*
* <p>
* The accounting format is defined in CLDR and varies by locale; in many Western locales, the format is a pair
* of parentheses around the number.
*
* <p>
* Note: Since CLDR defines the accounting format in the monetary context only, this option falls back to the
* AUTO sign display strategy when formatting without a currency unit. This limitation may be lifted in the
* future.
*
* @draft ICU 60
*/
UNUM_SIGN_ACCOUNTING,
/**
* Use the locale-dependent accounting format on negative numbers, and show the plus sign on
* positive numbers, including zero. For more information on the accounting format, see the
* ACCOUNTING sign display strategy. To hide the sign on zero, see
* {@link UNUM_SIGN_ACCOUNTING_EXCEPT_ZERO}.
*
* @draft ICU 60
*/
UNUM_SIGN_ACCOUNTING_ALWAYS,
/**
* Show the minus sign on negative numbers and the plus sign on positive numbers. Do not show a
* sign on zero.
*
* @draft ICU 61
*/
UNUM_SIGN_EXCEPT_ZERO,
/**
* Use the locale-dependent accounting format on negative numbers, and show the plus sign on
* positive numbers. Do not show a sign on zero. For more information on the accounting format,
* see the ACCOUNTING sign display strategy.
*
* @draft ICU 61
*/
UNUM_SIGN_ACCOUNTING_EXCEPT_ZERO,
/**
* One more than the highest UNumberSignDisplay value.
*
* @internal ICU 60: The numeric value may change over time; see ICU ticket #12420.
*/
UNUM_SIGN_COUNT
} UNumberSignDisplay;
/**
* An enum declaring how to render the decimal separator.
*
* <p>
* <ul>
* <li>UNUM_DECIMAL_SEPARATOR_AUTO: "1", "1.1"
* <li>UNUM_DECIMAL_SEPARATOR_ALWAYS: "1.", "1.1"
* </ul>
*/
typedef enum UNumberDecimalSeparatorDisplay {
/**
* Show the decimal separator when there are one or more digits to display after the separator, and do not show
* it otherwise. This is the default behavior.
*
* @draft ICU 60
*/
UNUM_DECIMAL_SEPARATOR_AUTO,
/**
* Always show the decimal separator, even if there are no digits to display after the separator.
*
* @draft ICU 60
*/
UNUM_DECIMAL_SEPARATOR_ALWAYS,
/**
* One more than the highest UNumberDecimalSeparatorDisplay value.
*
* @internal ICU 60: The numeric value may change over time; see ICU ticket #12420.
*/
UNUM_DECIMAL_SEPARATOR_COUNT
} UNumberDecimalSeparatorDisplay;
/**
* C-compatible version of icu::number::LocalizedNumberFormatter.
*
* NOTE: This is a C-compatible API; C++ users should build against numberformatter.h instead.
*
* @draft ICU 62
*/
typedef struct UNumberFormatter UNumberFormatter;
/**
* C-compatible version of icu::number::FormattedNumber.
*
* NOTE: This is a C-compatible API; C++ users should build against numberformatter.h instead.
*
* @draft ICU 62
*/
typedef struct UFormattedNumber UFormattedNumber;
/**
* Creates a new UNumberFormatter from the given skeleton string and locale.
*
* For more details on skeleton strings, see the documentation in numberformatter.h. For more details on
* the usage of this API, see the documentation at the top of unumberformatter.h.
*
* NOTE: This is a C-compatible API; C++ users should build against numberformatter.h instead.
*
* @draft ICU 62
*/
U_DRAFT UNumberFormatter* U_EXPORT2
unumf_openFromSkeletonAndLocale(const UChar* skeleton, int32_t skeletonLen, const char* locale,
UErrorCode* ec);
/**
* Creates a new UFormattedNumber for holding the result of a number formatting operation.
*
* NOTE: This is a C-compatible API; C++ users should build against numberformatter.h instead.
*
* @draft ICU 62
*/
U_DRAFT UFormattedNumber* U_EXPORT2
unumf_openResult(UErrorCode* ec);
/**
* Uses a UNumberFormatter to format a double to a UFormattedNumber. A string, field position, and other
* information can be retrieved from the UFormattedNumber.
*
* NOTE: This is a C-compatible API; C++ users should build against numberformatter.h instead.
*
* @draft ICU 62
*/
U_DRAFT void U_EXPORT2
unumf_formatInt(const UNumberFormatter* uformatter, int64_t value, UFormattedNumber* uresult,
UErrorCode* ec);
/**
* Uses a UNumberFormatter to format a double to a UFormattedNumber. A string, field position, and other
* information can be retrieved from the UFormattedNumber.
*
* NOTE: This is a C-compatible API; C++ users should build against numberformatter.h instead.
*
* @draft ICU 62
*/
U_DRAFT void U_EXPORT2
unumf_formatDouble(const UNumberFormatter* uformatter, double value, UFormattedNumber* uresult,
UErrorCode* ec);
/**
* Uses a UNumberFormatter to format a decimal number to a UFormattedNumber. A string, field position, and
* other information can be retrieved from the UFormattedNumber.
*
* The syntax of the unformatted number is a "numeric string" as defined in the Decimal Arithmetic
* Specification, available at http://speleotrove.com/decimal
*
* NOTE: This is a C-compatible API; C++ users should build against numberformatter.h instead.
*
* @draft ICU 62
*/
U_DRAFT void U_EXPORT2
unumf_formatDecimal(const UNumberFormatter* uformatter, const char* value, int32_t valueLen,
UFormattedNumber* uresult, UErrorCode* ec);
/**
* Extracts the result number string out of a UFormattedNumber to a UChar buffer. The usual ICU pattern
* is used for writing to the buffer:
*
* - If the string is shorter than the buffer, it will be written to the buffer and will be NUL-terminated.
* - If the string is exactly the length of the buffer, it will be written to the buffer, but it will not
* be NUL-terminated, and a warning will be set.
* - If the string is longer than the buffer, nothing will be written to the buffer, and an error will be
* set.
*
* In all cases, the actual length of the string is returned, whether or not it was written to the buffer.
*
* NOTE: This is a C-compatible API; C++ users should build against numberformatter.h instead.
*
* @draft ICU 62
*/
U_DRAFT int32_t U_EXPORT2
unumf_resultToString(const UFormattedNumber* uresult, UChar* buffer, int32_t bufferCapacity,
UErrorCode* ec);
/**
* Releases the UFormattedNumber returned by unumf_formatDouble and friends.
*
* NOTE: This is a C-compatible API; C++ users should build against numberformatter.h instead.
*
* @draft ICU 62
*/
U_DRAFT void U_EXPORT2
unumf_closeResult(const UFormattedNumber* uresult, UErrorCode* ec);
/**
* Releases the UNumberFormatter created by unumf_openFromSkeletonAndLocale.
*
* NOTE: This is a C-compatible API; C++ users should build against numberformatter.h instead.
*
* @draft ICU 62
*/
U_DRAFT void U_EXPORT2
unumf_close(UNumberFormatter* uformatter, UErrorCode* ec);
#endif //__UNUMBERFORMATTER_H__
#endif /* #if !UCONFIG_NO_FORMATTING */

View File

@ -54,7 +54,8 @@ idnatest.o nfsprep.o spreptst.o sprpdata.o \
hpmufn.o tracetst.o reapits.o uregiontest.o ulistfmttest.o\
utexttst.o ucsdetst.o spooftest.o \
cbiditransformtst.o \
cgendtst.o
cgendtst.o \
unumberformattertst.o
DEPS = $(OBJECTS:.o=.d)

View File

@ -45,6 +45,7 @@ void addUSpoofTest(TestNode** root);
#if !UCONFIG_NO_FORMATTING
void addGendInfoForTest(TestNode** root);
#endif
void addUNumberFormatterTest(TestNode** root);
void addAllTests(TestNode** root)
{
@ -88,5 +89,6 @@ void addAllTests(TestNode** root)
addPUtilTest(root);
#if !UCONFIG_NO_FORMATTING
addGendInfoForTest(root);
addUNumberFormatterTest(root);
#endif
}

View File

@ -709,4 +709,24 @@ U_CFUNC UBool assertEquals(const char* message, const char* expected,
return TRUE;
}
U_CFUNC UBool assertUEquals(const char* message, const UChar* expected,
const UChar* actual) {
for (int32_t i=0;; i++) {
if (expected[i] != actual[i]) {
log_err("FAIL: %s; got \"%s\"; expected \"%s\"\n",
message, actual, expected);
return FALSE;
}
UChar curr = expected[i];
U_ASSERT(curr == actual[i]);
if (curr == 0) {
break;
}
}
#ifdef VERBOSE_ASSERTIONS
log_verbose("Ok: %s; got \"%s\"\n", message, actual);
#endif
return TRUE;
}
#endif

View File

@ -135,6 +135,13 @@ U_CFUNC UBool assertTrue(const char* msg, int condition);
U_CFUNC UBool assertEquals(const char* msg, const char* expectedString,
const char* actualString);
/**
* Assert that the actualString equals the expectedString, and return
* TRUE if it does.
*/
U_CFUNC UBool assertUEquals(const char* msg, const UChar* expectedString,
const UChar* actualString);
/*
* note - isICUVersionBefore and isICUVersionAtLeast have been removed.
* use log_knownIssue() instead.

View File

@ -0,0 +1,65 @@
// © 2018 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
#include "unicode/utypes.h"
#if !UCONFIG_NO_FORMATTING && !UPRV_INCOMPLETE_CPP11_SUPPORT
// Allow implicit conversion from char16_t* to UnicodeString for this file:
// Helpful in toString methods and elsewhere.
#define UNISTR_FROM_STRING_EXPLICIT
#include "unicode/unumberformatter.h"
#include "cintltst.h"
static void TestSkeletonFormatToString();
void addUNumberFormatterTest(TestNode** root);
void addUNumberFormatterTest(TestNode** root) {
addTest(root, &TestSkeletonFormatToString, "unumberformatter/TestSkeletonFormatToString");
}
static void TestSkeletonFormatToString() {
UErrorCode ec = U_ZERO_ERROR;
static const int32_t CAPACITY = 30;
UChar buffer[CAPACITY];
// SETUP:
UNumberFormatter* f = unumf_openFromSkeletonAndLocale(
u"round-integer currency/USD sign-accounting", -1, "en", &ec);
assertSuccess("Should create without error", &ec);
UFormattedNumber* result = unumf_openResult(&ec);
assertSuccess("Should create result without error", &ec);
// INT TEST:
unumf_formatInt(f, -444444, result, &ec);
assertSuccess("Should format integer without error", &ec);
unumf_resultToString(result, buffer, CAPACITY, &ec);
assertSuccess("Should print string to buffer without error", &ec);
assertUEquals("Should produce expected string result", u"($444,444)", buffer);
// DOUBLE TEST:
unumf_formatDouble(f, -5142.3, result, &ec);
assertSuccess("Should format double without error", &ec);
unumf_resultToString(result, buffer, CAPACITY, &ec);
assertSuccess("Should print string to buffer without error", &ec);
assertUEquals("Should produce expected string result", u"($5,142)", buffer);
// DECIMAL TEST:
unumf_formatDecimal(f, "9.876E2", -1, result, &ec);
assertSuccess("Should format decimal without error", &ec);
unumf_resultToString(result, buffer, CAPACITY, &ec);
assertSuccess("Should print string to buffer without error", &ec);
assertUEquals("Should produce expected string result", u"$988", buffer);
// CLEANUP:
unumf_closeResult(result, &ec);
assertSuccess("Should close without error", &ec);
unumf_close(f, &ec);
assertSuccess("Should close without error", &ec);
}
#endif /* #if !UCONFIG_NO_FORMATTING */