dirent: Fix compilation error in C++ mode on OS/2 kLIBC.
[gnulib.git] / lib / unistr / u-strcoll.h
blobae1b8104c2b8278f3635a08a4e2b2bdf26a12d0e
1 /* Compare UTF-8/UTF-16/UTF-32 strings using the collation rules of the current
2 locale.
3 Copyright (C) 2009-2021 Free Software Foundation, Inc.
4 Written by Bruno Haible <bruno@clisp.org>, 2009.
6 This program is free software: you can redistribute it and/or modify it
7 under the terms of the GNU Lesser General Public License as published
8 by the Free Software Foundation; either version 3 of the License, or
9 (at your option) any later version.
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 Lesser General Public License for more details.
16 You should have received a copy of the GNU Lesser General Public License
17 along with this program. If not, see <https://www.gnu.org/licenses/>. */
19 int
20 FUNC (const UNIT *s1, const UNIT *s2)
22 /* When this function succeeds, it sets errno back to its original value.
23 When it fails, it sets errno, but also returns a meaningful return value,
24 for the sake of callers which ignore errno. */
25 int final_errno = errno;
26 const char *encoding = locale_charset ();
27 char *sl1;
28 char *sl2;
29 int result;
31 /* Pass iconveh_error here, not iconveh_question_mark. Otherwise the
32 conversion to locale encoding can do transliteration or map some
33 characters to question marks, leading to results that depend on the
34 iconv() implementation and are not obvious. */
35 sl1 = U_STRCONV_TO_ENCODING (s1, encoding, iconveh_error);
36 if (sl1 != NULL)
38 sl2 = U_STRCONV_TO_ENCODING (s2, encoding, iconveh_error);
39 if (sl2 != NULL)
41 /* Compare sl1 and sl2. */
42 errno = 0;
43 result = strcoll (sl1, sl2);
44 if (errno == 0)
46 /* strcoll succeeded. */
47 free (sl1);
48 free (sl2);
49 /* The conversion to locale encoding can drop Unicode TAG
50 characters. Therefore sl1 and sl2 may be equal when s1
51 and s2 were in fact different. Return a nonzero result
52 in this case. */
53 if (result == 0)
54 result = U_STRCMP (s1, s2);
56 else
58 /* strcoll failed. */
59 final_errno = errno;
60 free (sl1);
61 free (sl2);
62 result = U_STRCMP (s1, s2);
65 else
67 /* s1 could be converted to locale encoding, s2 not. */
68 final_errno = errno;
69 free (sl1);
70 result = -1;
73 else
75 final_errno = errno;
76 sl2 = U_STRCONV_TO_ENCODING (s2, encoding, iconveh_error);
77 if (sl2 != NULL)
79 /* s2 could be converted to locale encoding, s1 not. */
80 free (sl2);
81 result = 1;
83 else
85 /* Neither s1 nor s2 could be converted to locale encoding. */
86 result = U_STRCMP (s1, s2);
90 errno = final_errno;
91 return result;