diff --git a/td/telegram/MessageEntity.cpp b/td/telegram/MessageEntity.cpp index 1d5c0355c..42f241c66 100644 --- a/td/telegram/MessageEntity.cpp +++ b/td/telegram/MessageEntity.cpp @@ -3657,6 +3657,19 @@ static Result clean_input_string_with_entities(const string &text, vecto // entities must be sorted by offset and length, but not necessary by type // returns {last_non_whitespace_pos, last_non_whitespace_utf16_offset} static std::pair remove_invalid_entities(const string &text, vector &entities) { + if (entities.empty()) { + // fast path + for (size_t pos = 0; pos < text.size(); pos++) { + auto back_pos = text.size() - pos - 1; + auto c = text[back_pos]; + if (c != '\n' && c != ' ') { + return {back_pos, 0 /*unused*/}; + } + } + + return {text.size(), -1}; + } + // check_is_sorted(entities); vector nested_entities_stack; size_t current_entity = 0; diff --git a/test/message_entities.cpp b/test/message_entities.cpp index 49a635df6..2ba6130f8 100644 --- a/test/message_entities.cpp +++ b/test/message_entities.cpp @@ -733,6 +733,12 @@ TEST(MessageEntities, fix_formatted_text) { check_fix_formatted_text(str, {}, false, false, false, false); check_fix_formatted_text(str, {}, false, false, false, true); + check_fix_formatted_text(" aba\n ", {}, " aba\n ", {}, true, true, true, true); + check_fix_formatted_text(" aba\n ", {}, "aba", {}, true, true, true, false); + check_fix_formatted_text(" \n ", {}, "", {}, true, true, true, true); + check_fix_formatted_text(" \n ", {}, "", {}, true, true, true, false); + check_fix_formatted_text(" \n ", {}, false, true, true, false); + str += "a \r\n "; fixed_str += "a \n ";