36958f4af494456647e6e2dea99e7636188edc79
[gnulib.git] / lib / xmemcoll.c
1 /* Locale-specific memory comparison.
2
3    Copyright (C) 2002-2004, 2006, 2009-2010 Free Software Foundation, Inc.
4
5    This program is free software: you can redistribute it and/or modify
6    it under the terms of the GNU General Public License as published by
7    the Free Software Foundation; either version 3 of the License, or
8    (at your option) any later version.
9
10    This program 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
13    GNU General Public License for more details.
14
15    You should have received a copy of the GNU General Public License
16    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
17
18 /* Contributed by Paul Eggert <eggert@twinsun.com>.  */
19
20 #include <config.h>
21
22 #include <errno.h>
23 #include <stdlib.h>
24
25 #include "gettext.h"
26 #define _(msgid) gettext (msgid)
27
28 #include "error.h"
29 #include "exitfail.h"
30 #include "memcoll.h"
31 #include "quotearg.h"
32 #include "xmemcoll.h"
33
34 static inline void
35 collate_error (int collation_errno, const char *s1, size_t s1len,
36                const char *s2, size_t s2len)
37 {
38   error (0, collation_errno, _("string comparison failed"));
39   error (0, 0, _("Set LC_ALL='C' to work around the problem."));
40   error (exit_failure, 0,
41          _("The strings compared were %s and %s."),
42          quotearg_n_style_mem (0, locale_quoting_style, s1, s1len),
43          quotearg_n_style_mem (1, locale_quoting_style, s2, s2len));
44 }
45
46 /* Compare S1 (with length S1LEN) and S2 (with length S2LEN) according
47    to the LC_COLLATE locale.  S1 and S2 do not overlap, and are not
48    adjacent.  Temporarily modify the bytes after S1 and S2, but
49    restore their original contents before returning.  Report an error
50    and exit if there is an error.  */
51
52 int
53 xmemcoll (char *s1, size_t s1len, char *s2, size_t s2len)
54 {
55   int diff = memcoll (s1, s1len, s2, s2len);
56   int collation_errno = errno;
57
58   if (collation_errno)
59     collate_error (collation_errno, s1, s1len, s2, s2len);
60
61   return diff;
62 }
63
64 /* Like xmemcoll, but S1 and S2 are known to be NUL delimited, thus
65    no modifications to S1 and S2 are needed. */
66
67 int
68 xmemcoll0 (const char *s1, size_t s1len, const char *s2, size_t s2len)
69 {
70   int diff = memcoll0 (s1, s1len, s2, s2len);
71   int collation_errno = errno;
72
73   if (collation_errno)
74     collate_error (collation_errno, s1, s1len, s2, s2len);
75   return diff;
76 }