/******************************************
* Converts the UTF-8 string s into a MB string in a Windows
* 8-bit character set.
*
* Params:
* s = UTF-8 string to convert.
* codePage = is the number of the target codepage, or
* 0 - ANSI,
* 1 - OEM,
* 2 - Mac
*
* Authors:
* yaneurao, Walter Bright, Stewart Gordon
* D语言论坛
http://www.d-programming-language-china.org */
char[] toMBS(char[] s, uint codePage = 0)
{
// Only need to do this if any chars have the high bit set
foreach (char c; s)
{
if (c >= 0x80)
{
char[] result;
int readLen;
wchar* ws = std.utf.toUTF16z(s);
result.length = WideCharToMultiByte(codePage, 0, ws, -1, null, 0,
null, null);
if (result.length)
{
readLen = WideCharToMultiByte(codePage, 0, ws, -1, result.ptr,
result.length, null, null);
}
if (!readLen || readLen != result.length)
{
throw new Exception("Couldn't convert string: " ~
sysErrorString(GetLastError()));
}
return result[0..$-1];//去掉尾随的\0,只有这句和下句和toMBSz不同
}
}
return s;
}
/**********************************************
* Converts the MB string s from a Windows 8-bit character set
* into a UTF-8 char array.
*
* Params:
* s = UTF-8 string to convert.
* codePage = is the number of the source codepage, or
* 0 - ANSI,
* 1 - OEM,
* 2 - Mac
* Authors: Stewart Gordon, Walter Bright
* D语言论坛
http://www.d-programming-language-china.org */
char[] fromMBS(char* s, int codePage = 0)
{
char* c;
for (c = s; *c != 0; c++)
{
if (*c >= 0x80)
{
wchar[] result;
int readLen;
result.length = MultiByteToWideChar(codePage, 0, s, -1, null, 0);
if (result.length)
{
readLen = MultiByteToWideChar(codePage, 0, s, -1, result.ptr,
result.length);
}
if (!readLen || readLen != result.length)
{
throw new Exception("Couldn't convert string: " ~
sysErrorString(GetLastError()));
}
return std.utf.toUTF8(result[0 .. result.length-1]); // omit trailing null
}
}
return s[0 .. c-s+1]; // string is ASCII, no conversion necessary 只有这句和fromMBSz不同,也就是多了+1
}