1 /* Locale dependent string transformation for comparison.
2 Copyright (C) 2010-2011 Free Software Foundation, Inc.
3 Written by Bruno Haible <bruno@clisp.org>, 2010.
5 This program is free software: you can redistribute it and/or modify it
6 under the terms of the GNU Lesser General Public License as published
7 by the Free Software Foundation; either version 3 of the License, or
8 (at your option) any later version.
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 GNU
13 Lesser General Public License for more details.
15 You should have received a copy of the GNU Lesser General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>. */
28 astrxfrm (const char *s, char *resultbuf, size_t *lengthp)
31 char *result; /* either == resultbuf or == tmpbuf or freshly allocated
33 size_t allocated; /* number of bytes allocated at result */
36 if (resultbuf != NULL)
48 size_t l = strlen (s);
51 /* A call to strxfrm costs about 20 times more than a call to strdup of
52 the result. Therefore it is worth to try to avoid calling strxfrm
53 more than once on a given string, by making enough room before calling
54 strxfrm. The size of the strxfrm result, k, is likely to be between
56 if (3 * l + 1 > allocated)
58 /* Grow the result buffer. */
59 if (3 * l + 1 <= sizeof (tmpbuf))
62 allocated = sizeof (tmpbuf);
69 new_allocated = 3 * l + 1;
70 if (new_allocated < 2 * allocated)
71 new_allocated = 2 * allocated;
72 new_result = (char *) malloc (new_allocated);
73 if (new_result != NULL)
75 allocated = new_allocated;
82 k = strxfrm (result, s, allocated);
87 /* Grow the result buffer. */
88 if (result != resultbuf && result != tmpbuf)
90 if (k + 1 <= sizeof (tmpbuf))
93 allocated = sizeof (tmpbuf);
100 new_allocated = k + 1;
101 new_result = (char *) malloc (new_allocated);
102 if (new_result == NULL)
104 allocated = new_allocated;
107 /* Here k < allocated. */
111 if (strxfrm (result, s, allocated) != k)
112 /* strxfrm() is not producing reproducible results. */
118 /* Verify that strxfrm() has NUL-terminated the result. */
119 if (result[k] != '\0')
124 /* Here length > 0. */
126 if (result == tmpbuf)
128 if (resultbuf != NULL && length <= *lengthp)
130 memcpy (resultbuf, result, length);
135 char *memory = (char *) malloc (length);
139 memcpy (memory, result, length);
145 /* Shrink the allocated memory if possible. */
146 if (result != resultbuf && length < allocated)
148 if (length <= *lengthp)
150 memcpy (resultbuf, result, length);
156 char *memory = (char *) realloc (result, length);
159 memcpy (memory, result, length);
171 int saved_errno = errno;
172 if (result != resultbuf && result != tmpbuf)