*** empty log message ***
[coreutils.git] / lib / memxfrm.c
blob09bb5f4ad03167d42ad28f83a95eb0afc1d25da4
1 /* Locale-specific memory transformation
3 Copyright (C) 2006 Free Software Foundation, Inc.
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 2, or (at your option)
8 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
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software Foundation,
17 Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
19 /* Written by Paul Eggert <eggert@cs.ucla.edu>. */
21 #include <config.h>
23 #include "memxfrm.h"
25 #include <errno.h>
26 #include <stdlib.h>
27 #include <string.h>
29 /* Store into DEST (of size DESTSIZE) the text in SRC (of size SRCSIZE)
30 transformed so that the result of memcmp on two transformed texts
31 (with ties going to the longer text) is the same as the result of
32 memcoll on the two texts before their transformation. Perhaps
33 temporarily modify the byte after SRC, but restore its original
34 contents before returning.
36 Return the size of the resulting text, or an indeterminate value if
37 there is an error. Set errno to an error number if there is an
38 error, and to zero otherwise. DEST contains an indeterminate value
39 if there is an error or if the resulting size is greater than
40 DESTSIZE. */
42 size_t
43 memxfrm (char *restrict dest, size_t destsize,
44 char *restrict src, size_t srcsize)
46 #if HAVE_STRXFRM
48 size_t di = 0;
49 size_t si = 0;
50 size_t result = 0;
52 char ch = src[srcsize];
53 src[srcsize] = '\0';
55 while (si < srcsize)
57 size_t slen = strlen (src + si);
59 size_t result0 = result;
60 errno = 0;
61 result += strxfrm (dest + di, src + si, destsize - di) + 1;
62 if (errno != 0)
63 break;
64 if (result <= result0)
66 errno = ERANGE;
67 break;
70 if (result == destsize + 1 && si + slen == srcsize)
72 /* The destination is exactly the right size, but strxfrm wants
73 room for a trailing null. Work around the problem with a
74 temporary buffer. */
75 size_t bufsize = destsize - di + 1;
76 char stackbuf[4000];
77 char *buf = stackbuf;
78 if (sizeof stackbuf < bufsize)
80 buf = malloc (bufsize);
81 if (! buf)
82 break;
84 strxfrm (buf, src + si, bufsize);
85 memcpy (dest + di, buf, destsize - di);
86 if (sizeof stackbuf < bufsize)
87 free (buf);
88 errno = 0;
91 di = (result < destsize ? result : destsize);
92 si += slen + 1;
95 src[srcsize] = ch;
96 return result - (si != srcsize);
98 #else
100 if (srcsize < destsize)
101 memcpy (dest, src, srcsize);
102 errno = 0;
103 return srcsize;
105 #endif