File: utils.cpp

package info (click to toggle)
fcitx5-gtk 5.1.4-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 608 kB
  • sloc: cpp: 6,313; ansic: 1,268; makefile: 5
file content (60 lines) | stat: -rw-r--r-- 1,433 bytes parent folder | download | duplicates (4)
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
/*
 * SPDX-FileCopyrightText: 2021~2021 CSSlayer <wengxt@gmail.com>
 *
 * SPDX-License-Identifier: LGPL-2.1-or-later
 *
 */
#include <string>

namespace fcitx::gtk {

enum class UnescapeState { NORMAL, ESCAPE };

bool unescape(std::string &str) {
    if (str.empty()) {
        return true;
    }

    bool unescapeQuote = false;
    // having quote at beginning and end, escape
    if (str.size() >= 2 && str.front() == '"' && str.back() == '"') {
        unescapeQuote = true;
        str.pop_back();
        str.erase(0, 1);
    }

    size_t i = 0;
    size_t j = 0;
    UnescapeState state = UnescapeState::NORMAL;
    do {
        switch (state) {
        case UnescapeState::NORMAL:
            if (str[i] == '\\') {
                state = UnescapeState::ESCAPE;
            } else {
                str[j] = str[i];
                j++;
            }
            break;
        case UnescapeState::ESCAPE:
            if (str[i] == '\\') {
                str[j] = '\\';
                j++;
            } else if (str[i] == 'n') {
                str[j] = '\n';
                j++;
            } else if (str[i] == '\"' && unescapeQuote) {
                str[j] = '\"';
                j++;
            } else {
                return false;
            }
            state = UnescapeState::NORMAL;
            break;
        }
    } while (str[i++]);
    str.resize(j - 1);
    return true;
}

} // namespace fcitx::gtk