Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(429)

Side by Side Diff: src/extensions/i18n/number-format.cc

Issue 22266009: Move i18n's number-format C++ code to runtime (Closed) Base URL: https://v8.googlecode.com/svn/branches/bleeding_edge
Patch Set: Created 7 years, 4 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
« no previous file with comments | « src/extensions/i18n/number-format.h ('k') | src/extensions/i18n/number-format.js » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
(Empty)
1 // Copyright 2013 the V8 project authors. All rights reserved.
2 // Redistribution and use in source and binary forms, with or without
3 // modification, are permitted provided that the following conditions are
4 // met:
5 //
6 // * Redistributions of source code must retain the above copyright
7 // notice, this list of conditions and the following disclaimer.
8 // * Redistributions in binary form must reproduce the above
9 // copyright notice, this list of conditions and the following
10 // disclaimer in the documentation and/or other materials provided
11 // with the distribution.
12 // * Neither the name of Google Inc. nor the names of its
13 // contributors may be used to endorse or promote products derived
14 // from this software without specific prior written permission.
15 //
16 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 // limitations under the License.
28
29 #include "number-format.h"
30
31 #include <string.h>
32
33 #include "i18n-utils.h"
34 #include "unicode/curramt.h"
35 #include "unicode/dcfmtsym.h"
36 #include "unicode/decimfmt.h"
37 #include "unicode/locid.h"
38 #include "unicode/numfmt.h"
39 #include "unicode/numsys.h"
40 #include "unicode/uchar.h"
41 #include "unicode/ucurr.h"
42 #include "unicode/unum.h"
43 #include "unicode/uversion.h"
44
45 namespace v8_i18n {
46
47 static icu::DecimalFormat* InitializeNumberFormat(v8::Handle<v8::String>,
48 v8::Handle<v8::Object>,
49 v8::Handle<v8::Object>);
50 static icu::DecimalFormat* CreateICUNumberFormat(const icu::Locale&,
51 v8::Handle<v8::Object>);
52 static void SetResolvedSettings(const icu::Locale&,
53 icu::DecimalFormat*,
54 v8::Handle<v8::Object>);
55
56 icu::DecimalFormat* NumberFormat::UnpackNumberFormat(
57 v8::Handle<v8::Object> obj) {
58 v8::HandleScope handle_scope;
59
60 // v8::ObjectTemplate doesn't have HasInstance method so we can't check
61 // if obj is an instance of NumberFormat class. We'll check for a property
62 // that has to be in the object. The same applies to other services, like
63 // Collator and DateTimeFormat.
64 if (obj->HasOwnProperty(v8::String::New("numberFormat"))) {
65 return static_cast<icu::DecimalFormat*>(
66 obj->GetAlignedPointerFromInternalField(0));
67 }
68
69 return NULL;
70 }
71
72 void NumberFormat::DeleteNumberFormat(v8::Isolate* isolate,
73 v8::Persistent<v8::Object>* object,
74 void* param) {
75 // First delete the hidden C++ object.
76 // Unpacking should never return NULL here. That would only happen if
77 // this method is used as the weak callback for persistent handles not
78 // pointing to a date time formatter.
79 v8::HandleScope handle_scope(isolate);
80 v8::Local<v8::Object> handle = v8::Local<v8::Object>::New(isolate, *object);
81 delete UnpackNumberFormat(handle);
82
83 // Then dispose of the persistent handle to JS object.
84 object->Dispose(isolate);
85 }
86
87 void NumberFormat::JSInternalFormat(
88 const v8::FunctionCallbackInfo<v8::Value>& args) {
89 if (args.Length() != 2 || !args[0]->IsObject() || !args[1]->IsNumber()) {
90 v8::ThrowException(v8::Exception::Error(
91 v8::String::New("Formatter and numeric value have to be specified.")));
92 return;
93 }
94
95 icu::DecimalFormat* number_format = UnpackNumberFormat(args[0]->ToObject());
96 if (!number_format) {
97 v8::ThrowException(v8::Exception::Error(
98 v8::String::New("NumberFormat method called on an object "
99 "that is not a NumberFormat.")));
100 return;
101 }
102
103 // ICU will handle actual NaN value properly and return NaN string.
104 icu::UnicodeString result;
105 number_format->format(args[1]->NumberValue(), result);
106
107 args.GetReturnValue().Set(v8::String::New(
108 reinterpret_cast<const uint16_t*>(result.getBuffer()), result.length()));
109 }
110
111 void NumberFormat::JSInternalParse(
112 const v8::FunctionCallbackInfo<v8::Value>& args) {
113 if (args.Length() != 2 || !args[0]->IsObject() || !args[1]->IsString()) {
114 v8::ThrowException(v8::Exception::Error(
115 v8::String::New("Formatter and string have to be specified.")));
116 return;
117 }
118
119 icu::DecimalFormat* number_format = UnpackNumberFormat(args[0]->ToObject());
120 if (!number_format) {
121 v8::ThrowException(v8::Exception::Error(
122 v8::String::New("NumberFormat method called on an object "
123 "that is not a NumberFormat.")));
124 return;
125 }
126
127 // ICU will handle actual NaN value properly and return NaN string.
128 icu::UnicodeString string_number;
129 if (!Utils::V8StringToUnicodeString(args[1]->ToString(), &string_number)) {
130 string_number = "";
131 }
132
133 UErrorCode status = U_ZERO_ERROR;
134 icu::Formattable result;
135 // ICU 4.6 doesn't support parseCurrency call. We need to wait for ICU49
136 // to be part of Chrome.
137 // TODO(cira): Include currency parsing code using parseCurrency call.
138 // We need to check if the formatter parses all currencies or only the
139 // one it was constructed with (it will impact the API - how to return ISO
140 // code and the value).
141 number_format->parse(string_number, result, status);
142 if (U_FAILURE(status)) {
143 return;
144 }
145
146 switch (result.getType()) {
147 case icu::Formattable::kDouble:
148 args.GetReturnValue().Set(result.getDouble());
149 return;
150 case icu::Formattable::kLong:
151 args.GetReturnValue().Set(result.getLong());
152 return;
153 case icu::Formattable::kInt64:
154 args.GetReturnValue().Set(static_cast<double>(result.getInt64()));
155 return;
156 default:
157 return;
158 }
159 }
160
161 void NumberFormat::JSCreateNumberFormat(
162 const v8::FunctionCallbackInfo<v8::Value>& args) {
163 if (args.Length() != 3 ||
164 !args[0]->IsString() ||
165 !args[1]->IsObject() ||
166 !args[2]->IsObject()) {
167 v8::ThrowException(v8::Exception::Error(
168 v8::String::New("Internal error, wrong parameters.")));
169 return;
170 }
171
172 v8::Isolate* isolate = args.GetIsolate();
173 v8::Local<v8::ObjectTemplate> number_format_template =
174 Utils::GetTemplate(isolate);
175
176 // Create an empty object wrapper.
177 v8::Local<v8::Object> local_object = number_format_template->NewInstance();
178 // But the handle shouldn't be empty.
179 // That can happen if there was a stack overflow when creating the object.
180 if (local_object.IsEmpty()) {
181 args.GetReturnValue().Set(local_object);
182 return;
183 }
184
185 // Set number formatter as internal field of the resulting JS object.
186 icu::DecimalFormat* number_format = InitializeNumberFormat(
187 args[0]->ToString(), args[1]->ToObject(), args[2]->ToObject());
188
189 if (!number_format) {
190 v8::ThrowException(v8::Exception::Error(v8::String::New(
191 "Internal error. Couldn't create ICU number formatter.")));
192 return;
193 } else {
194 local_object->SetAlignedPointerInInternalField(0, number_format);
195
196 v8::TryCatch try_catch;
197 local_object->Set(v8::String::New("numberFormat"),
198 v8::String::New("valid"));
199 if (try_catch.HasCaught()) {
200 v8::ThrowException(v8::Exception::Error(
201 v8::String::New("Internal error, couldn't set property.")));
202 return;
203 }
204 }
205
206 v8::Persistent<v8::Object> wrapper(isolate, local_object);
207 // Make object handle weak so we can delete iterator once GC kicks in.
208 wrapper.MakeWeak<void>(NULL, &DeleteNumberFormat);
209 args.GetReturnValue().Set(wrapper);
210 wrapper.ClearAndLeak();
211 }
212
213 static icu::DecimalFormat* InitializeNumberFormat(
214 v8::Handle<v8::String> locale,
215 v8::Handle<v8::Object> options,
216 v8::Handle<v8::Object> resolved) {
217 // Convert BCP47 into ICU locale format.
218 UErrorCode status = U_ZERO_ERROR;
219 icu::Locale icu_locale;
220 char icu_result[ULOC_FULLNAME_CAPACITY];
221 int icu_length = 0;
222 v8::String::AsciiValue bcp47_locale(locale);
223 if (bcp47_locale.length() != 0) {
224 uloc_forLanguageTag(*bcp47_locale, icu_result, ULOC_FULLNAME_CAPACITY,
225 &icu_length, &status);
226 if (U_FAILURE(status) || icu_length == 0) {
227 return NULL;
228 }
229 icu_locale = icu::Locale(icu_result);
230 }
231
232 icu::DecimalFormat* number_format =
233 CreateICUNumberFormat(icu_locale, options);
234 if (!number_format) {
235 // Remove extensions and try again.
236 icu::Locale no_extension_locale(icu_locale.getBaseName());
237 number_format = CreateICUNumberFormat(no_extension_locale, options);
238
239 // Set resolved settings (pattern, numbering system).
240 SetResolvedSettings(no_extension_locale, number_format, resolved);
241 } else {
242 SetResolvedSettings(icu_locale, number_format, resolved);
243 }
244
245 return number_format;
246 }
247
248 static icu::DecimalFormat* CreateICUNumberFormat(
249 const icu::Locale& icu_locale, v8::Handle<v8::Object> options) {
250 // Make formatter from options. Numbering system is added
251 // to the locale as Unicode extension (if it was specified at all).
252 UErrorCode status = U_ZERO_ERROR;
253 icu::DecimalFormat* number_format = NULL;
254 icu::UnicodeString style;
255 icu::UnicodeString currency;
256 if (Utils::ExtractStringSetting(options, "style", &style)) {
257 if (style == UNICODE_STRING_SIMPLE("currency")) {
258 Utils::ExtractStringSetting(options, "currency", &currency);
259
260 icu::UnicodeString display;
261 Utils::ExtractStringSetting(options, "currencyDisplay", &display);
262 #if (U_ICU_VERSION_MAJOR_NUM == 4) && (U_ICU_VERSION_MINOR_NUM <= 6)
263 icu::NumberFormat::EStyles style;
264 if (display == UNICODE_STRING_SIMPLE("code")) {
265 style = icu::NumberFormat::kIsoCurrencyStyle;
266 } else if (display == UNICODE_STRING_SIMPLE("name")) {
267 style = icu::NumberFormat::kPluralCurrencyStyle;
268 } else {
269 style = icu::NumberFormat::kCurrencyStyle;
270 }
271 #else // ICU version is 4.8 or above (we ignore versions below 4.0).
272 UNumberFormatStyle style;
273 if (display == UNICODE_STRING_SIMPLE("code")) {
274 style = UNUM_CURRENCY_ISO;
275 } else if (display == UNICODE_STRING_SIMPLE("name")) {
276 style = UNUM_CURRENCY_PLURAL;
277 } else {
278 style = UNUM_CURRENCY;
279 }
280 #endif
281
282 number_format = static_cast<icu::DecimalFormat*>(
283 icu::NumberFormat::createInstance(icu_locale, style, status));
284 } else if (style == UNICODE_STRING_SIMPLE("percent")) {
285 number_format = static_cast<icu::DecimalFormat*>(
286 icu::NumberFormat::createPercentInstance(icu_locale, status));
287 if (U_FAILURE(status)) {
288 delete number_format;
289 return NULL;
290 }
291 // Make sure 1.1% doesn't go into 2%.
292 number_format->setMinimumFractionDigits(1);
293 } else {
294 // Make a decimal instance by default.
295 number_format = static_cast<icu::DecimalFormat*>(
296 icu::NumberFormat::createInstance(icu_locale, status));
297 }
298 }
299
300 if (U_FAILURE(status)) {
301 delete number_format;
302 return NULL;
303 }
304
305 // Set all options.
306 if (!currency.isEmpty()) {
307 number_format->setCurrency(currency.getBuffer(), status);
308 }
309
310 int32_t digits;
311 if (Utils::ExtractIntegerSetting(
312 options, "minimumIntegerDigits", &digits)) {
313 number_format->setMinimumIntegerDigits(digits);
314 }
315
316 if (Utils::ExtractIntegerSetting(
317 options, "minimumFractionDigits", &digits)) {
318 number_format->setMinimumFractionDigits(digits);
319 }
320
321 if (Utils::ExtractIntegerSetting(
322 options, "maximumFractionDigits", &digits)) {
323 number_format->setMaximumFractionDigits(digits);
324 }
325
326 bool significant_digits_used = false;
327 if (Utils::ExtractIntegerSetting(
328 options, "minimumSignificantDigits", &digits)) {
329 number_format->setMinimumSignificantDigits(digits);
330 significant_digits_used = true;
331 }
332
333 if (Utils::ExtractIntegerSetting(
334 options, "maximumSignificantDigits", &digits)) {
335 number_format->setMaximumSignificantDigits(digits);
336 significant_digits_used = true;
337 }
338
339 number_format->setSignificantDigitsUsed(significant_digits_used);
340
341 bool grouping;
342 if (Utils::ExtractBooleanSetting(options, "useGrouping", &grouping)) {
343 number_format->setGroupingUsed(grouping);
344 }
345
346 // Set rounding mode.
347 number_format->setRoundingMode(icu::DecimalFormat::kRoundHalfUp);
348
349 return number_format;
350 }
351
352 static void SetResolvedSettings(const icu::Locale& icu_locale,
353 icu::DecimalFormat* number_format,
354 v8::Handle<v8::Object> resolved) {
355 icu::UnicodeString pattern;
356 number_format->toPattern(pattern);
357 resolved->Set(v8::String::New("pattern"),
358 v8::String::New(reinterpret_cast<const uint16_t*>(
359 pattern.getBuffer()), pattern.length()));
360
361 // Set resolved currency code in options.currency if not empty.
362 icu::UnicodeString currency(number_format->getCurrency());
363 if (!currency.isEmpty()) {
364 resolved->Set(v8::String::New("currency"),
365 v8::String::New(reinterpret_cast<const uint16_t*>(
366 currency.getBuffer()), currency.length()));
367 }
368
369 // Ugly hack. ICU doesn't expose numbering system in any way, so we have
370 // to assume that for given locale NumberingSystem constructor produces the
371 // same digits as NumberFormat would.
372 UErrorCode status = U_ZERO_ERROR;
373 icu::NumberingSystem* numbering_system =
374 icu::NumberingSystem::createInstance(icu_locale, status);
375 if (U_SUCCESS(status)) {
376 const char* ns = numbering_system->getName();
377 resolved->Set(v8::String::New("numberingSystem"), v8::String::New(ns));
378 } else {
379 resolved->Set(v8::String::New("numberingSystem"), v8::Undefined());
380 }
381 delete numbering_system;
382
383 resolved->Set(v8::String::New("useGrouping"),
384 v8::Boolean::New(number_format->isGroupingUsed()));
385
386 resolved->Set(v8::String::New("minimumIntegerDigits"),
387 v8::Integer::New(number_format->getMinimumIntegerDigits()));
388
389 resolved->Set(v8::String::New("minimumFractionDigits"),
390 v8::Integer::New(number_format->getMinimumFractionDigits()));
391
392 resolved->Set(v8::String::New("maximumFractionDigits"),
393 v8::Integer::New(number_format->getMaximumFractionDigits()));
394
395 if (resolved->HasOwnProperty(v8::String::New("minimumSignificantDigits"))) {
396 resolved->Set(v8::String::New("minimumSignificantDigits"), v8::Integer::New(
397 number_format->getMinimumSignificantDigits()));
398 }
399
400 if (resolved->HasOwnProperty(v8::String::New("maximumSignificantDigits"))) {
401 resolved->Set(v8::String::New("maximumSignificantDigits"), v8::Integer::New(
402 number_format->getMaximumSignificantDigits()));
403 }
404
405 // Set the locale
406 char result[ULOC_FULLNAME_CAPACITY];
407 status = U_ZERO_ERROR;
408 uloc_toLanguageTag(
409 icu_locale.getName(), result, ULOC_FULLNAME_CAPACITY, FALSE, &status);
410 if (U_SUCCESS(status)) {
411 resolved->Set(v8::String::New("locale"), v8::String::New(result));
412 } else {
413 // This would never happen, since we got the locale from ICU.
414 resolved->Set(v8::String::New("locale"), v8::String::New("und"));
415 }
416 }
417
418 } // namespace v8_i18n
OLDNEW
« no previous file with comments | « src/extensions/i18n/number-format.h ('k') | src/extensions/i18n/number-format.js » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698