1 /* Locale dependent memory area transformation for comparison.
2 Copyright (C) 2009, 2010 Free Software Foundation, Inc.
3 Written by Bruno Haible <bruno@clisp.org>, 2009.
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 memxfrm (char *s, size_t n, char *resultbuf, size_t *lengthp)
30 /* Result accumulator. */
37 /* Initial memory allocation. */
38 if (resultbuf != NULL && *lengthp > 0)
45 allocated = (n > 0 ? n : 1);
46 result = (char *) malloc (allocated);
52 /* Add sentinel.byte. */
56 /* Iterate through S, transforming each NUL terminated segment.
57 Accumulate the resulting transformed segments in result, separated by
60 const char *p_end = s + n + 1;
66 /* Search next NUL byte. */
67 const char *q = p + strlen (p);
74 k = strxfrm (result + length, p, allocated - length);
77 if (k >= allocated - length)
79 /* Grow the result buffer. */
82 allocated = 2 * allocated;
85 if (result == resultbuf)
86 new_result = (char *) malloc (allocated);
88 new_result = (char *) realloc (result, allocated);
89 if (new_result == NULL)
103 result[length] = '\0';
108 /* Shrink the allocated memory if possible. */
109 if (result != resultbuf && (length > 0 ? length : 1) < allocated)
111 char *memory = (char *) realloc (result, length > 0 ? length : 1);
116 s[n] = orig_sentinel;
122 int saved_errno = errno;
123 if (result != resultbuf)
125 s[n] = orig_sentinel;
131 if (result != resultbuf)
133 s[n] = orig_sentinel;