1 // Written in the D programming language.
4 * Support UTF-8 on Windows 95, 98 and ME systems.
6 * Copyright: Copyright The D Language Foundation" 2005 - 2009.
7 * License: $(HTTP www.boost.org/LICENSE_1_0.txt, Boost License 1.0).
8 * Authors: $(HTTP digitalmars.com, Walter Bright)
10 /* Copyright The D Language Foundation" 2005 - 2009.
11 * Distributed under the Boost Software License, Version 1.0.
12 * (See accompanying file LICENSE_1_0.txt or copy at
13 * http://www.boost.org/LICENSE_1_0.txt)
15 module std.windows.charset;
19 /******************************************
20 * Converts the UTF-8 string s into a null-terminated string in a Windows
21 * 8-bit character set.
24 * s = UTF-8 string to convert.
25 * codePage = is the number of the target codepage, or
31 * yaneurao, Walter Bright, Stewart Gordon
33 const(char)* toMBSz(scope const(char)[] s, uint codePage = 0);
35 /**********************************************
36 * Converts the null-terminated string s from a Windows 8-bit character set
37 * into a UTF-8 char array.
40 * s = UTF-8 string to convert.
41 * codePage = is the number of the source codepage, or
45 * Authors: Stewart Gordon, Walter Bright
47 string fromMBSz(immutable(char)* s, int codePage = 0);
53 import core.sys.windows.winbase, core.sys.windows.winnls;
56 import std.windows.syserror;
58 import std.internal.cstring;
60 const(char)* toMBSz(scope const(char)[] s, uint codePage = 0)
62 // Only need to do this if any chars have the high bit set
69 auto wsTmp = s.tempCStringW();
70 result.length = WideCharToMultiByte(codePage, 0, wsTmp, -1, null, 0,
75 readLen = WideCharToMultiByte(codePage, 0, wsTmp, -1, result.ptr,
76 to!int(result.length), null, null);
79 if (!readLen || readLen != result.length)
81 throw new Exception("Couldn't convert string: " ~
82 sysErrorString(GetLastError()));
88 return std.string.toStringz(s);
91 string fromMBSz(return scope immutable(char)* s, int codePage = 0)
95 for (c = s; *c != 0; c++)
102 result.length = MultiByteToWideChar(codePage, 0, s, -1, null, 0);
106 readLen = MultiByteToWideChar(codePage, 0, s, -1, result.ptr,
107 to!int(result.length));
110 if (!readLen || readLen != result.length)
112 throw new Exception("Couldn't convert string: " ~
113 sysErrorString(GetLastError()));
116 return result[0 .. result.length-1].to!string; // omit trailing null
119 return s[0 .. c-s]; // string is ASCII, no conversion necessary