Repository: microsoft/terminal
File: src/inc/til/u8u16convert.h (C/C++)

Code before:

                state.reset();
                capa16 -= len16;
                len8 -= fetch8;
                cursor8 += fetch8;
            }

            if (!!len8)
            {
                auto backIter{ cursor8 + len8 };
                // If the last byte in the string was a byte belonging to a UTF-8 multi-byte character
                if (!!(backIter[-1] & MaskAscii))
                {
                    // Check only up to 3 last bytes, if no Lead Byte is found then the byte before will be the Lead Byte and no partials are in the string
                    const auto stopLen{ std::min(len8, 3) };
                    for (auto sequenceLen{ 1 }; sequenceLen <= stopLen; ++sequenceLen)
                    {
                        --backIter;
                        // If Lead Byte found
                        if ((*backIter & MaskCont) > IsCont)
                        {
                            // If the Lead Byte indicates that the last bytes in the string is a partial UTF-8 code point then cache them:
                            //  Use the bitmask at index `sequenceLen`. Compare the result with the operand having the same index. If they
                            //  are not equal then the sequence has to be cached because it is a partial code point. Otherwise the
                            //  sequence is a complete UTF-8 code point and the whole string is ready for the conversion into a UTF-16 string.
                            if ((*backIter & cmpMasks[gsl::narrow_cast<size_t>(sequenceLen)]) != cmpOperands[gsl::narrow_cast<size_t>(sequenceLen)])
                            {
                                std::move(backIter, backIter + sequenceLen, state.partials.data());
                                len8 -= sequenceLen;
                                state.partials[3] = gsl::narrow_cast<char>(sequenceLen);
                            }

                            break;
                        }
                    }
                }
            }

            if (!!len8)
            {
                const auto convLen{ MultiByteToWideChar(CP_UTF8, 0UL, cursor8, len8, out.data() + len16, capa16) };
                RETURN_HR_IF(E_UNEXPECTED, !convLen);

                len16 += convLen;
            }

            out.resize(gsl::narrow_cast<size_t>(len16));
            return S_OK;
        }
        catch (std::length_error&)
        {

Review comment (suggestion):
If you moved the `codePointLen` calculation down here to store the "remaining" count, then you can drop `cmpMasks` as it shouldn't be needed anymore.

Code after:
    template<class outT>
    [[nodiscard]] HRESULT u16u8(const std::wstring_view& in, outT& out) noexcept
    {
        try
        {
            out.clear();
            RETURN_HR_IF(S_OK, in.empty());

            int lengthIn{};
            int lengthRequired{};
            // Code Point U+0000..U+FFFF: 1 UTF-16 code unit --> 1..3 UTF-8 code units.
            // Code Points >U+FFFF: 2 UTF-16 code units --> 4 UTF-8 code units.
            // Thus, the worst ratio of UTF-16 code units to UTF-8 code units is 1 to 3.
            RETURN_HR_IF(E_ABORT, !base::MakeCheckedNum(in.length()).AssignIfValid(&lengthIn) || !base::CheckMul(lengthIn, 3).AssignIfValid(&lengthRequired));
            out.resize(gsl::narrow_cast<size_t>(lengthRequired)); // avoid to call WideCharToMultiByte twice only to get the required size
            const int lengthOut = WideCharToMultiByte(CP_UTF8, 0ul, in.data(), lengthIn, out.data(), lengthRequired, nullptr, nullptr);
            out.resize(gsl::narrow_cast<size_t>(lengthOut));

            return lengthOut == 0 ? E_UNEXPECTED : S_OK;
        }
        CATCH_RETURN();
    }

#pragma warning(push)
#pragma warning(disable : 26429 26446 26459 26481) // use not_null, subscript operator, use span, pointer arithmetic
    // Routine Description:
    // - Takes a UTF-16 string, complements and/or caches partials, and performs the conversion to UTF-8.
    // Arguments:
    // - in - UTF-16 string to be converted
    // - out - reference to the resulting UTF-8 string
    // - state - reference to a til::u16state class holding the status of the current partials handling
    // Return Value:
    // - S_OK          - the conversion succeeded without any change of the represented code points
    // - E_OUTOFMEMORY - the function failed to allocate memory for the resulting string
    // - E_ABORT       - the resulting string length would exceed the upper boundary of an int and thus, the conversion was aborted before the conversion has been completed
    // - E_UNEXPECTED  - the underlying conversion function failed
    // - HRESULT value converted from a caught exception
    template<class outT>
    [[nodiscard]] HRESULT u16u8(const std::wstring_view& in, outT& out, u16state& state) noexcept
    {
        try
        {
            out.clear();
            RETURN_HR_IF(S_OK, in.empty());

            int len16{};
            int capa8{};
            // The worst ratio of UTF-16 code units to UTF-8 code units is 1 to 3.
            RETURN_HR_IF(E_ABORT, !base::MakeCheckedNum(in.length()).AssignIfValid(&len16) || !base::CheckAdd(len16, gsl::narrow_cast<int>(state.partials[0]) != 0).AssignIfValid(&capa8) || !base::CheckMul(capa8, 3).AssignIfValid(&capa8));

            out.resize(gsl::narrow_cast<size_t>(capa8));