aboutsummaryrefslogtreecommitdiffstats
path: root/document/src/vespa/document/util/stringutil.cpp
blob: 51bf061661d02e17dd87acacc5b3c214a7674214 (plain) (blame)
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
// Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
/**
 *
 * $Id$

 *
 * String utilities
 *
 */

#include "stringutil.h"
#include <vespa/vespalib/util/exceptions.h>
#include <vespa/vespalib/stllike/asciistream.h>

#include <iomanip>
#include <sstream>
#include <vector>
#include <cassert>
#include <algorithm>

using vespalib::IllegalArgumentException;

namespace document {

namespace {
    char toHex(uint32_t val) {
        return (val < 10 ? '0' + val : 'a' + (val - 10));
    }
}

class ReplacementCharacters {
public:
    ReplacementCharacters();
    static int  needEscape(unsigned char c) { return _needEscape[c]; }
    static char getChar1(unsigned char c)   { return _replacement1[c]; }
    static char getChar2(unsigned char c)   { return _replacement2[c]; }
private:
    static char _needEscape[256];
    static char _replacement1[256];
    static char _replacement2[256];
};

char ReplacementCharacters::_needEscape[256];
char ReplacementCharacters::_replacement1[256];
char ReplacementCharacters::_replacement2[256];

ReplacementCharacters::ReplacementCharacters()
{
    for(size_t i(0); i < sizeof(_needEscape); i++) {
        const char c = i;
        if (c == '"') {
            _needEscape[i] = 1;
            _replacement1[i] = '\\';
            _replacement2[i] = '"';
        } else if (c == '\\') {
            _needEscape[i] = 1;
            _replacement1[i] = '\\';
            _replacement2[i] = '\\';
        } else if (c == '\t') {
            _needEscape[i] = 1;
            _replacement1[i] = '\\';
            _replacement2[i] = 't';
        } else if (c == '\n') {
            _needEscape[i] = 1;
            _replacement1[i] = '\\';
            _replacement2[i] = 'n';
        } else if (c == '\r') {
            _needEscape[i] = 1;
            _replacement1[i] = '\\';
            _replacement2[i] = 'r';
        } else if (c == '\f') {
            _needEscape[i] = 1;
            _replacement1[i] = '\\';
            _replacement2[i] = 'f';
        } else if ((c < 32) || (c > 126)) {
            _needEscape[i] = 3;
            _replacement1[i] = toHex((c >> 4) & 0xF);
            _replacement2[i] = toHex(c & 0xF);
        } else {
            _needEscape[i] = 0;
            _replacement1[i] = c;
            _replacement2[i] = c;
        }
    }
}

static ReplacementCharacters _G_ForceInitialisation;

const vespalib::string & StringUtil::escape(const vespalib::string & source, vespalib::string & destination,
                                       char delimiter)
{
    size_t escapeCount(0);
    for(size_t i(0), m(source.size()); i < m; i++) {
        if (source[i] == delimiter) {
            escapeCount += 3;
        } else {
            escapeCount += ReplacementCharacters::needEscape(source[i]);
        }
    }
    if (escapeCount > 0) {
        std::vector<char> dst;
        dst.reserve(source.size() + escapeCount);
        for(size_t i(0), m(source.size()); i < m; i++) {
            const char c = source[i];
            if (c == delimiter) {
                dst.push_back('\\');
                dst.push_back('x');
                dst.push_back(toHex((c >> 4) & 0xF));
                dst.push_back(toHex(c & 0xF));
            } else {
                int needEscape = ReplacementCharacters::needEscape(c);
                if (needEscape == 0) {
                    dst.push_back(c);
                } else {
                    if (needEscape == 3) {
                        dst.push_back('\\');
                        dst.push_back('x');
                    }
                    dst.push_back(ReplacementCharacters::getChar1(c));
                    dst.push_back(ReplacementCharacters::getChar2(c));
                }
            }
        }
        destination.assign(&dst[0], dst.size());
        return destination;
    }
    return source;
}

vespalib::string StringUtil::unescape(vespalib::stringref source)
{
    vespalib::asciistream ost;
    for (unsigned int i=0; i<source.size(); ++i) {
        if (source[i] != '\\') { ost << source[i]; continue; }
        // Here we know we have an escape
        if (i+1 == source.size()) {
            throw IllegalArgumentException("Found backslash at end of input",
                                           VESPA_STRLOC);
        }
        if (source[i+1] != 'x') {
            switch (source[i+1]) {
            case '\\': ost << '\\'; break;
            case '"': ost << '"'; break;
            case 't': ost << '\t'; break;
            case 'n': ost << '\n'; break;
            case 'r': ost << '\r'; break;
            case 'f': ost << '\f'; break;
            default:
                throw IllegalArgumentException(
                        vespalib::make_string("Illegal escape sequence \\%c found", source[i+1]), VESPA_STRLOC);
            }
            ++i;
            continue;
        }
        // Only \x## sequences left..
        if (i+3 >= source.size()) {
            throw IllegalArgumentException("Found \\x at end of input",
                                           VESPA_STRLOC);
        }
        vespalib::string hexdigits = source.substr(i+2, 2);
        char* endp(0);
        ost << static_cast<char>(strtol(hexdigits.c_str(), &endp, 16));
        if (*endp) {
            throw IllegalArgumentException("Value "+hexdigits
                                           + " is not a two digit hexadecimal number", VESPA_STRLOC);
        }
        i+=3;
    }
    return ost.str();
}

void StringUtil::
printAsHex(std::ostream& output, const void* source, unsigned int size,
           unsigned int columnwidth, bool inlinePrintables,
           const std::string& indent)
{
    assert(columnwidth > 0);
    unsigned char wildChar = '.';
    const unsigned char* start = reinterpret_cast<const unsigned char*>(source);
    uint32_t posWidth = 1;
    for (uint32_t i=size; i>9; i /= 10) { ++posWidth; }
    std::vector<unsigned char> printables(static_cast<size_t>(columnwidth) + 1);
    printables[columnwidth] = '\0';
    for (unsigned int i=0; i<size; i += columnwidth) {
        std::ostringstream ost;
        if (i != 0) ost << "\n" << indent;
        ost << std::dec << std::setw(posWidth) << i << ":";
        bool nonNull = false;
        for (unsigned int j=0; j<columnwidth; ++j)
        {
            if (i+j >= size) {
                ost << "   ";
                printables[j] = '\0'; // Avoid adding extra chars.
            } else {
                ost << " " << std::setw(2);
                bool printable = (start[i+j] >= 33 && start[i+j] <= 126);
                if (inlinePrintables && printable) {
                    ost << std::setfill(' ') << start[i+j];
                } else {
                    ost << std::hex << std::setfill('0')
                        << ((unsigned int) start[i+j]);
                    printables[j] = (printable ? start[i+j] : wildChar);
                }
                nonNull |= (start[i+j] != 0);
            }
        }
        if (nonNull) {
            output << ost.str();
            if (!inlinePrintables) {
                output << " " << &printables[0];
            }
        }
    }
}


} // namespace document