1 /********************************************************************
2  * COPYRIGHT:
3  * Copyright (c) 1997-2014, International Business Machines Corporation and
4  * others. All Rights Reserved.
5  ********************************************************************/
6 /********************************************************************************
7 *
8 * File CNUMTST.C
9 *
10 *     Madhu Katragadda              Creation
11 *
12 * Modification History:
13 *
14 *   Date        Name        Description
15 *   06/24/99    helena      Integrated Alan's NF enhancements and Java2 bug fixes
16 *   07/15/99    helena      Ported to HPUX 10/11 CC.
17 *********************************************************************************
18 */
19 
20 /* C API TEST FOR NUMBER FORMAT */
21 
22 #include "unicode/utypes.h"
23 
24 #if !UCONFIG_NO_FORMATTING
25 
26 #include "unicode/uloc.h"
27 #include "unicode/umisc.h"
28 #include "unicode/unum.h"
29 #include "unicode/unumsys.h"
30 #include "unicode/ustring.h"
31 #include "unicode/udisplaycontext.h"
32 
33 #include "cintltst.h"
34 #include "cnumtst.h"
35 #include "cmemory.h"
36 #include "cstring.h"
37 #include "putilimp.h"
38 #include <stdio.h>
39 #include <stdlib.h>
40 
41 #define LENGTH(arr) (sizeof(arr)/sizeof(arr[0]))
42 
tagAssert(const char * f,int32_t l,const char * msg)43 static const char *tagAssert(const char *f, int32_t l, const char *msg) {
44     static char _fileline[1000];
45     sprintf(_fileline, "%s:%d: ASSERT_TRUE(%s)", f, l, msg);
46     return _fileline;
47 }
48 
49 #define ASSERT_TRUE(x)   assertTrue(tagAssert(__FILE__, __LINE__, #x), (x))
50 
51 void addNumForTest(TestNode** root);
52 static void TestTextAttributeCrash(void);
53 static void TestNBSPInPattern(void);
54 static void TestInt64Parse(void);
55 static void TestParseCurrency(void);
56 static void TestMaxInt(void);
57 static void TestNoExponent(void);
58 static void TestUFormattable(void);
59 static void TestUNumberingSystem(void);
60 static void TestCurrencyIsoPluralFormat(void);
61 static void TestContext(void);
62 static void TestCurrencyUsage(void);
63 static void TestCurrFmtNegSameAsPositive(void);
64 
65 #define TESTCASE(x) addTest(root, &x, "tsformat/cnumtst/" #x)
66 
addNumForTest(TestNode ** root)67 void addNumForTest(TestNode** root)
68 {
69     TESTCASE(TestNumberFormat);
70     TESTCASE(TestSpelloutNumberParse);
71     TESTCASE(TestSignificantDigits);
72     TESTCASE(TestSigDigRounding);
73     TESTCASE(TestNumberFormatPadding);
74     TESTCASE(TestInt64Format);
75     TESTCASE(TestNonExistentCurrency);
76     TESTCASE(TestCurrencyRegression);
77     TESTCASE(TestTextAttributeCrash);
78     TESTCASE(TestRBNFFormat);
79     TESTCASE(TestNBSPInPattern);
80     TESTCASE(TestInt64Parse);
81     TESTCASE(TestParseZero);
82     TESTCASE(TestParseCurrency);
83     TESTCASE(TestCloneWithRBNF);
84     TESTCASE(TestMaxInt);
85     TESTCASE(TestNoExponent);
86     TESTCASE(TestUFormattable);
87     TESTCASE(TestUNumberingSystem);
88     TESTCASE(TestCurrencyIsoPluralFormat);
89     TESTCASE(TestContext);
90     TESTCASE(TestCurrencyUsage);
91     TESTCASE(TestCurrFmtNegSameAsPositive);
92 }
93 
94 /* test Parse int 64 */
95 
TestInt64Parse()96 static void TestInt64Parse()
97 {
98 
99     UErrorCode st = U_ZERO_ERROR;
100     UErrorCode* status = &st;
101 
102     const char* st1 = "009223372036854775808";
103     const int size = 21;
104     UChar text[21];
105 
106 
107     UNumberFormat* nf;
108 
109     int64_t a;
110 
111     u_charsToUChars(st1, text, size);
112     nf = unum_open(UNUM_DEFAULT, NULL, -1, NULL, NULL, status);
113 
114     if(U_FAILURE(*status))
115     {
116         log_data_err("Error in unum_open() %s \n", myErrorName(*status));
117         return;
118     }
119 
120     log_verbose("About to test unum_parseInt64() with out of range number\n");
121 
122     a = unum_parseInt64(nf, text, size, 0, status);
123     (void)a;     /* Suppress set but not used warning. */
124 
125 
126     if(!U_FAILURE(*status))
127     {
128         log_err("Error in unum_parseInt64(): %s \n", myErrorName(*status));
129     }
130     else
131     {
132         log_verbose("unum_parseInt64() successful\n");
133     }
134 
135     unum_close(nf);
136     return;
137 }
138 
139 /* test Number Format API */
TestNumberFormat()140 static void TestNumberFormat()
141 {
142     UChar *result=NULL;
143     UChar temp1[512];
144     UChar temp2[512];
145 
146     UChar temp[5];
147 
148     UChar prefix[5];
149     UChar suffix[5];
150     UChar symbol[20];
151     int32_t resultlength;
152     int32_t resultlengthneeded;
153     int32_t parsepos;
154     double d1 = -1.0;
155     int32_t l1;
156     double d = -10456.37;
157     double a = 1234.56, a1 = 1235.0;
158     int32_t l = 100000000;
159     UFieldPosition pos1;
160     UFieldPosition pos2;
161     int32_t numlocales;
162     int32_t i;
163 
164     UNumberFormatAttribute attr;
165     UNumberFormatSymbol symType = UNUM_DECIMAL_SEPARATOR_SYMBOL;
166     int32_t newvalue;
167     UErrorCode status=U_ZERO_ERROR;
168     UNumberFormatStyle style= UNUM_DEFAULT;
169     UNumberFormat *pattern;
170     UNumberFormat *def, *fr, *cur_def, *cur_fr, *per_def, *per_fr,
171                   *cur_frpattern, *myclone, *spellout_def;
172 
173     /* Testing unum_open() with various Numberformat styles and locales*/
174     status = U_ZERO_ERROR;
175     log_verbose("Testing  unum_open() with default style and locale\n");
176     def=unum_open(style, NULL,0,NULL, NULL,&status);
177 
178     /* Might as well pack it in now if we can't even get a default NumberFormat... */
179     if(U_FAILURE(status))
180     {
181         log_data_err("Error in creating default NumberFormat using unum_open(): %s (Are you missing data?)\n", myErrorName(status));
182         return;
183     }
184 
185     log_verbose("\nTesting unum_open() with french locale and default style(decimal)\n");
186     fr=unum_open(style,NULL,0, "fr_FR",NULL, &status);
187     if(U_FAILURE(status))
188         log_err("Error: could not create NumberFormat (french): %s\n", myErrorName(status));
189 
190     log_verbose("\nTesting unum_open(currency,NULL,status)\n");
191     style=UNUM_CURRENCY;
192     /* Can't hardcode the result to assume the default locale is "en_US". */
193     cur_def=unum_open(style, NULL,0,"en_US", NULL, &status);
194     if(U_FAILURE(status))
195         log_err("Error: could not create NumberFormat using \n unum_open(currency, NULL, &status) %s\n",
196                         myErrorName(status) );
197 
198     log_verbose("\nTesting unum_open(currency, frenchlocale, status)\n");
199     cur_fr=unum_open(style,NULL,0, "fr_FR", NULL, &status);
200     if(U_FAILURE(status))
201         log_err("Error: could not create NumberFormat using unum_open(currency, french, &status): %s\n",
202                 myErrorName(status));
203 
204     log_verbose("\nTesting unum_open(percent, NULL, status)\n");
205     style=UNUM_PERCENT;
206     per_def=unum_open(style,NULL,0, NULL,NULL, &status);
207     if(U_FAILURE(status))
208         log_err("Error: could not create NumberFormat using unum_open(percent, NULL, &status): %s\n", myErrorName(status));
209 
210     log_verbose("\nTesting unum_open(percent,frenchlocale, status)\n");
211     per_fr=unum_open(style, NULL,0,"fr_FR", NULL,&status);
212     if(U_FAILURE(status))
213         log_err("Error: could not create NumberFormat using unum_open(percent, french, &status): %s\n", myErrorName(status));
214 
215     log_verbose("\nTesting unum_open(spellout, NULL, status)");
216     style=UNUM_SPELLOUT;
217     spellout_def=unum_open(style, NULL, 0, "en_US", NULL, &status);
218     if(U_FAILURE(status))
219         log_err("Error: could not create NumberFormat using unum_open(spellout, NULL, &status): %s\n", myErrorName(status));
220 
221     /* Testing unum_clone(..) */
222     log_verbose("\nTesting unum_clone(fmt, status)");
223     status = U_ZERO_ERROR;
224     myclone = unum_clone(def,&status);
225     if(U_FAILURE(status))
226         log_err("Error: could not clone unum_clone(def, &status): %s\n", myErrorName(status));
227     else
228     {
229         log_verbose("unum_clone() successful\n");
230     }
231 
232     /*Testing unum_getAvailable() and unum_countAvailable()*/
233     log_verbose("\nTesting getAvailableLocales and countAvailable()\n");
234     numlocales=unum_countAvailable();
235     if(numlocales < 0)
236         log_err("error in countAvailable");
237     else{
238         log_verbose("unum_countAvialable() successful\n");
239         log_verbose("The no: of locales where number formattting is applicable is %d\n", numlocales);
240     }
241     for(i=0;i<numlocales;i++)
242     {
243         log_verbose("%s\n", unum_getAvailable(i));
244         if (unum_getAvailable(i) == 0)
245             log_err("No locale for which number formatting patterns are applicable\n");
246         else
247             log_verbose("A locale %s for which number formatting patterns are applicable\n",unum_getAvailable(i));
248     }
249 
250 
251     /*Testing unum_format() and unum_formatdouble()*/
252     u_uastrcpy(temp1, "$100,000,000.00");
253 
254     log_verbose("\nTesting unum_format() \n");
255     resultlength=0;
256     pos1.field = UNUM_INTEGER_FIELD;
257     resultlengthneeded=unum_format(cur_def, l, NULL, resultlength, &pos1, &status);
258     if(status==U_BUFFER_OVERFLOW_ERROR)
259     {
260         status=U_ZERO_ERROR;
261         resultlength=resultlengthneeded+1;
262         result=(UChar*)malloc(sizeof(UChar) * resultlength);
263 /*        for (i = 0; i < 100000; i++) */
264         {
265             unum_format(cur_def, l, result, resultlength, &pos1, &status);
266         }
267     }
268 
269     if(U_FAILURE(status))
270     {
271         log_err("Error in formatting using unum_format(.....): %s\n", myErrorName(status) );
272     }
273     if(u_strcmp(result, temp1)==0)
274         log_verbose("Pass: Number formatting using unum_format() successful\n");
275     else
276         log_err("Fail: Error in number Formatting using unum_format()\n");
277     if(pos1.beginIndex == 1 && pos1.endIndex == 12)
278         log_verbose("Pass: Complete number formatting using unum_format() successful\n");
279     else
280         log_err("Fail: Error in complete number Formatting using unum_format()\nGot: b=%d end=%d\nExpected: b=1 end=12\n",
281                 pos1.beginIndex, pos1.endIndex);
282 
283     free(result);
284     result = 0;
285 
286     log_verbose("\nTesting unum_formatDouble()\n");
287     u_uastrcpy(temp1, "-$10,456.37");
288     resultlength=0;
289     pos2.field = UNUM_FRACTION_FIELD;
290     resultlengthneeded=unum_formatDouble(cur_def, d, NULL, resultlength, &pos2, &status);
291     if(status==U_BUFFER_OVERFLOW_ERROR)
292     {
293         status=U_ZERO_ERROR;
294         resultlength=resultlengthneeded+1;
295         result=(UChar*)malloc(sizeof(UChar) * resultlength);
296 /*        for (i = 0; i < 100000; i++) */
297         {
298             unum_formatDouble(cur_def, d, result, resultlength, &pos2, &status);
299         }
300     }
301     if(U_FAILURE(status))
302     {
303         log_err("Error in formatting using unum_formatDouble(.....): %s\n", myErrorName(status));
304     }
305     if(result && u_strcmp(result, temp1)==0)
306         log_verbose("Pass: Number Formatting using unum_formatDouble() Successful\n");
307     else {
308       log_err("FAIL: Error in number formatting using unum_formatDouble() - got '%s' expected '%s'\n",
309               aescstrdup(result, -1), aescstrdup(temp1, -1));
310     }
311     if(pos2.beginIndex == 9 && pos2.endIndex == 11)
312         log_verbose("Pass: Complete number formatting using unum_format() successful\n");
313     else
314         log_err("Fail: Error in complete number Formatting using unum_formatDouble()\nGot: b=%d end=%d\nExpected: b=9 end=11",
315                 pos1.beginIndex, pos1.endIndex);
316 
317 
318     /* Testing unum_parse() and unum_parseDouble() */
319     log_verbose("\nTesting unum_parseDouble()\n");
320 /*    for (i = 0; i < 100000; i++)*/
321     parsepos=0;
322     if (result != NULL) {
323       d1=unum_parseDouble(cur_def, result, u_strlen(result), &parsepos, &status);
324     } else {
325       log_err("result is NULL\n");
326     }
327     if(U_FAILURE(status)) {
328       log_err("parse of '%s' failed. Parsepos=%d. The error is  : %s\n", aescstrdup(result,u_strlen(result)),parsepos, myErrorName(status));
329     }
330 
331     if(d1!=d)
332         log_err("Fail: Error in parsing\n");
333     else
334         log_verbose("Pass: parsing successful\n");
335     if (result)
336         free(result);
337     result = 0;
338 
339     status = U_ZERO_ERROR;
340     /* Testing unum_formatDoubleCurrency / unum_parseDoubleCurrency */
341     log_verbose("\nTesting unum_formatDoubleCurrency\n");
342     u_uastrcpy(temp1, "Y1,235");
343     temp1[0] = 0xA5; /* Yen sign */
344     u_uastrcpy(temp, "JPY");
345     resultlength=0;
346     pos2.field = UNUM_INTEGER_FIELD;
347     resultlengthneeded=unum_formatDoubleCurrency(cur_def, a, temp, NULL, resultlength, &pos2, &status);
348     if (status==U_BUFFER_OVERFLOW_ERROR) {
349         status=U_ZERO_ERROR;
350         resultlength=resultlengthneeded+1;
351         result=(UChar*)malloc(sizeof(UChar) * resultlength);
352         unum_formatDoubleCurrency(cur_def, a, temp, result, resultlength, &pos2, &status);
353     }
354     if (U_FAILURE(status)) {
355         log_err("Error in formatting using unum_formatDoubleCurrency(.....): %s\n", myErrorName(status));
356     }
357     if (result && u_strcmp(result, temp1)==0) {
358         log_verbose("Pass: Number Formatting using unum_formatDoubleCurrency() Successful\n");
359     } else {
360         log_err("FAIL: Error in number formatting using unum_formatDoubleCurrency() - got '%s' expected '%s'\n",
361                 aescstrdup(result, -1), aescstrdup(temp1, -1));
362     }
363     if (pos2.beginIndex == 1 && pos2.endIndex == 6) {
364         log_verbose("Pass: Complete number formatting using unum_format() successful\n");
365     } else {
366         log_err("Fail: Error in complete number Formatting using unum_formatDouble()\nGot: b=%d end=%d\nExpected: b=1 end=6\n",
367                 pos1.beginIndex, pos1.endIndex);
368     }
369 
370     log_verbose("\nTesting unum_parseDoubleCurrency\n");
371     parsepos=0;
372     if (result == NULL) {
373         log_err("result is NULL\n");
374     }
375     else {
376         d1=unum_parseDoubleCurrency(cur_def, result, u_strlen(result), &parsepos, temp2, &status);
377         if (U_FAILURE(status)) {
378           log_err("parseDoubleCurrency '%s' failed. The error is  : %s\n", aescstrdup(result, u_strlen(result)), myErrorName(status));
379         }
380         /* Note: a==1234.56, but on parse expect a1=1235.0 */
381         if (d1!=a1) {
382             log_err("Fail: Error in parsing currency, got %f, expected %f\n", d1, a1);
383         } else {
384             log_verbose("Pass: parsed currency amount successfully\n");
385         }
386         if (u_strcmp(temp2, temp)==0) {
387             log_verbose("Pass: parsed correct currency\n");
388         } else {
389             log_err("Fail: parsed incorrect currency\n");
390         }
391     }
392     status = U_ZERO_ERROR; /* reset */
393 
394     free(result);
395     result = 0;
396 
397 
398 /* performance testing */
399     u_uastrcpy(temp1, "$462.12345");
400     resultlength=u_strlen(temp1);
401 /*    for (i = 0; i < 100000; i++) */
402     {
403         parsepos=0;
404         d1=unum_parseDouble(cur_def, temp1, resultlength, &parsepos, &status);
405     }
406     if(U_FAILURE(status))
407     {
408         log_err("parseDouble('%s') failed. The error is  : %s\n", aescstrdup(temp1, resultlength), myErrorName(status));
409     }
410 
411     /*
412      * Note: "for strict standard conformance all operations and constants are now supposed to be
413               evaluated in precision of long double".  So,  we assign a1 before comparing to a double. Bug #7932.
414      */
415     a1 = 462.12345;
416 
417     if(d1!=a1)
418         log_err("Fail: Error in parsing\n");
419     else
420         log_verbose("Pass: parsing successful\n");
421 
422 free(result);
423 
424     u_uastrcpy(temp1, "($10,456.3E1])");
425     parsepos=0;
426     d1=unum_parseDouble(cur_def, temp1, u_strlen(temp1), &parsepos, &status);
427     if(U_SUCCESS(status))
428     {
429         log_err("Error in unum_parseDouble(..., %s, ...): %s\n", temp1, myErrorName(status));
430     }
431 
432 
433     log_verbose("\nTesting unum_format()\n");
434     status=U_ZERO_ERROR;
435     resultlength=0;
436     parsepos=0;
437     resultlengthneeded=unum_format(per_fr, l, NULL, resultlength, &pos1, &status);
438     if(status==U_BUFFER_OVERFLOW_ERROR)
439     {
440         status=U_ZERO_ERROR;
441         resultlength=resultlengthneeded+1;
442         result=(UChar*)malloc(sizeof(UChar) * resultlength);
443 /*        for (i = 0; i < 100000; i++)*/
444         {
445             unum_format(per_fr, l, result, resultlength, &pos1, &status);
446         }
447     }
448     if(U_FAILURE(status))
449     {
450         log_err("Error in formatting using unum_format(.....): %s\n", myErrorName(status));
451     }
452 
453 
454     log_verbose("\nTesting unum_parse()\n");
455 /*    for (i = 0; i < 100000; i++) */
456     {
457         parsepos=0;
458         l1=unum_parse(per_fr, result, u_strlen(result), &parsepos, &status);
459     }
460     if(U_FAILURE(status))
461     {
462         log_err("parse failed. The error is  : %s\n", myErrorName(status));
463     }
464 
465     if(l1!=l)
466         log_err("Fail: Error in parsing\n");
467     else
468         log_verbose("Pass: parsing successful\n");
469 
470 free(result);
471 
472     /* create a number format using unum_openPattern(....)*/
473     log_verbose("\nTesting unum_openPattern()\n");
474     u_uastrcpy(temp1, "#,##0.0#;(#,##0.0#)");
475     pattern=unum_open(UNUM_IGNORE,temp1, u_strlen(temp1), NULL, NULL,&status);
476     if(U_FAILURE(status))
477     {
478         log_err("error in unum_openPattern(): %s\n", myErrorName(status) );;
479     }
480     else
481         log_verbose("Pass: unum_openPattern() works fine\n");
482 
483     /*test for unum_toPattern()*/
484     log_verbose("\nTesting unum_toPattern()\n");
485     resultlength=0;
486     resultlengthneeded=unum_toPattern(pattern, FALSE, NULL, resultlength, &status);
487     if(status==U_BUFFER_OVERFLOW_ERROR)
488     {
489         status=U_ZERO_ERROR;
490         resultlength=resultlengthneeded+1;
491         result=(UChar*)malloc(sizeof(UChar) * resultlength);
492         unum_toPattern(pattern, FALSE, result, resultlength, &status);
493     }
494     if(U_FAILURE(status))
495     {
496         log_err("error in extracting the pattern from UNumberFormat: %s\n", myErrorName(status));
497     }
498     else
499     {
500         if(u_strcmp(result, temp1)!=0)
501             log_err("FAIL: Error in extracting the pattern using unum_toPattern()\n");
502         else
503             log_verbose("Pass: extracted the pattern correctly using unum_toPattern()\n");
504 free(result);
505     }
506 
507     /*Testing unum_getSymbols() and unum_setSymbols()*/
508     log_verbose("\nTesting unum_getSymbols and unum_setSymbols()\n");
509     /*when we try to change the symbols of french to default we need to apply the pattern as well to fetch correct results */
510     resultlength=0;
511     resultlengthneeded=unum_toPattern(cur_def, FALSE, NULL, resultlength, &status);
512     if(status==U_BUFFER_OVERFLOW_ERROR)
513     {
514         status=U_ZERO_ERROR;
515         resultlength=resultlengthneeded+1;
516         result=(UChar*)malloc(sizeof(UChar) * resultlength);
517         unum_toPattern(cur_def, FALSE, result, resultlength, &status);
518     }
519     if(U_FAILURE(status))
520     {
521         log_err("error in extracting the pattern from UNumberFormat: %s\n", myErrorName(status));
522     }
523 
524     status=U_ZERO_ERROR;
525     cur_frpattern=unum_open(UNUM_IGNORE,result, u_strlen(result), "fr_FR",NULL, &status);
526     if(U_FAILURE(status))
527     {
528         log_err("error in unum_openPattern(): %s\n", myErrorName(status));
529     }
530 
531 free(result);
532 
533     /*getting the symbols of cur_def */
534     /*set the symbols of cur_frpattern to cur_def */
535     for (symType = UNUM_DECIMAL_SEPARATOR_SYMBOL; symType < UNUM_FORMAT_SYMBOL_COUNT; symType++) {
536         status=U_ZERO_ERROR;
537         unum_getSymbol(cur_def, symType, temp1, sizeof(temp1), &status);
538         unum_setSymbol(cur_frpattern, symType, temp1, -1, &status);
539         if(U_FAILURE(status))
540         {
541             log_err("Error in get/set symbols: %s\n", myErrorName(status));
542         }
543     }
544 
545     /*format to check the result */
546     resultlength=0;
547     resultlengthneeded=unum_format(cur_def, l, NULL, resultlength, &pos1, &status);
548     if(status==U_BUFFER_OVERFLOW_ERROR)
549     {
550         status=U_ZERO_ERROR;
551         resultlength=resultlengthneeded+1;
552         result=(UChar*)malloc(sizeof(UChar) * resultlength);
553         unum_format(cur_def, l, result, resultlength, &pos1, &status);
554     }
555     if(U_FAILURE(status))
556     {
557         log_err("Error in formatting using unum_format(.....): %s\n", myErrorName(status));
558     }
559 
560     if(U_FAILURE(status)){
561         log_err("Fail: error in unum_setSymbols: %s\n", myErrorName(status));
562     }
563     unum_applyPattern(cur_frpattern, FALSE, result, u_strlen(result),NULL,NULL);
564 
565     for (symType = UNUM_DECIMAL_SEPARATOR_SYMBOL; symType < UNUM_FORMAT_SYMBOL_COUNT; symType++) {
566         status=U_ZERO_ERROR;
567         unum_getSymbol(cur_def, symType, temp1, sizeof(temp1), &status);
568         unum_getSymbol(cur_frpattern, symType, temp2, sizeof(temp2), &status);
569         if(U_FAILURE(status) || u_strcmp(temp1, temp2) != 0)
570         {
571             log_err("Fail: error in getting symbols\n");
572         }
573         else
574             log_verbose("Pass: get and set symbols successful\n");
575     }
576 
577     /*format and check with the previous result */
578 
579     resultlength=0;
580     resultlengthneeded=unum_format(cur_frpattern, l, NULL, resultlength, &pos1, &status);
581     if(status==U_BUFFER_OVERFLOW_ERROR)
582     {
583         status=U_ZERO_ERROR;
584         resultlength=resultlengthneeded+1;
585         unum_format(cur_frpattern, l, temp1, resultlength, &pos1, &status);
586     }
587     if(U_FAILURE(status))
588     {
589         log_err("Error in formatting using unum_format(.....): %s\n", myErrorName(status));
590     }
591     /* TODO:
592      * This test fails because we have not called unum_applyPattern().
593      * Currently, such an applyPattern() does not exist on the C API, and
594      * we have jitterbug 411 for it.
595      * Since it is close to the 1.5 release, I (markus) am disabling this test just
596      * for this release (I added the test itself only last week).
597      * For the next release, we need to fix this.
598      * Then, remove the uprv_strcmp("1.5", ...) and this comment, and the include "cstring.h" at the beginning of this file.
599      */
600     if(u_strcmp(result, temp1) != 0) {
601         log_err("Formatting failed after setting symbols. result=%s temp1=%s\n", result, temp1);
602     }
603 
604 
605     /*----------- */
606 
607 free(result);
608 
609     /* Testing unum_get/setSymbol() */
610     for(i = 0; i < UNUM_FORMAT_SYMBOL_COUNT; ++i) {
611         symbol[0] = (UChar)(0x41 + i);
612         symbol[1] = (UChar)(0x61 + i);
613         unum_setSymbol(cur_frpattern, (UNumberFormatSymbol)i, symbol, 2, &status);
614         if(U_FAILURE(status)) {
615             log_err("Error from unum_setSymbol(%d): %s\n", i, myErrorName(status));
616             return;
617         }
618     }
619     for(i = 0; i < UNUM_FORMAT_SYMBOL_COUNT; ++i) {
620         resultlength = unum_getSymbol(cur_frpattern, (UNumberFormatSymbol)i, symbol, sizeof(symbol)/U_SIZEOF_UCHAR, &status);
621         if(U_FAILURE(status)) {
622             log_err("Error from unum_getSymbol(%d): %s\n", i, myErrorName(status));
623             return;
624         }
625         if(resultlength != 2 || symbol[0] != 0x41 + i || symbol[1] != 0x61 + i) {
626             log_err("Failure in unum_getSymbol(%d): got unexpected symbol\n", i);
627         }
628     }
629     /*try getting from a bogus symbol*/
630     unum_getSymbol(cur_frpattern, (UNumberFormatSymbol)i, symbol, sizeof(symbol)/U_SIZEOF_UCHAR, &status);
631     if(U_SUCCESS(status)){
632         log_err("Error : Expected U_ILLEGAL_ARGUMENT_ERROR for bogus symbol");
633     }
634     if(U_FAILURE(status)){
635         if(status != U_ILLEGAL_ARGUMENT_ERROR){
636             log_err("Error: Expected U_ILLEGAL_ARGUMENT_ERROR for bogus symbol, Got %s\n", myErrorName(status));
637         }
638     }
639     status=U_ZERO_ERROR;
640 
641     /* Testing unum_getTextAttribute() and unum_setTextAttribute()*/
642     log_verbose("\nTesting getting and setting text attributes\n");
643     resultlength=5;
644     unum_getTextAttribute(cur_fr, UNUM_NEGATIVE_SUFFIX, temp, resultlength, &status);
645     if(U_FAILURE(status))
646     {
647         log_err("Failure in gettting the Text attributes of number format: %s\n", myErrorName(status));
648     }
649     unum_setTextAttribute(cur_def, UNUM_NEGATIVE_SUFFIX, temp, u_strlen(temp), &status);
650     if(U_FAILURE(status))
651     {
652         log_err("Failure in gettting the Text attributes of number format: %s\n", myErrorName(status));
653     }
654     unum_getTextAttribute(cur_def, UNUM_NEGATIVE_SUFFIX, suffix, resultlength, &status);
655     if(U_FAILURE(status))
656     {
657         log_err("Failure in gettting the Text attributes of number format: %s\n", myErrorName(status));
658     }
659     if(u_strcmp(suffix,temp)!=0)
660         log_err("Fail:Error in setTextAttribute or getTextAttribute in setting and getting suffix\n");
661     else
662         log_verbose("Pass: setting and getting suffix works fine\n");
663     /*set it back to normal */
664     u_uastrcpy(temp,"$");
665     unum_setTextAttribute(cur_def, UNUM_NEGATIVE_SUFFIX, temp, u_strlen(temp), &status);
666 
667     /*checking some more text setter conditions */
668     u_uastrcpy(prefix, "+");
669     unum_setTextAttribute(def, UNUM_POSITIVE_PREFIX, prefix, u_strlen(prefix) , &status);
670     if(U_FAILURE(status))
671     {
672         log_err("error in setting the text attributes : %s\n", myErrorName(status));
673     }
674     unum_getTextAttribute(def, UNUM_POSITIVE_PREFIX, temp, resultlength, &status);
675     if(U_FAILURE(status))
676     {
677         log_err("error in getting the text attributes : %s\n", myErrorName(status));
678     }
679 
680     if(u_strcmp(prefix, temp)!=0)
681         log_err("ERROR: get and setTextAttributes with positive prefix failed\n");
682     else
683         log_verbose("Pass: get and setTextAttributes with positive prefix works fine\n");
684 
685     u_uastrcpy(prefix, "+");
686     unum_setTextAttribute(def, UNUM_NEGATIVE_PREFIX, prefix, u_strlen(prefix), &status);
687     if(U_FAILURE(status))
688     {
689         log_err("error in setting the text attributes : %s\n", myErrorName(status));
690     }
691     unum_getTextAttribute(def, UNUM_NEGATIVE_PREFIX, temp, resultlength, &status);
692     if(U_FAILURE(status))
693     {
694         log_err("error in getting the text attributes : %s\n", myErrorName(status));
695     }
696     if(u_strcmp(prefix, temp)!=0)
697         log_err("ERROR: get and setTextAttributes with negative prefix failed\n");
698     else
699         log_verbose("Pass: get and setTextAttributes with negative prefix works fine\n");
700 
701     u_uastrcpy(suffix, "+");
702     unum_setTextAttribute(def, UNUM_NEGATIVE_SUFFIX, suffix, u_strlen(suffix) , &status);
703     if(U_FAILURE(status))
704     {
705         log_err("error in setting the text attributes: %s\n", myErrorName(status));
706     }
707 
708     unum_getTextAttribute(def, UNUM_NEGATIVE_SUFFIX, temp, resultlength, &status);
709     if(U_FAILURE(status))
710     {
711         log_err("error in getting the text attributes : %s\n", myErrorName(status));
712     }
713     if(u_strcmp(suffix, temp)!=0)
714         log_err("ERROR: get and setTextAttributes with negative suffix failed\n");
715     else
716         log_verbose("Pass: get and settextAttributes with negative suffix works fine\n");
717 
718     u_uastrcpy(suffix, "++");
719     unum_setTextAttribute(def, UNUM_POSITIVE_SUFFIX, suffix, u_strlen(suffix) , &status);
720     if(U_FAILURE(status))
721     {
722         log_err("error in setting the text attributes: %s\n", myErrorName(status));
723     }
724 
725     unum_getTextAttribute(def, UNUM_POSITIVE_SUFFIX, temp, resultlength, &status);
726     if(U_FAILURE(status))
727     {
728         log_err("error in getting the text attributes : %s\n", myErrorName(status));
729     }
730     if(u_strcmp(suffix, temp)!=0)
731         log_err("ERROR: get and setTextAttributes with negative suffix failed\n");
732     else
733         log_verbose("Pass: get and settextAttributes with negative suffix works fine\n");
734 
735     /*Testing unum_getAttribute and  unum_setAttribute() */
736     log_verbose("\nTesting get and set Attributes\n");
737     attr=UNUM_GROUPING_SIZE;
738     newvalue=unum_getAttribute(def, attr);
739     newvalue=2;
740     unum_setAttribute(def, attr, newvalue);
741     if(unum_getAttribute(def,attr)!=2)
742         log_err("Fail: error in setting and getting attributes for UNUM_GROUPING_SIZE\n");
743     else
744         log_verbose("Pass: setting and getting attributes for UNUM_GROUPING_SIZE works fine\n");
745 
746     attr=UNUM_MULTIPLIER;
747     newvalue=unum_getAttribute(def, attr);
748     newvalue=8;
749     unum_setAttribute(def, attr, newvalue);
750     if(unum_getAttribute(def,attr) != 8)
751         log_err("error in setting and getting attributes for UNUM_MULTIPLIER\n");
752     else
753         log_verbose("Pass:setting and getting attributes for UNUM_MULTIPLIER works fine\n");
754 
755     attr=UNUM_SECONDARY_GROUPING_SIZE;
756     newvalue=unum_getAttribute(def, attr);
757     newvalue=2;
758     unum_setAttribute(def, attr, newvalue);
759     if(unum_getAttribute(def,attr) != 2)
760         log_err("error in setting and getting attributes for UNUM_SECONDARY_GROUPING_SIZE\n");
761     else
762         log_verbose("Pass:setting and getting attributes for UNUM_SECONDARY_GROUPING_SIZE works fine\n");
763 
764     /*testing set and get Attributes extensively */
765     log_verbose("\nTesting get and set attributes extensively\n");
766     for(attr=UNUM_PARSE_INT_ONLY; attr<= UNUM_PADDING_POSITION; attr=(UNumberFormatAttribute)((int32_t)attr + 1) )
767     {
768         newvalue=unum_getAttribute(fr, attr);
769         unum_setAttribute(def, attr, newvalue);
770         if(unum_getAttribute(def,attr)!=unum_getAttribute(fr, attr))
771             log_err("error in setting and getting attributes\n");
772         else
773             log_verbose("Pass: attributes set and retrieved successfully\n");
774     }
775 
776     /*testing spellout format to make sure we can use it successfully.*/
777     log_verbose("\nTesting spellout format\n");
778     if (spellout_def)
779     {
780         static const int32_t values[] = { 0, -5, 105, 1005, 105050 };
781         for (i = 0; i < LENGTH(values); ++i) {
782             UChar buffer[128];
783             int32_t len;
784             int32_t value = values[i];
785             status = U_ZERO_ERROR;
786             len = unum_format(spellout_def, value, buffer, LENGTH(buffer), NULL, &status);
787             if(U_FAILURE(status)) {
788                 log_err("Error in formatting using unum_format(spellout_fmt, ...): %s\n", myErrorName(status));
789             } else {
790                 int32_t pp = 0;
791                 int32_t parseResult;
792                 /*ustrToAstr(buffer, len, logbuf, LENGTH(logbuf));*/
793                 log_verbose("formatted %d as '%s', length: %d\n", value, aescstrdup(buffer, len), len);
794 
795                 parseResult = unum_parse(spellout_def, buffer, len, &pp, &status);
796                 if (U_FAILURE(status)) {
797                     log_err("Error in parsing using unum_format(spellout_fmt, ...): %s\n", myErrorName(status));
798                 } else if (parseResult != value) {
799                     log_err("unum_format result %d != value %d\n", parseResult, value);
800                 }
801             }
802         }
803     }
804     else {
805         log_err("Spellout format is unavailable\n");
806     }
807 
808     {    /* Test for ticket #7079 */
809         UNumberFormat* dec_en;
810         UChar groupingSep[] = { 0 };
811         UChar numPercent[] = { 0x0031, 0x0032, 0x0025, 0 }; /* "12%" */
812         double parseResult = 0.0;
813 
814         status=U_ZERO_ERROR;
815         dec_en = unum_open(UNUM_DECIMAL, NULL, 0, "en_US", NULL, &status);
816         unum_setAttribute(dec_en, UNUM_LENIENT_PARSE, 0);
817         unum_setSymbol(dec_en, UNUM_GROUPING_SEPARATOR_SYMBOL, groupingSep, 0, &status);
818         parseResult = unum_parseDouble(dec_en, numPercent, -1, NULL, &status);
819         /* Without the fix in #7079, the above call will hang */
820         if ( U_FAILURE(status) || parseResult != 12.0 ) {
821             log_err("unum_parseDouble with empty groupingSep: status %s, parseResult %f not 12.0\n",
822                     myErrorName(status), parseResult);
823         } else {
824             log_verbose("unum_parseDouble with empty groupingSep: no hang, OK\n");
825         }
826         unum_close(dec_en);
827     }
828 
829     {   /* Test parse & format of big decimals.  Use a number with too many digits to fit in a double,
830                                          to verify that it is taking the pure decimal path. */
831         UNumberFormat *fmt;
832         const char *bdpattern = "#,##0.#########";
833         const char *numInitial     = "12345678900987654321.1234567896";
834         const char *numFormatted  = "12,345,678,900,987,654,321.12345679";
835         const char *parseExpected = "12345678900987654321.12345679";
836         int32_t resultSize    = 0;
837         int32_t parsePos      = 0;     /* Output parameter for Parse operations. */
838         #define DESTCAPACITY 100
839         UChar dest[DESTCAPACITY];
840         char  desta[DESTCAPACITY];
841         UFieldPosition fieldPos = {0};
842 
843         /* Format */
844 
845         status = U_ZERO_ERROR;
846         u_uastrcpy(dest, bdpattern);
847         fmt = unum_open(UNUM_PATTERN_DECIMAL, dest, -1, "en", NULL /*parseError*/, &status);
848         if (U_FAILURE(status)) log_err("File %s, Line %d, status = %s\n", __FILE__, __LINE__, u_errorName(status));
849 
850         resultSize = unum_formatDecimal(fmt, numInitial, -1, dest, DESTCAPACITY, NULL, &status);
851         if (U_FAILURE(status)) {
852             log_err("File %s, Line %d, status = %s\n", __FILE__, __LINE__, u_errorName(status));
853         }
854         u_austrncpy(desta, dest, DESTCAPACITY);
855         if (strcmp(numFormatted, desta) != 0) {
856             log_err("File %s, Line %d, (expected, acutal) =  (\"%s\", \"%s\")\n",
857                     __FILE__, __LINE__, numFormatted, desta);
858         }
859         if (strlen(numFormatted) != resultSize) {
860             log_err("File %s, Line %d, (expected, actual) = (%d, %d)\n",
861                      __FILE__, __LINE__, strlen(numFormatted), resultSize);
862         }
863 
864         /* Format with a FieldPosition parameter */
865 
866         fieldPos.field = UNUM_DECIMAL_SEPARATOR_FIELD;
867         resultSize = unum_formatDecimal(fmt, numInitial, -1, dest, DESTCAPACITY, &fieldPos, &status);
868         if (U_FAILURE(status)) {
869             log_err("File %s, Line %d, status = %s\n", __FILE__, __LINE__, u_errorName(status));
870         }
871         u_austrncpy(desta, dest, DESTCAPACITY);
872         if (strcmp(numFormatted, desta) != 0) {
873             log_err("File %s, Line %d, (expected, acutal) =  (\"%s\", \"%s\")\n",
874                     __FILE__, __LINE__, numFormatted, desta);
875         }
876         if (fieldPos.beginIndex != 26) {  /* index of "." in formatted number */
877             log_err("File %s, Line %d, (expected, acutal) =  (%d, %d)\n",
878                     __FILE__, __LINE__, 0, fieldPos.beginIndex);
879         }
880         if (fieldPos.endIndex != 27) {
881             log_err("File %s, Line %d, (expected, acutal) =  (%d, %d)\n",
882                     __FILE__, __LINE__, 0, fieldPos.endIndex);
883         }
884 
885         /* Parse */
886 
887         status = U_ZERO_ERROR;
888         u_uastrcpy(dest, numFormatted);   /* Parse the expected output of the formatting test */
889         resultSize = unum_parseDecimal(fmt, dest, -1, NULL, desta, DESTCAPACITY, &status);
890         if (U_FAILURE(status)) {
891             log_err("File %s, Line %d, status = %s\n", __FILE__, __LINE__, u_errorName(status));
892         }
893         if (strcmp(parseExpected, desta) != 0) {
894             log_err("File %s, Line %d, (expected, actual) = (\"%s\", \"%s\")\n",
895                     __FILE__, __LINE__, parseExpected, desta);
896         }
897         if (strlen(parseExpected) != resultSize) {
898             log_err("File %s, Line %d, (expected, actual) = (%d, %d)\n",
899                     __FILE__, __LINE__, strlen(parseExpected), resultSize);
900         }
901 
902         /* Parse with a parsePos parameter */
903 
904         status = U_ZERO_ERROR;
905         u_uastrcpy(dest, numFormatted);   /* Parse the expected output of the formatting test */
906         parsePos = 3;                 /*      12,345,678,900,987,654,321.12345679         */
907                                       /* start parsing at the the third char              */
908         resultSize = unum_parseDecimal(fmt, dest, -1, &parsePos, desta, DESTCAPACITY, &status);
909         if (U_FAILURE(status)) {
910             log_err("File %s, Line %d, status = %s\n", __FILE__, __LINE__, u_errorName(status));
911         }
912         if (strcmp(parseExpected+2, desta) != 0) {   /*  "345678900987654321.12345679" */
913             log_err("File %s, Line %d, (expected, actual) = (\"%s\", \"%s\")\n",
914                     __FILE__, __LINE__, parseExpected+2, desta);
915         }
916         if (strlen(numFormatted) != parsePos) {
917             log_err("File %s, Line %d, parsePos (expected, actual) = (\"%d\", \"%d\")\n",
918                     __FILE__, __LINE__, strlen(parseExpected), parsePos);
919         }
920 
921         unum_close(fmt);
922     }
923 
924     status = U_ZERO_ERROR;
925     /* Test invalid symbol argument */
926     {
927         int32_t badsymbolLarge = UNUM_FORMAT_SYMBOL_COUNT + 1;
928         int32_t badsymbolSmall = -1;
929         UChar value[10];
930         int32_t valueLength = 10;
931         UNumberFormat *fmt = unum_open(UNUM_DEFAULT, NULL, 0, NULL, NULL, &status);
932         if (U_FAILURE(status)) {
933             log_err("File %s, Line %d, status = %s\n", __FILE__, __LINE__, u_errorName(status));
934         } else {
935             unum_getSymbol(fmt, (UNumberFormatSymbol)badsymbolLarge, NULL, 0, &status);
936             if (U_SUCCESS(status)) log_err("unum_getSymbol()'s status should be ILLEGAL_ARGUMENT with invalid symbol (> UNUM_FORMAT_SYMBOL_COUNT) argument\n");
937 
938             status = U_ZERO_ERROR;
939             unum_getSymbol(fmt, (UNumberFormatSymbol)badsymbolSmall, NULL, 0, &status);
940             if (U_SUCCESS(status)) log_err("unum_getSymbol()'s status should be ILLEGAL_ARGUMENT with invalid symbol (less than 0) argument\n");
941 
942             status = U_ZERO_ERROR;
943             unum_setSymbol(fmt, (UNumberFormatSymbol)badsymbolLarge, value, valueLength, &status);
944             if (U_SUCCESS(status)) log_err("unum_setSymbol()'s status should be ILLEGAL_ARGUMENT with invalid symbol (> UNUM_FORMAT_SYMBOL_COUNT) argument\n");
945 
946             status = U_ZERO_ERROR;
947             unum_setSymbol(fmt, (UNumberFormatSymbol)badsymbolSmall, value, valueLength, &status);
948             if (U_SUCCESS(status)) log_err("unum_setSymbol()'s status should be ILLEGAL_ARGUMENT with invalid symbol (less than 0) argument\n");
949 
950             unum_close(fmt);
951         }
952     }
953 
954 
955     /*closing the NumberFormat() using unum_close(UNumberFormat*)")*/
956     unum_close(def);
957     unum_close(fr);
958     unum_close(cur_def);
959     unum_close(cur_fr);
960     unum_close(per_def);
961     unum_close(per_fr);
962     unum_close(spellout_def);
963     unum_close(pattern);
964     unum_close(cur_frpattern);
965     unum_close(myclone);
966 
967 }
968 
TestParseZero(void)969 static void TestParseZero(void)
970 {
971     UErrorCode errorCode = U_ZERO_ERROR;
972     UChar input[] = {0x30, 0};   /*  Input text is decimal '0' */
973     UChar pat[] = {0x0023,0x003b,0x0023,0}; /*  {'#', ';', '#', 0}; */
974     double  dbl;
975 
976 #if 0
977     UNumberFormat* unum = unum_open( UNUM_DECIMAL /*or UNUM_DEFAULT*/, NULL, -1, NULL, NULL, &errorCode);
978 #else
979     UNumberFormat* unum = unum_open( UNUM_PATTERN_DECIMAL /*needs pattern*/, pat, -1, NULL, NULL, &errorCode);
980 #endif
981 
982     dbl = unum_parseDouble( unum, input, -1 /*u_strlen(input)*/, 0 /* 0 = start */, &errorCode );
983     if (U_FAILURE(errorCode)) {
984         log_data_err("Result - %s\n", u_errorName(errorCode));
985     } else {
986         log_verbose("Double: %f\n", dbl);
987     }
988     unum_close(unum);
989 }
990 
991 static const UChar dollars2Sym[] = { 0x24,0x32,0x2E,0x30,0x30,0 }; /* $2.00 */
992 static const UChar dollars4Sym[] = { 0x24,0x34,0 }; /* $4 */
993 static const UChar dollars9Sym[] = { 0x39,0xA0,0x24,0 }; /* 9 $ */
994 static const UChar pounds3Sym[]  = { 0xA3,0x33,0x2E,0x30,0x30,0 }; /* [POUND]3.00 */
995 static const UChar pounds5Sym[]  = { 0xA3,0x35,0 }; /* [POUND]5 */
996 static const UChar pounds7Sym[]  = { 0x37,0xA0,0xA3,0 }; /* 7 [POUND] */
997 static const UChar euros4Sym[]   = { 0x34,0x2C,0x30,0x30,0xA0,0x20AC,0 }; /* 4,00 [EURO] */
998 static const UChar euros6Sym[]   = { 0x36,0xA0,0x20AC,0 }; /* 6 [EURO] */
999 static const UChar euros8Sym[]   = { 0x20AC,0x38,0 }; /* [EURO]8 */
1000 static const UChar dollars4PluEn[] = { 0x34,0x20,0x55,0x53,0x20,0x64,0x6F,0x6C,0x6C,0x61,0x72,0x73,0 }; /* 4 US dollars*/
1001 static const UChar pounds5PluEn[]  = { 0x35,0x20,0x42,0x72,0x69,0x74,0x69,0x73,0x68,0x20,0x70,0x6F,0x75,0x6E,0x64,0x73,0x20,0x73,0x74,0x65,0x72,0x6C,0x69,0x6E,0x67,0 }; /* 5 British pounds sterling */
1002 static const UChar euros8PluEn[]   = { 0x38,0x20,0x65,0x75,0x72,0x6F,0x73,0 }; /* 8 euros*/
1003 static const UChar euros6PluFr[]   = { 0x36,0x20,0x65,0x75,0x72,0x6F,0x73,0 }; /* 6 euros*/
1004 
1005 typedef struct {
1006     const char *  locale;
1007     const char *  descrip;
1008     const UChar * currStr;
1009     const UChar * plurStr;
1010     UErrorCode    parsDoubExpectErr;
1011     int32_t       parsDoubExpectPos;
1012     double        parsDoubExpectVal;
1013     UErrorCode    parsCurrExpectErr;
1014     int32_t       parsCurrExpectPos;
1015     double        parsCurrExpectVal;
1016     const char *  parsCurrExpectCurr;
1017 } ParseCurrencyItem;
1018 
1019 static const ParseCurrencyItem parseCurrencyItems[] = {
1020     { "en_US", "dollars2", dollars2Sym, NULL,          U_ZERO_ERROR,  5, 2.0, U_ZERO_ERROR,  5, 2.0, "USD" },
1021     { "en_US", "dollars4", dollars4Sym, dollars4PluEn, U_ZERO_ERROR,  2, 4.0, U_ZERO_ERROR,  2, 4.0, "USD" },
1022     { "en_US", "dollars9", dollars9Sym, NULL,          U_PARSE_ERROR, 1, 0.0, U_PARSE_ERROR, 1, 0.0, ""    },
1023     { "en_US", "pounds3",  pounds3Sym,  NULL,          U_PARSE_ERROR, 0, 0.0, U_ZERO_ERROR,  5, 3.0, "GBP" },
1024     { "en_US", "pounds5",  pounds5Sym,  pounds5PluEn,  U_PARSE_ERROR, 0, 0.0, U_ZERO_ERROR,  2, 5.0, "GBP" },
1025     { "en_US", "pounds7",  pounds7Sym,  NULL,          U_PARSE_ERROR, 1, 0.0, U_PARSE_ERROR, 1, 0.0, ""    },
1026     { "en_US", "euros8",   euros8Sym,   euros8PluEn,   U_PARSE_ERROR, 0, 0.0, U_ZERO_ERROR,  2, 8.0, "EUR" },
1027 
1028     { "en_GB", "pounds3",  pounds3Sym,  NULL,          U_ZERO_ERROR,  5, 3.0, U_ZERO_ERROR,  5, 3.0, "GBP" },
1029     { "en_GB", "pounds5",  pounds5Sym,  pounds5PluEn,  U_ZERO_ERROR,  2, 5.0, U_ZERO_ERROR,  2, 5.0, "GBP" },
1030     { "en_GB", "pounds7",  pounds7Sym,  NULL,          U_PARSE_ERROR, 1, 0.0, U_PARSE_ERROR, 1, 0.0, ""    },
1031     { "en_GB", "euros4",   euros4Sym,   NULL,          U_PARSE_ERROR, 4, 0.0, U_PARSE_ERROR, 4, 0.0, ""    },
1032     { "en_GB", "euros6",   euros6Sym,   NULL,          U_PARSE_ERROR, 1, 0.0, U_PARSE_ERROR, 1, 0.0, ""    },
1033     { "en_GB", "euros8",   euros8Sym,   euros8PluEn,   U_PARSE_ERROR, 0, 0.0, U_ZERO_ERROR,  2, 8.0, "EUR" },
1034     { "en_GB", "dollars4", dollars4Sym, dollars4PluEn, U_PARSE_ERROR, 0, 0.0, U_ZERO_ERROR,  2, 4.0, "USD" },
1035 
1036     { "fr_FR", "euros4",   euros4Sym,   NULL,          U_ZERO_ERROR,  6, 4.0, U_ZERO_ERROR,  6, 4.0, "EUR" },
1037     { "fr_FR", "euros6",   euros6Sym,   euros6PluFr,   U_ZERO_ERROR,  3, 6.0, U_ZERO_ERROR,  3, 6.0, "EUR" },
1038     { "fr_FR", "euros8",   euros8Sym,   NULL,          U_PARSE_ERROR, 0, 0.0, U_PARSE_ERROR, 0, 0.0, ""    },
1039     { "fr_FR", "dollars2", dollars2Sym, NULL,          U_PARSE_ERROR, 0, 0.0, U_PARSE_ERROR, 0, 0.0, ""    },
1040     { "fr_FR", "dollars4", dollars4Sym, NULL,          U_PARSE_ERROR, 0, 0.0, U_PARSE_ERROR, 0, 0.0, ""    },
1041 
1042     { NULL,    NULL,       NULL,        NULL,          0,             0, 0.0, 0,             0, 0.0, NULL  }
1043 };
1044 
TestParseCurrency()1045 static void TestParseCurrency()
1046 {
1047     const ParseCurrencyItem * itemPtr;
1048     for (itemPtr = parseCurrencyItems; itemPtr->locale != NULL; ++itemPtr) {
1049         UNumberFormat* unum;
1050         UErrorCode status;
1051         double parseVal;
1052         int32_t parsePos;
1053         UChar parseCurr[4];
1054         char parseCurrB[4];
1055 
1056         status = U_ZERO_ERROR;
1057         unum = unum_open(UNUM_CURRENCY, NULL, 0, itemPtr->locale, NULL, &status);
1058         if (U_SUCCESS(status)) {
1059             status = U_ZERO_ERROR;
1060             parsePos = 0;
1061             parseVal = unum_parseDouble(unum, itemPtr->currStr, -1, &parsePos, &status);
1062             if (status != itemPtr->parsDoubExpectErr || parsePos != itemPtr->parsDoubExpectPos || parseVal != itemPtr->parsDoubExpectVal) {
1063                 log_err("UNUM_CURRENCY parseDouble %s/%s, expect %s pos %d val %.1f, get %s pos %d val %.1f\n",
1064                         itemPtr->locale, itemPtr->descrip,
1065                         u_errorName(itemPtr->parsDoubExpectErr), itemPtr->parsDoubExpectPos, itemPtr->parsDoubExpectVal,
1066                         u_errorName(status), parsePos, parseVal );
1067             }
1068             status = U_ZERO_ERROR;
1069             parsePos = 0;
1070             parseCurr[0] = 0;
1071             parseVal = unum_parseDoubleCurrency(unum, itemPtr->currStr, -1, &parsePos, parseCurr, &status);
1072             u_austrncpy(parseCurrB, parseCurr, 4);
1073             if (status != itemPtr->parsCurrExpectErr || parsePos != itemPtr->parsCurrExpectPos || parseVal != itemPtr->parsCurrExpectVal ||
1074                     strncmp(parseCurrB, itemPtr->parsCurrExpectCurr, 4) != 0) {
1075                 log_err("UNUM_CURRENCY parseDoubleCurrency %s/%s, expect %s pos %d val %.1f cur %s, get %s pos %d val %.1f cur %s\n",
1076                         itemPtr->locale, itemPtr->descrip,
1077                         u_errorName(itemPtr->parsCurrExpectErr), itemPtr->parsCurrExpectPos, itemPtr->parsCurrExpectVal, itemPtr->parsCurrExpectCurr,
1078                         u_errorName(status), parsePos, parseVal, parseCurrB );
1079             }
1080             unum_close(unum);
1081         } else {
1082             log_data_err("unexpected error in unum_open UNUM_CURRENCY for locale %s: '%s'\n", itemPtr->locale, u_errorName(status));
1083         }
1084 
1085         if (itemPtr->plurStr != NULL) {
1086             status = U_ZERO_ERROR;
1087             unum = unum_open(UNUM_CURRENCY_PLURAL, NULL, 0, itemPtr->locale, NULL, &status);
1088             if (U_SUCCESS(status)) {
1089                 status = U_ZERO_ERROR;
1090                 parsePos = 0;
1091                 parseVal = unum_parseDouble(unum, itemPtr->plurStr, -1, &parsePos, &status);
1092                 if (status != itemPtr->parsDoubExpectErr || parseVal != itemPtr->parsDoubExpectVal) {
1093                     log_err("UNUM_CURRENCY parseDouble %s/%s, expect %s val %.1f, get %s val %.1f\n",
1094                             itemPtr->locale, itemPtr->descrip,
1095                             u_errorName(itemPtr->parsDoubExpectErr), itemPtr->parsDoubExpectVal,
1096                             u_errorName(status), parseVal );
1097                 }
1098                 status = U_ZERO_ERROR;
1099                 parsePos = 0;
1100                 parseCurr[0] = 0;
1101                 parseVal = unum_parseDoubleCurrency(unum, itemPtr->plurStr, -1, &parsePos, parseCurr, &status);
1102                 u_austrncpy(parseCurrB, parseCurr, 4);
1103                 if (status != itemPtr->parsCurrExpectErr || parseVal != itemPtr->parsCurrExpectVal ||
1104                         strncmp(parseCurrB, itemPtr->parsCurrExpectCurr, 4) != 0) {
1105                     log_err("UNUM_CURRENCY parseDoubleCurrency %s/%s, expect %s val %.1f cur %s, get %s val %.1f cur %s\n",
1106                             itemPtr->locale, itemPtr->descrip,
1107                             u_errorName(itemPtr->parsCurrExpectErr), itemPtr->parsCurrExpectVal, itemPtr->parsCurrExpectCurr,
1108                             u_errorName(status), parseVal, parseCurrB );
1109                 }
1110                 unum_close(unum);
1111             } else {
1112                 log_data_err("unexpected error in unum_open UNUM_CURRENCY_PLURAL for locale %s: '%s'\n", itemPtr->locale, u_errorName(status));
1113             }
1114         }
1115     }
1116 }
1117 
1118 typedef struct {
1119     const char *  testname;
1120     const char *  locale;
1121     const UChar * source;
1122     int32_t       startPos;
1123     int32_t       value;
1124     int32_t       endPos;
1125     UErrorCode    status;
1126 } SpelloutParseTest;
1127 
1128 static const UChar ustr_en0[]   = {0x7A, 0x65, 0x72, 0x6F, 0}; /* zero */
1129 static const UChar ustr_123[]   = {0x31, 0x32, 0x33, 0};       /* 123 */
1130 static const UChar ustr_en123[] = {0x6f, 0x6e, 0x65, 0x20, 0x68, 0x75, 0x6e, 0x64, 0x72, 0x65, 0x64,
1131                                    0x20, 0x74, 0x77, 0x65, 0x6e, 0x74, 0x79,
1132                                    0x2d, 0x74, 0x68, 0x72, 0x65, 0x65, 0}; /* one hundred twenty-three */
1133 static const UChar ustr_fr123[] = {0x63, 0x65, 0x6e, 0x74, 0x20, 0x76, 0x69, 0x6e, 0x67, 0x74, 0x2d,
1134                                    0x74, 0x72, 0x6f, 0x69, 0x73, 0};       /* cent vingt-trois */
1135 static const UChar ustr_ja123[] = {0x767e, 0x4e8c, 0x5341, 0x4e09, 0};     /* kanji 100(+)2(*)10(+)3 */
1136 
1137 static const SpelloutParseTest spelloutParseTests[] = {
1138     /* name    loc   src       start val  end status */
1139     { "en0",   "en", ustr_en0,    0,   0,  4, U_ZERO_ERROR },
1140     { "en0",   "en", ustr_en0,    2,   0,  2, U_PARSE_ERROR },
1141     { "en0",   "ja", ustr_en0,    0,   0,  0, U_PARSE_ERROR },
1142     { "123",   "en", ustr_123,    0, 123,  3, U_ZERO_ERROR },
1143     { "en123", "en", ustr_en123,  0, 123, 24, U_ZERO_ERROR },
1144     { "en123", "en", ustr_en123, 12,  23, 24, U_ZERO_ERROR },
1145     { "en123", "fr", ustr_en123, 16,   0, 16, U_PARSE_ERROR },
1146     { "fr123", "fr", ustr_fr123,  0, 123, 16, U_ZERO_ERROR },
1147     { "fr123", "fr", ustr_fr123,  5,  23, 16, U_ZERO_ERROR },
1148     { "fr123", "en", ustr_fr123,  0,   0,  0, U_PARSE_ERROR },
1149     { "ja123", "ja", ustr_ja123,  0, 123,  4, U_ZERO_ERROR },
1150     { "ja123", "ja", ustr_ja123,  1,  23,  4, U_ZERO_ERROR },
1151     { "ja123", "fr", ustr_ja123,  0,   0,  0, U_PARSE_ERROR },
1152     { NULL,    NULL, NULL,        0,   0,  0, 0 } /* terminator */
1153 };
1154 
TestSpelloutNumberParse()1155 static void TestSpelloutNumberParse()
1156 {
1157     const SpelloutParseTest * testPtr;
1158     for (testPtr = spelloutParseTests; testPtr->testname != NULL; ++testPtr) {
1159         UErrorCode status = U_ZERO_ERROR;
1160         int32_t value, position = testPtr->startPos;
1161         UNumberFormat *nf = unum_open(UNUM_SPELLOUT, NULL, 0, testPtr->locale, NULL, &status);
1162         if (U_FAILURE(status)) {
1163             log_err_status(status, "unum_open fails for UNUM_SPELLOUT with locale %s, status %s\n", testPtr->locale, myErrorName(status));
1164             continue;
1165         }
1166         value = unum_parse(nf, testPtr->source, -1, &position, &status);
1167         if ( value != testPtr->value || position != testPtr->endPos || status != testPtr->status ) {
1168             log_err("unum_parse SPELLOUT, locale %s, testname %s, startPos %d: for value / endPos / status, expected %d / %d / %s, got %d / %d / %s\n",
1169                     testPtr->locale, testPtr->testname, testPtr->startPos,
1170                     testPtr->value, testPtr->endPos, myErrorName(testPtr->status),
1171                     value, position, myErrorName(status) );
1172         }
1173         unum_close(nf);
1174     }
1175 }
1176 
TestSignificantDigits()1177 static void TestSignificantDigits()
1178 {
1179     UChar temp[128];
1180     int32_t resultlengthneeded;
1181     int32_t resultlength;
1182     UErrorCode status = U_ZERO_ERROR;
1183     UChar *result = NULL;
1184     UNumberFormat* fmt;
1185     double d = 123456.789;
1186 
1187     u_uastrcpy(temp, "###0.0#");
1188     fmt=unum_open(UNUM_IGNORE, temp, -1, NULL, NULL,&status);
1189     if (U_FAILURE(status)) {
1190         log_data_err("got unexpected error for unum_open: '%s'\n", u_errorName(status));
1191         return;
1192     }
1193     unum_setAttribute(fmt, UNUM_SIGNIFICANT_DIGITS_USED, TRUE);
1194     unum_setAttribute(fmt, UNUM_MAX_SIGNIFICANT_DIGITS, 6);
1195 
1196     u_uastrcpy(temp, "123457");
1197     resultlength=0;
1198     resultlengthneeded=unum_formatDouble(fmt, d, NULL, resultlength, NULL, &status);
1199     if(status==U_BUFFER_OVERFLOW_ERROR)
1200     {
1201         status=U_ZERO_ERROR;
1202         resultlength=resultlengthneeded+1;
1203         result=(UChar*)malloc(sizeof(UChar) * resultlength);
1204         unum_formatDouble(fmt, d, result, resultlength, NULL, &status);
1205     }
1206     if(U_FAILURE(status))
1207     {
1208         log_err("Error in formatting using unum_formatDouble(.....): %s\n", myErrorName(status));
1209         return;
1210     }
1211     if(u_strcmp(result, temp)==0)
1212         log_verbose("Pass: Number Formatting using unum_formatDouble() Successful\n");
1213     else
1214         log_err("FAIL: Error in number formatting using unum_formatDouble()\n");
1215     free(result);
1216     unum_close(fmt);
1217 }
1218 
TestSigDigRounding()1219 static void TestSigDigRounding()
1220 {
1221     UErrorCode status = U_ZERO_ERROR;
1222     UChar expected[128];
1223     UChar result[128];
1224     char  temp1[128];
1225     char  temp2[128];
1226     UNumberFormat* fmt;
1227     double d = 123.4;
1228 
1229     fmt=unum_open(UNUM_DECIMAL, NULL, 0, NULL /* "en_US"*/, NULL, &status);
1230     if (U_FAILURE(status)) {
1231         log_data_err("got unexpected error for unum_open: '%s'\n", u_errorName(status));
1232         return;
1233     }
1234     unum_setAttribute(fmt, UNUM_LENIENT_PARSE, FALSE);
1235     unum_setAttribute(fmt, UNUM_SIGNIFICANT_DIGITS_USED, TRUE);
1236     unum_setAttribute(fmt, UNUM_MAX_SIGNIFICANT_DIGITS, 2);
1237     /* unum_setAttribute(fmt, UNUM_MAX_FRACTION_DIGITS, 0); */
1238 
1239     unum_setAttribute(fmt, UNUM_ROUNDING_MODE, UNUM_ROUND_UP);
1240     unum_setDoubleAttribute(fmt, UNUM_ROUNDING_INCREMENT, 20.0);
1241 
1242     (void)unum_formatDouble(fmt, d, result, sizeof(result) / sizeof(result[0]), NULL, &status);
1243     if(U_FAILURE(status))
1244     {
1245         log_err("Error in formatting using unum_formatDouble(.....): %s\n", myErrorName(status));
1246         return;
1247     }
1248 
1249     u_uastrcpy(expected, "140");
1250     if(u_strcmp(result, expected)!=0)
1251         log_err("FAIL: Error in unum_formatDouble result %s instead of %s\n", u_austrcpy(temp1, result), u_austrcpy(temp2, expected) );
1252 
1253     unum_close(fmt);
1254 }
1255 
TestNumberFormatPadding()1256 static void TestNumberFormatPadding()
1257 {
1258     UChar *result=NULL;
1259     UChar temp1[512];
1260 
1261     UErrorCode status=U_ZERO_ERROR;
1262     int32_t resultlength;
1263     int32_t resultlengthneeded;
1264     UNumberFormat *pattern;
1265     double d1;
1266     double d = -10456.37;
1267     UFieldPosition pos1;
1268     int32_t parsepos;
1269 
1270     /* create a number format using unum_openPattern(....)*/
1271     log_verbose("\nTesting unum_openPattern() with padding\n");
1272     u_uastrcpy(temp1, "*#,##0.0#*;(#,##0.0#)");
1273     status=U_ZERO_ERROR;
1274     pattern=unum_open(UNUM_IGNORE,temp1, u_strlen(temp1), NULL, NULL,&status);
1275     if(U_SUCCESS(status))
1276     {
1277         log_err("error in unum_openPattern(%s): %s\n", temp1, myErrorName(status) );
1278     }
1279     else
1280     {
1281         unum_close(pattern);
1282     }
1283 
1284 /*    u_uastrcpy(temp1, "*x#,###,###,##0.0#;(*x#,###,###,##0.0#)"); */
1285     u_uastrcpy(temp1, "*x#,###,###,##0.0#;*x(###,###,##0.0#)");
1286     status=U_ZERO_ERROR;
1287     pattern=unum_open(UNUM_IGNORE,temp1, u_strlen(temp1), "en_US",NULL, &status);
1288     if(U_FAILURE(status))
1289     {
1290         log_err_status(status, "error in padding unum_openPattern(%s): %s\n", temp1, myErrorName(status) );;
1291     }
1292     else {
1293         log_verbose("Pass: padding unum_openPattern() works fine\n");
1294 
1295         /*test for unum_toPattern()*/
1296         log_verbose("\nTesting padding unum_toPattern()\n");
1297         resultlength=0;
1298         resultlengthneeded=unum_toPattern(pattern, FALSE, NULL, resultlength, &status);
1299         if(status==U_BUFFER_OVERFLOW_ERROR)
1300         {
1301             status=U_ZERO_ERROR;
1302             resultlength=resultlengthneeded+1;
1303             result=(UChar*)malloc(sizeof(UChar) * resultlength);
1304             unum_toPattern(pattern, FALSE, result, resultlength, &status);
1305         }
1306         if(U_FAILURE(status))
1307         {
1308             log_err("error in extracting the padding pattern from UNumberFormat: %s\n", myErrorName(status));
1309         }
1310         else
1311         {
1312             if(u_strcmp(result, temp1)!=0)
1313                 log_err("FAIL: Error in extracting the padding pattern using unum_toPattern()\n");
1314             else
1315                 log_verbose("Pass: extracted the padding pattern correctly using unum_toPattern()\n");
1316 free(result);
1317         }
1318 /*        u_uastrcpy(temp1, "(xxxxxxx10,456.37)"); */
1319         u_uastrcpy(temp1, "xxxxx(10,456.37)");
1320         resultlength=0;
1321         pos1.field = UNUM_FRACTION_FIELD;
1322         resultlengthneeded=unum_formatDouble(pattern, d, NULL, resultlength, &pos1, &status);
1323         if(status==U_BUFFER_OVERFLOW_ERROR)
1324         {
1325             status=U_ZERO_ERROR;
1326             resultlength=resultlengthneeded+1;
1327             result=(UChar*)malloc(sizeof(UChar) * resultlength);
1328             unum_formatDouble(pattern, d, result, resultlength, NULL, &status);
1329         }
1330         if(U_FAILURE(status))
1331         {
1332             log_err("Error in formatting using unum_formatDouble(.....) with padding : %s\n", myErrorName(status));
1333         }
1334         else
1335         {
1336             if(u_strcmp(result, temp1)==0)
1337                 log_verbose("Pass: Number Formatting using unum_formatDouble() padding Successful\n");
1338             else
1339                 log_data_err("FAIL: Error in number formatting using unum_formatDouble() with padding\n");
1340             if(pos1.beginIndex == 13 && pos1.endIndex == 15)
1341                 log_verbose("Pass: Complete number formatting using unum_formatDouble() successful\n");
1342             else
1343                 log_err("Fail: Error in complete number Formatting using unum_formatDouble()\nGot: b=%d end=%d\nExpected: b=13 end=15\n",
1344                         pos1.beginIndex, pos1.endIndex);
1345 
1346 
1347             /* Testing unum_parse() and unum_parseDouble() */
1348             log_verbose("\nTesting padding unum_parseDouble()\n");
1349             parsepos=0;
1350             d1=unum_parseDouble(pattern, result, u_strlen(result), &parsepos, &status);
1351             if(U_FAILURE(status))
1352             {
1353                 log_err("padding parse failed. The error is : %s\n", myErrorName(status));
1354             }
1355 
1356             if(d1!=d)
1357                 log_err("Fail: Error in padding parsing\n");
1358             else
1359                 log_verbose("Pass: padding parsing successful\n");
1360 free(result);
1361         }
1362     }
1363 
1364     unum_close(pattern);
1365 }
1366 
1367 static UBool
withinErr(double a,double b,double err)1368 withinErr(double a, double b, double err) {
1369     return uprv_fabs(a - b) < uprv_fabs(a * err);
1370 }
1371 
TestInt64Format()1372 static void TestInt64Format() {
1373     UChar temp1[512];
1374     UChar result[512];
1375     UNumberFormat *fmt;
1376     UErrorCode status = U_ZERO_ERROR;
1377     const double doubleInt64Max = (double)U_INT64_MAX;
1378     const double doubleInt64Min = (double)U_INT64_MIN;
1379     const double doubleBig = 10.0 * (double)U_INT64_MAX;
1380     int32_t val32;
1381     int64_t val64;
1382     double  valDouble;
1383     int32_t parsepos;
1384 
1385     /* create a number format using unum_openPattern(....) */
1386     log_verbose("\nTesting Int64Format\n");
1387     u_uastrcpy(temp1, "#.#E0");
1388     fmt = unum_open(UNUM_IGNORE, temp1, u_strlen(temp1), NULL, NULL, &status);
1389     if(U_FAILURE(status)) {
1390         log_data_err("error in unum_openPattern() - %s\n", myErrorName(status));
1391     } else {
1392         unum_setAttribute(fmt, UNUM_MAX_FRACTION_DIGITS, 20);
1393         unum_formatInt64(fmt, U_INT64_MAX, result, 512, NULL, &status);
1394         if (U_FAILURE(status)) {
1395             log_err("error in unum_format(): %s\n", myErrorName(status));
1396         } else {
1397             log_verbose("format int64max: '%s'\n", result);
1398             parsepos = 0;
1399             val32 = unum_parse(fmt, result, u_strlen(result), &parsepos, &status);
1400             if (status != U_INVALID_FORMAT_ERROR) {
1401                 log_err("parse didn't report error: %s\n", myErrorName(status));
1402             } else if (val32 != INT32_MAX) {
1403                 log_err("parse didn't pin return value, got: %d\n", val32);
1404             }
1405 
1406             status = U_ZERO_ERROR;
1407             parsepos = 0;
1408             val64 = unum_parseInt64(fmt, result, u_strlen(result), &parsepos, &status);
1409             if (U_FAILURE(status)) {
1410                 log_err("parseInt64 returned error: %s\n", myErrorName(status));
1411             } else if (val64 != U_INT64_MAX) {
1412                 log_err("parseInt64 returned incorrect value, got: %ld\n", val64);
1413             }
1414 
1415             status = U_ZERO_ERROR;
1416             parsepos = 0;
1417             valDouble = unum_parseDouble(fmt, result, u_strlen(result), &parsepos, &status);
1418             if (U_FAILURE(status)) {
1419                 log_err("parseDouble returned error: %s\n", myErrorName(status));
1420             } else if (valDouble != doubleInt64Max) {
1421                 log_err("parseDouble returned incorrect value, got: %g\n", valDouble);
1422             }
1423         }
1424 
1425         unum_formatInt64(fmt, U_INT64_MIN, result, 512, NULL, &status);
1426         if (U_FAILURE(status)) {
1427             log_err("error in unum_format(): %s\n", myErrorName(status));
1428         } else {
1429             log_verbose("format int64min: '%s'\n", result);
1430             parsepos = 0;
1431             val32 = unum_parse(fmt, result, u_strlen(result), &parsepos, &status);
1432             if (status != U_INVALID_FORMAT_ERROR) {
1433                 log_err("parse didn't report error: %s\n", myErrorName(status));
1434             } else if (val32 != INT32_MIN) {
1435                 log_err("parse didn't pin return value, got: %d\n", val32);
1436             }
1437 
1438             status = U_ZERO_ERROR;
1439             parsepos = 0;
1440             val64 = unum_parseInt64(fmt, result, u_strlen(result), &parsepos, &status);
1441             if (U_FAILURE(status)) {
1442                 log_err("parseInt64 returned error: %s\n", myErrorName(status));
1443             } else if (val64 != U_INT64_MIN) {
1444                 log_err("parseInt64 returned incorrect value, got: %ld\n", val64);
1445             }
1446 
1447             status = U_ZERO_ERROR;
1448             parsepos = 0;
1449             valDouble = unum_parseDouble(fmt, result, u_strlen(result), &parsepos, &status);
1450             if (U_FAILURE(status)) {
1451                 log_err("parseDouble returned error: %s\n", myErrorName(status));
1452             } else if (valDouble != doubleInt64Min) {
1453                 log_err("parseDouble returned incorrect value, got: %g\n", valDouble);
1454             }
1455         }
1456 
1457         unum_formatDouble(fmt, doubleBig, result, 512, NULL, &status);
1458         if (U_FAILURE(status)) {
1459             log_err("error in unum_format(): %s\n", myErrorName(status));
1460         } else {
1461             log_verbose("format doubleBig: '%s'\n", result);
1462             parsepos = 0;
1463             val32 = unum_parse(fmt, result, u_strlen(result), &parsepos, &status);
1464             if (status != U_INVALID_FORMAT_ERROR) {
1465                 log_err("parse didn't report error: %s\n", myErrorName(status));
1466             } else if (val32 != INT32_MAX) {
1467                 log_err("parse didn't pin return value, got: %d\n", val32);
1468             }
1469 
1470             status = U_ZERO_ERROR;
1471             parsepos = 0;
1472             val64 = unum_parseInt64(fmt, result, u_strlen(result), &parsepos, &status);
1473             if (status != U_INVALID_FORMAT_ERROR) {
1474                 log_err("parseInt64 didn't report error error: %s\n", myErrorName(status));
1475             } else if (val64 != U_INT64_MAX) {
1476                 log_err("parseInt64 returned incorrect value, got: %ld\n", val64);
1477             }
1478 
1479             status = U_ZERO_ERROR;
1480             parsepos = 0;
1481             valDouble = unum_parseDouble(fmt, result, u_strlen(result), &parsepos, &status);
1482             if (U_FAILURE(status)) {
1483                 log_err("parseDouble returned error: %s\n", myErrorName(status));
1484             } else if (!withinErr(valDouble, doubleBig, 1e-15)) {
1485                 log_err("parseDouble returned incorrect value, got: %g\n", valDouble);
1486             }
1487         }
1488 
1489         u_uastrcpy(result, "5.06e-27");
1490         parsepos = 0;
1491         valDouble = unum_parseDouble(fmt, result, u_strlen(result), &parsepos, &status);
1492         if (U_FAILURE(status)) {
1493             log_err("parseDouble() returned error: %s\n", myErrorName(status));
1494         } else if (!withinErr(valDouble, 5.06e-27, 1e-15)) {
1495             log_err("parseDouble() returned incorrect value, got: %g\n", valDouble);
1496         }
1497     }
1498     unum_close(fmt);
1499 }
1500 
1501 
test_fmt(UNumberFormat * fmt,UBool isDecimal)1502 static void test_fmt(UNumberFormat* fmt, UBool isDecimal) {
1503     char temp[512];
1504     UChar buffer[512];
1505     int32_t BUFSIZE = sizeof(buffer)/sizeof(buffer[0]);
1506     double vals[] = {
1507         -.2, 0, .2, 5.5, 15.2, 250, 123456789
1508     };
1509     int i;
1510 
1511     for (i = 0; i < sizeof(vals)/sizeof(vals[0]); ++i) {
1512         UErrorCode status = U_ZERO_ERROR;
1513         unum_formatDouble(fmt, vals[i], buffer, BUFSIZE, NULL, &status);
1514         if (U_FAILURE(status)) {
1515             log_err("failed to format: %g, returned %s\n", vals[i], u_errorName(status));
1516         } else {
1517             u_austrcpy(temp, buffer);
1518             log_verbose("formatting %g returned '%s'\n", vals[i], temp);
1519         }
1520     }
1521 
1522     /* check APIs now */
1523     {
1524         UErrorCode status = U_ZERO_ERROR;
1525         UParseError perr;
1526         u_uastrcpy(buffer, "#,##0.0#");
1527         unum_applyPattern(fmt, FALSE, buffer, -1, &perr, &status);
1528         if (isDecimal ? U_FAILURE(status) : (status != U_UNSUPPORTED_ERROR)) {
1529             log_err("got unexpected error for applyPattern: '%s'\n", u_errorName(status));
1530         }
1531     }
1532 
1533     {
1534         int isLenient = unum_getAttribute(fmt, UNUM_LENIENT_PARSE);
1535         log_verbose("lenient: 0x%x\n", isLenient);
1536         if (isLenient != FALSE) {
1537             log_err("didn't expect lenient value: %d\n", isLenient);
1538         }
1539 
1540         unum_setAttribute(fmt, UNUM_LENIENT_PARSE, TRUE);
1541         isLenient = unum_getAttribute(fmt, UNUM_LENIENT_PARSE);
1542         if (isLenient != TRUE) {
1543             log_err("didn't expect lenient value after set: %d\n", isLenient);
1544         }
1545     }
1546 
1547     {
1548         double val2;
1549         double val = unum_getDoubleAttribute(fmt, UNUM_LENIENT_PARSE);
1550         if (val != -1) {
1551             log_err("didn't expect double attribute\n");
1552         }
1553         val = unum_getDoubleAttribute(fmt, UNUM_ROUNDING_INCREMENT);
1554         if ((val == -1) == isDecimal) {
1555             log_err("didn't expect -1 rounding increment\n");
1556         }
1557         unum_setDoubleAttribute(fmt, UNUM_ROUNDING_INCREMENT, val+.5);
1558         val2 = unum_getDoubleAttribute(fmt, UNUM_ROUNDING_INCREMENT);
1559         if (isDecimal && (val2 - val != .5)) {
1560             log_err("set rounding increment had no effect on decimal format");
1561         }
1562     }
1563 
1564     {
1565         UErrorCode status = U_ZERO_ERROR;
1566         int len = unum_getTextAttribute(fmt, UNUM_DEFAULT_RULESET, buffer, BUFSIZE, &status);
1567         if (isDecimal ? (status != U_UNSUPPORTED_ERROR) : U_FAILURE(status)) {
1568             log_err("got unexpected error for get default ruleset: '%s'\n", u_errorName(status));
1569         }
1570         if (U_SUCCESS(status)) {
1571             u_austrcpy(temp, buffer);
1572             log_verbose("default ruleset: '%s'\n", temp);
1573         }
1574 
1575         status = U_ZERO_ERROR;
1576         len = unum_getTextAttribute(fmt, UNUM_PUBLIC_RULESETS, buffer, BUFSIZE, &status);
1577         if (isDecimal ? (status != U_UNSUPPORTED_ERROR) : U_FAILURE(status)) {
1578             log_err("got unexpected error for get public rulesets: '%s'\n", u_errorName(status));
1579         }
1580         if (U_SUCCESS(status)) {
1581             u_austrcpy(temp, buffer);
1582             log_verbose("public rulesets: '%s'\n", temp);
1583 
1584             /* set the default ruleset to the first one found, and retry */
1585 
1586             if (len > 0) {
1587                 for (i = 0; i < len && temp[i] != ';'; ++i){};
1588                 if (i < len) {
1589                     buffer[i] = 0;
1590                     unum_setTextAttribute(fmt, UNUM_DEFAULT_RULESET, buffer, -1, &status);
1591                     if (U_FAILURE(status)) {
1592                         log_err("unexpected error setting default ruleset: '%s'\n", u_errorName(status));
1593                     } else {
1594                         int len2 = unum_getTextAttribute(fmt, UNUM_DEFAULT_RULESET, buffer, BUFSIZE, &status);
1595                         if (U_FAILURE(status)) {
1596                             log_err("could not fetch default ruleset: '%s'\n", u_errorName(status));
1597                         } else if (len2 != i) {
1598                             u_austrcpy(temp, buffer);
1599                             log_err("unexpected ruleset len: %d ex: %d val: %s\n", len2, i, temp);
1600                         } else {
1601                             for (i = 0; i < sizeof(vals)/sizeof(vals[0]); ++i) {
1602                                 status = U_ZERO_ERROR;
1603                                 unum_formatDouble(fmt, vals[i], buffer, BUFSIZE, NULL, &status);
1604                                 if (U_FAILURE(status)) {
1605                                     log_err("failed to format: %g, returned %s\n", vals[i], u_errorName(status));
1606                                 } else {
1607                                     u_austrcpy(temp, buffer);
1608                                     log_verbose("formatting %g returned '%s'\n", vals[i], temp);
1609                                 }
1610                             }
1611                         }
1612                     }
1613                 }
1614             }
1615         }
1616     }
1617 
1618     {
1619         UErrorCode status = U_ZERO_ERROR;
1620         unum_toPattern(fmt, FALSE, buffer, BUFSIZE, &status);
1621         if (U_SUCCESS(status)) {
1622             u_austrcpy(temp, buffer);
1623             log_verbose("pattern: '%s'\n", temp);
1624         } else if (status != U_BUFFER_OVERFLOW_ERROR) {
1625             log_err("toPattern failed unexpectedly: %s\n", u_errorName(status));
1626         } else {
1627             log_verbose("pattern too long to display\n");
1628         }
1629     }
1630 
1631     {
1632         UErrorCode status = U_ZERO_ERROR;
1633         int len = unum_getSymbol(fmt, UNUM_CURRENCY_SYMBOL, buffer, BUFSIZE, &status);
1634         if (isDecimal ? U_FAILURE(status) : (status != U_UNSUPPORTED_ERROR)) {
1635             log_err("unexpected error getting symbol: '%s'\n", u_errorName(status));
1636         }
1637 
1638         unum_setSymbol(fmt, UNUM_CURRENCY_SYMBOL, buffer, len, &status);
1639         if (isDecimal ? U_FAILURE(status) : (status != U_UNSUPPORTED_ERROR)) {
1640             log_err("unexpected error setting symbol: '%s'\n", u_errorName(status));
1641         }
1642     }
1643 }
1644 
TestNonExistentCurrency()1645 static void TestNonExistentCurrency() {
1646     UNumberFormat *format;
1647     UErrorCode status = U_ZERO_ERROR;
1648     UChar currencySymbol[8];
1649     static const UChar QQQ[] = {0x51, 0x51, 0x51, 0};
1650 
1651     /* Get a non-existent currency and make sure it returns the correct currency code. */
1652     format = unum_open(UNUM_CURRENCY, NULL, 0, "th_TH@currency=QQQ", NULL, &status);
1653     if (format == NULL || U_FAILURE(status)) {
1654         log_data_err("unum_open did not return expected result for non-existent requested currency: '%s' (Are you missing data?)\n", u_errorName(status));
1655     }
1656     else {
1657         unum_getSymbol(format,
1658                 UNUM_CURRENCY_SYMBOL,
1659                 currencySymbol,
1660                 sizeof(currencySymbol)/sizeof(currencySymbol[0]),
1661                 &status);
1662         if (u_strcmp(currencySymbol, QQQ) != 0) {
1663             log_err("unum_open set the currency to QQQ\n");
1664         }
1665     }
1666     unum_close(format);
1667 }
1668 
TestRBNFFormat()1669 static void TestRBNFFormat() {
1670     UErrorCode status;
1671     UParseError perr;
1672     UChar pat[1024];
1673     UChar tempUChars[512];
1674     UNumberFormat *formats[5];
1675     int COUNT = sizeof(formats)/sizeof(formats[0]);
1676     int i;
1677 
1678     for (i = 0; i < COUNT; ++i) {
1679         formats[i] = 0;
1680     }
1681 
1682     /* instantiation */
1683     status = U_ZERO_ERROR;
1684     u_uastrcpy(pat, "#,##0.0#;(#,##0.0#)");
1685     formats[0] = unum_open(UNUM_PATTERN_DECIMAL, pat, -1, "en_US", &perr, &status);
1686     if (U_FAILURE(status)) {
1687         log_err_status(status, "unable to open decimal pattern -> %s\n", u_errorName(status));
1688         return;
1689     }
1690 
1691     status = U_ZERO_ERROR;
1692     formats[1] = unum_open(UNUM_SPELLOUT, NULL, 0, "en_US", &perr, &status);
1693     if (U_FAILURE(status)) {
1694         log_err_status(status, "unable to open spellout -> %s\n", u_errorName(status));
1695         return;
1696     }
1697 
1698     status = U_ZERO_ERROR;
1699     formats[2] = unum_open(UNUM_ORDINAL, NULL, 0, "en_US", &perr, &status);
1700     if (U_FAILURE(status)) {
1701         log_err_status(status, "unable to open ordinal -> %s\n", u_errorName(status));
1702         return;
1703     }
1704 
1705     status = U_ZERO_ERROR;
1706     formats[3] = unum_open(UNUM_DURATION, NULL, 0, "en_US", &perr, &status);
1707     if (U_FAILURE(status)) {
1708         log_err_status(status, "unable to open duration %s\n", u_errorName(status));
1709         return;
1710     }
1711 
1712     status = U_ZERO_ERROR;
1713     u_uastrcpy(pat,
1714         "%standard:\n"
1715         "-x: minus >>;\n"
1716         "x.x: << point >>;\n"
1717         "zero; one; two; three; four; five; six; seven; eight; nine;\n"
1718         "ten; eleven; twelve; thirteen; fourteen; fifteen; sixteen;\n"
1719         "seventeen; eighteen; nineteen;\n"
1720         "20: twenty[->>];\n"
1721         "30: thirty[->>];\n"
1722         "40: forty[->>];\n"
1723         "50: fifty[->>];\n"
1724         "60: sixty[->>];\n"
1725         "70: seventy[->>];\n"
1726         "80: eighty[->>];\n"
1727         "90: ninety[->>];\n"
1728         "100: =#,##0=;\n");
1729     u_uastrcpy(tempUChars,
1730         "%simple:\n"
1731         "=%standard=;\n"
1732         "20: twenty[ and change];\n"
1733         "30: thirty[ and change];\n"
1734         "40: forty[ and change];\n"
1735         "50: fifty[ and change];\n"
1736         "60: sixty[ and change];\n"
1737         "70: seventy[ and change];\n"
1738         "80: eighty[ and change];\n"
1739         "90: ninety[ and change];\n"
1740         "100: =#,##0=;\n"
1741         "%bogus:\n"
1742         "0.x: tiny;\n"
1743         "x.x: << point something;\n"
1744         "=%standard=;\n"
1745         "20: some reasonable number;\n"
1746         "100: some substantial number;\n"
1747         "100,000,000: some huge number;\n");
1748     /* This is to get around some compiler warnings about char * string length. */
1749     u_strcat(pat, tempUChars);
1750     formats[4] = unum_open(UNUM_PATTERN_RULEBASED, pat, -1, "en_US", &perr, &status);
1751     if (U_FAILURE(status)) {
1752         log_err_status(status, "unable to open rulebased pattern -> %s\n", u_errorName(status));
1753     }
1754     if (U_FAILURE(status)) {
1755         log_err_status(status, "Something failed with %s\n", u_errorName(status));
1756         return;
1757     }
1758 
1759     for (i = 0; i < COUNT; ++i) {
1760         log_verbose("\n\ntesting format %d\n", i);
1761         test_fmt(formats[i], (UBool)(i == 0));
1762     }
1763 
1764     #define FORMAT_BUF_CAPACITY 64
1765     {
1766         UChar fmtbuf[FORMAT_BUF_CAPACITY];
1767         int32_t len;
1768         double nanvalue = uprv_getNaN();
1769         status = U_ZERO_ERROR;
1770         len = unum_formatDouble(formats[1], nanvalue, fmtbuf, FORMAT_BUF_CAPACITY, NULL, &status);
1771         if (U_FAILURE(status)) {
1772             log_err_status(status, "unum_formatDouble NAN failed with %s\n", u_errorName(status));
1773         } else {
1774             UChar nansym[] = { 0x4E, 0x61, 0x4E, 0 }; /* NaN */
1775             if ( len != 3 || u_strcmp(fmtbuf, nansym) != 0 ) {
1776                 log_err("unum_formatDouble NAN produced wrong answer for en_US\n");
1777             }
1778         }
1779     }
1780 
1781     for (i = 0; i < COUNT; ++i) {
1782         unum_close(formats[i]);
1783     }
1784 }
1785 
TestCurrencyRegression(void)1786 static void TestCurrencyRegression(void) {
1787 /*
1788  I've found a case where unum_parseDoubleCurrency is not doing what I
1789 expect.  The value I pass in is $1234567890q123460000.00 and this
1790 returns with a status of zero error & a parse pos of 22 (I would
1791 expect a parse error at position 11).
1792 
1793 I stepped into DecimalFormat::subparse() and it looks like it parses
1794 the first 10 digits and then stops parsing at the q but doesn't set an
1795 error. Then later in DecimalFormat::parse() the value gets crammed
1796 into a long (which greatly truncates the value).
1797 
1798 This is very problematic for me 'cause I try to remove chars that are
1799 invalid but this allows my users to enter bad chars and truncates
1800 their data!
1801 */
1802 
1803     UChar buf[1024];
1804     UChar currency[8];
1805     char acurrency[16];
1806     double d;
1807     UNumberFormat *cur;
1808     int32_t pos;
1809     UErrorCode status  = U_ZERO_ERROR;
1810     const int32_t expected = 11;
1811 
1812     currency[0]=0;
1813     u_uastrcpy(buf, "$1234567890q643210000.00");
1814     cur = unum_open(UNUM_CURRENCY, NULL,0,"en_US", NULL, &status);
1815 
1816     if(U_FAILURE(status)) {
1817         log_data_err("unum_open failed: %s (Are you missing data?)\n", u_errorName(status));
1818         return;
1819     }
1820 
1821     status = U_ZERO_ERROR; /* so we can test it later. */
1822     pos = 0;
1823 
1824     d = unum_parseDoubleCurrency(cur,
1825                          buf,
1826                          -1,
1827                          &pos, /* 0 = start */
1828                          currency,
1829                          &status);
1830 
1831     u_austrcpy(acurrency, currency);
1832 
1833     if(U_FAILURE(status) || (pos != expected)) {
1834         log_err("unum_parseDoubleCurrency should have failed with pos %d, but gave: value %.9f, err %s, pos=%d, currency [%s]\n",
1835             expected, d, u_errorName(status), pos, acurrency);
1836     } else {
1837         log_verbose("unum_parseDoubleCurrency failed, value %.9f err %s, pos %d, currency [%s]\n", d, u_errorName(status), pos, acurrency);
1838     }
1839 
1840     unum_close(cur);
1841 }
1842 
TestTextAttributeCrash(void)1843 static void TestTextAttributeCrash(void) {
1844     UChar ubuffer[64] = {0x0049,0x004E,0x0052,0};
1845     static const UChar expectedNeg[] = {0x0049,0x004E,0x0052,0x0031,0x0032,0x0033,0x0034,0x002E,0x0035,0};
1846     static const UChar expectedPos[] = {0x0031,0x0032,0x0033,0x0034,0x002E,0x0035,0};
1847     int32_t used;
1848     UErrorCode status = U_ZERO_ERROR;
1849     UNumberFormat *nf = unum_open(UNUM_CURRENCY, NULL, 0, "en_US", NULL, &status);
1850     if (U_FAILURE(status)) {
1851         log_data_err("FAILED 1 -> %s (Are you missing data?)\n", u_errorName(status));
1852         return;
1853     }
1854     unum_setTextAttribute(nf, UNUM_CURRENCY_CODE, ubuffer, 3, &status);
1855     /*
1856      * the usual negative prefix and suffix seem to be '($' and ')' at this point
1857      * also crashes if UNUM_NEGATIVE_SUFFIX is substituted for UNUM_NEGATIVE_PREFIX here
1858      */
1859     used = unum_getTextAttribute(nf, UNUM_NEGATIVE_PREFIX, ubuffer, 64, &status);
1860     unum_setTextAttribute(nf, UNUM_NEGATIVE_PREFIX, ubuffer, used, &status);
1861     if (U_FAILURE(status)) {
1862         log_err("FAILED 2\n"); exit(1);
1863     }
1864     log_verbose("attempting to format...\n");
1865     used = unum_formatDouble(nf, -1234.5, ubuffer, 64, NULL, &status);
1866     if (U_FAILURE(status) || 64 < used) {
1867         log_err("Failed formatting %s\n", u_errorName(status));
1868         return;
1869     }
1870     if (u_strcmp(expectedNeg, ubuffer) == 0) {
1871         log_err("Didn't get expected negative result\n");
1872     }
1873     used = unum_formatDouble(nf, 1234.5, ubuffer, 64, NULL, &status);
1874     if (U_FAILURE(status) || 64 < used) {
1875         log_err("Failed formatting %s\n", u_errorName(status));
1876         return;
1877     }
1878     if (u_strcmp(expectedPos, ubuffer) == 0) {
1879         log_err("Didn't get expected positive result\n");
1880     }
1881     unum_close(nf);
1882 }
1883 
TestNBSPPatternRtNum(const char * testcase,int line,UNumberFormat * nf,double myNumber)1884 static void TestNBSPPatternRtNum(const char *testcase, int line, UNumberFormat *nf, double myNumber) {
1885     UErrorCode status = U_ZERO_ERROR;
1886     UChar myString[20];
1887     char tmpbuf[200];
1888     double aNumber = -1.0;
1889     unum_formatDouble(nf, myNumber, myString, 20, NULL, &status);
1890     log_verbose("%s:%d: formatted %.2f into %s\n", testcase, line, myNumber, u_austrcpy(tmpbuf, myString));
1891     if(U_FAILURE(status)) {
1892       log_err("%s:%d: failed format of %.2g with %s\n", testcase, line, myNumber, u_errorName(status));
1893         return;
1894     }
1895     aNumber = unum_parse(nf, myString, -1, NULL, &status);
1896     if(U_FAILURE(status)) {
1897       log_err("%s:%d: failed parse with %s\n", testcase, line, u_errorName(status));
1898         return;
1899     }
1900     if(uprv_fabs(aNumber-myNumber)>.001) {
1901       log_err("FAIL: %s:%d formatted %.2f, parsed into %.2f\n", testcase, line, myNumber, aNumber);
1902     } else {
1903       log_verbose("PASS: %s:%d formatted %.2f, parsed into %.2f\n", testcase, line, myNumber, aNumber);
1904     }
1905 }
1906 
TestNBSPPatternRT(const char * testcase,UNumberFormat * nf)1907 static void TestNBSPPatternRT(const char *testcase, UNumberFormat *nf) {
1908   TestNBSPPatternRtNum(testcase, __LINE__, nf, 12345.);
1909   TestNBSPPatternRtNum(testcase, __LINE__, nf, -12345.);
1910 }
1911 
TestNBSPInPattern(void)1912 static void TestNBSPInPattern(void) {
1913     UErrorCode status = U_ZERO_ERROR;
1914     UNumberFormat* nf = NULL;
1915     const char *testcase;
1916 
1917 
1918     testcase="ar_AE UNUM_CURRENCY";
1919     nf  = unum_open(UNUM_CURRENCY, NULL, -1, "ar_AE", NULL, &status);
1920     if(U_FAILURE(status) || nf == NULL) {
1921       log_data_err("%s:%d: %s: unum_open failed with %s (Are you missing data?)\n", __FILE__, __LINE__, testcase, u_errorName(status));
1922         return;
1923     }
1924     TestNBSPPatternRT(testcase, nf);
1925 
1926     /* if we don't have CLDR 1.6 data, bring out the problem anyways */
1927     {
1928 #define SPECIAL_PATTERN "\\u00A4\\u00A4'\\u062f.\\u0625.\\u200f\\u00a0'###0.00"
1929         UChar pat[200];
1930         testcase = "ar_AE special pattern: " SPECIAL_PATTERN;
1931         u_unescape(SPECIAL_PATTERN, pat, sizeof(pat)/sizeof(pat[0]));
1932         unum_applyPattern(nf, FALSE, pat, -1, NULL, &status);
1933         if(U_FAILURE(status)) {
1934             log_err("%s: unum_applyPattern failed with %s\n", testcase, u_errorName(status));
1935         } else {
1936             TestNBSPPatternRT(testcase, nf);
1937         }
1938 #undef SPECIAL_PATTERN
1939     }
1940     unum_close(nf); status = U_ZERO_ERROR;
1941 
1942     testcase="ar_AE UNUM_DECIMAL";
1943     nf  = unum_open(UNUM_DECIMAL, NULL, -1, "ar_AE", NULL, &status);
1944     if(U_FAILURE(status)) {
1945         log_err("%s: unum_open failed with %s\n", testcase, u_errorName(status));
1946     }
1947     TestNBSPPatternRT(testcase, nf);
1948     unum_close(nf); status = U_ZERO_ERROR;
1949 
1950     testcase="ar_AE UNUM_PERCENT";
1951     nf  = unum_open(UNUM_PERCENT, NULL, -1, "ar_AE", NULL, &status);
1952     if(U_FAILURE(status)) {
1953         log_err("%s: unum_open failed with %s\n", testcase, u_errorName(status));
1954     }
1955     TestNBSPPatternRT(testcase, nf);
1956     unum_close(nf); status = U_ZERO_ERROR;
1957 
1958 
1959 
1960 }
TestCloneWithRBNF(void)1961 static void TestCloneWithRBNF(void) {
1962     UChar pattern[1024];
1963     UChar pat2[512];
1964     UErrorCode status = U_ZERO_ERROR;
1965     UChar buffer[256];
1966     UChar buffer_cloned[256];
1967     char temp1[256];
1968     char temp2[256];
1969     UNumberFormat *pform_cloned;
1970     UNumberFormat *pform;
1971 
1972     u_uastrcpy(pattern,
1973         "%main:\n"
1974         "0.x: >%%millis-only>;\n"
1975         "x.0: <%%duration<;\n"
1976         "x.x: <%%durationwithmillis<>%%millis-added>;\n"
1977         "-x: ->>;%%millis-only:\n"
1978         "1000: 00:00.<%%millis<;\n"
1979         "%%millis-added:\n"
1980         "1000: .<%%millis<;\n"
1981         "%%millis:\n"
1982         "0: =000=;\n"
1983         "%%duration:\n"
1984         "0: =%%seconds-only=;\n"
1985         "60: =%%min-sec=;\n"
1986         "3600: =%%hr-min-sec=;\n"
1987         "86400/86400: <%%ddaayyss<[, >>];\n"
1988         "%%durationwithmillis:\n"
1989         "0: =%%seconds-only=;\n"
1990         "60: =%%min-sec=;\n"
1991         "3600: =%%hr-min-sec=;\n"
1992         "86400/86400: <%%ddaayyss<, >>;\n");
1993     u_uastrcpy(pat2,
1994         "%%seconds-only:\n"
1995         "0: 0:00:=00=;\n"
1996         "%%min-sec:\n"
1997         "0: :=00=;\n"
1998         "0/60: 0:<00<>>;\n"
1999         "%%hr-min-sec:\n"
2000         "0: :=00=;\n"
2001         "60/60: <00<>>;\n"
2002         "3600/60: <0<:>>>;\n"
2003         "%%ddaayyss:\n"
2004         "0 days;\n"
2005         "1 day;\n"
2006         "=0= days;");
2007 
2008     /* This is to get around some compiler warnings about char * string length. */
2009     u_strcat(pattern, pat2);
2010 
2011     pform = unum_open(UNUM_PATTERN_RULEBASED, pattern, -1, "en_US", NULL, &status);
2012     unum_formatDouble(pform, 3600, buffer, 256, NULL, &status);
2013 
2014     pform_cloned = unum_clone(pform,&status);
2015     unum_formatDouble(pform_cloned, 3600, buffer_cloned, 256, NULL, &status);
2016 
2017     unum_close(pform);
2018     unum_close(pform_cloned);
2019 
2020     if (u_strcmp(buffer,buffer_cloned)) {
2021         log_data_err("Result from cloned formatter not identical to the original. Original: %s Cloned: %s - (Are you missing data?)",u_austrcpy(temp1, buffer),u_austrcpy(temp2,buffer_cloned));
2022     }
2023 }
2024 
2025 
TestNoExponent(void)2026 static void TestNoExponent(void) {
2027     UErrorCode status = U_ZERO_ERROR;
2028     UChar str[100];
2029     const char *cstr;
2030     UNumberFormat *fmt;
2031     int32_t pos;
2032     int32_t expect = 0;
2033     int32_t num;
2034 
2035     fmt = unum_open(UNUM_DECIMAL, NULL, -1, "en_US", NULL, &status);
2036 
2037     if(U_FAILURE(status) || fmt == NULL) {
2038         log_data_err("%s:%d: unum_open failed with %s (Are you missing data?)\n", __FILE__, __LINE__, u_errorName(status));
2039         return;
2040     }
2041 
2042     cstr = "10E6";
2043     u_uastrcpy(str, cstr);
2044     expect = 10000000;
2045     pos = 0;
2046     num = unum_parse(fmt, str, -1, &pos, &status);
2047     ASSERT_TRUE(pos==4);
2048     if(U_FAILURE(status)) {
2049         log_data_err("%s:%d: unum_parse failed with %s for %s (Are you missing data?)\n", __FILE__, __LINE__, u_errorName(status), cstr);
2050     } else if(expect!=num) {
2051         log_data_err("%s:%d: unum_parse failed, got %d expected %d for '%s'(Are you missing data?)\n", __FILE__, __LINE__, num, expect, cstr);
2052     } else {
2053         log_verbose("%s:%d: unum_parse returned %d for '%s'\n", __FILE__, __LINE__, num, cstr);
2054     }
2055 
2056     ASSERT_TRUE(unum_getAttribute(fmt, UNUM_PARSE_NO_EXPONENT)==0);
2057 
2058     unum_setAttribute(fmt, UNUM_PARSE_NO_EXPONENT, 1); /* no error code */
2059     log_verbose("set UNUM_PARSE_NO_EXPONENT\n");
2060 
2061     ASSERT_TRUE(unum_getAttribute(fmt, UNUM_PARSE_NO_EXPONENT)==1);
2062 
2063     pos = 0;
2064     expect=10;
2065     num = unum_parse(fmt, str, -1, &pos, &status);
2066     if(num==10000000) {
2067         log_err("%s:%d: FAIL: unum_parse should have returned 10, not 10000000 on %s after UNUM_PARSE_NO_EXPONENT\n", __FILE__, __LINE__, cstr);
2068     } else if(num==expect) {
2069         log_verbose("%s:%d: unum_parse gave %d for %s - good.\n", __FILE__, __LINE__, num, cstr);
2070     }
2071     ASSERT_TRUE(pos==2);
2072 
2073     status = U_ZERO_ERROR;
2074 
2075     unum_close(fmt);
2076 
2077     /* ok, now try scientific */
2078     fmt = unum_open(UNUM_SCIENTIFIC, NULL, -1, "en_US", NULL, &status);
2079     assertSuccess("unum_open(UNUM_SCIENTIFIC, ...)", &status);
2080 
2081     ASSERT_TRUE(unum_getAttribute(fmt, UNUM_PARSE_NO_EXPONENT)==0);
2082 
2083     cstr = "10E6";
2084     u_uastrcpy(str, cstr);
2085     expect = 10000000;
2086     pos = 0;
2087     num = unum_parse(fmt, str, -1, &pos, &status);
2088     ASSERT_TRUE(pos==4);
2089     if(U_FAILURE(status)) {
2090         log_data_err("%s:%d: unum_parse failed with %s for %s (Are you missing data?)\n", __FILE__, __LINE__, u_errorName(status), cstr);
2091     } else if(expect!=num) {
2092         log_data_err("%s:%d: unum_parse failed, got %d expected %d for '%s'(Are you missing data?)\n", __FILE__, __LINE__, num, expect, cstr);
2093     } else {
2094         log_verbose("%s:%d: unum_parse returned %d for '%s'\n", __FILE__, __LINE__, num, cstr);
2095     }
2096 
2097     unum_setAttribute(fmt, UNUM_PARSE_NO_EXPONENT, 1); /* no error code */
2098     log_verbose("set UNUM_PARSE_NO_EXPONENT\n");
2099 
2100     ASSERT_TRUE(unum_getAttribute(fmt, UNUM_PARSE_NO_EXPONENT)==1);
2101 
2102 
2103     cstr = "10E6";
2104     u_uastrcpy(str, cstr);
2105     expect = 10000000;
2106     pos = 0;
2107     num = unum_parse(fmt, str, -1, &pos, &status);
2108     ASSERT_TRUE(pos==4);
2109     if(U_FAILURE(status)) {
2110         log_data_err("%s:%d: unum_parse failed with %s for %s (Are you missing data?)\n", __FILE__, __LINE__, u_errorName(status), cstr);
2111     } else if(expect!=num) {
2112         log_data_err("%s:%d: unum_parse failed, got %d expected %d for '%s'(Are you missing data?)\n", __FILE__, __LINE__, num, expect, cstr);
2113     } else {
2114         log_verbose("%s:%d: unum_parse returned %d for '%s'\n", __FILE__, __LINE__, num, cstr);
2115     }
2116 
2117     unum_close(fmt);
2118 }
2119 
TestMaxInt(void)2120 static void TestMaxInt(void) {
2121     UErrorCode status = U_ZERO_ERROR;
2122     UChar pattern_hash[] = { 0x23, 0x00 }; /* "#" */
2123     UChar result1[1024] = { 0 }, result2[1024] = { 0 };
2124     int32_t len1, len2;
2125     UChar expect[] = { 0x0039, 0x0037, 0 };
2126     UNumberFormat *fmt = unum_open(
2127                   UNUM_PATTERN_DECIMAL,      /* style         */
2128                   &pattern_hash[0],          /* pattern       */
2129                   u_strlen(pattern_hash),    /* patternLength */
2130                   0,
2131                   0,                         /* parseErr      */
2132                   &status);
2133     if(U_FAILURE(status) || fmt == NULL) {
2134         log_data_err("%s:%d: %s: unum_open failed with %s (Are you missing data?)\n", __FILE__, __LINE__, "TestMaxInt", u_errorName(status));
2135         return;
2136     }
2137 
2138     unum_setAttribute(fmt, UNUM_MAX_INTEGER_DIGITS, 2);
2139 
2140     status = U_ZERO_ERROR;
2141     /* #1 */
2142     len1 = unum_formatInt64(fmt, 1997, result1, 1024, NULL, &status);
2143     result1[len1]=0;
2144     if(U_FAILURE(status) || u_strcmp(expect, result1)) {
2145         log_err("unum_formatInt64 Expected %s but got %s status %s\n", austrdup(expect), austrdup(result1), u_errorName(status));
2146     }
2147 
2148     status = U_ZERO_ERROR;
2149     /* #2 */
2150     len2 = unum_formatDouble(fmt, 1997.0, result2, 1024, NULL, &status);
2151     result2[len2]=0;
2152     if(U_FAILURE(status) || u_strcmp(expect, result2)) {
2153         log_err("unum_formatDouble Expected %s but got %s status %s\n", austrdup(expect), austrdup(result2), u_errorName(status));
2154     }
2155 
2156 
2157 
2158     /* test UNUM_FORMAT_FAIL_IF_MORE_THAN_MAX_DIGITS */
2159     ASSERT_TRUE(unum_getAttribute(fmt, UNUM_FORMAT_FAIL_IF_MORE_THAN_MAX_DIGITS)==0);
2160 
2161     unum_setAttribute(fmt, UNUM_FORMAT_FAIL_IF_MORE_THAN_MAX_DIGITS, 1);
2162     /* test UNUM_FORMAT_FAIL_IF_MORE_THAN_MAX_DIGITS */
2163     ASSERT_TRUE(unum_getAttribute(fmt, UNUM_FORMAT_FAIL_IF_MORE_THAN_MAX_DIGITS)==1);
2164 
2165     status = U_ZERO_ERROR;
2166     /* max int digits still '2' */
2167     len1 = unum_formatInt64(fmt, 1997, result1, 1024, NULL, &status);
2168     ASSERT_TRUE(status==U_ILLEGAL_ARGUMENT_ERROR);
2169     status = U_ZERO_ERROR;
2170 
2171     /* But, formatting 97->'97' works fine. */
2172 
2173     /* #1 */
2174     len1 = unum_formatInt64(fmt, 97, result1, 1024, NULL, &status);
2175     result1[len1]=0;
2176     if(U_FAILURE(status) || u_strcmp(expect, result1)) {
2177         log_err("unum_formatInt64 Expected %s but got %s status %s\n", austrdup(expect), austrdup(result1), u_errorName(status));
2178     }
2179 
2180     status = U_ZERO_ERROR;
2181     /* #2 */
2182     len2 = unum_formatDouble(fmt, 97.0, result2, 1024, NULL, &status);
2183     result2[len2]=0;
2184     if(U_FAILURE(status) || u_strcmp(expect, result2)) {
2185         log_err("unum_formatDouble Expected %s but got %s status %s\n", austrdup(expect), austrdup(result2), u_errorName(status));
2186     }
2187 
2188 
2189     unum_close(fmt);
2190 }
2191 
TestUFormattable(void)2192 static void TestUFormattable(void) {
2193   UChar out2k[2048];
2194   // simple test for API docs
2195   {
2196     UErrorCode status = U_ZERO_ERROR;
2197     UNumberFormat *unum = unum_open(UNUM_DEFAULT, NULL, -1, "en_US_POSIX", NULL, &status);
2198     if(assertSuccessCheck("calling unum_open()", &status, TRUE)) {
2199       //! [unum_parseToUFormattable]
2200       const UChar str[] = { 0x0031, 0x0032, 0x0033, 0x0000 }; /* 123 */
2201       int32_t result = 0;
2202       UFormattable *ufmt = ufmt_open(&status);
2203       unum_parseToUFormattable(unum, ufmt, str, -1, NULL, &status);
2204       if (ufmt_isNumeric(ufmt)) {
2205           result = ufmt_getLong(ufmt, &status); /* == 123 */
2206       } /* else { ... } */
2207       ufmt_close(ufmt);
2208       //! [unum_parseToUFormattable]
2209       assertTrue("result == 123", (result == 123));
2210     }
2211     unum_close(unum);
2212   }
2213   // test with explicitly created ufmt_open
2214   {
2215     UChar buffer[2048];
2216     UErrorCode status = U_ZERO_ERROR;
2217     UFormattable *ufmt;
2218     UNumberFormat *unum;
2219     const char *pattern = "";
2220 
2221     ufmt = ufmt_open(&status);
2222     unum = unum_open(UNUM_DEFAULT, NULL, -1, "en_US_POSIX", NULL, &status);
2223     if(assertSuccessCheck("calling ufmt_open() || unum_open()", &status, TRUE)) {
2224 
2225       pattern = "31337";
2226       log_verbose("-- pattern: %s\n", pattern);
2227       u_uastrcpy(buffer, pattern);
2228       unum_parseToUFormattable(unum, ufmt, buffer, -1, NULL, &status);
2229       if(assertSuccess("unum_parseToUFormattable(31337)", &status)) {
2230         assertTrue("ufmt_getLong()=31337", ufmt_getLong(ufmt, &status) == 31337);
2231         assertTrue("ufmt_getType()=UFMT_LONG", ufmt_getType(ufmt, &status) == UFMT_LONG);
2232         log_verbose("long = %d\n", ufmt_getLong(ufmt, &status));
2233         assertSuccess("ufmt_getLong()", &status);
2234       }
2235       unum_formatUFormattable(unum, ufmt, out2k, 2048, NULL, &status);
2236       if(assertSuccess("unum_formatUFormattable(31337)", &status)) {
2237         assertEquals("unum_formatUFormattable r/t", austrdup(buffer), austrdup(out2k));
2238       }
2239 
2240       pattern = "3.14159";
2241       log_verbose("-- pattern: %s\n", pattern);
2242       u_uastrcpy(buffer, pattern);
2243       unum_parseToUFormattable(unum, ufmt, buffer, -1, NULL, &status);
2244       if(assertSuccess("unum_parseToUFormattable(3.14159)", &status)) {
2245         assertTrue("ufmt_getDouble()==3.14159", withinErr(ufmt_getDouble(ufmt, &status), 3.14159, 1e-15));
2246         assertSuccess("ufmt_getDouble()", &status);
2247         assertTrue("ufmt_getType()=UFMT_DOUBLE", ufmt_getType(ufmt, &status) == UFMT_DOUBLE);
2248         log_verbose("double = %g\n", ufmt_getDouble(ufmt, &status));
2249       }
2250       unum_formatUFormattable(unum, ufmt, out2k, 2048, NULL, &status);
2251       if(assertSuccess("unum_formatUFormattable(3.14159)", &status)) {
2252         assertEquals("unum_formatUFormattable r/t", austrdup(buffer), austrdup(out2k));
2253       }
2254     }
2255     ufmt_close(ufmt);
2256     unum_close(unum);
2257   }
2258 
2259   // test with auto-generated ufmt
2260   {
2261     UChar buffer[2048];
2262     UErrorCode status = U_ZERO_ERROR;
2263     UFormattable *ufmt = NULL;
2264     UNumberFormat *unum;
2265     const char *pattern = "73476730924573500000000"; // weight of the moon, kg
2266 
2267     log_verbose("-- pattern: %s (testing auto-opened UFormattable)\n", pattern);
2268     u_uastrcpy(buffer, pattern);
2269 
2270     unum = unum_open(UNUM_DEFAULT, NULL, -1, "en_US_POSIX", NULL, &status);
2271     if(assertSuccessCheck("calling unum_open()", &status, TRUE)) {
2272 
2273       ufmt = unum_parseToUFormattable(unum, NULL, /* will be ufmt_open()'ed for us */
2274                                    buffer, -1, NULL, &status);
2275       if(assertSuccess("unum_parseToUFormattable(weight of the moon)", &status)) {
2276         log_verbose("new formattable allocated at %p\n", (void*)ufmt);
2277         assertTrue("ufmt_isNumeric() TRUE", ufmt_isNumeric(ufmt));
2278         unum_formatUFormattable(unum, ufmt, out2k, 2048, NULL, &status);
2279         if(assertSuccess("unum_formatUFormattable(3.14159)", &status)) {
2280           assertEquals("unum_formatUFormattable r/t", austrdup(buffer), austrdup(out2k));
2281         }
2282 
2283         log_verbose("double: %g\n",  ufmt_getDouble(ufmt, &status));
2284         assertSuccess("ufmt_getDouble()", &status);
2285 
2286         log_verbose("long: %ld\n", ufmt_getLong(ufmt, &status));
2287         assertTrue("failure on ufmt_getLong() for huge number:", U_FAILURE(status));
2288         // status is now a failure due to ufmt_getLong() above.
2289         // the intltest does extensive r/t testing of Formattable vs. UFormattable.
2290       }
2291     }
2292 
2293     unum_close(unum);
2294     ufmt_close(ufmt); // was implicitly opened for us by the first unum_parseToUFormattable()
2295   }
2296 }
2297 
2298 typedef struct {
2299     const char*  locale;
2300     const char*  numsys;
2301     int32_t      radix;
2302     UBool        isAlgorithmic;
2303     const UChar* description;
2304 } NumSysTestItem;
2305 
2306 
2307 static const UChar latnDesc[]    = {0x0030,0x0031,0x0032,0x0033,0x0034,0x0035,0x0036,0x0037,0x0038,0x0039,0}; // 0123456789
2308 static const UChar romanDesc[]   = {0x25,0x72,0x6F,0x6D,0x61,0x6E,0x2D,0x75,0x70,0x70,0x65,0x72,0}; // %roman-upper
2309 static const UChar arabDesc[]    = {0x0660,0x0661,0x0662,0x0663,0x0664,0x0665,0x0666,0x0667,0x0668,0x0669,0}; //
2310 static const UChar arabextDesc[] = {0x06F0,0x06F1,0x06F2,0x06F3,0x06F4,0x06F5,0x06F6,0x06F7,0x06F8,0x06F9,0}; //
2311 static const UChar hanidecDesc[] = {0x3007,0x4E00,0x4E8C,0x4E09,0x56DB,0x4E94,0x516D,0x4E03,0x516B,0x4E5D,0}; //
2312 static const UChar hantDesc[]    = {0x7A,0x68,0x5F,0x48,0x61,0x6E,0x74,0x2F,0x53,0x70,0x65,0x6C,0x6C,0x6F,0x75,0x74,
2313                                     0x52,0x75,0x6C,0x65,0x73,0x2F,0x25,0x73,0x70,0x65,0x6C,0x6C,0x6F,0x75,0x74,0x2D,
2314                                     0x63,0x61,0x72,0x64,0x69,0x6E,0x61,0x6C,0}; // zh_Hant/SpelloutRules/%spellout-cardinal
2315 
2316 static const NumSysTestItem numSysTestItems[] = {
2317     //locale                         numsys    radix isAlgo  description
2318     { "en",                          "latn",    10,  FALSE,  latnDesc },
2319     { "en@numbers=roman",            "roman",   10,  TRUE,   romanDesc },
2320     { "en@numbers=finance",          "latn",    10,  FALSE,  latnDesc },
2321     { "ar",                          "arab",    10,  FALSE,  arabDesc },
2322     { "fa",                          "arabext", 10,  FALSE,  arabextDesc },
2323     { "zh_Hans@numbers=hanidec",     "hanidec", 10,  FALSE,  hanidecDesc },
2324     { "zh_Hant@numbers=traditional", "hant",    10,  TRUE,   hantDesc },
2325     { NULL,                          NULL,       0,  FALSE,  NULL },
2326 };
2327 enum { kNumSysDescripBufMax = 64 };
2328 
TestUNumberingSystem(void)2329 static void TestUNumberingSystem(void) {
2330     const NumSysTestItem * itemPtr;
2331     UNumberingSystem * unumsys;
2332     UEnumeration * uenum;
2333     const char * numsys;
2334     UErrorCode status;
2335 
2336     for (itemPtr = numSysTestItems; itemPtr->locale != NULL; itemPtr++) {
2337         status = U_ZERO_ERROR;
2338         unumsys = unumsys_open(itemPtr->locale, &status);
2339         if ( U_SUCCESS(status) ) {
2340             UChar ubuf[kNumSysDescripBufMax];
2341             int32_t ulen, radix = unumsys_getRadix(unumsys);
2342             UBool isAlgorithmic = unumsys_isAlgorithmic(unumsys);
2343             numsys = unumsys_getName(unumsys);
2344             if ( uprv_strcmp(numsys, itemPtr->numsys) != 0 || radix != itemPtr->radix || !isAlgorithmic != !itemPtr->isAlgorithmic ) {
2345                 log_data_err("unumsys name/radix/isAlgorithmic for locale %s, expected %s/%d/%d, got %s/%d/%d\n",
2346                         itemPtr->locale, itemPtr->numsys, itemPtr->radix, itemPtr->isAlgorithmic, numsys, radix, isAlgorithmic);
2347             }
2348             ulen = unumsys_getDescription(unumsys, ubuf, kNumSysDescripBufMax, &status);
2349             (void)ulen;   // Suppress variable not used warning.
2350             if ( U_FAILURE(status) || u_strcmp(ubuf, itemPtr->description) != 0 ) {
2351                 log_data_err("unumsys description for locale %s, description unexpected and/or status %\n", myErrorName(status));
2352             }
2353             unumsys_close(unumsys);
2354         } else {
2355             log_data_err("unumsys_open for locale %s fails with status %s\n", itemPtr->locale, myErrorName(status));
2356         }
2357     }
2358 
2359     status = U_ZERO_ERROR;
2360     uenum = unumsys_openAvailableNames(&status);
2361     if ( U_SUCCESS(status) ) {
2362         int32_t numsysCount = 0;
2363         // sanity check for a couple of number systems that must be in the enumeration
2364         UBool foundLatn = FALSE;
2365         UBool foundArab = FALSE;
2366         while ( (numsys = uenum_next(uenum, NULL, &status)) != NULL && U_SUCCESS(status) ) {
2367             status = U_ZERO_ERROR;
2368             unumsys = unumsys_openByName(numsys, &status);
2369             if ( U_SUCCESS(status) ) {
2370                 numsysCount++;
2371                 if ( uprv_strcmp(numsys, "latn") ) foundLatn = TRUE;
2372                 if ( uprv_strcmp(numsys, "arab") ) foundArab = TRUE;
2373                 unumsys_close(unumsys);
2374             } else {
2375                 log_err("unumsys_openAvailableNames includes %s but unumsys_openByName on it fails with status %s\n",
2376                         numsys, myErrorName(status));
2377             }
2378         }
2379         uenum_close(uenum);
2380         if ( numsysCount < 40 || !foundLatn || !foundArab ) {
2381             log_err("unumsys_openAvailableNames results incomplete: numsysCount %d, foundLatn %d, foundArab %d\n",
2382                     numsysCount, foundLatn, foundArab);
2383         }
2384     } else {
2385         log_data_err("unumsys_openAvailableNames fails with status %s\n", myErrorName(status));
2386     }
2387 }
2388 
2389 /* plain-C version of test in numfmtst.cpp */
2390 enum { kUBufMax = 64 };
TestCurrencyIsoPluralFormat(void)2391 static void TestCurrencyIsoPluralFormat(void) {
2392     static const char* DATA[][6] = {
2393         // the data are:
2394         // locale,
2395         // currency amount to be formatted,
2396         // currency ISO code to be formatted,
2397         // format result using CURRENCYSTYLE,
2398         // format result using ISOCURRENCYSTYLE,
2399         // format result using PLURALCURRENCYSTYLE,
2400 
2401         {"en_US", "1", "USD", "$1.00", "USD1.00", "1.00 US dollars"},
2402         {"en_US", "1234.56", "USD", "$1,234.56", "USD1,234.56", "1,234.56 US dollars"},
2403         {"en_US", "-1234.56", "USD", "-$1,234.56", "-USD1,234.56", "-1,234.56 US dollars"},
2404         {"zh_CN", "1", "USD", "US$\\u00A01.00", "USD\\u00A01.00", "1.00\\u7F8E\\u5143"},
2405         {"zh_CN", "1234.56", "USD", "US$\\u00A01,234.56", "USD\\u00A01,234.56", "1,234.56\\u7F8E\\u5143"},
2406         // wrong ISO code {"zh_CN", "1", "CHY", "CHY1.00", "CHY1.00", "1.00 CHY"},
2407         // wrong ISO code {"zh_CN", "1234.56", "CHY", "CHY1,234.56", "CHY1,234.56", "1,234.56 CHY"},
2408         {"zh_CN", "1", "CNY", "\\uFFE5\\u00A01.00", "CNY\\u00A01.00", "1.00\\u4EBA\\u6C11\\u5E01"},
2409         {"zh_CN", "1234.56", "CNY", "\\uFFE5\\u00A01,234.56", "CNY\\u00A01,234.56", "1,234.56\\u4EBA\\u6C11\\u5E01"},
2410         {"ru_RU", "1", "RUB", "1,00\\u00A0\\u0440\\u0443\\u0431.", "1,00\\u00A0RUB", "1,00 \\u0440\\u043E\\u0441\\u0441\\u0438\\u0439\\u0441\\u043A\\u043E\\u0433\\u043E \\u0440\\u0443\\u0431\\u043B\\u044F"},
2411         {"ru_RU", "2", "RUB", "2,00\\u00A0\\u0440\\u0443\\u0431.", "2,00\\u00A0RUB", "2,00 \\u0440\\u043E\\u0441\\u0441\\u0438\\u0439\\u0441\\u043A\\u043E\\u0433\\u043E \\u0440\\u0443\\u0431\\u043B\\u044F"},
2412         {"ru_RU", "5", "RUB", "5,00\\u00A0\\u0440\\u0443\\u0431.", "5,00\\u00A0RUB", "5,00 \\u0440\\u043E\\u0441\\u0441\\u0438\\u0439\\u0441\\u043A\\u043E\\u0433\\u043E \\u0440\\u0443\\u0431\\u043B\\u044F"},
2413         // test locale without currency information
2414         {"root", "-1.23", "USD", "-US$\\u00A01.23", "-USD\\u00A01.23", "-1.23 USD"},
2415         // test choice format
2416         {"es_AR", "1", "INR", "INR1,00", "INR1,00", "1,00 rupia india"},
2417     };
2418     static const UNumberFormatStyle currencyStyles[] = {
2419         UNUM_CURRENCY,
2420         UNUM_CURRENCY_ISO,
2421         UNUM_CURRENCY_PLURAL
2422     };
2423 
2424     int32_t i, sIndex;
2425 
2426     for (i=0; i<LENGTH(DATA); ++i) {
2427       const char* localeString = DATA[i][0];
2428       double numberToBeFormat = atof(DATA[i][1]);
2429       const char* currencyISOCode = DATA[i][2];
2430       for (sIndex = 0; sIndex < LENGTH(currencyStyles); ++sIndex) {
2431         UNumberFormatStyle style = currencyStyles[sIndex];
2432         UErrorCode status = U_ZERO_ERROR;
2433         UChar currencyCode[4];
2434         UChar ubufResult[kUBufMax];
2435         UChar ubufExpected[kUBufMax];
2436         int32_t ulenRes;
2437 
2438         UNumberFormat* unumFmt = unum_open(style, NULL, 0, localeString, NULL, &status);
2439         if (U_FAILURE(status)) {
2440             log_data_err("FAIL: unum_open, locale %s, style %d - %s\n", localeString, (int)style, myErrorName(status));
2441             continue;
2442         }
2443         u_charsToUChars(currencyISOCode, currencyCode, 4);
2444         unum_setTextAttribute(unumFmt, UNUM_CURRENCY_CODE, currencyCode, 3, &status);
2445         if (U_FAILURE(status)) {
2446             log_err("FAIL: unum_setTextAttribute, locale %s, UNUM_CURRENCY_CODE %s\n", localeString, currencyISOCode);
2447         }
2448         ulenRes = unum_formatDouble(unumFmt, numberToBeFormat, ubufResult, kUBufMax, NULL, &status);
2449         if (U_FAILURE(status)) {
2450             log_err("FAIL: unum_formatDouble, locale %s, UNUM_CURRENCY_CODE %s - %s\n", localeString, currencyISOCode, myErrorName(status));
2451         } else {
2452             int32_t ulenExp = u_unescape(DATA[i][3 + sIndex], ubufExpected, kUBufMax);
2453             if (ulenRes != ulenExp || u_strncmp(ubufResult, ubufExpected, ulenExp) != 0) {
2454                 log_err("FAIL: unum_formatDouble, locale %s, UNUM_CURRENCY_CODE %s, expected %s, got something else\n",
2455                         localeString, currencyISOCode, DATA[i][3 + sIndex]);
2456             }
2457         }
2458         unum_close(unumFmt);
2459       }
2460     }
2461 }
2462 
2463 typedef struct {
2464     const char * locale;
2465     UNumberFormatStyle style;
2466     UDisplayContext context;
2467     const char * expectedResult;
2468 } TestContextItem;
2469 
2470 /* currently no locales have contextTransforms data for "symbol" type */
2471 static const TestContextItem tcItems[] = { /* results for 123.45 */
2472     { "sv", UNUM_SPELLOUT, UDISPCTX_CAPITALIZATION_FOR_MIDDLE_OF_SENTENCE,    "ett\\u00ADhundra\\u00ADtjugo\\u00ADtre komma fyra fem" },
2473     { "sv", UNUM_SPELLOUT, UDISPCTX_CAPITALIZATION_FOR_BEGINNING_OF_SENTENCE, "Ett\\u00ADhundra\\u00ADtjugo\\u00ADtre komma fyra fem" },
2474     { "sv", UNUM_SPELLOUT, UDISPCTX_CAPITALIZATION_FOR_UI_LIST_OR_MENU,       "ett\\u00ADhundra\\u00ADtjugo\\u00ADtre komma fyra fem" },
2475     { "sv", UNUM_SPELLOUT, UDISPCTX_CAPITALIZATION_FOR_STANDALONE,            "ett\\u00ADhundra\\u00ADtjugo\\u00ADtre komma fyra fem" },
2476     { "en", UNUM_SPELLOUT, UDISPCTX_CAPITALIZATION_FOR_MIDDLE_OF_SENTENCE,    "one hundred twenty-three point four five" },
2477     { "en", UNUM_SPELLOUT, UDISPCTX_CAPITALIZATION_FOR_BEGINNING_OF_SENTENCE, "One hundred twenty-three point four five" },
2478     { "en", UNUM_SPELLOUT, UDISPCTX_CAPITALIZATION_FOR_UI_LIST_OR_MENU,       "One hundred twenty-three point four five" },
2479     { "en", UNUM_SPELLOUT, UDISPCTX_CAPITALIZATION_FOR_STANDALONE,            "One hundred twenty-three point four five" },
2480     { NULL, (UNumberFormatStyle)0, (UDisplayContext)0, NULL }
2481 };
2482 
TestContext(void)2483 static void TestContext(void) {
2484     UErrorCode status = U_ZERO_ERROR;
2485     const TestContextItem* itemPtr;
2486 
2487     UNumberFormat *unum = unum_open(UNUM_SPELLOUT, NULL, 0, "en", NULL, &status);
2488     if ( U_SUCCESS(status) ) {
2489         UDisplayContext context = unum_getContext(unum, UDISPCTX_TYPE_CAPITALIZATION, &status);
2490         if ( U_FAILURE(status) || context != UDISPCTX_CAPITALIZATION_NONE) {
2491             log_err("FAIL: Initial unum_getContext is not UDISPCTX_CAPITALIZATION_NONE\n");
2492             status = U_ZERO_ERROR;
2493         }
2494         unum_setContext(unum, UDISPCTX_CAPITALIZATION_FOR_STANDALONE, &status);
2495         context = unum_getContext(unum, UDISPCTX_TYPE_CAPITALIZATION, &status);
2496         if ( U_FAILURE(status) || context != UDISPCTX_CAPITALIZATION_FOR_STANDALONE) {
2497             log_err("FAIL: unum_getContext does not return the value set, UDISPCTX_CAPITALIZATION_FOR_STANDALONE\n");
2498         }
2499         unum_close(unum);
2500     } else {
2501         log_data_err("unum_open UNUM_SPELLOUT for en fails with status %s\n", myErrorName(status));
2502     }
2503 #if !UCONFIG_NO_NORMALIZATION && !UCONFIG_NO_BREAK_ITERATION
2504     for (itemPtr = tcItems; itemPtr->locale != NULL; itemPtr++) {
2505         UChar ubufResult[kUBufMax];
2506         int32_t ulenRes;
2507 
2508         status = U_ZERO_ERROR;
2509         unum = unum_open(itemPtr->style, NULL, 0, itemPtr->locale, NULL, &status);
2510         if (U_FAILURE(status)) {
2511             log_data_err("FAIL: unum_open, locale %s, style %d - %s\n",
2512                         itemPtr->locale, (int)itemPtr->style, myErrorName(status));
2513             continue;
2514         }
2515         unum_setContext(unum, itemPtr->context, &status);
2516         ulenRes = unum_formatDouble(unum, 123.45, ubufResult, kUBufMax, NULL, &status);
2517         if (U_FAILURE(status)) {
2518             log_err("FAIL: unum_formatDouble, locale %s, style %d, context %d - %s\n",
2519                     itemPtr->locale, (int)itemPtr->style, (int)itemPtr->context, myErrorName(status));
2520         } else {
2521             UChar ubufExpected[kUBufMax];
2522             int32_t ulenExp = u_unescape(itemPtr->expectedResult, ubufExpected, kUBufMax);
2523             if (ulenRes != ulenExp || u_strncmp(ubufResult, ubufExpected, ulenExp) != 0) {
2524                 char bbuf[kUBufMax*2];
2525                 u_austrncpy(bbuf, ubufResult, sizeof(bbuf));
2526                 log_err("FAIL: unum_formatDouble, locale %s, style %d, context %d, expected %d:\"%s\", got %d:\"%s\"\n",
2527                         itemPtr->locale, (int)itemPtr->style, (int)itemPtr->context, ulenExp,
2528                         itemPtr->expectedResult, ulenRes, bbuf);
2529             }
2530         }
2531         unum_close(unum);
2532     }
2533 #endif /* #if !UCONFIG_NO_NORMALIZATION && !UCONFIG_NO_BREAK_ITERATION */
2534 }
2535 
TestCurrencyUsage(void)2536 static void TestCurrencyUsage(void) {
2537     static const char* DATA[][2] = {
2538         /* the data are:
2539          * currency ISO code to be formatted,
2540          * format result using CURRENCYSTYLE with CASH purpose,-
2541          * Note that as of CLDR 26:-
2542          * - TWD switches from 0 decimals to 2; PKR still has 0, so change test to that
2543          * - CAD and all other currencies that rounded to .05 no longer do
2544          */
2545 
2546         {"PKR", "PKR124"},
2547         {"CAD", "CA$123.57"},
2548         {"USD", "$123.57"}
2549     };
2550 
2551     // 1st time for getter/setter, 2nd for factory method
2552     int32_t i;
2553     for(i=0; i<2; i++){
2554         const char* localeString = "en_US";
2555         double numberToBeFormat = 123.567;
2556         UNumberFormat* unumFmt;
2557         UNumberFormatStyle style = UNUM_CURRENCY;
2558         UErrorCode status = U_ZERO_ERROR;
2559         int32_t j;
2560 
2561         if(i == 1){ // change for factory method
2562             style = UNUM_CASH_CURRENCY;
2563         }
2564 
2565         unumFmt = unum_open(style, NULL, 0, localeString, NULL, &status);
2566         if (U_FAILURE(status)) {
2567             log_data_err("FAIL: unum_open, locale %s, style %d - %s\n",
2568                         localeString, (int)style, myErrorName(status));
2569             continue;
2570         }
2571 
2572         if(i == 0){ // this is for the getter/setter
2573             if(unum_getAttribute(unumFmt, UNUM_CURRENCY_USAGE) != UCURR_USAGE_STANDARD) {
2574                 log_err("FAIL: currency usage attribute is not UNUM_CURRENCY_STANDARD\n");
2575             }
2576 
2577             unum_setAttribute(unumFmt, UNUM_CURRENCY_USAGE, UCURR_USAGE_CASH);
2578         }
2579 
2580         if(unum_getAttribute(unumFmt, UNUM_CURRENCY_USAGE) != UCURR_USAGE_CASH) {
2581             log_err("FAIL: currency usage attribute is not UNUM_CURRENCY_CASH\n");
2582         }
2583 
2584         for (j=0; j<LENGTH(DATA); ++j) {
2585             UChar expect[64];
2586             int32_t expectLen;
2587             UChar currencyCode[4];
2588             UChar result[64];
2589             int32_t resultLen;
2590             UFieldPosition pos = {0};
2591 
2592             u_charsToUChars(DATA[j][0], currencyCode, 3);
2593             expectLen = u_unescape(DATA[j][1], expect, LENGTH(expect));
2594 
2595             unum_setTextAttribute(unumFmt, UNUM_CURRENCY_CODE, currencyCode, 3, &status);
2596             assertSuccess("num_setTextAttribute()", &status);
2597 
2598             resultLen = unum_formatDouble(unumFmt, numberToBeFormat, result, LENGTH(result),
2599                                         &pos, &status);
2600             assertSuccess("num_formatDouble()", &status);
2601 
2602             if(resultLen != expectLen || u_strcmp(result, expect) != 0) {
2603                 log_err("Fail: Error in Number Format Currency Purpose using unum_setAttribute() expected: %s, got %s\n",
2604                 aescstrdup(expect, expectLen), aescstrdup(result, resultLen));
2605             }
2606 
2607         }
2608 
2609         unum_close(unumFmt);
2610     }
2611 }
2612 
2613 static UChar currFmtNegSameAsPos[] = /* "\u00A4#,##0.00;\u00A4#,##0.00" */
2614     {0xA4,0x23,0x2C,0x23,0x23,0x30,0x2E,0x30,0x30,0x3B,0xA4,0x23,0x2C,0x23,0x23,0x30,0x2E,0x30,0x30,0};
2615 
2616 static UChar currFmtToPatExpected[] = /* "\u00A4#,##0.00" */
2617     {0xA4,0x23,0x2C,0x23,0x23,0x30,0x2E,0x30,0x30,0};
2618 
2619 static UChar currFmtResultExpected[] = /* "$100.00" */
2620     {0x24,0x31,0x30,0x30,0x2E,0x30,0x30,0};
2621 
2622 static UChar emptyString[] = {0};
2623 
2624 enum { kUBufSize = 64 };
2625 
TestCurrFmtNegSameAsPositive(void)2626 static void TestCurrFmtNegSameAsPositive(void) {
2627     UErrorCode status = U_ZERO_ERROR;
2628     UNumberFormat* unumfmt = unum_open(UNUM_CURRENCY, NULL, 0, "en_US", NULL, &status);
2629     if ( U_SUCCESS(status) ) {
2630         unum_applyPattern(unumfmt, FALSE, currFmtNegSameAsPos, -1, NULL, &status);
2631         if (U_SUCCESS(status)) {
2632             UChar ubuf[kUBufSize];
2633             int32_t ulen = unum_toPattern(unumfmt, FALSE, ubuf, kUBufSize, &status);
2634             if (U_FAILURE(status)) {
2635                 log_err("unum_toPattern fails with status %s\n", myErrorName(status));
2636             } else if (u_strcmp(ubuf, currFmtToPatExpected) != 0) {
2637                 log_err("unum_toPattern result wrong, expected %s, got %s\n", aescstrdup(currFmtToPatExpected,-1), aescstrdup(ubuf,ulen));
2638             }
2639             unum_setSymbol(unumfmt, UNUM_MINUS_SIGN_SYMBOL, emptyString, 0, &status);
2640             if (U_SUCCESS(status)) {
2641                 ulen = unum_formatDouble(unumfmt, -100.0, ubuf, kUBufSize, NULL, &status);
2642                 if (U_FAILURE(status)) {
2643                     log_err("unum_formatDouble fails with status %s\n", myErrorName(status));
2644                 } else if (u_strcmp(ubuf, currFmtResultExpected) != 0) {
2645                     log_err("unum_formatDouble result wrong, expected %s, got %s\n", aescstrdup(currFmtResultExpected,-1), aescstrdup(ubuf,ulen));
2646                 }
2647             } else {
2648                 log_err("unum_setSymbol fails with status %s\n", myErrorName(status));
2649             }
2650         } else {
2651             log_err("unum_applyPattern fails with status %s\n", myErrorName(status));
2652         }
2653         unum_close(unumfmt);
2654     } else {
2655         log_data_err("unum_open UNUM_CURRENCY for en_US fails with status %s\n", myErrorName(status));
2656     }
2657 }
2658 
2659 #endif /* #if !UCONFIG_NO_FORMATTING */
2660