]> git.ipfire.org Git - thirdparty/bash.git/blob - lib/sh/mbscmp.c
Bash-4.4 distribution sources and documentation
[thirdparty/bash.git] / lib / sh / mbscmp.c
1 /* mbscmp - multibyte string comparison. */
2
3 /* Copyright (C) 1995-2015 Free Software Foundation, Inc.
4
5 This file is part of GNU Bash, the Bourne Again SHell.
6
7 Bash is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 3 of the License, or
10 (at your option) any later version.
11
12 Bash is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with Bash. If not, see <http://www.gnu.org/licenses/>.
19 */
20
21 #include <config.h>
22
23 #if !defined (HAVE_MBSCMP) && defined (HANDLE_MULTIBYTE)
24
25 #include <stdlib.h>
26 #include <stddef.h>
27 #include <string.h>
28
29 /* Compare MBS1 and MBS2. */
30 int
31 mbscmp (mbs1, mbs2)
32 const char *mbs1;
33 const char *mbs2;
34 {
35 int len1, len2, mb_cur_max;
36 wchar_t c1, c2;
37
38 len1 = len2 = 0;
39 /* Reset multibyte characters to their initial state. */
40 (void) mblen ((char *) NULL, 0);
41
42 mb_cur_max = MB_CUR_MAX;
43 do
44 {
45 len1 = mbtowc (&c1, mbs1, mb_cur_max);
46 len2 = mbtowc (&c2, mbs2, mb_cur_max);
47
48 if (len1 == 0)
49 return len2 == 0 ? 0 : -1;
50 else if (len2 == 0)
51 return 1;
52 else if (len1 > 0 && len2 < 0)
53 return -1;
54 else if (len1 < 0 && len2 > 0)
55 return 1;
56 else if (len1 < 0 && len2 < 0)
57 {
58 len1 = strlen (mbs1);
59 len2 = strlen (mbs2);
60 return (len1 == len2 ? memcmp (mbs1, mbs2, len1)
61 : ((len1 < len2) ? (memcmp (mbs1, mbs2, len1) > 0 ? 1 : -1)
62 : (memcmp (mbs1, mbs2, len2) >= 0 ? 1 : -1)));
63 }
64
65 mbs1 += len1;
66 mbs2 += len2;
67 }
68 while (c1 == c2);
69
70 return c1 - c2;
71 }
72
73 #endif