goldendict-ng/iconv.cc

71 lines
1.7 KiB
C++
Raw Normal View History

2012-02-20 21:47:14 +00:00
/* This file is (c) 2008-2012 Konstantin Isakov <ikm@goldendict.org>
* Part of GoldenDict. Licensed under GPLv3 or later, see the LICENSE file */
#include "iconv.hh"
#include <vector>
#include <errno.h>
#include <string.h>
2021-07-06 13:01:50 +00:00
#include <QDebug>
2022-02-26 00:56:46 +00:00
#include "wstring_qt.hh"
2022-02-26 00:56:46 +00:00
char const * const Iconv::GdWchar = "UTF-32LE";
char const * const Iconv::Utf16Le = "UTF-16LE";
char const * const Iconv::Utf8 = "UTF-8";
using gd::wchar;
2022-02-26 00:56:46 +00:00
Iconv::Iconv( char const * to, char const * from )
{
2022-02-26 00:56:46 +00:00
codec = QTextCodec::codecForName(from);
}
2022-02-26 00:56:46 +00:00
Iconv::~Iconv()
{
2022-02-26 00:56:46 +00:00
}
2022-02-26 00:56:46 +00:00
QString Iconv::convert(void const* & inBuf, size_t& inBytesLeft)
{
2023-01-24 13:07:24 +00:00
if( codec )
return codec->toUnicode( static_cast< const char * >( inBuf ), inBytesLeft );
QByteArray ba( static_cast< const char * >( inBuf ), inBytesLeft );
return QString( ba );
}
gd::wstring Iconv::toWstring( char const * fromEncoding, void const * fromData,
size_t dataSize )
2022-01-09 08:35:07 +00:00
{
/// Special-case the dataSize == 0 to avoid any kind of iconv-specific
/// behaviour in that regard.
if ( !dataSize )
return gd::wstring();
Iconv ic( GdWchar, fromEncoding );
/// This size is usually enough, but may be enlarged during the conversion
std::vector< wchar > outBuf( dataSize );
2022-02-26 00:56:46 +00:00
QString outStr = ic.convert(fromData, dataSize);
return gd::toWString(outStr);
}
std::string Iconv::toUtf8( char const * fromEncoding, void const * fromData,
size_t dataSize )
2022-01-09 08:35:07 +00:00
{
// Similar to toWstring
if ( !dataSize )
return std::string();
Iconv ic( Utf8, fromEncoding );
std::vector< char > outBuf( dataSize );
2022-02-26 00:56:46 +00:00
QString outStr = ic.convert(fromData, dataSize);
return gd::toStdString(outStr);
}