...one of the most highly
regarded and expertly designed C++ library projects in the
world.
— Herb Sutter and Andrei
Alexandrescu, C++
Coding Standards
Boost.Nowide
|
Table of Contents:
Boost.Nowide is a library originally implemented by Artyom Beilis that makes cross platform Unicode aware programming easier.
The library provides an implementation of standard C and C++ library functions, such that their inputs are UTF-8 aware on Windows without requiring to use the Wide API. On Non-Windows/POSIX platforms the StdLib equivalents are aliased instead, so no conversion is performed there as UTF-8 is commonly used already.
Hence you can use the Boost.Nowide functions with the same name as their std counterparts with narrow strings on all platforms and just have it work.
Consider a simple application that splits a big file into chunks, such that they can be sent by e-mail. It requires doing a few very simple tasks:
int main(int argc,char **argv)
std::fstream::open(const char*,std::ios::openmode m)
std::remove(const char* file)
std::cout << file_name
Unfortunately it is impossible to implement this simple task in plain C++ if the file names contain non-ASCII characters.
The simple program that uses the API would work on the systems that use UTF-8 internally – the vast majority of Unix-Line operating systems: Linux, Mac OS X, Solaris, BSD. But it would fail on files like War and Peace - Война и мир - מלחמה ושלום.zip
under Microsoft Windows because the native Windows Unicode aware API is Wide-API – UTF-16.
This incredibly trivial task is very hard to implement in a cross platform manner.
Boost.Nowide provides a set of standard library functions that are UTF-8 aware on Windows and make Unicode aware programming easier.
The library provides:
argc
, argc
and env
parameters of main
use UTF-8cstdio
functions:fopen
freopen
remove
rename
cstdlib
functions:system
getenv
setenv
unsetenv
putenv
fstream
filebuf
fstream/ofstream/ifstream
iostream
cout
cerr
clog
cin
All these functions are available in Boost.Nowide in headers of the same name. So instead of including cstdio
and using std::fopen
you simply include boost/nowide/cstdio.hpp
and use boost::nowide::fopen
. The functions accept the same arguments as their std
counterparts, in fact on non-Windows builds they are just aliases for those. But on Windows Boost.Nowide does its magic: The narrow string arguments are interpreted as UTF-8, converted to wide strings (UTF-16) and passed to the wide API which handles special chars correctly.
If there are non-UTF-8 characters in the passed string, the conversion will replace them by a replacement character (default: U+FFFD
) similar to what the NT kernel does. This means invalid UTF-8 sequences will not roundtrip from narrow->wide->narrow resulting in e.g. failure to open a file if the filename is ilformed.
Why not provide both Wide and Narrow implementations so the developer can choose to use Wide characters on Unix-like platforms?
Several reasons:
wchar_t
is not really portable, it can be 2 bytes, 4 bytes or even 1 byte making Unicode aware programming harderfopen(const wchar_t*, const wchar_t*)
in the standard library, so it is better to stick to the standards rather than re-implement Wide API in "Microsoft Windows Style"Since the May 2019 update Windows 10 does support UTF-8 for narrow strings via a manifest file. So setting "UTF-8" as the active code page would allow using the narrow API without any other changes with UTF-8 encoded strings. See the documentation for details.
Since April 2018 there is a (Beta) function available in Windows 10 to use UTF-8 code pages by default via a user setting.
Both methods do work but have a major drawback: They are not fully reliable for the app developer. The code page via manifest method falls back to a legacy code page when an older Windows version than 1903 is used. Hence it is only usable if the targetted system is Windows 10 after May 2019.
The second method relies on user interaction prior to starting the program. Obviously this is not reliable when expecting only UTF-8 in the code.
Hence under some circumstances (and hopefully always somewhen in the future) this library will not be required and even Windows I/O can be used with UTF-8 encoded text.
As a developer you are expected to use boost::nowide
functions instead of the functions available in the std
namespace.
For example, here is a Unicode unaware implementation of a line counter:
To make this program handle Unicode properly, we do the following changes:
This very simple and straightforward approach helps writing Unicode aware programs.
Watch the use of boost::nowide::args
, boost::nowide::ifstream
and boost::nowide::cerr/cout
. On Non-Windows it does nothing, but on Windows the following happens:
boost::nowide::args
retrieves UTF-16 arguments from the Windows API, converts them to UTF-8, and temporarily replaces the original argv
(and optionally env
) with pointers to those internally stored UTF-8 strings for the lifetime of the instance.boost::nowide::ifstream
converts the passed filename (which is now valid UTF-8) to UTF-16 and calls the Windows Wide API to open the file stream which can then be used as usual.boost::nowide::cerr
and boost::nowide::cout
use an underlying stream buffer that converts the UTF-8 string to UTF-16 and use another Wide API function to write it to console.Of course, this simple set of functions does not cover all needs. If you need to access Wide API from a Windows application that uses UTF-8 internally you can use the functions boost::nowide::widen
and boost::nowide::narrow
.
For example:
The conversion is done at the last stage, and you continue using UTF-8 strings everywhere else. You only switch to the Wide API at glue points.
boost::nowide::widen
returns std::string
. Sometimes it is useful to prevent allocation and use on-stack buffers instead. Boost.Nowide provides the boost::nowide::basic_stackstring
class for this purpose.
The example above could be rewritten as:
stackstring
and wstackstring
using 256-character buffers, and short_stackstring
and wshort_stackstring
using 16-character buffers. If the string is longer, they fall back to heap memory allocation.The library does not include the windows.h
in order to prevent namespace pollution with numerous defines and types. Instead, the library defines the prototypes of the Win32 API functions.
However, you may request to use the windows.h
header by defining BOOST_USE_WINDOWS_H
before including any of the Boost.Nowide headers
Boost.Filesystem supports selection of narrow encoding. Unfortunatelly the default narrow encoding on Windows isn't UTF-8. But you can enable UTF-8 as default encoding on Boost.Filesystem by calling boost::nowide::nowide_filesystem()
in the beginning of your program which imbues a locale with a UTF-8 conversion facet to convert between char
wchar_t
. This interprets all narrow strings passed to and from boost::filesystem::path
as UTF-8 when converting them to wide strings (as required for internal storage). On POSIX this has usually no effect, as no conversion is done due to narrow strings being used as the storage format.
For Microsoft Windows, the library provides UTF-8 aware variants of some std:
: functions in the boost::nowide
namespace. For example, std::fopen
becomes boost::nowide::fopen
.
Under POSIX platforms, the functions in boost::nowide are aliases of their standard library counterparts:
There is also a std::filebuf
compatible implementation provided for Windows which supports UTF-8 filepaths for open
and behaves otherwise identical (API-wise).
On all systems the std::fstream
class and friends are provided as custom implementations supporting std::string
and *::filesystem::path
as well as wchar_t*
(Windows only) overloads for the constructor and open
. This is done so users can use e.g. boost::filesystem::path
with boost::nowide::fstream
without depending on C++17 support. Furthermore any path-like class is supported if it matches the interface of std::filesystem::path
"enough".
Note that there is no universal support for path
and std::string
in boost::nowide::filebuf
. This is due to using the std variant on non-Windows systems which might be faster in some cases. As filebuf
is rarely used by user code but rather indirectly through fstream
not having string or path support seems a small price to pay especially as C++11 adds std::string
support, C++17 path
support and usage via string_or_path.c_str()
is still possible and portable.
Console I/O is implemented as a wrapper around ReadConsoleW/WriteConsoleW when the stream goes to the "real" console. When the stream was piped/redirected the standard cin/cout
is used instead.
This approach eliminates a need of manual code page handling. If TrueType fonts are used the Unicode aware input and output works as intended.
Q: What happens to invalid UTF passed through Boost.Nowide? For example Windows using UCS-2 instead of UTF-16.
A: The policy of Boost.Nowide is to always yield valid UTF encoded strings. So invalid UTF characters are replaced by the replacement character U+FFFD
.
This happens in both directions:
When passing a (presumptly) UTF-8 encoded string to Boost.Nowide it will convert it to UTF-16 and replace every invalid character before passing it to the OS.
On retrieval of a value from the OS (e.g. boost::nowide::getenv
or command line arguments through boost::nowide::args
) the value is assumed to be UTF-16 and converted to UTF-8 replacing any invalid character.
This means that if one somehow manages to create an invalid UTF-16 filename in Windows it will be impossible to handle it with Boost.Nowide. But as Microsoft switched from UCS-2 (aka strings with arbitrary 2 Byte values) to UTF-16 in Windows 2000 it won't be a problem in most environments.
Q: What kind of error reporting is used?
A: There are in fact 3:
Q: Why doesn't the library convert the string to/from the locale's encoding (instead of UTF-8) on POSIX systems?
A: It is inherently incorrect to convert strings to/from locale encodings on POSIX platforms.
You can create a file named "\xFF\xFF.txt" (invalid UTF-8), remove it, pass its name as a parameter to a program and it would work whether the current locale is UTF-8 or not. Also, changing the locale from let's say en_US.UTF-8
to en_US.ISO-8859-1
would not magically change all files in the OS or the strings a user may pass to the program (which is different on Windows)
POSIX OSs treat strings as NULL
terminated cookies.
So altering their content according to the locale would actually lead to incorrect behavior.
For example, this is a naive implementation of a standard program "rm"
It would work with ANY locale and changing the strings would lead to incorrect behavior.
The meaning of a locale under POSIX and Windows platforms is different and has very different effects.
It is possible to use Nowide library without having the huge Boost project as a dependency. There is a standalone version that has all the functionality in the nowide
namespace instead of boost::nowide
. The example above would look like
The upstream sources can be found at GitHub: https://github.com/boostorg/nowide
You can download the latest sources there: