; _______________________________________________________________________________________
;|                                                                                       |
;| ..::FreshLib::..  Free, open source. Licensed under "BSD 2-clause" license."          |
;|_______________________________________________________________________________________|
;
;  Description: Library for converting UTF8 to and from WideChar
;
;  Target OS: Win32
;
;  Dependencies:
;
;  Notes:
;_________________________________________________________________________________________


;-----------------------------------------------------------
; Returns:
;    eax - pointer to the widechar string.
;    ecx - length of the widechar string in characters.
;-----------------------------------------------------------
proc utf8ToWideChar, .hString
begin
        push    edx edi

        stdcall StrPtr, [.hString]
        invoke  MultiByteToWideChar, CP_UTF8, 0, eax, -1, 0, 0

        lea     edx, [2*eax+8]
        stdcall GetMem, edx
        mov     edi, eax

        stdcall StrPtr, [.hString]

        sar     edx, 1
        invoke  MultiByteToWideChar, CP_UTF8, 0, eax, -1, edi, edx
        mov     ecx, eax
        mov     eax, edi

        pop     edi edx
        return
endp




proc WideCharToUtf8, .ptrWideChar
begin
        push    ebx ecx edx edi
        invoke  WideCharToMultiByte, CP_UTF8, 0, [.ptrWideChar], -1, 0, 0, 0, 0
        test    eax, eax
        jz      .error

        lea     ebx, [eax+8]
        stdcall GetMem, ebx
        mov     edi, eax

        invoke  WideCharToMultiByte, CP_UTF8, 0, [.ptrWideChar], -1, edi, ebx, 0, 0
        test    eax, eax
        jz      .error

        stdcall StrDup, edi
        stdcall FreeMem, edi

        clc
.finish:
        pop     edi edx ecx ebx
        return

.error:
        stc
        jmp     .finish
endp