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

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