/*** Copyright (C) 2021 J Reece Wilson (a/k/a "Reece"). All rights reserved. File: ConvertInternal.cpp Date: 2021-8-19 Author: Reece ***/ #include #include "Encoding.hpp" #include "ConvertInternal.hpp" namespace Aurora::Locale::Encoding { template void NormalizeEndianness(const AuUInt8 *in, AuUInt32 length, bool isEncodingLE, const AuFunction &out) { if (isEncodingLE == (Aurora::Build::kCurrentEndian == Aurora::Build::ECPUEndian::eCPULittle)) { out(in, length); return; } auto temp = _new AuUInt8[length]; if (!temp) { return; } for (AuUInt i = 0; i < length; i += sizeof(charout_t)) { *reinterpret_cast(temp[i]) = AuFlipEndian(*reinterpret_cast(in[i])); } try { out(temp, length); } catch (...) { } delete[] temp; } template void NormalizeEndianness(AuUInt8 *in, AuUInt32 length, bool isEncodingLE) { if (isEncodingLE == (Aurora::Build::kCurrentEndian == Aurora::Build::ECPUEndian::eCPULittle)) { return; } for (AuUInt i = 0; i < length; i += sizeof(charout_t)) { *reinterpret_cast(in[i]) = AuFlipEndian(*reinterpret_cast(in[i])); } } AuStreamReadWrittenPair_t EncodeUTF8Internal(const void *utf8, AuUInt32 utf8Length, void *binary, AuUInt32 binaryLength, ECodePage page) { AuStreamReadWrittenPair_t ret {}; switch (page) { default: return {}; case ECodePage::eUTF16: case ECodePage::eUTF16BE: ret = UTF16::UTF8ToCp({utf8, utf8Length}, {binary, binaryLength}); NormalizeEndianness((AuUInt8 *)binary, ret.second, page == ECodePage::eUTF16); break; case ECodePage::eUTF32: case ECodePage::eUTF32BE: ret = UTF32::UTF8ToCp({utf8, utf8Length}, {binary, binaryLength}); NormalizeEndianness((AuUInt8 *)binary, ret.second, page == ECodePage::eUTF32); break; } return ret; } AuStreamReadWrittenPair_t DecodeUTF8Internal(const void *binary, AuUInt32 binaryLength, void *utf8, AuUInt32 utf8Max, ECodePage page) { AuStreamReadWrittenPair_t ret {}; switch (page) { default: case ECodePage::eEnumInvalid: return {}; case ECodePage::eUTF16: case ECodePage::eUTF16BE: NormalizeEndianness((const AuUInt8*)binary, binaryLength, page == ECodePage::eUTF16, [&](const AuUInt8 *leCodePage, AuUInt32 length) { ret = UTF16::CPToUTF8({binary, binaryLength}, {utf8, utf8Max}); }); break; case ECodePage::eUTF32: case ECodePage::eUTF32BE: NormalizeEndianness((const AuUInt8 *)binary, binaryLength, page == ECodePage::eUTF32, [&](const AuUInt8 *leCodePage, AuUInt32 length) { ret = UTF32::CPToUTF8({binary, binaryLength}, {utf8, utf8Max}); }); break; } return ret; } AuStreamReadWrittenPair_t STLCPToUTF8(ECodePage page, const void *in, AuUInt32 length, void *utf8, AuUInt32 utf8Max) { return DecodeUTF8Internal(in, length, utf8, utf8Max, page); } AuStreamReadWrittenPair_t STLUTF8ToCp(ECodePage page, const void *utf8, AuUInt32 utf8Length, void *cp, AuUInt32 cpLen) { return EncodeUTF8Internal(utf8, utf8Length, cp, cpLen, page); } }