1 /*
2 *******************************************************************************
3 *
4 *   © 2016 and later: Unicode, Inc. and others.
5 *   License & terms of use: http://www.unicode.org/copyright.html#License
6 *
7 *******************************************************************************
8 *******************************************************************************
9 *
10 *   Copyright (C) 2000-2014, International Business Machines
11 *   Corporation and others.  All Rights Reserved.
12 *
13 *******************************************************************************
14 *   file name:  ustring.c
15 *   encoding:   UTF-8
16 *   tab size:   8 (not used)
17 *   indentation:4
18 *
19 *   created on: 2000aug15
20 *   created by: Markus W. Scherer
21 *
22 *   This file contains sample code that illustrates the use of Unicode strings
23 *   with ICU.
24 */
25 
26 #include <stdio.h>
27 #include "unicode/utypes.h"
28 #include "unicode/uchar.h"
29 #include "unicode/locid.h"
30 #include "unicode/ustring.h"
31 #include "unicode/ucnv.h"
32 #include "unicode/unistr.h"
33 
34 using namespace icu;
35 
36 #ifndef UPRV_LENGTHOF
37 #define UPRV_LENGTHOF(array) (int32_t)(sizeof(array)/sizeof((array)[0]))
38 #endif
39 
40 // helper functions -------------------------------------------------------- ***
41 
42 // default converter for the platform encoding
43 static UConverter *cnv=NULL;
44 
45 static void
printUString(const char * announce,const UChar * s,int32_t length)46 printUString(const char *announce, const UChar *s, int32_t length) {
47     static char out[200];
48     UChar32 c;
49     int32_t i;
50     UErrorCode errorCode=U_ZERO_ERROR;
51 
52     /*
53      * Convert to the "platform encoding". See notes in printUnicodeString().
54      * ucnv_fromUChars(), like most ICU APIs understands length==-1
55      * to mean that the string is NUL-terminated.
56      */
57     ucnv_fromUChars(cnv, out, sizeof(out), s, length, &errorCode);
58     if(U_FAILURE(errorCode) || errorCode==U_STRING_NOT_TERMINATED_WARNING) {
59         printf("%sproblem converting string from Unicode: %s\n", announce, u_errorName(errorCode));
60         return;
61     }
62 
63     printf("%s%s {", announce, out);
64 
65     /* output the code points (not code units) */
66     if(length>=0) {
67         /* s is not NUL-terminated */
68         for(i=0; i<length; /* U16_NEXT post-increments */) {
69             U16_NEXT(s, i, length, c);
70             printf(" %04x", c);
71         }
72     } else {
73         /* s is NUL-terminated */
74         for(i=0; /* condition in loop body */; /* U16_NEXT post-increments */) {
75             U16_NEXT(s, i, length, c);
76             if(c==0) {
77                 break;
78             }
79             printf(" %04x", c);
80         }
81     }
82     printf(" }\n");
83 }
84 
85 static void
printUnicodeString(const char * announce,const UnicodeString & s)86 printUnicodeString(const char *announce, const UnicodeString &s) {
87     static char out[200];
88     int32_t i, length;
89 
90     // output the string, converted to the platform encoding
91 
92     // Note for Windows: The "platform encoding" defaults to the "ANSI codepage",
93     // which is different from the "OEM codepage" in the console window.
94     // However, if you pipe the output into a file and look at it with Notepad
95     // or similar, then "ANSI" characters will show correctly.
96     // Production code should be aware of what encoding is required,
97     // and use a UConverter or at least a charset name explicitly.
98     out[s.extract(0, 99, out)]=0;
99     printf("%s%s {", announce, out);
100 
101     // output the code units (not code points)
102     length=s.length();
103     for(i=0; i<length; ++i) {
104         printf(" %04x", s.charAt(i));
105     }
106     printf(" }\n");
107 }
108 
109 // sample code for utf.h macros -------------------------------------------- ***
110 
111 static void
demo_utf_h_macros()112 demo_utf_h_macros() {
113     static UChar input[]={ 0x0061, 0xd800, 0xdc00, 0xdbff, 0xdfff, 0x0062 };
114     UChar32 c;
115     int32_t i;
116     UBool isError;
117 
118     printf("\n* demo_utf_h_macros() -------------- ***\n\n");
119 
120     printUString("iterate forward through: ", input, UPRV_LENGTHOF(input));
121     for(i=0; i<UPRV_LENGTHOF(input); /* U16_NEXT post-increments */) {
122         /* Iterating forwards
123            Codepoint at offset 0: U+0061
124            Codepoint at offset 1: U+10000
125            Codepoint at offset 3: U+10ffff
126            Codepoint at offset 5: U+0062
127         */
128         printf("Codepoint at offset %d: U+", i);
129         U16_NEXT(input, i, UPRV_LENGTHOF(input), c);
130         printf("%04x\n", c);
131     }
132 
133     puts("");
134 
135     isError=FALSE;
136     i=1; /* write position, gets post-incremented so needs to be in an l-value */
137     U16_APPEND(input, i, UPRV_LENGTHOF(input), 0x0062, isError);
138 
139     printUString("iterate backward through: ", input, UPRV_LENGTHOF(input));
140     for(i=UPRV_LENGTHOF(input); i>0; /* U16_PREV pre-decrements */) {
141         U16_PREV(input, 0, i, c);
142         /* Iterating backwards
143            Codepoint at offset 5: U+0062
144            Codepoint at offset 3: U+10ffff
145            Codepoint at offset 2: U+dc00 -- unpaired surrogate because lead surr. overwritten
146            Codepoint at offset 1: U+0062 -- by this BMP code point
147            Codepoint at offset 0: U+0061
148         */
149         printf("Codepoint at offset %d: U+%04x\n", i, c);
150     }
151 }
152 
153 // sample code for Unicode strings in C ------------------------------------ ***
154 
demo_C_Unicode_strings()155 static void demo_C_Unicode_strings() {
156     printf("\n* demo_C_Unicode_strings() --------- ***\n\n");
157 
158     static const UChar text[]={ 0x41, 0x42, 0x43, 0 };          /* "ABC" */
159     static const UChar appendText[]={ 0x61, 0x62, 0x63, 0 };    /* "abc" */
160     static const UChar cmpText[]={ 0x61, 0x53, 0x73, 0x43, 0 }; /* "aSsC" */
161     UChar buffer[32];
162     int32_t compare;
163     int32_t length=u_strlen(text); /* length=3 */
164 
165     /* simple ANSI C-style functions */
166     buffer[0]=0;                    /* empty, NUL-terminated string */
167     u_strncat(buffer, text, 1);     /* append just n=1 character ('A') */
168     u_strcat(buffer, appendText);   /* buffer=="Aabc" */
169     length=u_strlen(buffer);        /* length=4 */
170     printUString("should be \"Aabc\": ", buffer, -1);
171 
172     /* bitwise comparing buffer with text */
173     compare=u_strcmp(buffer, text);
174     if(compare<=0) {
175         printf("String comparison error, expected \"Aabc\" > \"ABC\"\n");
176     }
177 
178     /* Build "A<sharp s>C" in the buffer... */
179     u_strcpy(buffer, text);
180     buffer[1]=0xdf; /* sharp s, case-compares equal to "ss" */
181     printUString("should be \"A<sharp s>C\": ", buffer, -1);
182 
183     /* Compare two strings case-insensitively using full case folding */
184     compare=u_strcasecmp(buffer, cmpText, U_FOLD_CASE_DEFAULT);
185     if(compare!=0) {
186         printf("String case insensitive comparison error, expected \"AbC\" to be equal to \"ABC\"\n");
187     }
188 }
189 
190 // sample code for case mappings with C APIs -------------------------------- ***
191 
demoCaseMapInC()192 static void demoCaseMapInC() {
193     /*
194      * input=
195      *   "aB<capital sigma>"
196      *   "iI<small dotless i><capital dotted I> "
197      *   "<sharp s> <small lig. ffi>"
198      *   "<small final sigma><small sigma><capital sigma>"
199      */
200     static const UChar input[]={
201         0x61, 0x42, 0x3a3,
202         0x69, 0x49, 0x131, 0x130, 0x20,
203         0xdf, 0x20, 0xfb03,
204         0x3c2, 0x3c3, 0x3a3, 0
205     };
206     UChar buffer[32];
207 
208     UErrorCode errorCode;
209     UChar32 c;
210     int32_t i, j, length;
211     UBool isError;
212 
213     printf("\n* demoCaseMapInC() ----------------- ***\n\n");
214 
215     /*
216      * First, use simple case mapping functions which provide
217      * 1:1 code point mappings without context/locale ID.
218      *
219      * Note that some mappings will not be "right" because some "real"
220      * case mappings require context, depend on the locale ID,
221      * and/or result in a change in the number of code points.
222      */
223     printUString("input string: ", input, -1);
224 
225     /* uppercase */
226     isError=FALSE;
227     for(i=j=0; j<UPRV_LENGTHOF(buffer) && !isError; /* U16_NEXT post-increments */) {
228         U16_NEXT(input, i, INT32_MAX, c); /* without length because NUL-terminated */
229         if(c==0) {
230             break; /* stop at terminating NUL, no need to terminate buffer */
231         }
232         c=u_toupper(c);
233         U16_APPEND(buffer, j, UPRV_LENGTHOF(buffer), c, isError);
234     }
235     printUString("simple-uppercased: ", buffer, j);
236     /* lowercase */
237     isError=FALSE;
238     for(i=j=0; j<UPRV_LENGTHOF(buffer) && !isError; /* U16_NEXT post-increments */) {
239         U16_NEXT(input, i, INT32_MAX, c); /* without length because NUL-terminated */
240         if(c==0) {
241             break; /* stop at terminating NUL, no need to terminate buffer */
242         }
243         c=u_tolower(c);
244         U16_APPEND(buffer, j, UPRV_LENGTHOF(buffer), c, isError);
245     }
246     printUString("simple-lowercased: ", buffer, j);
247     /* titlecase */
248     isError=FALSE;
249     for(i=j=0; j<UPRV_LENGTHOF(buffer) && !isError; /* U16_NEXT post-increments */) {
250         U16_NEXT(input, i, INT32_MAX, c); /* without length because NUL-terminated */
251         if(c==0) {
252             break; /* stop at terminating NUL, no need to terminate buffer */
253         }
254         c=u_totitle(c);
255         U16_APPEND(buffer, j, UPRV_LENGTHOF(buffer), c, isError);
256     }
257     printUString("simple-titlecased: ", buffer, j);
258     /* case-fold/default */
259     isError=FALSE;
260     for(i=j=0; j<UPRV_LENGTHOF(buffer) && !isError; /* U16_NEXT post-increments */) {
261         U16_NEXT(input, i, INT32_MAX, c); /* without length because NUL-terminated */
262         if(c==0) {
263             break; /* stop at terminating NUL, no need to terminate buffer */
264         }
265         c=u_foldCase(c, U_FOLD_CASE_DEFAULT);
266         U16_APPEND(buffer, j, UPRV_LENGTHOF(buffer), c, isError);
267     }
268     printUString("simple-case-folded/default: ", buffer, j);
269     /* case-fold/Turkic */
270     isError=FALSE;
271     for(i=j=0; j<UPRV_LENGTHOF(buffer) && !isError; /* U16_NEXT post-increments */) {
272         U16_NEXT(input, i, INT32_MAX, c); /* without length because NUL-terminated */
273         if(c==0) {
274             break; /* stop at terminating NUL, no need to terminate buffer */
275         }
276         c=u_foldCase(c, U_FOLD_CASE_EXCLUDE_SPECIAL_I);
277         U16_APPEND(buffer, j, UPRV_LENGTHOF(buffer), c, isError);
278     }
279     printUString("simple-case-folded/Turkic: ", buffer, j);
280 
281     /*
282      * Second, use full case mapping functions which provide
283      * 1:n code point mappings (n can be 0!) and are sensitive to context and locale ID.
284      *
285      * Note that lower/upper/titlecasing take a locale ID while case-folding
286      * has bit flag options instead, by design of the Unicode SpecialCasing.txt UCD file.
287      *
288      * Also, string titlecasing requires a BreakIterator to find starts of words.
289      * The sample code here passes in a NULL pointer; u_strToTitle() will open and close a default
290      * titlecasing BreakIterator automatically.
291      * For production code where many strings are titlecased it would be more efficient
292      * to open a BreakIterator externally and pass it in.
293      */
294     printUString("\ninput string: ", input, -1);
295 
296     /* lowercase/English */
297     errorCode=U_ZERO_ERROR;
298     length=u_strToLower(buffer, UPRV_LENGTHOF(buffer), input, -1, "en", &errorCode);
299     if(U_SUCCESS(errorCode)) {
300         printUString("full-lowercased/en: ", buffer, length);
301     } else {
302         printf("error in u_strToLower(en)=%ld error=%s\n", length, u_errorName(errorCode));
303     }
304     /* lowercase/Turkish */
305     errorCode=U_ZERO_ERROR;
306     length=u_strToLower(buffer, UPRV_LENGTHOF(buffer), input, -1, "tr", &errorCode);
307     if(U_SUCCESS(errorCode)) {
308         printUString("full-lowercased/tr: ", buffer, length);
309     } else {
310         printf("error in u_strToLower(tr)=%ld error=%s\n", length, u_errorName(errorCode));
311     }
312     /* uppercase/English */
313     errorCode=U_ZERO_ERROR;
314     length=u_strToUpper(buffer, UPRV_LENGTHOF(buffer), input, -1, "en", &errorCode);
315     if(U_SUCCESS(errorCode)) {
316         printUString("full-uppercased/en: ", buffer, length);
317     } else {
318         printf("error in u_strToUpper(en)=%ld error=%s\n", length, u_errorName(errorCode));
319     }
320     /* uppercase/Turkish */
321     errorCode=U_ZERO_ERROR;
322     length=u_strToUpper(buffer, UPRV_LENGTHOF(buffer), input, -1, "tr", &errorCode);
323     if(U_SUCCESS(errorCode)) {
324         printUString("full-uppercased/tr: ", buffer, length);
325     } else {
326         printf("error in u_strToUpper(tr)=%ld error=%s\n", length, u_errorName(errorCode));
327     }
328     /* titlecase/English */
329     errorCode=U_ZERO_ERROR;
330     length=u_strToTitle(buffer, UPRV_LENGTHOF(buffer), input, -1, NULL, "en", &errorCode);
331     if(U_SUCCESS(errorCode)) {
332         printUString("full-titlecased/en: ", buffer, length);
333     } else {
334         printf("error in u_strToTitle(en)=%ld error=%s\n", length, u_errorName(errorCode));
335     }
336     /* titlecase/Turkish */
337     errorCode=U_ZERO_ERROR;
338     length=u_strToTitle(buffer, UPRV_LENGTHOF(buffer), input, -1, NULL, "tr", &errorCode);
339     if(U_SUCCESS(errorCode)) {
340         printUString("full-titlecased/tr: ", buffer, length);
341     } else {
342         printf("error in u_strToTitle(tr)=%ld error=%s\n", length, u_errorName(errorCode));
343     }
344     /* case-fold/default */
345     errorCode=U_ZERO_ERROR;
346     length=u_strFoldCase(buffer, UPRV_LENGTHOF(buffer), input, -1, U_FOLD_CASE_DEFAULT, &errorCode);
347     if(U_SUCCESS(errorCode)) {
348         printUString("full-case-folded/default: ", buffer, length);
349     } else {
350         printf("error in u_strFoldCase(default)=%ld error=%s\n", length, u_errorName(errorCode));
351     }
352     /* case-fold/Turkic */
353     errorCode=U_ZERO_ERROR;
354     length=u_strFoldCase(buffer, UPRV_LENGTHOF(buffer), input, -1, U_FOLD_CASE_EXCLUDE_SPECIAL_I, &errorCode);
355     if(U_SUCCESS(errorCode)) {
356         printUString("full-case-folded/Turkic: ", buffer, length);
357     } else {
358         printf("error in u_strFoldCase(Turkic)=%ld error=%s\n", length, u_errorName(errorCode));
359     }
360 }
361 
362 // sample code for case mappings with C++ APIs ------------------------------ ***
363 
demoCaseMapInCPlusPlus()364 static void demoCaseMapInCPlusPlus() {
365     /*
366      * input=
367      *   "aB<capital sigma>"
368      *   "iI<small dotless i><capital dotted I> "
369      *   "<sharp s> <small lig. ffi>"
370      *   "<small final sigma><small sigma><capital sigma>"
371      */
372     static const UChar input[]={
373         0x61, 0x42, 0x3a3,
374         0x69, 0x49, 0x131, 0x130, 0x20,
375         0xdf, 0x20, 0xfb03,
376         0x3c2, 0x3c3, 0x3a3, 0
377     };
378 
379     printf("\n* demoCaseMapInCPlusPlus() --------- ***\n\n");
380 
381     UnicodeString s(input), t;
382     const Locale &en=Locale::getEnglish();
383     Locale tr("tr");
384 
385     /*
386      * Full case mappings as in demoCaseMapInC(), using UnicodeString functions.
387      * These functions modify the string object itself.
388      * Since we want to keep the input string around, we copy it each time
389      * and case-map the copy.
390      */
391     printUnicodeString("input string: ", s);
392 
393     /* lowercase/English */
394     printUnicodeString("full-lowercased/en: ", (t=s).toLower(en));
395     /* lowercase/Turkish */
396     printUnicodeString("full-lowercased/tr: ", (t=s).toLower(tr));
397     /* uppercase/English */
398     printUnicodeString("full-uppercased/en: ", (t=s).toUpper(en));
399     /* uppercase/Turkish */
400     printUnicodeString("full-uppercased/tr: ", (t=s).toUpper(tr));
401     /* titlecase/English */
402     printUnicodeString("full-titlecased/en: ", (t=s).toTitle(NULL, en));
403     /* titlecase/Turkish */
404     printUnicodeString("full-titlecased/tr: ", (t=s).toTitle(NULL, tr));
405     /* case-folde/default */
406     printUnicodeString("full-case-folded/default: ", (t=s).foldCase(U_FOLD_CASE_DEFAULT));
407     /* case-folde/Turkic */
408     printUnicodeString("full-case-folded/Turkic: ", (t=s).foldCase(U_FOLD_CASE_EXCLUDE_SPECIAL_I));
409 }
410 
411 // sample code for UnicodeString storage models ----------------------------- ***
412 
413 static const UChar readonly[]={
414     0x61, 0x31, 0x20ac
415 };
416 static UChar writeable[]={
417     0x62, 0x32, 0xdbc0, 0xdc01 // includes a surrogate pair for a supplementary code point
418 };
419 static char out[100];
420 
421 static void
demoUnicodeStringStorage()422 demoUnicodeStringStorage() {
423     // These sample code lines illustrate how to use UnicodeString, and the
424     // comments tell what happens internally. There are no APIs to observe
425     // most of this programmatically, except for stepping into the code
426     // with a debugger.
427     // This is by design to hide such details from the user.
428     int32_t i;
429 
430     printf("\n* demoUnicodeStringStorage() ------- ***\n\n");
431 
432     // * UnicodeString with internally stored contents
433     // instantiate a UnicodeString from a single code point
434     // the few (2) UChars will be stored in the object itself
435     UnicodeString one((UChar32)0x24001);
436     // this copies the few UChars into the "two" object
437     UnicodeString two=one;
438     printf("length of short string copy: %d\n", two.length());
439     // set "one" to contain the 3 UChars from readonly
440     // this setTo() variant copies the characters
441     one.setTo(readonly, UPRV_LENGTHOF(readonly));
442 
443     // * UnicodeString with allocated contents
444     // build a longer string that will not fit into the object's buffer
445     one+=UnicodeString(writeable, UPRV_LENGTHOF(writeable));
446     one+=one;
447     one+=one;
448     printf("length of longer string: %d\n", one.length());
449     // copying will use the same allocated buffer and increment the reference
450     // counter
451     two=one;
452     printf("length of longer string copy: %d\n", two.length());
453 
454     // * UnicodeString using readonly-alias to a const UChar array
455     // construct a string that aliases a readonly buffer
456     UnicodeString three(FALSE, readonly, UPRV_LENGTHOF(readonly));
457     printUnicodeString("readonly-alias string: ", three);
458     // copy-on-write: any modification to the string results in
459     // a copy to either the internal buffer or to a newly allocated one
460     three.setCharAt(1, 0x39);
461     printUnicodeString("readonly-aliasing string after modification: ", three);
462     // the aliased array is not modified
463     for(i=0; i<three.length(); ++i) {
464         printf("readonly buffer[%d] after modifying its string: 0x%lx\n",
465                i, readonly[i]);
466     }
467     // setTo() readonly alias
468     one.setTo(FALSE, writeable, UPRV_LENGTHOF(writeable));
469     // copying the readonly-alias object with fastCopyFrom() (new in ICU 2.4)
470     // will readonly-alias the same buffer
471     two.fastCopyFrom(one);
472     printUnicodeString("fastCopyFrom(readonly alias of \"writeable\" array): ", two);
473     printf("verify that a fastCopyFrom(readonly alias) uses the same buffer pointer: %d (should be 1)\n",
474         one.getBuffer()==two.getBuffer());
475     // a normal assignment will clone the contents (new in ICU 2.4)
476     two=one;
477     printf("verify that a regular copy of a readonly alias uses a different buffer pointer: %d (should be 0)\n",
478         one.getBuffer()==two.getBuffer());
479 
480     // * UnicodeString using writeable-alias to a non-const UChar array
481     UnicodeString four(writeable, UPRV_LENGTHOF(writeable), UPRV_LENGTHOF(writeable));
482     printUnicodeString("writeable-alias string: ", four);
483     // a modification writes through to the buffer
484     four.setCharAt(1, 0x39);
485     for(i=0; i<four.length(); ++i) {
486         printf("writeable-alias backing buffer[%d]=0x%lx "
487                "after modification\n", i, writeable[i]);
488     }
489     // a copy will not alias any more;
490     // instead, it will get a copy of the contents into allocated memory
491     two=four;
492     two.setCharAt(1, 0x21);
493     for(i=0; i<two.length(); ++i) {
494         printf("writeable-alias backing buffer[%d]=0x%lx after "
495                "modification of string copy\n", i, writeable[i]);
496     }
497     // setTo() writeable alias, capacity==length
498     one.setTo(writeable, UPRV_LENGTHOF(writeable), UPRV_LENGTHOF(writeable));
499     // grow the string - it will not fit into the backing buffer any more
500     // and will get copied before modification
501     one.append((UChar)0x40);
502     // shrink it back so it would fit
503     one.truncate(one.length()-1);
504     // we still operate on the copy
505     one.setCharAt(1, 0x25);
506     printf("string after growing too much and then shrinking[1]=0x%lx\n"
507            "                          backing store for this[1]=0x%lx\n",
508            one.charAt(1), writeable[1]);
509     // if we need it in the original buffer, then extract() to it
510     // extract() does not do anything if the string aliases that same buffer
511     // i=min(one.length(), length of array)
512     if(one.length()<UPRV_LENGTHOF(writeable)) {
513         i=one.length();
514     } else {
515         i=UPRV_LENGTHOF(writeable);
516     }
517     one.extract(0, i, writeable);
518     for(i=0; i<UPRV_LENGTHOF(writeable); ++i) {
519         printf("writeable-alias backing buffer[%d]=0x%lx after re-extract\n",
520                i, writeable[i]);
521     }
522 }
523 
524 // sample code for UnicodeString instantiations ----------------------------- ***
525 
526 static void
demoUnicodeStringInit()527 demoUnicodeStringInit() {
528     // *** Make sure to read about invariant characters in utypes.h! ***
529     // Initialization of Unicode strings from C literals works _only_ for
530     // invariant characters!
531 
532     printf("\n* demoUnicodeStringInit() ---------- ***\n\n");
533 
534     // the string literal is 32 chars long - this must be counted for the macro
535     UnicodeString invariantOnly=UNICODE_STRING("such characters are safe 123 %-.", 32);
536 
537     /*
538      * In C, we need two macros: one to declare the UChar[] array, and
539      * one to populate it; the second one is a noop on platforms where
540      * wchar_t is compatible with UChar and ASCII-based.
541      * The length of the string literal must be counted for both macros.
542      */
543     /* declare the invString array for the string */
544     U_STRING_DECL(invString, "such characters are safe 123 %-.", 32);
545     /* populate it with the characters */
546     U_STRING_INIT(invString, "such characters are safe 123 %-.", 32);
547 
548     // compare the C and C++ strings
549     printf("C and C++ Unicode strings are equal: %d\n", invariantOnly==UnicodeString(TRUE, invString, 32));
550 
551     /*
552      * convert between char * and UChar * strings that
553      * contain only invariant characters
554      */
555     static const char *cs1="such characters are safe 123 %-.";
556     static UChar us1[40];
557     static char cs2[40];
558     u_charsToUChars(cs1, us1, 33); /* include the terminating NUL */
559     u_UCharsToChars(us1, cs2, 33);
560     printf("char * -> UChar * -> char * with only "
561            "invariant characters: \"%s\"\n",
562            cs2);
563 
564     // initialize a UnicodeString from a string literal that contains
565     // escape sequences written with invariant characters
566     // do not forget to duplicate the backslashes for ICU to see them
567     // then, count each double backslash only once!
568     UnicodeString german=UNICODE_STRING(
569         "Sch\\u00f6nes Auto: \\u20ac 11240.\\fPrivates Zeichen: \\U00102345\\n", 64).
570         unescape();
571     printUnicodeString("german UnicodeString from unescaping:\n    ", german);
572 
573     /*
574      * C: convert and unescape a char * string with only invariant
575      * characters to fill a UChar * string
576      */
577     UChar buffer[200];
578     int32_t length;
579     length=u_unescape(
580         "Sch\\u00f6nes Auto: \\u20ac 11240.\\fPrivates Zeichen: \\U00102345\\n",
581         buffer, UPRV_LENGTHOF(buffer));
582     printf("german C Unicode string from char * unescaping: (length %d)\n    ", length);
583     printUnicodeString("", UnicodeString(buffer));
584 }
585 
586 extern int
main(int argc,const char * argv[])587 main(int argc, const char *argv[]) {
588     UErrorCode errorCode=U_ZERO_ERROR;
589 
590     // Note: Using a global variable for any object is not exactly thread-safe...
591 
592     // You can change this call to e.g. ucnv_open("UTF-8", &errorCode) if you pipe
593     // the output to a file and look at it with a Unicode-capable editor.
594     // This will currently affect only the printUString() function, see the code above.
595     // printUnicodeString() could use this, too, by changing to an extract() overload
596     // that takes a UConverter argument.
597     cnv=ucnv_open(NULL, &errorCode);
598     if(U_FAILURE(errorCode)) {
599         fprintf(stderr, "error %s opening the default converter\n", u_errorName(errorCode));
600         return errorCode;
601     }
602 
603     ucnv_setFromUCallBack(cnv, UCNV_FROM_U_CALLBACK_ESCAPE, UCNV_ESCAPE_C, NULL, NULL, &errorCode);
604     if(U_FAILURE(errorCode)) {
605         fprintf(stderr, "error %s setting the escape callback in the default converter\n", u_errorName(errorCode));
606         ucnv_close(cnv);
607         return errorCode;
608     }
609 
610     demo_utf_h_macros();
611     demo_C_Unicode_strings();
612     demoCaseMapInC();
613     demoCaseMapInCPlusPlus();
614     demoUnicodeStringStorage();
615     demoUnicodeStringInit();
616 
617     ucnv_close(cnv);
618     return 0;
619 }
620