aslze / asl

A compact C++ cross-platform library including JSON, XML, HTTP, Sockets, WebSockets, threads, processes, logs, file system, CSV, INI files, vectors and matrices, etc.
Other
69 stars 17 forks source link

question: printing out single character #20

Closed dezashibi closed 1 year ago

dezashibi commented 1 year ago

when iterating in an asl::String using a for (auto& character : my_text) loop a codepoint for each character is received, to print that individual character I came up with this code, is there any missing feature or shorter way or it's just fine?

asl::String code_point_to_utf8(int codePoint)
{
    std::string utf8;
    if (codePoint <= 0x7F)
    {
        utf8 += static_cast<char>(codePoint);
    }
    else if (codePoint <= 0x7FF)
    {
        utf8 += static_cast<char>((codePoint >> 6) | 0xC0);
        utf8 += static_cast<char>((codePoint & 0x3F) | 0x80);
    }
    else if (codePoint <= 0xFFFF)
    {
        utf8 += static_cast<char>((codePoint >> 12) | 0xE0);
        utf8 += static_cast<char>(((codePoint >> 6) & 0x3F) | 0x80);
        utf8 += static_cast<char>((codePoint & 0x3F) | 0x80);
    }
    else if (codePoint <= 0x10FFFF)
    {
        utf8 += static_cast<char>((codePoint >> 18) | 0xF0);
        utf8 += static_cast<char>(((codePoint >> 12) & 0x3F) | 0x80);
        utf8 += static_cast<char>(((codePoint >> 6) & 0x3F) | 0x80);
        utf8 += static_cast<char>((codePoint & 0x3F) | 0x80);
    }
    return utf8;
}

well this works fine with both asl::String and std::string.

aslze commented 1 year ago

I very recently added two functions to create a String from a list of code points or from one code point:

auto String::fromCodes(someString.chars());  // to code points and back to string

auto one = String::fromCode(0x1F4BB);  // a laptop emoji (I think)
dezashibi commented 1 year ago

yes thanks, works fine 👍