From 79788d2cdc869d794dff088e84b2604a3f7d114b Mon Sep 17 00:00:00 2001 From: super1207 Date: Tue, 26 Dec 2023 19:53:00 +0800 Subject: [PATCH] fix cq code parse --- app/src/main/cpp/cqcode.cpp | 75 ++++++++++++++++++++++--------------- 1 file changed, 44 insertions(+), 31 deletions(-) diff --git a/app/src/main/cpp/cqcode.cpp b/app/src/main/cpp/cqcode.cpp index 817ac9d..60a5682 100644 --- a/app/src/main/cpp/cqcode.cpp +++ b/app/src/main/cpp/cqcode.cpp @@ -9,52 +9,61 @@ inline void replace_string(std::string& str, const std::string& from, const std: } } +inline int utf8_next_len(const std::string& str, size_t offset) +{ + uint8_t c = (uint8_t)str[offset]; + if (c >= 0xFC) + return 6; + else if (c >= 0xF8) + return 5; + else if (c >= 0xF0) + return 4; + else if (c >= 0xE0) + return 3; + else if (c >= 0xC0) + return 2; + else if (c > 0x00) + return 1; + else + return 0; +} + + void decode_cqcode(const std::string& code, std::vector>& dest) { std::string cache; bool is_start = false; std::string key_tmp; std::unordered_map kv; - for(int i = 0; i < code.size(); i++) { - auto c = code[i]; - if (c == '[') { + for(size_t i = 0; i < code.size(); i++) { + int utf8_char_len = utf8_next_len(code, i); + if(utf8_char_len == 0) { + continue; + } + std::string_view c(&code[i],utf8_char_len); + if (c == "[") { if (is_start) { throw illegal_code(); } else { if (!cache.empty()) { std::unordered_map kv; + replace_string(cache, "[", "["); + replace_string(cache, "]", "]"); + replace_string(cache, "&", "&"); kv.emplace("_type", "text"); kv.emplace("text", cache); dest.push_back(kv); cache.clear(); } - auto c1 = code[i + 1]; - if (c1 == 'C') { - i++; - auto c2 = code[i + 1]; - if(c2 == 'Q') { - i++; - auto c3 = code[i + 1]; - if (c3 == ':') { - i++; - is_start = true; - } else { - cache += c; - cache += c1; - cache += c2; - continue; - } - } else { - cache += c; - cache += c1; - continue; - } - } else { + std::string_view cq_flag(&code[i],4); + if(cq_flag == "[CQ:"){ + is_start = true; + i += 3; + }else{ cache += c; - continue; } } } - else if (c == '=') { + else if (c == "=") { if (is_start) { if (cache.empty()) { throw illegal_code(); @@ -70,17 +79,17 @@ void decode_cqcode(const std::string& code, std::vector kv; + replace_string(cache, "[", "["); + replace_string(cache, "]", "]"); + replace_string(cache, "&", "&"); kv.emplace("_type", "text"); kv.emplace("text", cache); dest.push_back(kv);