aboutsummaryrefslogtreecommitdiffstats
path: root/library/cpp/protobuf/json/string_transform.cpp
blob: 6f982ece61a82a6e6d074bd8cb041c5e202b3527 (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
#include "string_transform.h"

#include <google/protobuf/stubs/strutil.h>

#include <library/cpp/string_utils/base64/base64.h>

namespace NProtobufJson {
    void TCEscapeTransform::Transform(TString& str) const { 
        str = google::protobuf::CEscape(str); 
    } 

    void TSafeUtf8CEscapeTransform::Transform(TString& str) const { 
        str = google::protobuf::strings::Utf8SafeCEscape(str); 
    } 

    void TDoubleEscapeTransform::Transform(TString& str) const { 
        TString escaped = google::protobuf::CEscape(str); 
        str = ""; 
        for (char* it = escaped.begin(); *it; ++it) { 
            if (*it == '\\' || *it == '\"') 
                str += "\\"; 
            str += *it; 
        } 
    } 

    void TDoubleUnescapeTransform::Transform(TString& str) const { 
        str = google::protobuf::UnescapeCEscapeString(Unescape(str)); 
    }

    TString TDoubleUnescapeTransform::Unescape(const TString& str) const { 
        if (str.empty()) { 
            return str; 
        } 

        TString result; 
        result.reserve(str.size()); 

        char prev = str[0]; 
        bool doneOutput = true; 
        for (const char* it = str.c_str() + 1; *it; ++it) { 
            if (doneOutput && prev == '\\' && (*it == '\\' || *it == '\"')) { 
                doneOutput = false; 
            } else { 
                result += prev; 
                doneOutput = true; 
            } 
            prev = *it; 
        } 

        if ((doneOutput && prev != '\\') || !doneOutput) { 
            result += prev;
        }

        return result; 
    }

    void TBase64EncodeBytesTransform::TransformBytes(TString &str) const {
        str = Base64Encode(str);
    }

    void TBase64DecodeBytesTransform::TransformBytes(TString &str) const {
        str = Base64Decode(str);
    }
}