#include "tskv_escape.h"

#include <util/string/util.h>
#include <util/generic/yexception.h>

namespace NFormatPrivate {

//
// We don't use library/cpp/string_utils/tskv_format here, because of the following:
// * it escapes too much ('"', '='), therefore messes with JSON and urls
// * it is badly implemented (slow, no stream support, no templates, etc.)
//
// The escaping here is what is actually required by StatBox:
// https://wiki.yandex-team.ru/Statbox/LogRequirements/#tskvformat
//

static str_spn TskvMinEscape("\t\n\r\\"); // \0 is always included

void TskvEscapeData(const TTempBuf& buf, IOutputStream& o) {
    const char* begin = buf.Data();
    const char* const end = buf.Current();
    while (begin < end) {
        const char* p = TskvMinEscape.brk(begin, end);
        if (p != begin)
            o << TStringBuf(begin, p - begin);
        if (p == end)
            break;
        switch (*p) {
            case '\t':
                o << TStringBuf("\\t");
                break;
            case '\n':
                o << TStringBuf("\\n");
                break;
            case '\r':
                o << TStringBuf("\\r");
                break;
            case '\\':
                o << TStringBuf("\\\\");
                break;
            case '\0':
                o << TStringBuf("\\0");
                break;
            default:
                Y_ENSURE(0);
        }
        begin = p + 1;
    }
}

}
