Echo Writes Code

transcoding.cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#include "crucible/windows/transcoding.hpp"

#include <Windows.h>

#include <limits>

namespace crucible::windows::transcoding {
  auto transcode_utf8_to_utf16(std::string const &utf8) -> errors::WindowsResult<std::wstring> {
    constexpr ::UINT CODEPAGE { CP_UTF8 };
    constexpr ::DWORD FLAGS { MB_ERR_INVALID_CHARS };

    if (utf8.size() > std::numeric_limits<int>::max()) {
      return core::either::make_lhs<errors::WindowsError>(errors::InputTooLarge {});
    }

    auto const utf8_size { static_cast<int>(utf8.size()) };

    int const required_size { ::MultiByteToWideChar(CODEPAGE, FLAGS, utf8.data(), utf8_size, nullptr, 0) };
    if (required_size <= 0) {
      return core::either::make_lhs<errors::WindowsError>(errors::MultiByteToWideCharFailed {});
    }

    std::wstring utf16(required_size, L'\0');
    int const characters_written { ::MultiByteToWideChar(CODEPAGE, FLAGS, utf8.data(), utf8_size, utf16.data(), required_size) };

    if (characters_written <= 0) {
      return core::either::make_lhs<errors::WindowsError>(errors::MultiByteToWideCharFailed {});
    } else if (characters_written != required_size) {
      return core::either::make_lhs<errors::WindowsError>(errors::OutputTruncated {});
    } else {
      return core::either::make_rhs(std::move(utf16));
    }
  }

  auto transcode_utf16_to_utf8(std::wstring const &utf16) -> errors::WindowsResult<std::string> {
    constexpr ::UINT CODEPAGE { CP_UTF8 };
    constexpr ::DWORD FLAGS { WC_ERR_INVALID_CHARS };

    ::LPCCH default_character { nullptr };
    ::LPBOOL used_default_character { nullptr };

    if (utf16.size() > std::numeric_limits<int>::max()) {
      return core::either::make_lhs<errors::WindowsError>(errors::InputTooLarge {});
    }

    auto const utf16_size { static_cast<int>(utf16.size()) };

    int const required_size { ::WideCharToMultiByte(CODEPAGE, FLAGS, utf16.data(), utf16_size, nullptr, 0, default_character, used_default_character) };
    if (required_size <= 0) {
      return core::either::make_lhs<errors::WindowsError>(errors::WideCharToMultiByteFailed {});
    }

    std::string utf8(required_size, '\0');
    int const bytes_written { ::WideCharToMultiByte(CODEPAGE, FLAGS, utf16.data(), utf16_size, utf8.data(), required_size, default_character, used_default_character) };

    if (bytes_written <= 0) {
      return core::either::make_lhs<errors::WindowsError>(errors::WideCharToMultiByteFailed {});
    } else if (bytes_written != required_size) {
      return core::either::make_lhs<errors::WindowsError>(errors::OutputTruncated {});
    } else {
      return core::either::make_rhs(std::move(utf8));
    }
  }
}