summaryrefslogtreecommitdiffstats
path: root/src/parser/json_global.cpp
blob: f01f77899c3cf16177d5a06c2eacb356288a0f58 (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
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

#include "orcus/json_global.hpp"
#include "orcus/parser_global.hpp"

#include <sstream>

namespace orcus { namespace json {

namespace {

const char backslash = '\\';

}

std::string escape_string(const std::string& input)
{
    std::ostringstream os;

    for (auto it = input.begin(), ite = input.end(); it != ite; ++it)
    {
        char c = *it;
        if (c == '"')
            // Escape double quote, but not forward slash.
            os << backslash;
        else if (c == backslash)
        {
            // Escape a '\' if and only if the next character is not one of control characters.
            auto itnext = it + 1;
            if (itnext == ite || get_string_escape_char_type(*itnext) != string_escape_char_t::control_char)
                os << backslash;
        }
        os << c;
    }

    return os.str();
}

}}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */