testiconv.c 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. /*
  2. Copyright (C) 1997-2014 Sam Lantinga <slouken@libsdl.org>
  3. This software is provided 'as-is', without any express or implied
  4. warranty. In no event will the authors be held liable for any damages
  5. arising from the use of this software.
  6. Permission is granted to anyone to use this software for any purpose,
  7. including commercial applications, and to alter it and redistribute it
  8. freely.
  9. */
  10. #include <stdio.h>
  11. #include "SDL.h"
  12. static size_t
  13. widelen(char *data)
  14. {
  15. size_t len = 0;
  16. Uint32 *p = (Uint32 *) data;
  17. while (*p++) {
  18. ++len;
  19. }
  20. return len;
  21. }
  22. int
  23. main(int argc, char *argv[])
  24. {
  25. const char *formats[] = {
  26. "UTF8",
  27. "UTF-8",
  28. "UTF16BE",
  29. "UTF-16BE",
  30. "UTF16LE",
  31. "UTF-16LE",
  32. "UTF32BE",
  33. "UTF-32BE",
  34. "UTF32LE",
  35. "UTF-32LE",
  36. "UCS4",
  37. "UCS-4",
  38. };
  39. char buffer[BUFSIZ];
  40. char *ucs4;
  41. char *test[2];
  42. int i;
  43. FILE *file;
  44. int errors = 0;
  45. /* Enable standard application logging */
  46. SDL_LogSetPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO);
  47. if (!argv[1]) {
  48. argv[1] = "utf8.txt";
  49. }
  50. file = fopen(argv[1], "rb");
  51. if (!file) {
  52. SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Unable to open %s\n", argv[1]);
  53. return (1);
  54. }
  55. while (fgets(buffer, sizeof(buffer), file)) {
  56. /* Convert to UCS-4 */
  57. size_t len;
  58. ucs4 =
  59. SDL_iconv_string("UCS-4", "UTF-8", buffer,
  60. SDL_strlen(buffer) + 1);
  61. len = (widelen(ucs4) + 1) * 4;
  62. for (i = 0; i < SDL_arraysize(formats); ++i) {
  63. test[0] = SDL_iconv_string(formats[i], "UCS-4", ucs4, len);
  64. test[1] = SDL_iconv_string("UCS-4", formats[i], test[0], len);
  65. if (!test[1] || SDL_memcmp(test[1], ucs4, len) != 0) {
  66. SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "FAIL: %s\n", formats[i]);
  67. ++errors;
  68. }
  69. SDL_free(test[0]);
  70. SDL_free(test[1]);
  71. }
  72. test[0] = SDL_iconv_string("UTF-8", "UCS-4", ucs4, len);
  73. SDL_free(ucs4);
  74. fputs(test[0], stdout);
  75. SDL_free(test[0]);
  76. }
  77. fclose(file);
  78. return (errors ? errors + 1 : 0);
  79. }