utf.h 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. #ifndef _LINUX_UTF_H
  2. #define _LINUX_UTF_H
  3. #include <asm/unaligned.h>
  4. static inline int utf8_to_utf16le(const char *s, __le16 *cp, unsigned len)
  5. {
  6. int count = 0;
  7. u8 c;
  8. u16 uchar;
  9. /*
  10. * this insists on correct encodings, though not minimal ones.
  11. * BUT it currently rejects legit 4-byte UTF-8 code points,
  12. * which need surrogate pairs. (Unicode 3.1 can use them.)
  13. */
  14. while (len != 0 && (c = (u8) *s++) != 0) {
  15. if ((c & 0x80)) {
  16. /*
  17. * 2-byte sequence:
  18. * 00000yyyyyxxxxxx = 110yyyyy 10xxxxxx
  19. */
  20. if ((c & 0xe0) == 0xc0) {
  21. uchar = (c & 0x1f) << 6;
  22. c = (u8) *s++;
  23. if ((c & 0xc0) != 0x80)
  24. goto fail;
  25. c &= 0x3f;
  26. uchar |= c;
  27. /*
  28. * 3-byte sequence (most CJKV characters):
  29. * zzzzyyyyyyxxxxxx = 1110zzzz 10yyyyyy 10xxxxxx
  30. */
  31. } else if ((c & 0xf0) == 0xe0) {
  32. uchar = (c & 0x0f) << 12;
  33. c = (u8) *s++;
  34. if ((c & 0xc0) != 0x80)
  35. goto fail;
  36. c &= 0x3f;
  37. uchar |= c << 6;
  38. c = (u8) *s++;
  39. if ((c & 0xc0) != 0x80)
  40. goto fail;
  41. c &= 0x3f;
  42. uchar |= c;
  43. /* no bogus surrogates */
  44. if (0xd800 <= uchar && uchar <= 0xdfff)
  45. goto fail;
  46. /*
  47. * 4-byte sequence (surrogate pairs, currently rare):
  48. * 11101110wwwwzzzzyy + 110111yyyyxxxxxx
  49. * = 11110uuu 10uuzzzz 10yyyyyy 10xxxxxx
  50. * (uuuuu = wwww + 1)
  51. * FIXME accept the surrogate code points (only)
  52. */
  53. } else
  54. goto fail;
  55. } else
  56. uchar = c;
  57. put_unaligned_le16(uchar, cp++);
  58. count++;
  59. len--;
  60. }
  61. return count;
  62. fail:
  63. return -1;
  64. }
  65. #endif /* _LINUX_UTF_H */