1 /* gunicollate.c - Collation
3 * Copyright 2001,2005 Red Hat, Inc.
5 * The Gnome Library is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU Lesser General Public License as
7 * published by the Free Software Foundation; either version 2 of the
8 * License, or (at your option) any later version.
10 * The Gnome Library is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Lesser General Public License for more details.
15 * You should have received a copy of the GNU Lesser General Public
16 * License along with the Gnome Library; see the file COPYING.LIB. If not,
17 * write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18 * Boston, MA 02111-1307, USA.
25 #ifdef __STDC_ISO_10646__
30 #include <CoreServices/CoreServices.h>
34 #include "gunicodeprivate.h"
38 /* Workaround for bug in MSVCR80.DLL */
40 msc_strxfrm_wrapper (char *string1,
44 if (!string1 || count <= 0)
48 return strxfrm (&tmp, string2, 1);
50 return strxfrm (string1, string2, count);
52 #define strxfrm msc_strxfrm_wrapper
57 * @str1: a UTF-8 encoded string
58 * @str2: a UTF-8 encoded string
60 * Compares two strings for ordering using the linguistically
61 * correct rules for the <link linkend="setlocale">current locale</link>.
62 * When sorting a large number of strings, it will be significantly
63 * faster to obtain collation keys with g_utf8_collate_key() and
64 * compare the keys with strcmp() when sorting instead of sorting
65 * the original strings.
67 * Return value: < 0 if @str1 compares before @str2,
68 * 0 if they compare equal, > 0 if @str1 compares after @str2.
71 g_utf8_collate (const gchar *str1,
84 g_return_val_if_fail (str1 != NULL, 0);
85 g_return_val_if_fail (str2 != NULL, 0);
87 str1_utf16 = g_utf8_to_utf16 (str1, -1, NULL, &len1, NULL);
88 str2_utf16 = g_utf8_to_utf16 (str2, -1, NULL, &len2, NULL);
90 UCCompareTextDefault (kUCCollateStandardOptions,
91 str1_utf16, len1, str2_utf16, len2,
98 #elif defined(__STDC_ISO_10646__)
103 g_return_val_if_fail (str1 != NULL, 0);
104 g_return_val_if_fail (str2 != NULL, 0);
106 str1_norm = _g_utf8_normalize_wc (str1, -1, G_NORMALIZE_ALL_COMPOSE);
107 str2_norm = _g_utf8_normalize_wc (str2, -1, G_NORMALIZE_ALL_COMPOSE);
109 result = wcscoll ((wchar_t *)str1_norm, (wchar_t *)str2_norm);
114 #else /* !__STDC_ISO_10646__ */
116 const gchar *charset;
120 g_return_val_if_fail (str1 != NULL, 0);
121 g_return_val_if_fail (str2 != NULL, 0);
123 str1_norm = g_utf8_normalize (str1, -1, G_NORMALIZE_ALL_COMPOSE);
124 str2_norm = g_utf8_normalize (str2, -1, G_NORMALIZE_ALL_COMPOSE);
126 if (g_get_charset (&charset))
128 result = strcoll (str1_norm, str2_norm);
132 gchar *str1_locale = g_convert (str1_norm, -1, charset, "UTF-8", NULL, NULL, NULL);
133 gchar *str2_locale = g_convert (str2_norm, -1, charset, "UTF-8", NULL, NULL, NULL);
135 if (str1_locale && str2_locale)
136 result = strcoll (str1_locale, str2_locale);
137 else if (str1_locale)
139 else if (str2_locale)
142 result = strcmp (str1_norm, str2_norm);
144 g_free (str1_locale);
145 g_free (str2_locale);
151 #endif /* __STDC_ISO_10646__ */
156 #if defined(__STDC_ISO_10646__) || defined(HAVE_CARBON)
157 /* We need UTF-8 encoding of numbers to encode the weights if
158 * we are using wcsxfrm. However, we aren't encoding Unicode
159 * characters, so we can't simply use g_unichar_to_utf8.
161 * The following routine is taken (with modification) from GNU
162 * libc's strxfrm routine:
164 * Copyright (C) 1995-1999,2000,2001 Free Software Foundation, Inc.
165 * Written by Ulrich Drepper <drepper@cygnus.com>, 1995.
168 utf8_encode (char *buf, wchar_t val)
182 for (step = 2; step < 6; ++step)
183 if ((val & (~(guint32)0 << (5 * step + 1))) == 0)
189 *buf = (unsigned char) (~0xff >> step);
193 buf[step] = 0x80 | (val & 0x3f);
203 #endif /* __STDC_ISO_10646__ || HAVE_CARBON */
208 collate_key_to_string (UCCollationValue *key,
215 /* Pretty smart algorithm here: ignore first eight bytes of the
216 * collation key. It doesn't produce results equivalent to
217 * UCCompareCollationKeys's, but the difference seems to be only
218 * that UCCompareCollationKeys in some cases produces 0 where our
219 * comparison gets -1 or 1. */
221 if (key_len * sizeof (UCCollationValue) <= 8)
222 return g_strdup ("");
225 for (i = 8; i < key_len * sizeof (UCCollationValue); i++)
226 /* there may be nul bytes, encode byteval+1 */
227 result_len += utf8_encode (NULL, *((guchar*)key + i) + 1);
229 result = g_malloc (result_len + 1);
231 for (i = 8; i < key_len * sizeof (UCCollationValue); i++)
232 result_len += utf8_encode (result + result_len, *((guchar*)key + i) + 1);
234 result[result_len] = 0;
239 carbon_collate_key_with_collator (const gchar *str,
241 CollatorRef collator)
243 UniChar *str_utf16 = NULL;
246 UCCollationValue staticbuf[512];
247 UCCollationValue *freeme = NULL;
248 UCCollationValue *buf;
252 gchar *result = NULL;
254 str_utf16 = g_utf8_to_utf16 (str, len, NULL, &len_utf16, NULL);
255 try_len = len_utf16 * 5 + 2;
257 if (try_len <= sizeof staticbuf)
260 buf_len = sizeof staticbuf;
264 freeme = g_new (UCCollationValue, try_len);
269 ret = UCGetCollationKey (collator, str_utf16, len_utf16,
270 buf_len, &key_len, buf);
272 if (ret == kCollateBufferTooSmall)
274 freeme = g_renew (UCCollationValue, freeme, try_len * 2);
276 buf_len = try_len * 2;
277 ret = UCGetCollationKey (collator, str_utf16, len_utf16,
278 buf_len, &key_len, buf);
282 result = collate_key_to_string (buf, key_len);
284 result = g_strdup ("");
292 carbon_collate_key (const gchar *str,
295 static CollatorRef collator;
297 if (G_UNLIKELY (!collator))
299 UCCreateCollator (NULL, 0, kUCCollateStandardOptions, &collator);
303 static gboolean been_here;
305 g_warning ("%s: UCCreateCollator failed", G_STRLOC);
307 return g_strdup ("");
311 return carbon_collate_key_with_collator (str, len, collator);
315 carbon_collate_key_for_filename (const gchar *str,
318 static CollatorRef collator;
320 if (G_UNLIKELY (!collator))
322 /* http://developer.apple.com/qa/qa2004/qa1159.html */
323 UCCreateCollator (NULL, 0,
324 kUCCollateComposeInsensitiveMask
325 | kUCCollateWidthInsensitiveMask
326 | kUCCollateCaseInsensitiveMask
327 | kUCCollateDigitsOverrideMask
328 | kUCCollateDigitsAsNumberMask
329 | kUCCollatePunctuationSignificantMask,
334 static gboolean been_here;
336 g_warning ("%s: UCCreateCollator failed", G_STRLOC);
338 return g_strdup ("");
342 return carbon_collate_key_with_collator (str, len, collator);
345 #endif /* HAVE_CARBON */
348 * g_utf8_collate_key:
349 * @str: a UTF-8 encoded string.
350 * @len: length of @str, in bytes, or -1 if @str is nul-terminated.
352 * Converts a string into a collation key that can be compared
353 * with other collation keys produced by the same function using
356 * The results of comparing the collation keys of two strings
357 * with strcmp() will always be the same as comparing the two
358 * original keys with g_utf8_collate().
360 * Note that this function depends on the
361 * <link linkend="setlocale">current locale</link>.
363 * Return value: a newly allocated string. This string should
364 * be freed with g_free() when you are done with it.
367 g_utf8_collate_key (const gchar *str,
374 g_return_val_if_fail (str != NULL, NULL);
375 result = carbon_collate_key (str, len);
377 #elif defined(__STDC_ISO_10646__)
383 gsize result_len = 0;
385 g_return_val_if_fail (str != NULL, NULL);
387 str_norm = _g_utf8_normalize_wc (str, len, G_NORMALIZE_ALL_COMPOSE);
389 xfrm_len = wcsxfrm (NULL, (wchar_t *)str_norm, 0);
390 result_wc = g_new (wchar_t, xfrm_len + 1);
391 wcsxfrm (result_wc, (wchar_t *)str_norm, xfrm_len + 1);
393 for (i=0; i < xfrm_len; i++)
394 result_len += utf8_encode (NULL, result_wc[i]);
396 result = g_malloc (result_len + 1);
398 for (i=0; i < xfrm_len; i++)
399 result_len += utf8_encode (result + result_len, result_wc[i]);
401 result[result_len] = '\0';
407 #else /* !__STDC_ISO_10646__ */
410 const gchar *charset;
413 g_return_val_if_fail (str != NULL, NULL);
415 str_norm = g_utf8_normalize (str, len, G_NORMALIZE_ALL_COMPOSE);
419 if (g_get_charset (&charset))
421 xfrm_len = strxfrm (NULL, str_norm, 0);
422 if (xfrm_len >= 0 && xfrm_len < G_MAXINT - 2)
424 result = g_malloc (xfrm_len + 1);
425 strxfrm (result, str_norm, xfrm_len + 1);
430 gchar *str_locale = g_convert (str_norm, -1, charset, "UTF-8", NULL, NULL, NULL);
434 xfrm_len = strxfrm (NULL, str_locale, 0);
435 if (xfrm_len < 0 || xfrm_len >= G_MAXINT - 2)
443 result = g_malloc (xfrm_len + 2);
445 strxfrm (result + 1, str_locale, xfrm_len + 1);
453 xfrm_len = strlen (str_norm);
454 result = g_malloc (xfrm_len + 2);
456 memcpy (result + 1, str_norm, xfrm_len);
457 result[xfrm_len+1] = '\0';
461 #endif /* __STDC_ISO_10646__ */
466 /* This is a collation key that is very very likely to sort before any
467 collation key that libc strxfrm generates. We use this before any
468 special case (dot or number) to make sure that its sorted before
471 #define COLLATION_SENTINEL "\1\1\1"
474 * g_utf8_collate_key_for_filename:
475 * @str: a UTF-8 encoded string.
476 * @len: length of @str, in bytes, or -1 if @str is nul-terminated.
478 * Converts a string into a collation key that can be compared
479 * with other collation keys produced by the same function using strcmp().
481 * In order to sort filenames correctly, this function treats the dot '.'
482 * as a special case. Most dictionary orderings seem to consider it
483 * insignificant, thus producing the ordering "event.c" "eventgenerator.c"
484 * "event.h" instead of "event.c" "event.h" "eventgenerator.c". Also, we
485 * would like to treat numbers intelligently so that "file1" "file10" "file5"
486 * is sorted as "file1" "file5" "file10".
488 * Note that this function depends on the
489 * <link linkend="setlocale">current locale</link>.
491 * Return value: a newly allocated string. This string should
492 * be freed with g_free() when you are done with it.
497 g_utf8_collate_key_for_filename (const gchar *str,
513 * Split the filename into collatable substrings which do
514 * not contain [.0-9] and special-cased substrings. The collatable
515 * substrings are run through the normal g_utf8_collate_key() and the
516 * resulting keys are concatenated with keys generated from the
517 * special-cased substrings.
519 * Special cases: Dots are handled by replacing them with '\1' which
520 * implies that short dot-delimited substrings are before long ones,
527 * Numbers are handled by prepending to each number d-1 superdigits
528 * where d = number of digits in the number and SUPERDIGIT is a
529 * character with an integer value higher than any digit (for instance
530 * ':'). This ensures that single-digit numbers are sorted before
531 * double-digit numbers which in turn are sorted separately from
532 * triple-digit numbers, etc. To avoid strange side-effects when
533 * sorting strings that already contain SUPERDIGITs, a '\2'
534 * is also prepended, like this
540 * file\2::100 (file100)
541 * file:foo (file:foo)
543 * This has the side-effect of sorting numbers before everything else (except
544 * dots), but this is probably OK.
546 * Leading digits are ignored when doing the above. To discriminate
547 * numbers which differ only in the number of leading digits, we append
548 * the number of leading digits as a byte at the very end of the collation
551 * To try avoid conflict with any collation key sequence generated by libc we
552 * start each switch to a special cased part with a sentinel that hopefully
553 * will sort before anything libc will generate.
559 result = g_string_sized_new (len * 2);
560 append = g_string_sized_new (0);
564 /* No need to use utf8 functions, since we're only looking for ascii chars */
565 for (prev = p = str; p < end; p++)
572 collate_key = g_utf8_collate_key (prev, p - prev);
573 g_string_append (result, collate_key);
574 g_free (collate_key);
577 g_string_append (result, COLLATION_SENTINEL "\1");
595 collate_key = g_utf8_collate_key (prev, p - prev);
596 g_string_append (result, collate_key);
597 g_free (collate_key);
600 g_string_append (result, COLLATION_SENTINEL "\2");
604 /* write d-1 colons */
618 if (*p == '0' && !digits)
620 else if (g_ascii_isdigit(*p))
624 /* count an all-zero sequence as
625 * one digit plus leading zeros
638 g_string_append_c (result, ':');
642 if (leading_zeros > 0)
644 g_string_append_c (append, (char)leading_zeros);
645 prev += leading_zeros;
648 /* write the number itself */
649 g_string_append_len (result, prev, p - prev);
652 --p; /* go one step back to avoid disturbing outer loop */
656 /* other characters just accumulate */
663 collate_key = g_utf8_collate_key (prev, p - prev);
664 g_string_append (result, collate_key);
665 g_free (collate_key);
668 g_string_append (result, append->str);
669 g_string_free (append, TRUE);
671 return g_string_free (result, FALSE);
672 #else /* HAVE_CARBON */
673 return carbon_collate_key_for_filename (str, len);
678 #define __G_UNICOLLATE_C__
679 #include "galiasdef.c"