1
0

sys2utf8.c 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. #include "geniconv.h"
  2. #include <stdlib.h>
  3. int StrUTF8(int fToUTF8, char *pcDst, int cbDst, char *pcSrc, int cbSrc)
  4. {
  5. size_t rc;
  6. char *pcDstStart = pcDst;
  7. iconv_t cd;
  8. char *pszToCP, *pszFromCP;
  9. int fError = 0;
  10. if ( cbDst < 4 )
  11. return -1;
  12. if ( fToUTF8 )
  13. {
  14. pszToCP = "UTF-8";
  15. pszFromCP = "";
  16. }
  17. else
  18. {
  19. pszToCP = "";
  20. pszFromCP = "UTF-8";
  21. }
  22. cd = iconv_open( pszToCP, pszFromCP );
  23. if ( cd == (iconv_t)-1 )
  24. return -1;
  25. while( cbSrc > 0 )
  26. {
  27. rc = iconv( cd, &pcSrc, (size_t *)&cbSrc, &pcDst, (size_t *)&cbDst );
  28. if ( rc == (size_t)-1 )
  29. {
  30. if ( errno == EILSEQ )
  31. {
  32. // Try to skip invalid character.
  33. pcSrc++;
  34. cbSrc--;
  35. continue;
  36. }
  37. fError = 1;
  38. break;
  39. }
  40. }
  41. iconv_close( cd );
  42. // Write trailing ZERO (1 byte for UTF-8, 2 bytes for the system cp).
  43. if ( fToUTF8 )
  44. {
  45. if ( cbDst < 1 )
  46. {
  47. pcDst--;
  48. fError = 1; // The destination buffer overflow.
  49. }
  50. *pcDst = '\0';
  51. }
  52. else
  53. {
  54. if ( cbDst < 2 )
  55. {
  56. pcDst -= ( cbDst == 0 ) ? 2 : 1;
  57. fError = 1; // The destination buffer overflow.
  58. }
  59. *((short *)pcDst) = '\0';
  60. }
  61. return fError ? -1 : ( pcDst - pcDstStart );
  62. }
  63. char *StrUTF8New(int fToUTF8, char *pcStr, int cbStr)
  64. {
  65. int cbNewStr = ( ( cbStr > 4 ? cbStr : 4 ) + 1 ) * 2;
  66. char *pszNewStr = malloc( cbNewStr );
  67. if ( pszNewStr == NULL )
  68. return NULL;
  69. cbNewStr = StrUTF8( fToUTF8, pszNewStr, cbNewStr, pcStr, cbStr );
  70. if ( cbNewStr != -1 )
  71. {
  72. pcStr = realloc( pszNewStr, cbNewStr + ( fToUTF8 ? 1 : sizeof(short) ) );
  73. if ( pcStr != NULL )
  74. return pcStr;
  75. }
  76. free( pszNewStr );
  77. return NULL;
  78. }
  79. void StrUTF8Free(char *pszStr)
  80. {
  81. free( pszStr );
  82. }