]> git.saurik.com Git - apple/icu.git/blob - icuSources/i18n/ucol_sit.cpp
ICU-8.11.1.tar.gz
[apple/icu.git] / icuSources / i18n / ucol_sit.cpp
1 /*
2 *******************************************************************************
3 * Copyright (C) 2004-2006, International Business Machines
4 * Corporation and others. All Rights Reserved.
5 *******************************************************************************
6 * file name: ucol_sit.cpp
7 * encoding: US-ASCII
8 * tab size: 8 (not used)
9 * indentation:4
10 *
11 * Modification history
12 * Date Name Comments
13 * 03/12/2004 weiv Creation
14 */
15
16 #include "unicode/ustring.h"
17
18 #include "utracimp.h"
19 #include "ucol_imp.h"
20 #include "ucol_tok.h"
21 #include "unormimp.h"
22 #include "cmemory.h"
23 #include "cstring.h"
24
25 #if !UCONFIG_NO_COLLATION
26
27 enum OptionsList {
28 UCOL_SIT_LANGUAGE = 0,
29 UCOL_SIT_SCRIPT,
30 UCOL_SIT_REGION,
31 UCOL_SIT_VARIANT,
32 UCOL_SIT_KEYWORD,
33 UCOL_SIT_RFC3166BIS,
34 UCOL_SIT_STRENGTH,
35 UCOL_SIT_CASE_LEVEL,
36 UCOL_SIT_CASE_FIRST,
37 UCOL_SIT_NUMERIC_COLLATION,
38 UCOL_SIT_ALTERNATE_HANDLING,
39 UCOL_SIT_NORMALIZATION_MODE,
40 UCOL_SIT_FRENCH_COLLATION,
41 UCOL_SIT_HIRAGANA_QUATERNARY,
42 UCOL_SIT_VARIABLE_TOP,
43 UCOL_SIT_VARIABLE_TOP_VALUE,
44 UCOL_SIT_ITEMS_COUNT
45 };
46
47 /* list of locales for packing of a collator to an integer.
48 * This list corresponds to ICU 3.0. If more collation bearing
49 * locales are added in the future, this won't be a simple array
50 * but a mapping allowing forward and reverse lookup would have to
51 * be established. Currently, the mapping is from locale name to
52 * index.
53 */
54 static const char* const locales[] = {
55 /* 00 - 09 */ "ar", "be", "bg", "ca", "cs", "da", "de", "de__PHONEBOOK", "el", "en",
56 /* 10 - 19 */ "en_BE", "eo", "es", "es__TRADITIONAL", "et", "fa", "fa_AF", "fi", "fo", "fr",
57 /* 20 - 29 */ "gu", "he", "hi", "hi__DIRECT", "hr", "hu", "is", "it", "ja", "kk",
58 /* 30 - 39 */ "kl", "kn", "ko", "lt", "lv", "mk", "mr", "mt", "nb", "nn",
59 /* 40 - 49 */ "om", "pa", "pl", "ps", "ro", "root", "ru", "sh", "sk", "sl",
60 /* 50 - 59 */ "sq", "sr", "sv", "ta", "te", "th", "tr", "uk", "vi", "zh",
61 /* 60 - 64 */ "zh_HK", "zh_MO", "zh_TW", "zh_TW_STROKE", "zh__PINYIN"
62 };
63
64 static const char* const keywords[] = {
65 /* 00 */ "",
66 /* 01 */ "direct",
67 /* 02 */ "phonebook",
68 /* 03 */ "pinyin",
69 /* 04 */ "standard",
70 /* 05 */ "stroke",
71 /* 06 */ "traditional"
72 };
73
74
75 /* option starters chars. */
76 static const char alternateHArg = 'A';
77 static const char variableTopValArg = 'B';
78 static const char caseFirstArg = 'C';
79 static const char numericCollArg = 'D';
80 static const char caseLevelArg = 'E';
81 static const char frenchCollArg = 'F';
82 static const char hiraganaQArg = 'H';
83 static const char keywordArg = 'K';
84 static const char languageArg = 'L';
85 static const char normArg = 'N';
86 static const char regionArg = 'R';
87 static const char strengthArg = 'S';
88 static const char variableTopArg = 'T';
89 static const char variantArg = 'V';
90 static const char RFC3066Arg = 'X';
91 static const char scriptArg = 'Z';
92
93 static const char collationKeyword[] = "@collation=";
94
95 static const int32_t locElementCount = 5;
96 static const int32_t locElementCapacity = 32;
97 static const int32_t loc3066Capacity = 256;
98 static const int32_t internalBufferSize = 512;
99
100 /* structure containing specification of a collator. Initialized
101 * from a short string. Also used to construct a short string from a
102 * collator instance
103 */
104 struct CollatorSpec {
105 char locElements[locElementCount][locElementCapacity];
106 char locale[loc3066Capacity];
107 UColAttributeValue options[UCOL_ATTRIBUTE_COUNT];
108 uint32_t variableTopValue;
109 UChar variableTopString[locElementCapacity];
110 int32_t variableTopStringLen;
111 UBool variableTopSet;
112 struct {
113 const char *start;
114 int32_t len;
115 } entries[UCOL_SIT_ITEMS_COUNT];
116 };
117
118
119 /* structure for converting between character attribute
120 * representation and real collation attribute value.
121 */
122 struct AttributeConversion {
123 char letter;
124 UColAttributeValue value;
125 };
126
127 static const AttributeConversion conversions[12] = {
128 { '1', UCOL_PRIMARY },
129 { '2', UCOL_SECONDARY },
130 { '3', UCOL_TERTIARY },
131 { '4', UCOL_QUATERNARY },
132 { 'D', UCOL_DEFAULT },
133 { 'I', UCOL_IDENTICAL },
134 { 'L', UCOL_LOWER_FIRST },
135 { 'N', UCOL_NON_IGNORABLE },
136 { 'O', UCOL_ON },
137 { 'S', UCOL_SHIFTED },
138 { 'U', UCOL_UPPER_FIRST },
139 { 'X', UCOL_OFF }
140 };
141
142
143 static char
144 ucol_sit_attributeValueToLetter(UColAttributeValue value, UErrorCode *status) {
145 uint32_t i = 0;
146 for(i = 0; i < sizeof(conversions)/sizeof(conversions[0]); i++) {
147 if(conversions[i].value == value) {
148 return conversions[i].letter;
149 }
150 }
151 *status = U_ILLEGAL_ARGUMENT_ERROR;
152 return 0;
153 }
154
155 static UColAttributeValue
156 ucol_sit_letterToAttributeValue(char letter, UErrorCode *status) {
157 uint32_t i = 0;
158 for(i = 0; i < sizeof(conversions)/sizeof(conversions[0]); i++) {
159 if(conversions[i].letter == letter) {
160 return conversions[i].value;
161 }
162 }
163 *status = U_ILLEGAL_ARGUMENT_ERROR;
164 return UCOL_DEFAULT;
165 }
166
167 /* function prototype for functions used to parse a short string */
168 U_CDECL_BEGIN
169 typedef const char* U_CALLCONV
170 ActionFunction(CollatorSpec *spec, uint32_t value1, const char* string,
171 UErrorCode *status);
172 U_CDECL_END
173
174 U_CDECL_BEGIN
175 static const char* U_CALLCONV
176 _processLocaleElement(CollatorSpec *spec, uint32_t value, const char* string,
177 UErrorCode *status)
178 {
179 int32_t len = 0;
180 do {
181 if(value == 0 || value == 4) {
182 spec->locElements[value][len++] = uprv_tolower(*string);
183 } else {
184 spec->locElements[value][len++] = *string;
185 }
186 } while(*(++string) != '_' && *string && len < locElementCapacity);
187 if(len >= locElementCapacity) {
188 *status = U_BUFFER_OVERFLOW_ERROR;
189 return string;
190 }
191 // don't skip the underscore at the end
192 return string;
193 }
194 U_CDECL_END
195
196 U_CDECL_BEGIN
197 static const char* U_CALLCONV
198 _processRFC3066Locale(CollatorSpec *spec, uint32_t, const char* string,
199 UErrorCode *status)
200 {
201 char terminator = *string;
202 string++;
203 const char *end = uprv_strchr(string+1, terminator);
204 if(end == NULL || end - string >= loc3066Capacity) {
205 *status = U_BUFFER_OVERFLOW_ERROR;
206 return string;
207 } else {
208 uprv_strncpy(spec->locale, string, end-string);
209 return end+1;
210 }
211 }
212
213 U_CDECL_END
214
215 U_CDECL_BEGIN
216 static const char* U_CALLCONV
217 _processCollatorOption(CollatorSpec *spec, uint32_t option, const char* string,
218 UErrorCode *status)
219 {
220 spec->options[option] = ucol_sit_letterToAttributeValue(*string, status);
221 if((*(++string) != '_' && *string) || U_FAILURE(*status)) {
222 *status = U_ILLEGAL_ARGUMENT_ERROR;
223 }
224 return string;
225 }
226 U_CDECL_END
227
228
229 static UChar
230 readHexCodeUnit(const char **string, UErrorCode *status)
231 {
232 UChar result = 0;
233 int32_t value = 0;
234 char c;
235 int32_t noDigits = 0;
236 while((c = **string) != 0 && noDigits < 4) {
237 if( c >= '0' && c <= '9') {
238 value = c - '0';
239 } else if ( c >= 'a' && c <= 'f') {
240 value = c - 'a' + 10;
241 } else if ( c >= 'A' && c <= 'F') {
242 value = c - 'A' + 10;
243 } else {
244 *status = U_ILLEGAL_ARGUMENT_ERROR;
245 return 0;
246 }
247 result = (result << 4) | (UChar)value;
248 noDigits++;
249 (*string)++;
250 }
251 // if the string was terminated before we read 4 digits, set an error
252 if(noDigits < 4) {
253 *status = U_ILLEGAL_ARGUMENT_ERROR;
254 }
255 return result;
256 }
257
258 U_CDECL_BEGIN
259 static const char* U_CALLCONV
260 _processVariableTop(CollatorSpec *spec, uint32_t value1, const char* string, UErrorCode *status)
261 {
262 // get four digits
263 int32_t i = 0;
264 if(!value1) {
265 while(U_SUCCESS(*status) && i < locElementCapacity && *string != 0 && *string != '_') {
266 spec->variableTopString[i++] = readHexCodeUnit(&string, status);
267 }
268 spec->variableTopStringLen = i;
269 if(i == locElementCapacity && (*string != 0 || *string != '_')) {
270 *status = U_BUFFER_OVERFLOW_ERROR;
271 }
272 } else {
273 spec->variableTopValue = readHexCodeUnit(&string, status);
274 }
275 if(U_SUCCESS(*status)) {
276 spec->variableTopSet = TRUE;
277 }
278 return string;
279 }
280 U_CDECL_END
281
282
283 /* Table for parsing short strings */
284 struct ShortStringOptions {
285 char optionStart;
286 ActionFunction *action;
287 uint32_t attr;
288 };
289
290 static const ShortStringOptions options[UCOL_SIT_ITEMS_COUNT] =
291 {
292 /* 10 ALTERNATE_HANDLING */ {alternateHArg, _processCollatorOption, UCOL_ALTERNATE_HANDLING }, // alternate N, S, D
293 /* 15 VARIABLE_TOP_VALUE */ {variableTopValArg, _processVariableTop, 1 },
294 /* 08 CASE_FIRST */ {caseFirstArg, _processCollatorOption, UCOL_CASE_FIRST }, // case first L, U, X, D
295 /* 09 NUMERIC_COLLATION */ {numericCollArg, _processCollatorOption, UCOL_NUMERIC_COLLATION }, // codan O, X, D
296 /* 07 CASE_LEVEL */ {caseLevelArg, _processCollatorOption, UCOL_CASE_LEVEL }, // case level O, X, D
297 /* 12 FRENCH_COLLATION */ {frenchCollArg, _processCollatorOption, UCOL_FRENCH_COLLATION }, // french O, X, D
298 /* 13 HIRAGANA_QUATERNARY] */ {hiraganaQArg, _processCollatorOption, UCOL_HIRAGANA_QUATERNARY_MODE }, // hiragana O, X, D
299 /* 04 KEYWORD */ {keywordArg, _processLocaleElement, 4 }, // keyword
300 /* 00 LANGUAGE */ {languageArg, _processLocaleElement, 0 }, // language
301 /* 11 NORMALIZATION_MODE */ {normArg, _processCollatorOption, UCOL_NORMALIZATION_MODE }, // norm O, X, D
302 /* 02 REGION */ {regionArg, _processLocaleElement, 2 }, // region
303 /* 06 STRENGTH */ {strengthArg, _processCollatorOption, UCOL_STRENGTH }, // strength 1, 2, 3, 4, I, D
304 /* 14 VARIABLE_TOP */ {variableTopArg, _processVariableTop, 0 },
305 /* 03 VARIANT */ {variantArg, _processLocaleElement, 3 }, // variant
306 /* 05 RFC3066BIS */ {RFC3066Arg, _processRFC3066Locale, 0 }, // rfc3066bis locale name
307 /* 01 SCRIPT */ {scriptArg, _processLocaleElement, 1 } // script
308 };
309
310
311 static
312 const char* ucol_sit_readOption(const char *start, CollatorSpec *spec,
313 UErrorCode *status)
314 {
315 int32_t i = 0;
316
317 for(i = 0; i < UCOL_SIT_ITEMS_COUNT; i++) {
318 if(*start == options[i].optionStart) {
319 spec->entries[i].start = start;
320 const char* end = options[i].action(spec, options[i].attr, start+1, status);
321 spec->entries[i].len = end - start;
322 return end;
323 }
324 }
325 *status = U_ILLEGAL_ARGUMENT_ERROR;
326 return start;
327 }
328
329 static
330 void ucol_sit_initCollatorSpecs(CollatorSpec *spec)
331 {
332 // reset everything
333 uprv_memset(spec, 0, sizeof(CollatorSpec));
334 // set collation options to default
335 int32_t i = 0;
336 for(i = 0; i < UCOL_ATTRIBUTE_COUNT; i++) {
337 spec->options[i] = UCOL_DEFAULT;
338 }
339 }
340
341 static const char*
342 ucol_sit_readSpecs(CollatorSpec *s, const char *string,
343 UParseError *parseError, UErrorCode *status)
344 {
345 const char *definition = string;
346 while(U_SUCCESS(*status) && *string) {
347 string = ucol_sit_readOption(string, s, status);
348 // advance over '_'
349 while(*string && *string == '_') {
350 string++;
351 }
352 }
353 if(U_FAILURE(*status)) {
354 parseError->offset = string - definition;
355 }
356 return string;
357 }
358
359 static
360 int32_t ucol_sit_dumpSpecs(CollatorSpec *s, char *destination, int32_t capacity, UErrorCode *status)
361 {
362 int32_t i = 0, j = 0;
363 int32_t len = 0;
364 char optName;
365 if(U_SUCCESS(*status)) {
366 for(i = 0; i < UCOL_SIT_ITEMS_COUNT; i++) {
367 if(s->entries[i].start) {
368 if(len) {
369 if(len < capacity) {
370 uprv_strcat(destination, "_");
371 }
372 len++;
373 }
374 optName = *(s->entries[i].start);
375 if(optName == languageArg || optName == regionArg || optName == variantArg || optName == keywordArg) {
376 for(j = 0; j < s->entries[i].len; j++) {
377 if(len + j < capacity) {
378 destination[len+j] = uprv_toupper(*(s->entries[i].start+j));
379 }
380 }
381 len += s->entries[i].len;
382 } else {
383 len += s->entries[i].len;
384 if(len < capacity) {
385 uprv_strncat(destination,s->entries[i].start, s->entries[i].len);
386 }
387 }
388 }
389 }
390 return len;
391 } else {
392 return 0;
393 }
394 }
395
396 static void
397 ucol_sit_calculateWholeLocale(CollatorSpec *s) {
398 // put the locale together, unless we have a done
399 // locale
400 if(s->locale[0] == 0) {
401 // first the language
402 uprv_strcat(s->locale, s->locElements[0]);
403 // then the script, if present
404 if(*(s->locElements[1])) {
405 uprv_strcat(s->locale, "_");
406 uprv_strcat(s->locale, s->locElements[1]);
407 }
408 // then the region, if present
409 if(*(s->locElements[2])) {
410 uprv_strcat(s->locale, "_");
411 uprv_strcat(s->locale, s->locElements[2]);
412 } else if(*(s->locElements[3])) { // if there is a variant, we need an underscore
413 uprv_strcat(s->locale, "_");
414 }
415 // add variant, if there
416 if(*(s->locElements[3])) {
417 uprv_strcat(s->locale, "_");
418 uprv_strcat(s->locale, s->locElements[3]);
419 }
420
421 // if there is a collation keyword, add that too
422 if(*(s->locElements[4])) {
423 uprv_strcat(s->locale, collationKeyword);
424 uprv_strcat(s->locale, s->locElements[4]);
425 }
426 }
427 }
428
429
430 U_CAPI void U_EXPORT2
431 ucol_prepareShortStringOpen( const char *definition,
432 UBool,
433 UParseError *parseError,
434 UErrorCode *status)
435 {
436 if(U_FAILURE(*status)) return;
437
438 UParseError internalParseError;
439
440 if(!parseError) {
441 parseError = &internalParseError;
442 }
443 parseError->line = 0;
444 parseError->offset = 0;
445 parseError->preContext[0] = 0;
446 parseError->postContext[0] = 0;
447
448
449 // first we want to pick stuff out of short string.
450 // we'll end up with an UCA version, locale and a bunch of
451 // settings
452
453 // analyse the string in order to get everything we need.
454 const char *string = definition;
455 CollatorSpec s;
456 ucol_sit_initCollatorSpecs(&s);
457 string = ucol_sit_readSpecs(&s, definition, parseError, status);
458 ucol_sit_calculateWholeLocale(&s);
459
460 char buffer[internalBufferSize];
461 uprv_memset(buffer, 0, internalBufferSize);
462 uloc_canonicalize(s.locale, buffer, internalBufferSize, status);
463
464 UResourceBundle *b = ures_open(U_ICUDATA_COLL, buffer, status);
465 /* we try to find stuff from keyword */
466 UResourceBundle *collations = ures_getByKey(b, "collations", NULL, status);
467 UResourceBundle *collElem = NULL;
468 char keyBuffer[256];
469 // if there is a keyword, we pick it up and try to get elements
470 if(!uloc_getKeywordValue(buffer, "collation", keyBuffer, 256, status)) {
471 // no keyword. we try to find the default setting, which will give us the keyword value
472 UResourceBundle *defaultColl = ures_getByKeyWithFallback(collations, "default", NULL, status);
473 if(U_SUCCESS(*status)) {
474 int32_t defaultKeyLen = 0;
475 const UChar *defaultKey = ures_getString(defaultColl, &defaultKeyLen, status);
476 u_UCharsToChars(defaultKey, keyBuffer, defaultKeyLen);
477 keyBuffer[defaultKeyLen] = 0;
478 } else {
479 *status = U_INTERNAL_PROGRAM_ERROR;
480 return;
481 }
482 ures_close(defaultColl);
483 }
484 collElem = ures_getByKeyWithFallback(collations, keyBuffer, collElem, status);
485 ures_close(collElem);
486 ures_close(collations);
487 ures_close(b);
488 }
489
490
491 U_CAPI UCollator* U_EXPORT2
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 ucol_sit_initCollatorSpecs(&s);
521 string = ucol_sit_readSpecs(&s, definition, parseError, status);
522 ucol_sit_calculateWholeLocale(&s);
523
524 char buffer[internalBufferSize];
525 uprv_memset(buffer, 0, internalBufferSize);
526 uloc_canonicalize(s.locale, buffer, internalBufferSize, status);
527
528 UCollator *result = ucol_open(buffer, status);
529 int32_t i = 0;
530
531 for(i = 0; i < UCOL_ATTRIBUTE_COUNT; i++) {
532 if(s.options[i] != UCOL_DEFAULT) {
533 if(forceDefaults || ucol_getAttribute(result, (UColAttribute)i, status) != s.options[i]) {
534 ucol_setAttribute(result, (UColAttribute)i, s.options[i], status);
535 }
536
537 if(U_FAILURE(*status)) {
538 parseError->offset = string - definition;
539 ucol_close(result);
540 return NULL;
541 }
542
543 }
544 }
545 if(s.variableTopSet) {
546 if(s.variableTopString[0]) {
547 ucol_setVariableTop(result, s.variableTopString, s.variableTopStringLen, status);
548 } else { // we set by value, using 'B'
549 ucol_restoreVariableTop(result, s.variableTopValue, status);
550 }
551 }
552
553
554 if(U_FAILURE(*status)) { // here it can only be a bogus value
555 ucol_close(result);
556 result = NULL;
557 }
558
559 UTRACE_EXIT_PTR_STATUS(result, *status);
560 return result;
561 }
562
563
564 static void appendShortStringElement(const char *src, int32_t len, char *result, int32_t *resultSize, int32_t capacity, char arg)
565 {
566 if(len) {
567 if(*resultSize) {
568 if(*resultSize < capacity) {
569 uprv_strcat(result, "_");
570 }
571 (*resultSize)++;
572 }
573 *resultSize += len + 1;
574 if(*resultSize < capacity) {
575 uprv_strncat(result, &arg, 1);
576 uprv_strncat(result, src, len);
577 }
578 }
579 }
580
581 U_CAPI int32_t U_EXPORT2
582 ucol_getShortDefinitionString(const UCollator *coll,
583 const char *locale,
584 char *dst,
585 int32_t capacity,
586 UErrorCode *status)
587 {
588 if(U_FAILURE(*status)) return 0;
589 char buffer[internalBufferSize];
590 uprv_memset(buffer, 0, internalBufferSize*sizeof(char));
591 int32_t resultSize = 0;
592 char tempbuff[internalBufferSize];
593 char locBuff[internalBufferSize];
594 uprv_memset(buffer, 0, internalBufferSize*sizeof(char));
595 int32_t elementSize = 0;
596 UBool isAvailable = 0;
597 CollatorSpec s;
598 ucol_sit_initCollatorSpecs(&s);
599
600 if(!locale) {
601 locale = ucol_getLocale(coll, ULOC_VALID_LOCALE, status);
602 }
603 elementSize = ucol_getFunctionalEquivalent(locBuff, internalBufferSize, "collation", locale, &isAvailable, status);
604
605 if(elementSize) {
606 // we should probably canonicalize here...
607 elementSize = uloc_getLanguage(locBuff, tempbuff, internalBufferSize, status);
608 appendShortStringElement(tempbuff, elementSize, buffer, &resultSize, capacity, languageArg);
609 elementSize = uloc_getCountry(locBuff, tempbuff, internalBufferSize, status);
610 appendShortStringElement(tempbuff, elementSize, buffer, &resultSize, capacity, regionArg);
611 elementSize = uloc_getScript(locBuff, tempbuff, internalBufferSize, status);
612 appendShortStringElement(tempbuff, elementSize, buffer, &resultSize, capacity, scriptArg);
613 elementSize = uloc_getVariant(locBuff, tempbuff, internalBufferSize, status);
614 appendShortStringElement(tempbuff, elementSize, buffer, &resultSize, capacity, variantArg);
615 elementSize = uloc_getKeywordValue(locBuff, "collation", tempbuff, internalBufferSize, status);
616 appendShortStringElement(tempbuff, elementSize, buffer, &resultSize, capacity, keywordArg);
617 }
618
619 int32_t i = 0;
620 UColAttributeValue attribute = UCOL_DEFAULT;
621 for(i = 0; i < UCOL_SIT_ITEMS_COUNT; i++) {
622 if(options[i].action == _processCollatorOption) {
623 attribute = ucol_getAttributeOrDefault(coll, (UColAttribute)options[i].attr, status);
624 if(attribute != UCOL_DEFAULT) {
625 char letter = ucol_sit_attributeValueToLetter(attribute, status);
626 appendShortStringElement(&letter, 1,
627 buffer, &resultSize, capacity, options[i].optionStart);
628 }
629 }
630 }
631 if(coll->variableTopValueisDefault == FALSE) {
632 //s.variableTopValue = ucol_getVariableTop(coll, status);
633 elementSize = T_CString_integerToString(tempbuff, coll->variableTopValue, 16);
634 appendShortStringElement(tempbuff, elementSize, buffer, &resultSize, capacity, variableTopValArg);
635 }
636
637 UParseError parseError;
638 return ucol_normalizeShortDefinitionString(buffer, dst, capacity, &parseError, status);
639 }
640
641 U_CAPI int32_t U_EXPORT2
642 ucol_normalizeShortDefinitionString(const char *definition,
643 char *destination,
644 int32_t capacity,
645 UParseError *parseError,
646 UErrorCode *status)
647 {
648
649 if(U_FAILURE(*status)) {
650 return 0;
651 }
652
653 if(destination) {
654 uprv_memset(destination, 0, capacity*sizeof(char));
655 }
656
657 UParseError pe;
658 if(!parseError) {
659 parseError = &pe;
660 }
661
662 // validate
663 CollatorSpec s;
664 ucol_sit_initCollatorSpecs(&s);
665 ucol_sit_readSpecs(&s, definition, parseError, status);
666 return ucol_sit_dumpSpecs(&s, destination, capacity, status);
667 }
668
669 // structure for packing the bits of the attributes in the
670 // identifier number.
671 // locale is packed separately
672 struct bitPacking {
673 char letter;
674 uint32_t offset;
675 uint32_t width;
676 UColAttribute attribute;
677 UColAttributeValue values[6];
678 };
679
680 static const bitPacking attributesToBits[UCOL_ATTRIBUTE_COUNT] = {
681 /* french */ { frenchCollArg, 29, 2, UCOL_FRENCH_COLLATION, { UCOL_DEFAULT, UCOL_OFF, UCOL_ON }},
682 /* alternate */ { alternateHArg, 27, 2, UCOL_ALTERNATE_HANDLING, { UCOL_DEFAULT, UCOL_NON_IGNORABLE, UCOL_SHIFTED }},
683 /* case first */ { caseFirstArg, 25, 2, UCOL_CASE_FIRST, { UCOL_DEFAULT, UCOL_OFF, UCOL_LOWER_FIRST, UCOL_UPPER_FIRST }},
684 /* case level */ { caseLevelArg, 23, 2, UCOL_CASE_LEVEL, { UCOL_DEFAULT, UCOL_OFF, UCOL_ON }},
685 /* normalization */ { normArg, 21, 2, UCOL_NORMALIZATION_MODE, { UCOL_DEFAULT, UCOL_OFF, UCOL_ON }},
686 /* strength */ { strengthArg, 18, 3, UCOL_STRENGTH, { UCOL_DEFAULT, UCOL_PRIMARY, UCOL_SECONDARY, UCOL_TERTIARY, UCOL_QUATERNARY, UCOL_IDENTICAL }},
687 /* hiragana */ { hiraganaQArg, 16, 2, UCOL_HIRAGANA_QUATERNARY_MODE, { UCOL_DEFAULT, UCOL_OFF, UCOL_ON }},
688 /* numeric coll */ { numericCollArg, 14, 2, UCOL_NUMERIC_COLLATION, { UCOL_DEFAULT, UCOL_OFF, UCOL_ON }}
689 };
690
691 static const uint32_t keywordShift = 9;
692 static const uint32_t keywordWidth = 5;
693 static const uint32_t localeShift = 0;
694 static const uint32_t localeWidth = 7;
695
696
697 static uint32_t ucol_sit_putLocaleInIdentifier(uint32_t result, const char* locale, UErrorCode* status) {
698 char buffer[internalBufferSize], keywordBuffer[internalBufferSize],
699 baseName[internalBufferSize], localeBuffer[internalBufferSize];
700 int32_t len = 0, keywordLen = 0,
701 baseNameLen = 0, localeLen = 0;
702 uint32_t i = 0;
703 UBool isAvailable = FALSE;
704 if(locale) {
705 len = uloc_canonicalize(locale, buffer, internalBufferSize, status);
706 localeLen = ucol_getFunctionalEquivalent(localeBuffer, internalBufferSize, "collation", buffer, &isAvailable, status);
707 keywordLen = uloc_getKeywordValue(buffer, "collation", keywordBuffer, internalBufferSize, status);
708 baseNameLen = uloc_getBaseName(buffer, baseName, internalBufferSize, status);
709
710 /*Binary search for the map entry for normal cases */
711
712 uint32_t low = 0;
713 uint32_t high = sizeof(locales)/sizeof(locales[0]);
714 uint32_t mid = high;
715 uint32_t oldmid = 0;
716 int32_t compVal = 0;
717
718
719 while (high > low) /*binary search*/{
720
721 mid = (high+low) >> 1; /*Finds median*/
722
723 if (mid == oldmid)
724 return UCOL_SIT_COLLATOR_NOT_ENCODABLE; // we didn't find it
725
726 compVal = uprv_strcmp(baseName, locales[mid]);
727 if (compVal < 0){
728 high = mid;
729 }
730 else if (compVal > 0){
731 low = mid;
732 }
733 else /*we found it*/{
734 break;
735 }
736 oldmid = mid;
737 }
738
739 result |= (mid & ((1 << localeWidth) - 1)) << localeShift;
740 }
741
742 if(keywordLen) {
743 for(i = 1; i < sizeof(keywords)/sizeof(keywords[0]); i++) {
744 if(uprv_strcmp(keywords[i], keywordBuffer) == 0) {
745 result |= (i & ((1 << keywordWidth) - 1)) << keywordShift;
746 break;
747 }
748 }
749 }
750 return result;
751 }
752
753 U_CAPI uint32_t U_EXPORT2
754 ucol_collatorToIdentifier(const UCollator *coll,
755 const char *locale,
756 UErrorCode *status)
757 {
758 uint32_t result = 0;
759 uint32_t i = 0, j = 0;
760 UColAttributeValue attrValue = UCOL_DEFAULT;
761
762 // if variable top is not default, we need to use strings
763 if(coll->variableTopValueisDefault != TRUE) {
764 return UCOL_SIT_COLLATOR_NOT_ENCODABLE;
765 }
766
767 if(locale == NULL) {
768 locale = ucol_getLocale(coll, ULOC_VALID_LOCALE, status);
769 }
770
771 result = ucol_sit_putLocaleInIdentifier(result, locale, status);
772
773 for(i = 0; i < sizeof(attributesToBits)/sizeof(attributesToBits[0]); i++) {
774 attrValue = ucol_getAttributeOrDefault(coll, attributesToBits[i].attribute, status);
775 j = 0;
776 while(attributesToBits[i].values[j] != attrValue) {
777 j++;
778 }
779 result |= (j & ((1 << attributesToBits[i].width) - 1)) << attributesToBits[i].offset;
780 }
781
782 return result;
783 }
784
785 U_CAPI UCollator* U_EXPORT2
786 ucol_openFromIdentifier(uint32_t identifier,
787 UBool forceDefaults,
788 UErrorCode *status)
789 {
790 uint32_t i = 0;
791 int32_t value = 0, keyword = 0;
792 char locale[internalBufferSize];
793
794 value = (identifier >> localeShift) & ((1 << localeWidth) - 1);
795 keyword = (identifier >> keywordShift) & ((1 << keywordWidth) - 1);
796
797 uprv_strcpy(locale, locales[value]);
798
799 if(keyword) {
800 uprv_strcat(locale, collationKeyword);
801 uprv_strcat(locale, keywords[keyword]);
802 }
803
804 UColAttributeValue attrValue = UCOL_DEFAULT;
805
806 UCollator *result = ucol_open(locale, status);
807
808 // variable top is not set in the identifier, so we can easily skip that on
809
810 for(i = 0; i < sizeof(attributesToBits)/sizeof(attributesToBits[0]); i++) {
811 value = (identifier >> attributesToBits[i].offset) & ((1 << attributesToBits[i].width) - 1);
812 attrValue = attributesToBits[i].values[value];
813 // the collator is all default, so we will set only the values that will differ from
814 // the default values.
815 if(attrValue != UCOL_DEFAULT) {
816 if(forceDefaults ||
817 ucol_getAttribute(result, attributesToBits[i].attribute, status) != attrValue) {
818 ucol_setAttribute(result, attributesToBits[i].attribute, attrValue, status);
819 }
820 }
821 }
822
823 return result;
824 }
825
826 U_CAPI int32_t U_EXPORT2
827 ucol_identifierToShortString(uint32_t identifier,
828 char *buffer,
829 int32_t capacity,
830 UBool forceDefaults,
831 UErrorCode *status)
832 {
833 int32_t locIndex = (identifier >> localeShift) & ((1 << localeWidth) - 1);
834 int32_t keywordIndex = (identifier >> keywordShift) & ((1 << keywordWidth) - 1);
835 CollatorSpec s;
836 ucol_sit_initCollatorSpecs(&s);
837 uprv_strcpy(s.locale, locales[locIndex]);
838 if(keywordIndex) {
839 uprv_strcat(s.locale, collationKeyword);
840 uprv_strcat(s.locale, keywords[keywordIndex]);
841 }
842 UCollator *coll = ucol_openFromIdentifier(identifier, forceDefaults, status);
843 int32_t resultLen = ucol_getShortDefinitionString(coll, s.locale, buffer, capacity, status);
844 ucol_close(coll);
845 return resultLen;
846
847 #if 0
848 // TODO: Crumy, crumy, crumy... Very hard to currently go algorithmically from
849 // identifier to short string. Do rethink
850 if(forceDefaults == FALSE) {
851 UCollator *coll = ucol_openFromIdentifier(identifier, FALSE, status);
852 int32_t resultLen = ucol_getShortDefinitionString(coll, s.locale, buffer, capacity, status);
853 ucol_close(coll);
854 return resultLen;
855 } else { // forceDefaults == TRUE
856 char letter;
857 UColAttributeValue value;
858 int32_t i = 0;
859 for(i = 0; i < sizeof(attributesToBits)/sizeof(attributesToBits[0]); i++) {
860 value = attributesToBits[i].values[(identifier >> attributesToBits[i].offset) & ((1 << attributesToBits[i].width) - 1)];
861 if(value != UCOL_DEFAULT) {
862 uprv_strcat(buffer, "_");
863 uprv_strncat(buffer, &attributesToBits[i].letter, 1);
864 letter = ucol_sit_attributeValueToLetter(value, status);
865 uprv_strncat(buffer, &letter, 1);
866 }
867 }
868 return ucol_sit_dumpSpecs(&s, buffer, capacity, status);
869 }
870 #endif
871 }
872
873 U_CAPI uint32_t U_EXPORT2
874 ucol_shortStringToIdentifier(const char *definition,
875 UBool forceDefaults,
876 UErrorCode *status)
877 {
878 UParseError parseError;
879 CollatorSpec s;
880 uint32_t result = 0;
881 uint32_t i = 0, j = 0;
882 ucol_sit_initCollatorSpecs(&s);
883
884 ucol_sit_readSpecs(&s, definition, &parseError, status);
885 ucol_sit_calculateWholeLocale(&s);
886
887 char locBuffer[internalBufferSize];
888 UBool isAvailable = FALSE;
889 UColAttributeValue attrValue = UCOL_DEFAULT;
890
891 ucol_getFunctionalEquivalent(locBuffer, internalBufferSize, "collation", s.locale, &isAvailable, status);
892
893 if(forceDefaults == FALSE) {
894 UCollator *coll = ucol_openFromShortString(definition, FALSE, &parseError, status);
895 result = ucol_collatorToIdentifier(coll, locBuffer, status);
896 ucol_close(coll);
897 } else { // forceDefaults == TRUE
898 result = ucol_sit_putLocaleInIdentifier(result, locBuffer, status);
899
900 for(i = 0; i < sizeof(attributesToBits)/sizeof(attributesToBits[0]); i++) {
901 attrValue = s.options[i];
902 j = 0;
903 while(attributesToBits[i].values[j] != attrValue) {
904 j++;
905 }
906 result |= (j & ((1 << attributesToBits[i].width) - 1)) << attributesToBits[i].offset;
907 }
908
909 }
910 return result;
911
912 }
913
914 U_CAPI UColAttributeValue U_EXPORT2
915 ucol_getAttributeOrDefault(const UCollator *coll, UColAttribute attr, UErrorCode *status)
916 {
917 if(U_FAILURE(*status) || coll == NULL) {
918 return UCOL_DEFAULT;
919 }
920 switch(attr) {
921 case UCOL_NUMERIC_COLLATION:
922 return coll->numericCollationisDefault?UCOL_DEFAULT:coll->numericCollation;
923 case UCOL_HIRAGANA_QUATERNARY_MODE:
924 return coll->hiraganaQisDefault?UCOL_DEFAULT:coll->hiraganaQ;
925 case UCOL_FRENCH_COLLATION: /* attribute for direction of secondary weights*/
926 return coll->frenchCollationisDefault?UCOL_DEFAULT:coll->frenchCollation;
927 case UCOL_ALTERNATE_HANDLING: /* attribute for handling variable elements*/
928 return coll->alternateHandlingisDefault?UCOL_DEFAULT:coll->alternateHandling;
929 case UCOL_CASE_FIRST: /* who goes first, lower case or uppercase */
930 return coll->caseFirstisDefault?UCOL_DEFAULT:coll->caseFirst;
931 case UCOL_CASE_LEVEL: /* do we have an extra case level */
932 return coll->caseLevelisDefault?UCOL_DEFAULT:coll->caseLevel;
933 case UCOL_NORMALIZATION_MODE: /* attribute for normalization */
934 return coll->normalizationModeisDefault?UCOL_DEFAULT:coll->normalizationMode;
935 case UCOL_STRENGTH: /* attribute for strength */
936 return coll->strengthisDefault?UCOL_DEFAULT:coll->strength;
937 case UCOL_ATTRIBUTE_COUNT:
938 default:
939 *status = U_ILLEGAL_ARGUMENT_ERROR;
940 break;
941 }
942 return UCOL_DEFAULT;
943 }
944
945
946 struct contContext {
947 const UCollator *coll;
948 USet *conts;
949 USet *expansions;
950 USet *removedContractions;
951 UBool addPrefixes;
952 UErrorCode *status;
953 };
954
955
956
957 static void
958 addSpecial(contContext *context, UChar *buffer, int32_t bufLen,
959 uint32_t CE, int32_t leftIndex, int32_t rightIndex, UErrorCode *status)
960 {
961 const UCollator *coll = context->coll;
962 USet *contractions = context->conts;
963 USet *expansions = context->expansions;
964 UBool addPrefixes = context->addPrefixes;
965
966 const UChar *UCharOffset = (UChar *)coll->image+getContractOffset(CE);
967 uint32_t newCE = *(coll->contractionCEs + (UCharOffset - coll->contractionIndex));
968 // we might have a contraction that ends from previous level
969 if(newCE != UCOL_NOT_FOUND) {
970 if(isSpecial(CE) && getCETag(CE) == CONTRACTION_TAG && isSpecial(newCE) && getCETag(newCE) == SPEC_PROC_TAG && addPrefixes) {
971 addSpecial(context, buffer, bufLen, newCE, leftIndex, rightIndex, status);
972 }
973 if(contractions && rightIndex-leftIndex > 1) {
974 uset_addString(contractions, buffer+leftIndex, rightIndex-leftIndex);
975 if(expansions && isSpecial(CE) && getCETag(CE) == EXPANSION_TAG) {
976 uset_addString(expansions, buffer+leftIndex, rightIndex-leftIndex);
977 }
978 }
979 }
980
981 UCharOffset++;
982 // check whether we're doing contraction or prefix
983 if(getCETag(CE) == SPEC_PROC_TAG && addPrefixes) {
984 if(leftIndex == 0) {
985 *status = U_INTERNAL_PROGRAM_ERROR;
986 return;
987 }
988 --leftIndex;
989 while(*UCharOffset != 0xFFFF) {
990 newCE = *(coll->contractionCEs + (UCharOffset - coll->contractionIndex));
991 buffer[leftIndex] = *UCharOffset;
992 if(isSpecial(newCE) && (getCETag(newCE) == CONTRACTION_TAG || getCETag(newCE) == SPEC_PROC_TAG)) {
993 addSpecial(context, buffer, bufLen, newCE, leftIndex, rightIndex, status);
994 } else {
995 if(contractions) {
996 uset_addString(contractions, buffer+leftIndex, rightIndex-leftIndex);
997 }
998 if(expansions && isSpecial(newCE) && getCETag(newCE) == EXPANSION_TAG) {
999 uset_addString(expansions, buffer+leftIndex, rightIndex-leftIndex);
1000 }
1001 }
1002 UCharOffset++;
1003 }
1004 } else if(getCETag(CE) == CONTRACTION_TAG) {
1005 if(rightIndex == bufLen-1) {
1006 *status = U_INTERNAL_PROGRAM_ERROR;
1007 return;
1008 }
1009 while(*UCharOffset != 0xFFFF) {
1010 newCE = *(coll->contractionCEs + (UCharOffset - coll->contractionIndex));
1011 buffer[rightIndex] = *UCharOffset;
1012 if(isSpecial(newCE) && (getCETag(newCE) == CONTRACTION_TAG || getCETag(newCE) == SPEC_PROC_TAG)) {
1013 addSpecial(context, buffer, bufLen, newCE, leftIndex, rightIndex+1, status);
1014 } else {
1015 if(contractions) {
1016 uset_addString(contractions, buffer+leftIndex, rightIndex+1-leftIndex);
1017 }
1018 if(expansions && isSpecial(newCE) && getCETag(newCE) == EXPANSION_TAG) {
1019 uset_addString(expansions, buffer+leftIndex, rightIndex+1-leftIndex);
1020 }
1021 }
1022 UCharOffset++;
1023 }
1024 }
1025
1026 }
1027
1028 U_CDECL_BEGIN
1029 static UBool U_CALLCONV
1030 _processSpecials(const void *context, UChar32 start, UChar32 limit, uint32_t CE)
1031 {
1032 UErrorCode *status = ((contContext *)context)->status;
1033 USet *expansions = ((contContext *)context)->expansions;
1034 USet *removed = ((contContext *)context)->removedContractions;
1035 UBool addPrefixes = ((contContext *)context)->addPrefixes;
1036 UChar contraction[internalBufferSize];
1037 if(isSpecial(CE)) {
1038 if(((getCETag(CE) == SPEC_PROC_TAG && addPrefixes) || getCETag(CE) == CONTRACTION_TAG)) {
1039 while(start < limit && U_SUCCESS(*status)) {
1040 // if there are suppressed contractions, we don't
1041 // want to add them.
1042 if(removed && uset_contains(removed, start)) {
1043 start++;
1044 continue;
1045 }
1046 // we start our contraction from middle, since we don't know if it
1047 // will grow toward right or left
1048 contraction[internalBufferSize/2] = (UChar)start;
1049 addSpecial(((contContext *)context), contraction, internalBufferSize, CE, internalBufferSize/2, internalBufferSize/2+1, status);
1050 start++;
1051 }
1052 } else if(expansions && getCETag(CE) == EXPANSION_TAG) {
1053 while(start < limit && U_SUCCESS(*status)) {
1054 uset_add(expansions, start++);
1055 }
1056 }
1057 }
1058 if(U_FAILURE(*status)) {
1059 return FALSE;
1060 } else {
1061 return TRUE;
1062 }
1063 }
1064
1065 U_CDECL_END
1066
1067
1068
1069 /**
1070 * Get a set containing the contractions defined by the collator. The set includes
1071 * both the UCA contractions and the contractions defined by the collator
1072 * @param coll collator
1073 * @param conts the set to hold the result
1074 * @param status to hold the error code
1075 * @return the size of the contraction set
1076 *
1077 * @draft ICU 3.0
1078 */
1079 U_CAPI int32_t U_EXPORT2
1080 ucol_getContractions( const UCollator *coll,
1081 USet *contractions,
1082 UErrorCode *status)
1083 {
1084 ucol_getContractionsAndExpansions(coll, contractions, NULL, FALSE, status);
1085 return uset_getItemCount(contractions);
1086 }
1087
1088 /**
1089 * Get a set containing the expansions defined by the collator. The set includes
1090 * both the UCA expansions and the expansions defined by the tailoring
1091 * @param coll collator
1092 * @param conts the set to hold the result
1093 * @param addPrefixes add the prefix contextual elements to contractions
1094 * @param status to hold the error code
1095 *
1096 * @draft ICU 3.4
1097 */
1098 U_CAPI void U_EXPORT2
1099 ucol_getContractionsAndExpansions( const UCollator *coll,
1100 USet *contractions,
1101 USet *expansions,
1102 UBool addPrefixes,
1103 UErrorCode *status)
1104 {
1105 if(U_FAILURE(*status)) {
1106 return;
1107 }
1108 if(coll == NULL) {
1109 *status = U_ILLEGAL_ARGUMENT_ERROR;
1110 return;
1111 }
1112
1113 if(contractions) {
1114 uset_clear(contractions);
1115 }
1116 if(expansions) {
1117 uset_clear(expansions);
1118 }
1119 int32_t rulesLen = 0;
1120 const UChar* rules = ucol_getRules(coll, &rulesLen);
1121 UColTokenParser src;
1122 ucol_tok_initTokenList(&src, rules, rulesLen, coll->UCA, status);
1123
1124 contContext c = { NULL, contractions, expansions, src.removeSet, addPrefixes, status };
1125
1126 // Add the UCA contractions
1127 c.coll = coll->UCA;
1128 utrie_enum(&coll->UCA->mapping, NULL, _processSpecials, &c);
1129
1130 // This is collator specific. Add contractions from a collator
1131 c.coll = coll;
1132 c.removedContractions = NULL;
1133 utrie_enum(&coll->mapping, NULL, _processSpecials, &c);
1134 ucol_tok_closeTokenList(&src);
1135 }
1136
1137 U_CAPI int32_t U_EXPORT2
1138 ucol_getUnsafeSet( const UCollator *coll,
1139 USet *unsafe,
1140 UErrorCode *status)
1141 {
1142 UChar buffer[internalBufferSize];
1143 int32_t len = 0;
1144
1145 uset_clear(unsafe);
1146
1147 // cccpattern = "[[:^tccc=0:][:^lccc=0:]]", unfortunately variant
1148 static const UChar cccpattern[25] = { 0x5b, 0x5b, 0x3a, 0x5e, 0x74, 0x63, 0x63, 0x63, 0x3d, 0x30, 0x3a, 0x5d,
1149 0x5b, 0x3a, 0x5e, 0x6c, 0x63, 0x63, 0x63, 0x3d, 0x30, 0x3a, 0x5d, 0x5d, 0x00 };
1150
1151 // add chars that fail the fcd check
1152 uset_applyPattern(unsafe, cccpattern, 24, USET_IGNORE_SPACE, status);
1153
1154 // add Thai/Lao prevowels
1155 uset_addRange(unsafe, 0xe40, 0xe44);
1156 uset_addRange(unsafe, 0xec0, 0xec4);
1157 // add lead/trail surrogates
1158 uset_addRange(unsafe, 0xd800, 0xdfff);
1159
1160 USet *contractions = uset_open(0,0);
1161
1162 int32_t i = 0, j = 0;
1163 int32_t contsSize = ucol_getContractions(coll, contractions, status);
1164 UChar32 c = 0;
1165 // Contraction set consists only of strings
1166 // to get unsafe code points, we need to
1167 // break the strings apart and add them to the unsafe set
1168 for(i = 0; i < contsSize; i++) {
1169 len = uset_getItem(contractions, i, NULL, NULL, buffer, internalBufferSize, status);
1170 if(len > 0) {
1171 j = 0;
1172 while(j < len) {
1173 U16_NEXT(buffer, j, len, c);
1174 if(j < len) {
1175 uset_add(unsafe, c);
1176 }
1177 }
1178 }
1179 }
1180
1181 uset_close(contractions);
1182
1183 return uset_size(unsafe);
1184 }
1185 #endif