iconv.c (2190B)
1 /* 2 This file is part of libextractor. 3 Copyright (C) 2002, 2003, 2004 Vidyut Samanta and Christian Grothoff 4 5 libextractor is free software; you can redistribute it and/or modify 6 it under the terms of the GNU General Public License as published 7 by the Free Software Foundation; either version 2, or (at your 8 option) any later version. 9 10 libextractor is distributed in the hope that it will be useful, but 11 WITHOUT ANY WARRANTY; without even the implied warranty of 12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 13 General Public License for more details. 14 15 You should have received a copy of the GNU General Public License 16 along with libextractor; see the file COPYING. If not, write to the 17 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, 18 Boston, MA 02110-1301, USA. 19 */ 20 21 /** 22 * @file main/iconv.c 23 * @brief convenience functions for character conversion 24 * @author Christian Grothoff 25 */ 26 27 /** 28 * Convert the given input using the given converter 29 * and return as a 0-terminated string. 30 * 31 * @param cd converter to use 32 * @param in input string 33 * @param inSize number of bytes in 'in' 34 * @return NULL on error, otherwise the converted string (to be free'd by caller) 35 */ 36 static char * 37 iconv_helper (iconv_t cd, 38 const char *in, 39 size_t inSize) 40 { 41 #if HAVE_ICONV 42 char *buf; 43 char *ibuf; 44 const char *i; 45 size_t outSize; 46 size_t outLeft; 47 48 if (inSize > 1024 * 1024) 49 return NULL; /* too big to be meta data */ 50 i = in; 51 /* reset iconv */ 52 iconv (cd, NULL, NULL, NULL, NULL); 53 outSize = 4 * inSize + 2; 54 outLeft = outSize - 2; /* make sure we have 2 0-terminations! */ 55 if (NULL == (buf = malloc (outSize))) 56 return NULL; 57 ibuf = buf; 58 memset (buf, 0, outSize); 59 if (iconv (cd, 60 (char**) &in, 61 &inSize, 62 &ibuf, 63 &outLeft) == SIZE_MAX) 64 { 65 /* conversion failed */ 66 free (buf); 67 return strdup (i); 68 } 69 return buf; 70 #else 71 /* good luck, just copying string... */ 72 char *buf; 73 74 buf = malloc (inSize + 1); 75 memcpy (buf, in, inSize); 76 buf[inSize] = '\0'; 77 #endif 78 } 79 80 81 /* end of iconv.c */