u8-uctomb-aux.c 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. /* Conversion UCS-4 to UTF-8.
  2. Copyright (C) 2002, 2006-2007, 2009-2020 Free Software Foundation, Inc.
  3. Written by Bruno Haible <bruno@clisp.org>, 2002.
  4. This program is free software: you can redistribute it and/or modify it
  5. under the terms of the GNU General Public License as published
  6. by the Free Software Foundation; either version 3 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  11. General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program. If not, see <https://www.gnu.org/licenses/>. */
  14. #include <config.h>
  15. /* Specification. */
  16. #include "unistr.h"
  17. #include "attribute.h"
  18. int
  19. u8_uctomb_aux (uint8_t *s, ucs4_t uc, ptrdiff_t n)
  20. {
  21. int count;
  22. if (uc < 0x80)
  23. /* The case n >= 1 is already handled by the caller. */
  24. return -2;
  25. else if (uc < 0x800)
  26. count = 2;
  27. else if (uc < 0x10000)
  28. {
  29. if (uc < 0xd800 || uc >= 0xe000)
  30. count = 3;
  31. else
  32. return -1;
  33. }
  34. else if (uc < 0x110000)
  35. count = 4;
  36. else
  37. return -1;
  38. if (n < count)
  39. return -2;
  40. switch (count) /* note: code falls through cases! */
  41. {
  42. case 4: s[3] = 0x80 | (uc & 0x3f); uc = uc >> 6; uc |= 0x10000;
  43. FALLTHROUGH;
  44. case 3: s[2] = 0x80 | (uc & 0x3f); uc = uc >> 6; uc |= 0x800;
  45. FALLTHROUGH;
  46. case 2: s[1] = 0x80 | (uc & 0x3f); uc = uc >> 6; uc |= 0xc0;
  47. /*case 1:*/ s[0] = uc;
  48. }
  49. return count;
  50. }