Blame lib/unistr/u8-uctomb-aux.c

Packit 33f14e
/* Conversion UCS-4 to UTF-8.
Packit 33f14e
   Copyright (C) 2002, 2006-2007, 2009-2017 Free Software Foundation, Inc.
Packit 33f14e
   Written by Bruno Haible <bruno@clisp.org>, 2002.
Packit 33f14e
Packit 33f14e
   This program is free software: you can redistribute it and/or modify it
Packit 33f14e
   under the terms of the GNU General Public License as published
Packit 33f14e
   by the Free Software Foundation; either version 3 of the License, or
Packit 33f14e
   (at your option) any later version.
Packit 33f14e
Packit 33f14e
   This program is distributed in the hope that it will be useful,
Packit 33f14e
   but WITHOUT ANY WARRANTY; without even the implied warranty of
Packit 33f14e
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
Packit 33f14e
   General Public License for more details.
Packit 33f14e
Packit 33f14e
   You should have received a copy of the GNU General Public License
Packit 33f14e
   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
Packit 33f14e
Packit 33f14e
#include <config.h>
Packit 33f14e
Packit 33f14e
/* Specification.  */
Packit 33f14e
#include "unistr.h"
Packit 33f14e
Packit 33f14e
#ifndef FALLTHROUGH
Packit 33f14e
# if __GNUC__ < 7
Packit 33f14e
#  define FALLTHROUGH ((void) 0)
Packit 33f14e
# else
Packit 33f14e
#  define FALLTHROUGH __attribute__ ((__fallthrough__))
Packit 33f14e
# endif
Packit 33f14e
#endif
Packit 33f14e
Packit 33f14e
int
Packit 33f14e
u8_uctomb_aux (uint8_t *s, ucs4_t uc, int n)
Packit 33f14e
{
Packit 33f14e
  int count;
Packit 33f14e
Packit 33f14e
  if (uc < 0x80)
Packit 33f14e
    /* The case n >= 1 is already handled by the caller.  */
Packit 33f14e
    return -2;
Packit 33f14e
  else if (uc < 0x800)
Packit 33f14e
    count = 2;
Packit 33f14e
  else if (uc < 0x10000)
Packit 33f14e
    {
Packit 33f14e
      if (uc < 0xd800 || uc >= 0xe000)
Packit 33f14e
        count = 3;
Packit 33f14e
      else
Packit 33f14e
        return -1;
Packit 33f14e
    }
Packit 33f14e
  else if (uc < 0x110000)
Packit 33f14e
    count = 4;
Packit 33f14e
  else
Packit 33f14e
    return -1;
Packit 33f14e
Packit 33f14e
  if (n < count)
Packit 33f14e
    return -2;
Packit 33f14e
Packit 33f14e
  switch (count) /* note: code falls through cases! */
Packit 33f14e
    {
Packit 33f14e
    case 4: s[3] = 0x80 | (uc & 0x3f); uc = uc >> 6; uc |= 0x10000;
Packit 33f14e
      FALLTHROUGH;
Packit 33f14e
    case 3: s[2] = 0x80 | (uc & 0x3f); uc = uc >> 6; uc |= 0x800;
Packit 33f14e
      FALLTHROUGH;
Packit 33f14e
    case 2: s[1] = 0x80 | (uc & 0x3f); uc = uc >> 6; uc |= 0xc0;
Packit 33f14e
  /*case 1:*/ s[0] = uc;
Packit 33f14e
    }
Packit 33f14e
  return count;
Packit 33f14e
}