xref: /llvm-project/libcxx/src/support/win32/support.cpp (revision dbe8111948d372a6f7445e86a0ac985717fbe1bc)
1 // -*- C++ -*-
2 //===--------------------------- support/win32/support.h --------------------------===//
3 //
4 //                     The LLVM Compiler Infrastructure
5 //
6 // This file is dual licensed under the MIT and the University of Illinois Open
7 // Source Licenses. See LICENSE.TXT for details.
8 //
9 //===----------------------------------------------------------------------===//
10 
11 #include <stddef.h> // size_t
12 #include <stdlib.h> // malloc
13 #include <stdio.h>  // vsprintf, vsnprintf
14 #include <string.h> // strcpy, wcsncpy
15 #include <wchar.h>  // mbstate_t
16 
17 int vasprintf( char **sptr, const char *__restrict__ fmt, va_list ap )
18 {
19     *sptr = NULL;
20     int count = vsnprintf( *sptr, 0, fmt, ap );
21     if( (count >= 0) && ((*sptr = (char*)malloc(count+1)) != NULL) )
22     {
23         vsprintf( *sptr, fmt, ap );
24         sptr[count] = '\0';
25     }
26 
27     return count;
28 }
29 
30 // FIXME: use wcrtomb and avoid copy
31 // use mbsrtowcs which is available, first copy first nwc elements of src
32 size_t mbsnrtowcs( wchar_t *__restrict__ dst, const char **__restrict__ src,
33                    size_t nmc, size_t len, mbstate_t *__restrict__ ps )
34 {
35     char* local_src = new char[nmc+1];
36     char* nmcsrc = local_src;
37     strncpy( nmcsrc, *src, nmc );
38     nmcsrc[nmc] = '\0';
39     const size_t result = mbsrtowcs( dst, const_cast<const char **>(&nmcsrc), len, ps );
40     // propagate error
41     if( nmcsrc == NULL )
42         *src = NULL;
43     delete[] local_src;
44     return result;
45 }
46 // FIXME: use wcrtomb and avoid copy
47 // use wcsrtombs which is available, first copy first nwc elements of src
48 size_t wcsnrtombs( char *__restrict__ dst, const wchar_t **__restrict__ src,
49                    size_t nwc, size_t len, mbstate_t *__restrict__ ps )
50 {
51     wchar_t* local_src = new wchar_t[nwc];
52     wchar_t* nwcsrc = local_src;
53     wcsncpy(nwcsrc, *src, nwc);
54     nwcsrc[nwc] = '\0';
55     const size_t result = wcsrtombs( dst, const_cast<const wchar_t **>(&nwcsrc), len, ps );
56     // propogate error
57     if( nwcsrc == NULL )
58         *src = NULL;
59     delete[] nwcsrc;
60     return result;
61 }
62