Utf16Encoder.h 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. /**
  2. * @file Utf16Encoder.h
  3. * @author Ambroz Bizjak <ambrop7@gmail.com>
  4. *
  5. * @section LICENSE
  6. *
  7. * This file is part of BadVPN.
  8. *
  9. * BadVPN is free software: you can redistribute it and/or modify
  10. * it under the terms of the GNU General Public License version 2
  11. * as published by the Free Software Foundation.
  12. *
  13. * BadVPN is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU General Public License along
  19. * with this program; if not, write to the Free Software Foundation, Inc.,
  20. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  21. */
  22. #ifndef BADVPN_UTF16ENCODER_H
  23. #define BADVPN_UTF16ENCODER_H
  24. #include <stdint.h>
  25. /**
  26. * Encodes a Unicode character into a sequence of 16-bit values according to UTF-16.
  27. *
  28. * @param ch Unicode character to encode
  29. * @param out will receive the encoded 16-bit values. Must have space for 2 values.
  30. * @return number of 16-bit values written, 0-2, with 0 meaning the character cannot
  31. * be encoded
  32. */
  33. static int Utf16Encoder_EncodeCharacter (uint32_t ch, uint16_t *out);
  34. int Utf16Encoder_EncodeCharacter (uint32_t ch, uint16_t *out)
  35. {
  36. if (ch <= UINT32_C(0xFFFF)) {
  37. // surrogates
  38. if (ch >= UINT32_C(0xD800) && ch <= UINT32_C(0xDFFF)) {
  39. return 0;
  40. }
  41. out[0] = ch;
  42. return 1;
  43. }
  44. if (ch <= UINT32_C(0x10FFFF)) {
  45. uint32_t x = ch - UINT32_C(0x10000);
  46. out[0] = UINT32_C(0xD800) + (x >> 10);
  47. out[1] = UINT32_C(0xDC00) + (x & UINT32_C(0x3FF));
  48. return 2;
  49. }
  50. return 0;
  51. }
  52. #endif