summaryrefslogtreecommitdiffstats
path: root/src/threadcidmap.cpp
blob: c6f1cc7912cf1c6bfb9c0509c734ef7777e6df6c (plain)
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
#include "threadcidmap.h"

#include "cidschemehandler.h"

namespace {

/// Removes '!' from a prefix without ever mapping two distinct prefixes onto
/// one another.
///
/// A plain replace of '!' with '_' is NOT safe here: "m0!x" and "m0_x" would
/// both become "m0_x", merging two messages into one key space, which is
/// precisely the collision the namespacing exists to prevent. Escaping the
/// escape character first keeps the transform injective: '_' doubles, and '!'
/// becomes "_x", so no output is reachable from two different inputs.
QString sanitizePrefix(const QString &prefix)
{
    if (!prefix.contains(QLatin1Char('!')) && !prefix.contains(QLatin1Char('_')))
        return prefix;

    QString result;
    result.reserve(prefix.size() + 4);
    for (const QChar c : prefix) {
        if (c == QLatin1Char('_'))
            result += QLatin1String("__");
        else if (c == QLatin1Char('!'))
            result += QLatin1String("_x");
        else
            result += c;
    }
    return result;
}

} // namespace

ThreadCidMap buildThreadCidMap(const QList<ThreadRenderItem> &items)
{
    ThreadCidMap map;

    for (const ThreadRenderItem &item : items) {
        const QString prefix = sanitizePrefix(item.cidPrefix);

        for (auto it = item.message.inlineParts.cbegin();
             it != item.message.inlineParts.cend(); ++it) {
            const QString key = CidSchemeHandler::namespacedKey(prefix, it.key());
            map.parts.insert(key, it.value());
            map.allowedCids.insert(key);
        }
    }

    return map;
}