Commit 2b77b784 authored by cira@chromium.org's avatar cira@chromium.org

Adding support for number formating to the JS i18n API.

This is the last part of the API that belongs in public spec.

Methods supported:
- format
- derive

Options supported:
- style (decimal, scientific, currency and percent)
- pattern
- skeleton

TEST= Visit i18n.kaziprst.org/numberformat.html
Review URL: http://codereview.chromium.org/7129051

git-svn-id: http://v8.googlecode.com/svn/branches/bleeding_edge@8379 ce2b1a6d-e550-0410-aec6-3dcde31c8c00
parent 286f1d6b
......@@ -52,6 +52,8 @@
'i18n-utils.h',
'language-matcher.cc',
'language-matcher.h',
'number-format.cc',
'number-format.h',
'<(SHARED_INTERMEDIATE_DIR)/i18n-js.cc',
],
'include_dirs': [
......@@ -76,7 +78,7 @@
'type': 'none',
'toolsets': ['host'],
'variables': {
'library_files': [
'js_files': [
'i18n.js'
],
},
......@@ -85,7 +87,7 @@
'action_name': 'js2c_i18n',
'inputs': [
'i18n-js2c.py',
'<@(library_files)',
'<@(js_files)',
],
'outputs': [
'<(SHARED_INTERMEDIATE_DIR)/i18n-js.cc',
......@@ -94,7 +96,7 @@
'python',
'i18n-js2c.py',
'<@(_outputs)',
'<@(library_files)'
'<@(js_files)'
],
},
],
......
......@@ -32,6 +32,7 @@
#include "src/extensions/experimental/datetime-format.h"
#include "src/extensions/experimental/i18n-locale.h"
#include "src/extensions/experimental/i18n-natives.h"
#include "src/extensions/experimental/number-format.h"
namespace v8 {
namespace internal {
......@@ -52,6 +53,8 @@ v8::Handle<v8::FunctionTemplate> I18NExtension::GetNativeFunction(
return v8::FunctionTemplate::New(Collator::JSCollator);
} else if (name->Equals(v8::String::New("NativeJSDateTimeFormat"))) {
return v8::FunctionTemplate::New(DateTimeFormat::JSDateTimeFormat);
} else if (name->Equals(v8::String::New("NativeJSNumberFormat"))) {
return v8::FunctionTemplate::New(NumberFormat::JSNumberFormat);
}
return v8::Handle<v8::FunctionTemplate>();
......
......@@ -65,4 +65,23 @@ bool I18NUtils::ExtractStringSetting(const v8::Handle<v8::Object>& settings,
return false;
}
// static
void I18NUtils::AsciiToUChar(const char* source,
int32_t source_length,
UChar* target,
int32_t target_length) {
int32_t length =
source_length < target_length ? source_length : target_length;
if (length <= 0) {
return;
}
for (int32_t i = 0; i < length - 1; ++i) {
target[i] = static_cast<UChar>(source[i]);
}
target[length - 1] = 0x0u;
}
} } // namespace v8::internal
......@@ -53,6 +53,13 @@ class I18NUtils {
const char* setting,
icu::UnicodeString* result);
// Converts ASCII array into UChar array.
// Target is always \0 terminated.
static void AsciiToUChar(const char* source,
int32_t source_length,
UChar* target,
int32_t target_length);
private:
I18NUtils() {}
};
......
......@@ -222,6 +222,102 @@ v8Locale.prototype.createDateTimeFormat = function(settings) {
return new v8Locale.__DateTimeFormat(this, settings);
};
/**
* NumberFormat class implements locale-aware number formatting.
* Constructor is not part of public API.
* @param {Object} locale - locale object to pass to formatter.
* @param {Object} settings - formatting flags:
* - skeleton
* - pattern
* - style - decimal, currency, percent or scientific
* - currencyCode - ISO 4217 3-letter currency code
* @private
* @constructor
*/
v8Locale.__NumberFormat = function(locale, settings) {
native function NativeJSNumberFormat();
settings = v8Locale.__createSettingsOrDefault(settings, {});
var cleanSettings = {};
if (settings.hasOwnProperty('skeleton')) {
// Assign skeleton to cleanSettings and fix invalid currency pattern
// if present - 'ooxo' becomes 'o'.
cleanSettings['skeleton'] =
settings['skeleton'].replace(/\u00a4+[^\u00a4]+\u00a4+/g, '\u00a4');
} else if (settings.hasOwnProperty('pattern')) {
cleanSettings['pattern'] = settings['pattern'];
} else if (settings.hasOwnProperty('style')) {
var style = settings['style'];
if (!/^decimal|currency|percent|scientific$/.test(style)) {
style = 'decimal';
}
cleanSettings['style'] = style;
}
// Default is to show decimal style.
if (!cleanSettings.hasOwnProperty('skeleton') &&
!cleanSettings.hasOwnProperty('pattern') &&
!cleanSettings.hasOwnProperty('style')) {
cleanSettings = {'style': 'decimal'};
}
// Add currency code if available and valid (3-letter ASCII code).
if (settings.hasOwnProperty('currencyCode') &&
/^[a-zA-Z]{3}$/.test(settings['currencyCode'])) {
cleanSettings['currencyCode'] = settings['currencyCode'].toUpperCase();
}
locale = v8Locale.__createLocaleOrDefault(locale);
// Pass in region ID for proper currency detection. Use ZZ if region is empty.
var region = locale.options.regionID !== '' ? locale.options.regionID : 'ZZ';
var formatter = NativeJSNumberFormat(
locale.__icuLocaleID, 'und_' + region, cleanSettings);
// ICU doesn't always uppercase the currency code.
if (formatter.options.hasOwnProperty('currencyCode')) {
formatter.options['currencyCode'] =
formatter.options['currencyCode'].toUpperCase();
}
for (key in cleanSettings) {
// Don't overwrite keys that are alredy in.
if (formatter.options.hasOwnProperty(key)) continue;
formatter.options[key] = cleanSettings[key];
}
/**
* Clones existing number format with possible overrides for some
* of the options.
* @param {!Object} overrideSettings - overrides for current format settings.
* @returns {Object} - new or cached NumberFormat object.
* @public
*/
formatter.derive = function(overrideSettings) {
// To remove a setting user can specify undefined as its value. We'll remove
// it from the map in that case.
for (var prop in overrideSettings) {
if (settings.hasOwnProperty(prop) && !overrideSettings[prop]) {
delete settings[prop];
}
}
return new v8Locale.__NumberFormat(
locale, v8Locale.__createSettingsOrDefault(overrideSettings, settings));
};
return formatter;
};
/**
* Creates new NumberFormat based on current locale.
* @param {Object} - formatting flags. See constructor.
* @returns {Object} - new or cached NumberFormat object.
*/
v8Locale.prototype.createNumberFormat = function(settings) {
return new v8Locale.__NumberFormat(this, settings);
};
/**
* Merges user settings and defaults.
* Settings that are not of object type are rejected.
......
This diff is collapsed.
// Copyright 2011 the V8 project authors. All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#ifndef V8_EXTENSIONS_EXPERIMENTAL_NUMBER_FORMAT_H_
#define V8_EXTENSIONS_EXPERIMENTAL_NUMBER_FORMAT_H_
#include "include/v8.h"
#include "unicode/uversion.h"
namespace U_ICU_NAMESPACE {
class DecimalFormat;
}
namespace v8 {
namespace internal {
class NumberFormat {
public:
// 3-letter ISO 4217 currency code plus \0.
static const int kCurrencyCodeLength;
static v8::Handle<v8::Value> JSNumberFormat(const v8::Arguments& args);
// Helper methods for various bindings.
// Unpacks date format object from corresponding JavaScript object.
static icu::DecimalFormat* UnpackNumberFormat(
v8::Handle<v8::Object> obj);
// Release memory we allocated for the NumberFormat once the JS object that
// holds the pointer gets garbage collected.
static void DeleteNumberFormat(v8::Persistent<v8::Value> object,
void* param);
// Formats number and returns corresponding string.
static v8::Handle<v8::Value> Format(const v8::Arguments& args);
private:
NumberFormat();
static v8::Persistent<v8::FunctionTemplate> number_format_template_;
};
} } // namespace v8::internal
#endif // V8_EXTENSIONS_EXPERIMENTAL_NUMBER_FORMAT_H_
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment