EncodingC.c 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. /*============================================================================
  2. KWSys - Kitware System Library
  3. Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
  4. Distributed under the OSI-approved BSD License (the "License");
  5. see accompanying file Copyright.txt for details.
  6. This software is distributed WITHOUT ANY WARRANTY; without even the
  7. implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  8. See the License for more information.
  9. ============================================================================*/
  10. #include "kwsysPrivate.h"
  11. #include KWSYS_HEADER(Encoding.h)
  12. /* Work-around CMake dependency scanning limitation. This must
  13. duplicate the above list of headers. */
  14. #if 0
  15. # include "Encoding.h.in"
  16. #endif
  17. #include <stdlib.h>
  18. #ifdef _WIN32
  19. #include <windows.h>
  20. #endif
  21. size_t kwsysEncoding_mbstowcs(wchar_t* dest, const char* str, size_t n)
  22. {
  23. if(str == 0)
  24. {
  25. return (size_t)-1;
  26. }
  27. #ifdef _WIN32
  28. return MultiByteToWideChar(KWSYS_ENCODING_DEFAULT_CODEPAGE, 0,
  29. str, -1, dest, (int)n) - 1;
  30. #else
  31. return mbstowcs(dest, str, n);
  32. #endif
  33. }
  34. wchar_t* kwsysEncoding_DupToWide(const char* str)
  35. {
  36. wchar_t* ret = NULL;
  37. size_t length = kwsysEncoding_mbstowcs(NULL, str, 0) + 1;
  38. if(length > 0)
  39. {
  40. ret = (wchar_t*)malloc((length)*sizeof(wchar_t));
  41. if(ret)
  42. {
  43. ret[0] = 0;
  44. kwsysEncoding_mbstowcs(ret, str, length);
  45. }
  46. }
  47. return ret;
  48. }
  49. size_t kwsysEncoding_wcstombs(char* dest, const wchar_t* str, size_t n)
  50. {
  51. if(str == 0)
  52. {
  53. return (size_t)-1;
  54. }
  55. #ifdef _WIN32
  56. return WideCharToMultiByte(KWSYS_ENCODING_DEFAULT_CODEPAGE, 0, str, -1,
  57. dest, (int)n, NULL, NULL) - 1;
  58. #else
  59. return wcstombs(dest, str, n);
  60. #endif
  61. }
  62. char* kwsysEncoding_DupToNarrow(const wchar_t* str)
  63. {
  64. char* ret = NULL;
  65. size_t length = kwsysEncoding_wcstombs(0, str, 0) + 1;
  66. if(length > 0)
  67. {
  68. ret = (char*)malloc(length);
  69. if(ret)
  70. {
  71. ret[0] = 0;
  72. kwsysEncoding_wcstombs(ret, str, length);
  73. }
  74. }
  75. return ret;
  76. }