gunicollate.c 17.1 KB
Newer Older
1 2
/* gunicollate.c - Collation
 *
3
 *  Copyright 2001,2005 Red Hat, Inc.
4
 *
5 6 7
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
8
 * version 2.1 of the License, or (at your option) any later version.
9
 *
10
 * This library is distributed in the hope that it will be useful,
11 12 13 14
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
15 16
 * You should have received a copy of the GNU Lesser General Public License
 * along with this library; if not, see <http://www.gnu.org/licenses/>.
17 18
 */

19 20
#include "config.h"

21 22 23 24 25 26
#include <locale.h>
#include <string.h>
#ifdef __STDC_ISO_10646__
#include <wchar.h>
#endif

27 28 29 30
#ifdef HAVE_CARBON
#include <CoreServices/CoreServices.h>
#endif

Matthias Clasen's avatar
Matthias Clasen committed
31 32
#include "gmem.h"
#include "gunicode.h"
33
#include "gunicodeprivate.h"
Matthias Clasen's avatar
Matthias Clasen committed
34 35 36
#include "gstring.h"
#include "gstrfuncs.h"
#include "gtestutils.h"
37
#include "gcharset.h"
38 39 40
#ifndef __STDC_ISO_10646__
#include "gconvert.h"
#endif
Matthias Clasen's avatar
Matthias Clasen committed
41

42

43 44
#ifdef _MSC_VER
/* Workaround for bug in MSVCR80.DLL */
45
static gsize
46 47
msc_strxfrm_wrapper (char       *string1,
		     const char *string2,
48
		     gsize       count)
49 50 51 52 53 54 55 56 57 58 59 60
{
  if (!string1 || count <= 0)
    {
      char tmp;

      return strxfrm (&tmp, string2, 1);
    }
  return strxfrm (string1, string2, count);
}
#define strxfrm msc_strxfrm_wrapper
#endif

61 62 63 64 65 66
/**
 * g_utf8_collate:
 * @str1: a UTF-8 encoded string
 * @str2: a UTF-8 encoded string
 * 
 * Compares two strings for ordering using the linguistically
67
 * correct rules for the [current locale][setlocale].
Matthias Clasen's avatar
Matthias Clasen committed
68 69 70 71
 * When sorting a large number of strings, it will be significantly 
 * faster to obtain collation keys with g_utf8_collate_key() and 
 * compare the keys with strcmp() when sorting instead of sorting 
 * the original strings.
72
 * 
73
 * Returns: < 0 if @str1 compares before @str2, 
74
 *   0 if they compare equal, > 0 if @str1 compares after @str2.
75 76 77 78 79 80
 **/
gint
g_utf8_collate (const gchar *str1,
		const gchar *str2)
{
  gint result;
81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104

#ifdef HAVE_CARBON

  UniChar *str1_utf16;
  UniChar *str2_utf16;
  glong len1;
  glong len2;
  SInt32 retval = 0;

  g_return_val_if_fail (str1 != NULL, 0);
  g_return_val_if_fail (str2 != NULL, 0);

  str1_utf16 = g_utf8_to_utf16 (str1, -1, NULL, &len1, NULL);
  str2_utf16 = g_utf8_to_utf16 (str2, -1, NULL, &len2, NULL);

  UCCompareTextDefault (kUCCollateStandardOptions,
                        str1_utf16, len1, str2_utf16, len2,
                        NULL, &retval);
  result = retval;

  g_free (str2_utf16);
  g_free (str1_utf16);

#elif defined(__STDC_ISO_10646__)
105

106 107 108 109 110 111 112 113
  gunichar *str1_norm;
  gunichar *str2_norm;

  g_return_val_if_fail (str1 != NULL, 0);
  g_return_val_if_fail (str2 != NULL, 0);

  str1_norm = _g_utf8_normalize_wc (str1, -1, G_NORMALIZE_ALL_COMPOSE);
  str2_norm = _g_utf8_normalize_wc (str2, -1, G_NORMALIZE_ALL_COMPOSE);
114 115 116 117 118 119 120 121 122

  result = wcscoll ((wchar_t *)str1_norm, (wchar_t *)str2_norm);

  g_free (str1_norm);
  g_free (str2_norm);

#else /* !__STDC_ISO_10646__ */

  const gchar *charset;
123 124 125 126 127 128 129 130
  gchar *str1_norm;
  gchar *str2_norm;

  g_return_val_if_fail (str1 != NULL, 0);
  g_return_val_if_fail (str2 != NULL, 0);

  str1_norm = g_utf8_normalize (str1, -1, G_NORMALIZE_ALL_COMPOSE);
  str2_norm = g_utf8_normalize (str2, -1, G_NORMALIZE_ALL_COMPOSE);
131 132 133 134 135 136 137

  if (g_get_charset (&charset))
    {
      result = strcoll (str1_norm, str2_norm);
    }
  else
    {
138 139
      gchar *str1_locale = g_convert (str1_norm, -1, charset, "UTF-8", NULL, NULL, NULL);
      gchar *str2_locale = g_convert (str2_norm, -1, charset, "UTF-8", NULL, NULL, NULL);
140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161

      if (str1_locale && str2_locale)
	result =  strcoll (str1_locale, str2_locale);
      else if (str1_locale)
	result = -1;
      else if (str2_locale)
	result = 1;
      else
	result = strcmp (str1_norm, str2_norm);

      g_free (str1_locale);
      g_free (str2_locale);
    }

  g_free (str1_norm);
  g_free (str2_norm);

#endif /* __STDC_ISO_10646__ */

  return result;
}

162
#if defined(__STDC_ISO_10646__)
163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208
/* We need UTF-8 encoding of numbers to encode the weights if
 * we are using wcsxfrm. However, we aren't encoding Unicode
 * characters, so we can't simply use g_unichar_to_utf8.
 *
 * The following routine is taken (with modification) from GNU
 * libc's strxfrm routine:
 *
 * Copyright (C) 1995-1999,2000,2001 Free Software Foundation, Inc.
 * Written by Ulrich Drepper <drepper@cygnus.com>, 1995.
 */
static inline int
utf8_encode (char *buf, wchar_t val)
{
  int retval;

  if (val < 0x80)
    {
      if (buf)
	*buf++ = (char) val;
      retval = 1;
    }
  else
    {
      int step;

      for (step = 2; step < 6; ++step)
        if ((val & (~(guint32)0 << (5 * step + 1))) == 0)
          break;
      retval = step;

      if (buf)
	{
	  *buf = (unsigned char) (~0xff >> step);
	  --step;
	  do
	    {
	      buf[step] = 0x80 | (val & 0x3f);
	      val >>= 6;
	    }
	  while (--step > 0);
	  *buf |= val;
	}
    }

  return retval;
}
209
#endif /* __STDC_ISO_10646__ */
210 211 212 213 214 215 216 217

#ifdef HAVE_CARBON

static gchar *
collate_key_to_string (UCCollationValue *key,
                       gsize             key_len)
{
  gchar *result;
218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236
  gsize result_len;
  long *lkey = (long *) key;

  /* UCCollationValue format:
   *
   * UCCollateOptions (32/64 bits)
   * SizeInBytes      (32/64 bits)
   * Value            (8 bits arrey)
   *
   * UCCollateOptions: ordering option mask of the collator
   * used to create the key. Size changes on 32-bit / 64-bit
   * hosts. On 64-bits also the extra half-word seems to have
   * some extra (unknown) meaning.
   * SizeInBytes: size of the whole structure, in bytes
   * (including UCCollateOptions and SizeInBytes fields). Size
   * changes on 32-bit & 64-bit hosts.
   * Value: array of bytes containing the comparison weights.
   * Seems to have several sub-strings separated by \001 and \002
   * chars. Also, experience shows this is directly strcmp-able.
237
   */
238

239
  result_len = lkey[1];
240
  result = g_malloc (result_len + 1);
241
  memcpy (result, &lkey[2], result_len);
242
  result[result_len] = '\0';
243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354

  return result;
}

static gchar *
carbon_collate_key_with_collator (const gchar *str,
                                  gssize       len,
                                  CollatorRef  collator)
{
  UniChar *str_utf16 = NULL;
  glong len_utf16;
  OSStatus ret;
  UCCollationValue staticbuf[512];
  UCCollationValue *freeme = NULL;
  UCCollationValue *buf;
  ItemCount buf_len;
  ItemCount key_len;
  ItemCount try_len;
  gchar *result = NULL;

  str_utf16 = g_utf8_to_utf16 (str, len, NULL, &len_utf16, NULL);
  try_len = len_utf16 * 5 + 2;

  if (try_len <= sizeof staticbuf)
    {
      buf = staticbuf;
      buf_len = sizeof staticbuf;
    }
  else
    {
      freeme = g_new (UCCollationValue, try_len);
      buf = freeme;
      buf_len = try_len;
    }

  ret = UCGetCollationKey (collator, str_utf16, len_utf16,
                           buf_len, &key_len, buf);

  if (ret == kCollateBufferTooSmall)
    {
      freeme = g_renew (UCCollationValue, freeme, try_len * 2);
      buf = freeme;
      buf_len = try_len * 2;
      ret = UCGetCollationKey (collator, str_utf16, len_utf16,
                               buf_len, &key_len, buf);
    }

  if (ret == 0)
    result = collate_key_to_string (buf, key_len);
  else
    result = g_strdup ("");

  g_free (freeme);
  g_free (str_utf16);
  return result;
}

static gchar *
carbon_collate_key (const gchar *str,
                    gssize       len)
{
  static CollatorRef collator;

  if (G_UNLIKELY (!collator))
    {
      UCCreateCollator (NULL, 0, kUCCollateStandardOptions, &collator);

      if (!collator)
        {
          static gboolean been_here;
          if (!been_here)
            g_warning ("%s: UCCreateCollator failed", G_STRLOC);
          been_here = TRUE;
          return g_strdup ("");
        }
    }

  return carbon_collate_key_with_collator (str, len, collator);
}

static gchar *
carbon_collate_key_for_filename (const gchar *str,
                                 gssize       len)
{
  static CollatorRef collator;

  if (G_UNLIKELY (!collator))
    {
      /* http://developer.apple.com/qa/qa2004/qa1159.html */
      UCCreateCollator (NULL, 0,
                        kUCCollateComposeInsensitiveMask
                         | kUCCollateWidthInsensitiveMask
                         | kUCCollateCaseInsensitiveMask
                         | kUCCollateDigitsOverrideMask
                         | kUCCollateDigitsAsNumberMask
                         | kUCCollatePunctuationSignificantMask, 
                        &collator);

      if (!collator)
        {
          static gboolean been_here;
          if (!been_here)
            g_warning ("%s: UCCreateCollator failed", G_STRLOC);
          been_here = TRUE;
          return g_strdup ("");
        }
    }

  return carbon_collate_key_with_collator (str, len, collator);
}

#endif /* HAVE_CARBON */
355 356 357 358

/**
 * g_utf8_collate_key:
 * @str: a UTF-8 encoded string.
359 360
 * @len: length of @str, in bytes, or -1 if @str is nul-terminated.
 *
361
 * Converts a string into a collation key that can be compared
362 363
 * with other collation keys produced by the same function using 
 * strcmp(). 
Matthias Clasen's avatar
Matthias Clasen committed
364
 *
365
 * The results of comparing the collation keys of two strings 
Matthias Clasen's avatar
Matthias Clasen committed
366 367 368
 * with strcmp() will always be the same as comparing the two 
 * original keys with g_utf8_collate().
 * 
369
 * Note that this function depends on the [current locale][setlocale].
370
 * 
371
 * Returns: a newly allocated string. This string should
372
 *   be freed with g_free() when you are done with it.
373 374
 **/
gchar *
375 376
g_utf8_collate_key (const gchar *str,
		    gssize       len)
377 378 379
{
  gchar *result;

380 381 382 383 384 385 386 387
#ifdef HAVE_CARBON

  g_return_val_if_fail (str != NULL, NULL);
  result = carbon_collate_key (str, len);

#elif defined(__STDC_ISO_10646__)

  gsize xfrm_len;
388
  gunichar *str_norm;
389
  wchar_t *result_wc;
390 391
  gsize i;
  gsize result_len = 0;
392

393
  g_return_val_if_fail (str != NULL, NULL);
394 395 396

  str_norm = _g_utf8_normalize_wc (str, len, G_NORMALIZE_ALL_COMPOSE);

397 398 399
  xfrm_len = wcsxfrm (NULL, (wchar_t *)str_norm, 0);
  result_wc = g_new (wchar_t, xfrm_len + 1);
  wcsxfrm (result_wc, (wchar_t *)str_norm, xfrm_len + 1);
400

401
  for (i = 0; i < xfrm_len; i++)
402 403 404 405
    result_len += utf8_encode (NULL, result_wc[i]);

  result = g_malloc (result_len + 1);
  result_len = 0;
406
  for (i = 0; i < xfrm_len; i++)
407 408 409 410 411 412 413 414 415 416
    result_len += utf8_encode (result + result_len, result_wc[i]);

  result[result_len] = '\0';

  g_free (result_wc);
  g_free (str_norm);

  return result;
#else /* !__STDC_ISO_10646__ */

417
  gsize xfrm_len;
418
  const gchar *charset;
419 420
  gchar *str_norm;

421
  g_return_val_if_fail (str != NULL, NULL);
422 423

  str_norm = g_utf8_normalize (str, len, G_NORMALIZE_ALL_COMPOSE);
424

425 426
  result = NULL;

427 428
  if (g_get_charset (&charset))
    {
429
      xfrm_len = strxfrm (NULL, str_norm, 0);
430 431 432 433 434
      if (xfrm_len >= 0 && xfrm_len < G_MAXINT - 2)
        {
          result = g_malloc (xfrm_len + 1);
          strxfrm (result, str_norm, xfrm_len + 1);
        }
435 436 437
    }
  else
    {
438
      gchar *str_locale = g_convert (str_norm, -1, charset, "UTF-8", NULL, NULL, NULL);
439 440 441

      if (str_locale)
	{
442
	  xfrm_len = strxfrm (NULL, str_locale, 0);
443 444 445 446 447 448 449 450
	  if (xfrm_len < 0 || xfrm_len >= G_MAXINT - 2)
	    {
	      g_free (str_locale);
	      str_locale = NULL;
	    }
	}
      if (str_locale)
	{
451
	  result = g_malloc (xfrm_len + 2);
452
	  result[0] = 'A';
453
	  strxfrm (result + 1, str_locale, xfrm_len + 1);
454 455 456
	  
	  g_free (str_locale);
	}
457 458 459 460 461 462 463 464 465
    }
    
  if (!result) 
    {
      xfrm_len = strlen (str_norm);
      result = g_malloc (xfrm_len + 2);
      result[0] = 'B';
      memcpy (result + 1, str_norm, xfrm_len);
      result[xfrm_len+1] = '\0';
466 467 468 469 470 471 472
    }

  g_free (str_norm);
#endif /* __STDC_ISO_10646__ */

  return result;
}
473

474
/* This is a collation key that is very very likely to sort before any
475 476 477
 * collation key that libc strxfrm generates. We use this before any
 * special case (dot or number) to make sure that its sorted before
 * anything else.
478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494
 */
#define COLLATION_SENTINEL "\1\1\1"

/**
 * g_utf8_collate_key_for_filename:
 * @str: a UTF-8 encoded string.
 * @len: length of @str, in bytes, or -1 if @str is nul-terminated.
 *
 * Converts a string into a collation key that can be compared
 * with other collation keys produced by the same function using strcmp(). 
 * 
 * In order to sort filenames correctly, this function treats the dot '.' 
 * as a special case. Most dictionary orderings seem to consider it
 * insignificant, thus producing the ordering "event.c" "eventgenerator.c"
 * "event.h" instead of "event.c" "event.h" "eventgenerator.c". Also, we
 * would like to treat numbers intelligently so that "file1" "file10" "file5"
 * is sorted as "file1" "file5" "file10".
Matthias Clasen's avatar
Matthias Clasen committed
495
 * 
496
 * Note that this function depends on the [current locale][setlocale].
497
 *
498
 * Returns: a newly allocated string. This string should
499 500 501 502
 *   be freed with g_free() when you are done with it.
 *
 * Since: 2.8
 */
503
gchar *
504 505 506
g_utf8_collate_key_for_filename (const gchar *str,
				 gssize       len)
{
507
#ifndef HAVE_CARBON
508 509 510 511
  GString *result;
  GString *append;
  const gchar *p;
  const gchar *prev;
512
  const gchar *end;
513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568
  gchar *collate_key;
  gint digits;
  gint leading_zeros;

  /*
   * How it works:
   *
   * Split the filename into collatable substrings which do
   * not contain [.0-9] and special-cased substrings. The collatable 
   * substrings are run through the normal g_utf8_collate_key() and the 
   * resulting keys are concatenated with keys generated from the 
   * special-cased substrings.
   *
   * Special cases: Dots are handled by replacing them with '\1' which 
   * implies that short dot-delimited substrings are before long ones, 
   * e.g.
   * 
   *   a\1a   (a.a)
   *   a-\1a  (a-.a)
   *   aa\1a  (aa.a)
   * 
   * Numbers are handled by prepending to each number d-1 superdigits 
   * where d = number of digits in the number and SUPERDIGIT is a 
   * character with an integer value higher than any digit (for instance 
   * ':'). This ensures that single-digit numbers are sorted before 
   * double-digit numbers which in turn are sorted separately from 
   * triple-digit numbers, etc. To avoid strange side-effects when 
   * sorting strings that already contain SUPERDIGITs, a '\2'
   * is also prepended, like this
   *
   *   file\21      (file1)
   *   file\25      (file5)
   *   file\2:10    (file10)
   *   file\2:26    (file26)
   *   file\2::100  (file100)
   *   file:foo     (file:foo)
   * 
   * This has the side-effect of sorting numbers before everything else (except
   * dots), but this is probably OK.
   *
   * Leading digits are ignored when doing the above. To discriminate
   * numbers which differ only in the number of leading digits, we append
   * the number of leading digits as a byte at the very end of the collation
   * key.
   *
   * To try avoid conflict with any collation key sequence generated by libc we
   * start each switch to a special cased part with a sentinel that hopefully
   * will sort before anything libc will generate.
   */

  if (len < 0)
    len = strlen (str);

  result = g_string_sized_new (len * 2);
  append = g_string_sized_new (0);

569 570
  end = str + len;

571
  /* No need to use utf8 functions, since we're only looking for ascii chars */
572
  for (prev = p = str; p < end; p++)
573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622
    {
      switch (*p)
	{
	case '.':
	  if (prev != p) 
	    {
	      collate_key = g_utf8_collate_key (prev, p - prev);
	      g_string_append (result, collate_key);
	      g_free (collate_key);
	    }
	  
	  g_string_append (result, COLLATION_SENTINEL "\1");
	  
	  /* skip the dot */
	  prev = p + 1;
	  break;
	  
	case '0':
	case '1':
	case '2':
	case '3':
	case '4':
	case '5':
	case '6':
	case '7':
	case '8':
	case '9':
	  if (prev != p) 
	    {
	      collate_key = g_utf8_collate_key (prev, p - prev);
	      g_string_append (result, collate_key);
	      g_free (collate_key);
	    }
	  
	  g_string_append (result, COLLATION_SENTINEL "\2");
	  
	  prev = p;
	  
	  /* write d-1 colons */
	  if (*p == '0')
	    {
	      leading_zeros = 1;
	      digits = 0;
	    }
	  else
	    {
	      leading_zeros = 0;
	      digits = 1;
	    }
	  
623
	  while (++p < end)
624 625 626 627 628 629
	    {
	      if (*p == '0' && !digits)
		++leading_zeros;
	      else if (g_ascii_isdigit(*p))
		++digits;
	      else
630 631 632 633 634 635 636 637 638 639 640
                {
 		  /* count an all-zero sequence as
                   * one digit plus leading zeros
                   */
          	  if (!digits)
                    {
                      ++digits;
                      --leading_zeros;
                    }        
		  break;
                }
641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678
	    }

	  while (digits > 1)
	    {
	      g_string_append_c (result, ':');
	      --digits;
	    }

	  if (leading_zeros > 0)
	    {
	      g_string_append_c (append, (char)leading_zeros);
	      prev += leading_zeros;
	    }
	  
	  /* write the number itself */
	  g_string_append_len (result, prev, p - prev);
	  
	  prev = p;
	  --p;	  /* go one step back to avoid disturbing outer loop */
	  break;
	  
	default:
	  /* other characters just accumulate */
	  break;
	}
    }
  
  if (prev != p) 
    {
      collate_key = g_utf8_collate_key (prev, p - prev);
      g_string_append (result, collate_key);
      g_free (collate_key);
    }
  
  g_string_append (result, append->str);
  g_string_free (append, TRUE);

  return g_string_free (result, FALSE);
679 680 681
#else /* HAVE_CARBON */
  return carbon_collate_key_for_filename (str, len);
#endif
682
}