about summary refs log tree commit diff
path: root/stdlib/wcstombs.c
blob: 6ddbfb17252a5b6a5d0f54ecaf2ad15f15589a1f (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
/* Copyright (C) 1991, 1992, 1995 Free Software Foundation, Inc.
This file is part of the GNU C Library.

The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public License as
published by the Free Software Foundation; either version 2 of the
License, or (at your option) any later version.

The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
Library General Public License for more details.

You should have received a copy of the GNU Library General Public
License along with the GNU C Library; see the file COPYING.LIB.  If
not, write to the Free Software Foundation, Inc., 675 Mass Ave,
Cambridge, MA 02139, USA.  */

#include <ansidecl.h>
#include "../locale/localeinfo.h"
#include <ctype.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>


/* Convert the `wchar_t' string in PWCS to a multibyte character string
   in S, writing no more than N characters.  Return the number of bytes
   written, or (size_t) -1 if an invalid `wchar_t' was found.  */
size_t
DEFUN(wcstombs, (s, pwcs, n),
      register char *s AND register CONST wchar_t *pwcs AND register size_t n)
{
#if 0
  register CONST mb_char *mb;
  register int shift = 0;
#endif

  register size_t written = 0;
  register wchar_t w;

  while ((w = *pwcs++) != (wchar_t) '\0')
    {
      if (isascii (w))
	{
	  /* A normal character.  */
	  *s++ = (unsigned char) w;
	  --n;
	  ++written;
	}
      else
	{
#if 1
	  written = (size_t) -1;
	  break;
#else
	  mb = &_ctype_info->mbchar->mb_chars[w + shift];
	  if (mb->string == NULL || mb->len == 0)
	    {
	      written = (size_t) -1;
	      break;
	    }
	  else if (mb->len > n)
	    break;
	  else
	    {
	      memcpy ((PTR) s, (CONST PTR) mb->string, mb->len);
	      s += mb->len;
	      n -= mb->len;
	      written += mb->len;
	      shift += mb->shift;
	    }
#endif
	}
    }

  /* Terminate the string if it has space.  */
  if (n > 0)
    *s = '\0';

  /* Return the number of characters written (or maybe an error).  */
  return written;
}