xref: /aosp_15_r20/external/cronet/third_party/icu/source/i18n/ucol_sit.cpp (revision 6777b5387eb2ff775bb5750e3f5d96f37fb7352b)
1 // © 2016 and later: Unicode, Inc. and others.
2 // License & terms of use: http://www.unicode.org/copyright.html
3 /*
4 *******************************************************************************
5 *   Copyright (C) 2004-2016, International Business Machines
6 *   Corporation and others.  All Rights Reserved.
7 *******************************************************************************
8 *   file name:  ucol_sit.cpp
9 *   encoding:   UTF-8
10 *   tab size:   8 (not used)
11 *   indentation:4
12 *
13 * Modification history
14 * Date        Name      Comments
15 * 03/12/2004  weiv      Creation
16 */
17 
18 #include "unicode/ustring.h"
19 #include "unicode/udata.h"
20 #include "unicode/utf16.h"
21 #include "utracimp.h"
22 #include "ucol_imp.h"
23 #include "ulocimp.h"
24 #include "bytesinkutil.h"
25 #include "cmemory.h"
26 #include "cstring.h"
27 #include "uresimp.h"
28 #include "unicode/coll.h"
29 #include "unicode/stringpiece.h"
30 #include "charstr.h"
31 
32 U_NAMESPACE_USE
33 
34 #ifdef UCOL_TRACE_SIT
35 # include <stdio.h>
36 #endif
37 
38 #if !UCONFIG_NO_COLLATION
39 
40 #include "unicode/tblcoll.h"
41 
42 enum OptionsList {
43     UCOL_SIT_LANGUAGE = 0,
44     UCOL_SIT_SCRIPT   = 1,
45     UCOL_SIT_REGION   = 2,
46     UCOL_SIT_VARIANT  = 3,
47     UCOL_SIT_KEYWORD  = 4,
48     UCOL_SIT_PROVIDER = 5,
49     UCOL_SIT_LOCELEMENT_MAX = UCOL_SIT_PROVIDER, /* the last element that's part of LocElements */
50 
51     UCOL_SIT_BCP47,
52     UCOL_SIT_STRENGTH,
53     UCOL_SIT_CASE_LEVEL,
54     UCOL_SIT_CASE_FIRST,
55     UCOL_SIT_NUMERIC_COLLATION,
56     UCOL_SIT_ALTERNATE_HANDLING,
57     UCOL_SIT_NORMALIZATION_MODE,
58     UCOL_SIT_FRENCH_COLLATION,
59     UCOL_SIT_HIRAGANA_QUATERNARY,
60     UCOL_SIT_VARIABLE_TOP,
61     UCOL_SIT_VARIABLE_TOP_VALUE,
62     UCOL_SIT_ITEMS_COUNT
63 };
64 
65 /* option starters chars. */
66 static const char alternateHArg     = 'A';
67 static const char variableTopValArg = 'B';
68 static const char caseFirstArg      = 'C';
69 static const char numericCollArg    = 'D';
70 static const char caseLevelArg      = 'E';
71 static const char frenchCollArg     = 'F';
72 static const char hiraganaQArg      = 'H';
73 static const char keywordArg        = 'K';
74 static const char languageArg       = 'L';
75 static const char normArg           = 'N';
76 static const char providerArg       = 'P';
77 static const char regionArg         = 'R';
78 static const char strengthArg       = 'S';
79 static const char variableTopArg    = 'T';
80 static const char variantArg        = 'V';
81 static const char RFC3066Arg        = 'X';
82 static const char scriptArg         = 'Z';
83 
84 static const char collationKeyword[]  = "@collation=";
85 static const char providerKeyword[]  = "@sp=";
86 
87 
88 static const int32_t locElementCount = UCOL_SIT_LOCELEMENT_MAX+1;
89 static const int32_t locElementCapacity = 32;
90 static const int32_t loc3066Capacity = 256;
91 
92 /* structure containing specification of a collator. Initialized
93  * from a short string. Also used to construct a short string from a
94  * collator instance
95  */
96 struct CollatorSpec {
97     inline CollatorSpec();
98 
99     CharString locElements[locElementCount];
100     CharString locale;
101     UColAttributeValue options[UCOL_ATTRIBUTE_COUNT];
102     uint32_t variableTopValue;
103     char16_t variableTopString[locElementCapacity];
104     int32_t variableTopStringLen;
105     UBool variableTopSet;
106     CharString entries[UCOL_SIT_ITEMS_COUNT];
107 };
108 
CollatorSpec()109 CollatorSpec::CollatorSpec() :
110 locale(),
111 variableTopValue(0),
112 variableTopString(),
113 variableTopSet(false)
114  {
115     // set collation options to default
116     for(int32_t i = 0; i < UCOL_ATTRIBUTE_COUNT; i++) {
117         options[i] = UCOL_DEFAULT;
118     }
119 }
120 
121 
122 /* structure for converting between character attribute
123  * representation and real collation attribute value.
124  */
125 struct AttributeConversion {
126     char letter;
127     UColAttributeValue value;
128 };
129 
130 static const AttributeConversion conversions[12] = {
131     { '1', UCOL_PRIMARY },
132     { '2', UCOL_SECONDARY },
133     { '3', UCOL_TERTIARY },
134     { '4', UCOL_QUATERNARY },
135     { 'D', UCOL_DEFAULT },
136     { 'I', UCOL_IDENTICAL },
137     { 'L', UCOL_LOWER_FIRST },
138     { 'N', UCOL_NON_IGNORABLE },
139     { 'O', UCOL_ON },
140     { 'S', UCOL_SHIFTED },
141     { 'U', UCOL_UPPER_FIRST },
142     { 'X', UCOL_OFF }
143 };
144 
145 
146 static UColAttributeValue
ucol_sit_letterToAttributeValue(char letter,UErrorCode * status)147 ucol_sit_letterToAttributeValue(char letter, UErrorCode *status) {
148     uint32_t i = 0;
149     for(i = 0; i < UPRV_LENGTHOF(conversions); i++) {
150         if(conversions[i].letter == letter) {
151             return conversions[i].value;
152         }
153     }
154     *status = U_ILLEGAL_ARGUMENT_ERROR;
155 #ifdef UCOL_TRACE_SIT
156     fprintf(stderr, "%s:%d: unknown letter %c: %s\n", __FILE__, __LINE__, letter, u_errorName(*status));
157 #endif
158     return UCOL_DEFAULT;
159 }
160 
161 /* function prototype for functions used to parse a short string */
162 U_CDECL_BEGIN
163 typedef const char* U_CALLCONV
164 ActionFunction(CollatorSpec *spec, uint32_t value1, const char* string,
165                UErrorCode *status);
166 U_CDECL_END
167 
168 U_CDECL_BEGIN
169 static const char* U_CALLCONV
_processLocaleElement(CollatorSpec * spec,uint32_t value,const char * string,UErrorCode * status)170 _processLocaleElement(CollatorSpec *spec, uint32_t value, const char* string,
171                       UErrorCode *status)
172 {
173     do {
174         if(value == UCOL_SIT_LANGUAGE || value == UCOL_SIT_KEYWORD || value == UCOL_SIT_PROVIDER) {
175             spec->locElements[value].append(uprv_tolower(*string), *status);
176         } else {
177             spec->locElements[value].append(*string, *status);
178         }
179     } while(*(++string) != '_' && *string && U_SUCCESS(*status));
180     // don't skip the underscore at the end
181     return string;
182 }
183 U_CDECL_END
184 
185 U_CDECL_BEGIN
186 static const char* U_CALLCONV
_processRFC3066Locale(CollatorSpec * spec,uint32_t,const char * string,UErrorCode * status)187 _processRFC3066Locale(CollatorSpec *spec, uint32_t, const char* string,
188                       UErrorCode *status)
189 {
190     char terminator = *string;
191     string++;
192     const char *end = uprv_strchr(string+1, terminator);
193     if(end == nullptr || end - string >= loc3066Capacity) {
194         *status = U_BUFFER_OVERFLOW_ERROR;
195         return string;
196     } else {
197         spec->locale.copyFrom(CharString(string, static_cast<int32_t>(end-string), *status), *status);
198         return end+1;
199     }
200 }
201 
202 U_CDECL_END
203 
204 U_CDECL_BEGIN
205 static const char* U_CALLCONV
_processCollatorOption(CollatorSpec * spec,uint32_t option,const char * string,UErrorCode * status)206 _processCollatorOption(CollatorSpec *spec, uint32_t option, const char* string,
207                        UErrorCode *status)
208 {
209     spec->options[option] = ucol_sit_letterToAttributeValue(*string, status);
210     if((*(++string) != '_' && *string) || U_FAILURE(*status)) {
211 #ifdef UCOL_TRACE_SIT
212     fprintf(stderr, "%s:%d: unknown collator option at '%s': %s\n", __FILE__, __LINE__, string, u_errorName(*status));
213 #endif
214         *status = U_ILLEGAL_ARGUMENT_ERROR;
215     }
216     return string;
217 }
218 U_CDECL_END
219 
220 
221 static char16_t
readHexCodeUnit(const char ** string,UErrorCode * status)222 readHexCodeUnit(const char **string, UErrorCode *status)
223 {
224     char16_t result = 0;
225     int32_t value = 0;
226     char c;
227     int32_t noDigits = 0;
228     while((c = **string) != 0 && noDigits < 4) {
229         if( c >= '0' && c <= '9') {
230             value = c - '0';
231         } else if ( c >= 'a' && c <= 'f') {
232             value = c - 'a' + 10;
233         } else if ( c >= 'A' && c <= 'F') {
234             value = c - 'A' + 10;
235         } else {
236             *status = U_ILLEGAL_ARGUMENT_ERROR;
237 #ifdef UCOL_TRACE_SIT
238             fprintf(stderr, "%s:%d: Bad hex char at '%s': %s\n", __FILE__, __LINE__, *string, u_errorName(*status));
239 #endif
240             return 0;
241         }
242         result = (result << 4) | (char16_t)value;
243         noDigits++;
244         (*string)++;
245     }
246     // if the string was terminated before we read 4 digits, set an error
247     if(noDigits < 4) {
248         *status = U_ILLEGAL_ARGUMENT_ERROR;
249 #ifdef UCOL_TRACE_SIT
250         fprintf(stderr, "%s:%d: Short (only %d digits, wanted 4) at '%s': %s\n", __FILE__, __LINE__, noDigits,*string, u_errorName(*status));
251 #endif
252     }
253     return result;
254 }
255 
256 U_CDECL_BEGIN
257 static const char* U_CALLCONV
_processVariableTop(CollatorSpec * spec,uint32_t value1,const char * string,UErrorCode * status)258 _processVariableTop(CollatorSpec *spec, uint32_t value1, const char* string, UErrorCode *status)
259 {
260     // get four digits
261     int32_t i = 0;
262     if(!value1) {
263         while(U_SUCCESS(*status) && i < locElementCapacity && *string != 0 && *string != '_') {
264             spec->variableTopString[i++] = readHexCodeUnit(&string, status);
265         }
266         spec->variableTopStringLen = i;
267         if(i == locElementCapacity && *string != 0 && *string != '_') {
268             *status = U_BUFFER_OVERFLOW_ERROR;
269         }
270     } else {
271         spec->variableTopValue = readHexCodeUnit(&string, status);
272     }
273     if(U_SUCCESS(*status)) {
274         spec->variableTopSet = true;
275     }
276     return string;
277 }
278 U_CDECL_END
279 
280 
281 /* Table for parsing short strings */
282 struct ShortStringOptions {
283     char optionStart;
284     ActionFunction *action;
285     uint32_t attr;
286 };
287 
288 static const ShortStringOptions options[UCOL_SIT_ITEMS_COUNT] =
289 {
290 /* 10 ALTERNATE_HANDLING */   {alternateHArg,     _processCollatorOption, UCOL_ALTERNATE_HANDLING }, // alternate  N, S, D
291 /* 15 VARIABLE_TOP_VALUE */   {variableTopValArg, _processVariableTop,    1 },
292 /* 08 CASE_FIRST */           {caseFirstArg,      _processCollatorOption, UCOL_CASE_FIRST }, // case first L, U, X, D
293 /* 09 NUMERIC_COLLATION */    {numericCollArg,    _processCollatorOption, UCOL_NUMERIC_COLLATION }, // codan      O, X, D
294 /* 07 CASE_LEVEL */           {caseLevelArg,      _processCollatorOption, UCOL_CASE_LEVEL }, // case level O, X, D
295 /* 12 FRENCH_COLLATION */     {frenchCollArg,     _processCollatorOption, UCOL_FRENCH_COLLATION }, // french     O, X, D
296 /* 13 HIRAGANA_QUATERNARY] */ {hiraganaQArg,      _processCollatorOption, UCOL_HIRAGANA_QUATERNARY_MODE }, // hiragana   O, X, D
297 /* 04 KEYWORD */              {keywordArg,        _processLocaleElement,  UCOL_SIT_KEYWORD }, // keyword
298 /* 00 LANGUAGE */             {languageArg,       _processLocaleElement,  UCOL_SIT_LANGUAGE }, // language
299 /* 11 NORMALIZATION_MODE */   {normArg,           _processCollatorOption, UCOL_NORMALIZATION_MODE }, // norm       O, X, D
300 /* 02 REGION */               {regionArg,         _processLocaleElement,  UCOL_SIT_REGION }, // region
301 /* 06 STRENGTH */             {strengthArg,       _processCollatorOption, UCOL_STRENGTH }, // strength   1, 2, 3, 4, I, D
302 /* 14 VARIABLE_TOP */         {variableTopArg,    _processVariableTop,    0 },
303 /* 03 VARIANT */              {variantArg,        _processLocaleElement,  UCOL_SIT_VARIANT }, // variant
304 /* 05 RFC3066BIS */           {RFC3066Arg,        _processRFC3066Locale,  0 }, // rfc3066bis locale name
305 /* 01 SCRIPT */               {scriptArg,         _processLocaleElement,  UCOL_SIT_SCRIPT },  // script
306 /*    PROVIDER */             {providerArg,       _processLocaleElement, UCOL_SIT_PROVIDER }
307 };
308 
309 
310 static
ucol_sit_readOption(const char * start,CollatorSpec * spec,UErrorCode * status)311 const char* ucol_sit_readOption(const char *start, CollatorSpec *spec,
312                             UErrorCode *status)
313 {
314   int32_t i = 0;
315 
316   for(i = 0; i < UCOL_SIT_ITEMS_COUNT; i++) {
317       if(*start == options[i].optionStart) {
318           const char* end = options[i].action(spec, options[i].attr, start+1, status);
319 #ifdef UCOL_TRACE_SIT
320           fprintf(stderr, "***Set %d to %s...\n", i, start);
321 #endif
322           // assume 'start' does not go away through all this
323           spec->entries[i].copyFrom(CharString(start, (int32_t)(end - start), *status), *status);
324           return end;
325       }
326   }
327   *status = U_ILLEGAL_ARGUMENT_ERROR;
328 #ifdef UCOL_TRACE_SIT
329   fprintf(stderr, "%s:%d: Unknown option at '%s': %s\n", __FILE__, __LINE__, start, u_errorName(*status));
330 #endif
331   return start;
332 }
333 
334 static const char*
ucol_sit_readSpecs(CollatorSpec * s,const char * string,UParseError * parseError,UErrorCode * status)335 ucol_sit_readSpecs(CollatorSpec *s, const char *string,
336                         UParseError *parseError, UErrorCode *status)
337 {
338     const char *definition = string;
339     while(U_SUCCESS(*status) && *string) {
340         string = ucol_sit_readOption(string, s, status);
341         // advance over '_'
342         while(*string && *string == '_') {
343             string++;
344         }
345     }
346     if(U_FAILURE(*status)) {
347         parseError->offset = (int32_t)(string - definition);
348     }
349     return string;
350 }
351 
352 static
ucol_sit_dumpSpecs(CollatorSpec * s,char * destination,int32_t capacity,UErrorCode * status)353 int32_t ucol_sit_dumpSpecs(CollatorSpec *s, char *destination, int32_t capacity, UErrorCode *status)
354 {
355     int32_t i = 0, j = 0;
356     int32_t len = 0;
357     char optName;
358     if(U_SUCCESS(*status)) {
359         for(i = 0; i < UCOL_SIT_ITEMS_COUNT; i++) {
360             if(!s->entries[i].isEmpty()) {
361                 if(len) {
362                     if(len < capacity) {
363                         uprv_strcat(destination, "_");
364                     }
365                     len++;
366                 }
367                 optName = s->entries[i][0];
368                 if(optName == languageArg || optName == regionArg || optName == variantArg || optName == keywordArg) {
369                     for(j = 0; j < s->entries[i].length(); j++) {
370                         if(len + j < capacity) {
371                             destination[len+j] = uprv_toupper(s->entries[i][j]);
372                         }
373                     }
374                     len += s->entries[i].length();
375                 } else {
376                     len += s->entries[i].extract(destination + len, capacity - len, *status);
377                 }
378             }
379         }
380         return len;
381     } else {
382         return 0;
383     }
384 }
385 
386 static void
ucol_sit_calculateWholeLocale(CollatorSpec * s,UErrorCode & status)387 ucol_sit_calculateWholeLocale(CollatorSpec *s, UErrorCode &status) {
388     // put the locale together, unless we have a done
389     // locale
390     if(s->locale.isEmpty()) {
391         // first the language
392         s->locale.append(s->locElements[UCOL_SIT_LANGUAGE], status);
393         // then the script, if present
394         if(!s->locElements[UCOL_SIT_SCRIPT].isEmpty()) {
395             s->locale.append("_", status);
396             s->locale.append(s->locElements[UCOL_SIT_SCRIPT], status);
397         }
398         // then the region, if present
399         if(!s->locElements[UCOL_SIT_REGION].isEmpty()) {
400             s->locale.append("_", status);
401             s->locale.append(s->locElements[UCOL_SIT_REGION], status);
402         } else if(!s->locElements[UCOL_SIT_VARIANT].isEmpty()) { // if there is a variant, we need an underscore
403             s->locale.append("_", status);
404         }
405         // add variant, if there
406         if(!s->locElements[UCOL_SIT_VARIANT].isEmpty()) {
407             s->locale.append("_", status);
408             s->locale.append(s->locElements[UCOL_SIT_VARIANT], status);
409         }
410 
411         // if there is a collation keyword, add that too
412         if(!s->locElements[UCOL_SIT_KEYWORD].isEmpty()) {
413             s->locale.append(collationKeyword, status);
414             s->locale.append(s->locElements[UCOL_SIT_KEYWORD], status);
415         }
416 
417         // if there is a provider keyword, add that too
418         if(!s->locElements[UCOL_SIT_PROVIDER].isEmpty()) {
419             s->locale.append(providerKeyword, status);
420             s->locale.append(s->locElements[UCOL_SIT_PROVIDER], status);
421         }
422     }
423 }
424 
425 
426 U_CAPI void U_EXPORT2
ucol_prepareShortStringOpen(const char * definition,UBool,UParseError * parseError,UErrorCode * status)427 ucol_prepareShortStringOpen( const char *definition,
428                           UBool,
429                           UParseError *parseError,
430                           UErrorCode *status)
431 {
432     if(U_FAILURE(*status)) return;
433 
434     UParseError internalParseError;
435 
436     if(!parseError) {
437         parseError = &internalParseError;
438     }
439     parseError->line = 0;
440     parseError->offset = 0;
441     parseError->preContext[0] = 0;
442     parseError->postContext[0] = 0;
443 
444 
445     // first we want to pick stuff out of short string.
446     // we'll end up with an UCA version, locale and a bunch of
447     // settings
448 
449     // analyse the string in order to get everything we need.
450     CollatorSpec s;
451     ucol_sit_readSpecs(&s, definition, parseError, status);
452     ucol_sit_calculateWholeLocale(&s, *status);
453 
454     CharString buffer;
455     {
456         CharStringByteSink sink(&buffer);
457         ulocimp_canonicalize(s.locale.data(), sink, status);
458     }
459 
460     UResourceBundle *b = ures_open(U_ICUDATA_COLL, buffer.data(), status);
461     /* we try to find stuff from keyword */
462     UResourceBundle *collations = ures_getByKey(b, "collations", nullptr, status);
463     UResourceBundle *collElem = nullptr;
464     CharString keyBuffer;
465     {
466         // if there is a keyword, we pick it up and try to get elements
467         CharStringByteSink sink(&keyBuffer);
468         ulocimp_getKeywordValue(buffer.data(), "collation", sink, status);
469     }
470     if(keyBuffer.isEmpty()) {
471       // no keyword
472       // we try to find the default setting, which will give us the keyword value
473       UResourceBundle *defaultColl = ures_getByKeyWithFallback(collations, "default", nullptr, status);
474       if(U_SUCCESS(*status)) {
475         int32_t defaultKeyLen = 0;
476         const char16_t *defaultKey = ures_getString(defaultColl, &defaultKeyLen, status);
477         keyBuffer.appendInvariantChars(defaultKey, defaultKeyLen, *status);
478       } else {
479         *status = U_INTERNAL_PROGRAM_ERROR;
480         return;
481       }
482       ures_close(defaultColl);
483     }
484     collElem = ures_getByKeyWithFallback(collations, keyBuffer.data(), collElem, status);
485     ures_close(collElem);
486     ures_close(collations);
487     ures_close(b);
488 }
489 
490 
491 U_CAPI UCollator* U_EXPORT2
ucol_openFromShortString(const char * definition,UBool forceDefaults,UParseError * parseError,UErrorCode * status)492 ucol_openFromShortString( const char *definition,
493                           UBool forceDefaults,
494                           UParseError *parseError,
495                           UErrorCode *status)
496 {
497     UTRACE_ENTRY_OC(UTRACE_UCOL_OPEN_FROM_SHORT_STRING);
498     UTRACE_DATA1(UTRACE_INFO, "short string = \"%s\"", definition);
499 
500     if(U_FAILURE(*status)) return 0;
501 
502     UParseError internalParseError;
503 
504     if(!parseError) {
505         parseError = &internalParseError;
506     }
507     parseError->line = 0;
508     parseError->offset = 0;
509     parseError->preContext[0] = 0;
510     parseError->postContext[0] = 0;
511 
512 
513     // first we want to pick stuff out of short string.
514     // we'll end up with an UCA version, locale and a bunch of
515     // settings
516 
517     // analyse the string in order to get everything we need.
518     const char *string = definition;
519     CollatorSpec s;
520     string = ucol_sit_readSpecs(&s, definition, parseError, status);
521     ucol_sit_calculateWholeLocale(&s, *status);
522 
523 #ifdef UCOL_TRACE_SIT
524     fprintf(stderr, "DEF %s, DATA %s, ERR %s\n", definition, s.locale.data(), u_errorName(*status));
525 #endif
526     CharString buffer;
527     {
528         CharStringByteSink sink(&buffer);
529         ulocimp_canonicalize(s.locale.data(), sink, status);
530     }
531 
532     UCollator *result = ucol_open(buffer.data(), status);
533     int32_t i = 0;
534 
535     for(i = 0; i < UCOL_ATTRIBUTE_COUNT; i++) {
536         if(s.options[i] != UCOL_DEFAULT) {
537             if(forceDefaults || ucol_getAttribute(result, (UColAttribute)i, status) != s.options[i]) {
538                 ucol_setAttribute(result, (UColAttribute)i, s.options[i], status);
539             }
540 
541             if(U_FAILURE(*status)) {
542                 parseError->offset = (int32_t)(string - definition);
543                 ucol_close(result);
544                 return nullptr;
545             }
546 
547         }
548     }
549     if(s.variableTopSet) {
550         if(s.variableTopString[0]) {
551             ucol_setVariableTop(result, s.variableTopString, s.variableTopStringLen, status);
552         } else { // we set by value, using 'B'
553             ucol_restoreVariableTop(result, s.variableTopValue, status);
554         }
555     }
556 
557 
558     if(U_FAILURE(*status)) { // here it can only be a bogus value
559         ucol_close(result);
560         result = nullptr;
561     }
562 
563     UTRACE_EXIT_PTR_STATUS(result, *status);
564     return result;
565 }
566 
567 
568 U_CAPI int32_t U_EXPORT2
ucol_getShortDefinitionString(const UCollator * coll,const char * locale,char * dst,int32_t capacity,UErrorCode * status)569 ucol_getShortDefinitionString(const UCollator *coll,
570                               const char *locale,
571                               char *dst,
572                               int32_t capacity,
573                               UErrorCode *status)
574 {
575     if(U_FAILURE(*status)) return 0;
576     if(coll == nullptr) {
577         *status = U_ILLEGAL_ARGUMENT_ERROR;
578         return 0;
579     }
580     return ((icu::Collator*)coll)->internalGetShortDefinitionString(locale,dst,capacity,*status);
581 }
582 
583 U_CAPI int32_t U_EXPORT2
ucol_normalizeShortDefinitionString(const char * definition,char * destination,int32_t capacity,UParseError * parseError,UErrorCode * status)584 ucol_normalizeShortDefinitionString(const char *definition,
585                                     char *destination,
586                                     int32_t capacity,
587                                     UParseError *parseError,
588                                     UErrorCode *status)
589 {
590 
591     if(U_FAILURE(*status)) {
592         return 0;
593     }
594 
595     if(destination) {
596         uprv_memset(destination, 0, capacity*sizeof(char));
597     }
598 
599     UParseError pe;
600     if(!parseError) {
601         parseError = &pe;
602     }
603 
604     // validate
605     CollatorSpec s;
606     ucol_sit_readSpecs(&s, definition, parseError, status);
607     return ucol_sit_dumpSpecs(&s, destination, capacity, status);
608 }
609 
610 /**
611  * Get a set containing the contractions defined by the collator. The set includes
612  * both the UCA contractions and the contractions defined by the collator
613  * @param coll collator
614  * @param conts the set to hold the result
615  * @param status to hold the error code
616  * @return the size of the contraction set
617  */
618 U_CAPI int32_t U_EXPORT2
ucol_getContractions(const UCollator * coll,USet * contractions,UErrorCode * status)619 ucol_getContractions( const UCollator *coll,
620                   USet *contractions,
621                   UErrorCode *status)
622 {
623   ucol_getContractionsAndExpansions(coll, contractions, nullptr, false, status);
624   return uset_getItemCount(contractions);
625 }
626 
627 /**
628  * Get a set containing the expansions defined by the collator. The set includes
629  * both the UCA expansions and the expansions defined by the tailoring
630  * @param coll collator
631  * @param conts the set to hold the result
632  * @param addPrefixes add the prefix contextual elements to contractions
633  * @param status to hold the error code
634  *
635  * @draft ICU 3.4
636  */
637 U_CAPI void U_EXPORT2
ucol_getContractionsAndExpansions(const UCollator * coll,USet * contractions,USet * expansions,UBool addPrefixes,UErrorCode * status)638 ucol_getContractionsAndExpansions( const UCollator *coll,
639                   USet *contractions,
640                   USet *expansions,
641                   UBool addPrefixes,
642                   UErrorCode *status)
643 {
644     if(U_FAILURE(*status)) {
645         return;
646     }
647     if(coll == nullptr) {
648         *status = U_ILLEGAL_ARGUMENT_ERROR;
649         return;
650     }
651     const icu::RuleBasedCollator *rbc = icu::RuleBasedCollator::rbcFromUCollator(coll);
652     if(rbc == nullptr) {
653         *status = U_UNSUPPORTED_ERROR;
654         return;
655     }
656     rbc->internalGetContractionsAndExpansions(
657             icu::UnicodeSet::fromUSet(contractions),
658             icu::UnicodeSet::fromUSet(expansions),
659             addPrefixes, *status);
660 }
661 #endif
662