aboutsummaryrefslogtreecommitdiffstats
path: root/library/cpp/yt/yson_string/convert.cpp
blob: 27f5c30d01f29284de7e9d6211a7b5d17e4f76ca (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
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
#include "convert.h"
#include "format.h"

#include <library/cpp/yt/assert/assert.h>

#include <library/cpp/yt/string/format.h>

#include <library/cpp/yt/coding/varint.h>

#include <library/cpp/yt/misc/cast.h>

#include <array>

#include <util/stream/mem.h>

namespace NYT::NYson {

////////////////////////////////////////////////////////////////////////////////

template <>
TYsonString ConvertToYsonString<i8>(const i8& value)
{
    return ConvertToYsonString(static_cast<i64>(value));
}

template <>
TYsonString ConvertToYsonString<i32>(const i32& value)
{
    return ConvertToYsonString(static_cast<i64>(value));
}

template <>
TYsonString ConvertToYsonString<i64>(const i64& value)
{
    std::array<char, 1 + MaxVarInt64Size> buffer;
    auto* ptr = buffer.data();
    *ptr++ = NDetail::Int64Marker;
    ptr += WriteVarInt64(ptr, value);
    return TYsonString(TStringBuf(buffer.data(), ptr - buffer.data()));
}

template <>
TYsonString ConvertToYsonString<ui8>(const ui8& value)
{
    return ConvertToYsonString(static_cast<ui64>(value));
}

template <>
TYsonString ConvertToYsonString<ui32>(const ui32& value)
{
    return ConvertToYsonString(static_cast<ui64>(value));
}

template <>
TYsonString ConvertToYsonString<ui64>(const ui64& value)
{
    std::array<char, 1 + MaxVarInt64Size> buffer;
    auto* ptr = buffer.data();
    *ptr++ = NDetail::Uint64Marker;
    ptr += WriteVarUint64(ptr, value);
    return TYsonString(TStringBuf(buffer.data(), ptr - buffer.data()));
}

template <>
TYsonString ConvertToYsonString<TString>(const TString& value)
{
    return ConvertToYsonString(static_cast<TStringBuf>(value));
}

struct TConvertStringToYsonStringTag
{ };

template <>
TYsonString ConvertToYsonString<TStringBuf>(const TStringBuf& value)
{
    auto buffer = TSharedMutableRef::Allocate<TConvertStringToYsonStringTag>(
        1 + MaxVarInt64Size + value.length(),
        /*initializeStorage*/ false);
    auto* ptr = buffer.Begin();
    *ptr++ = NDetail::StringMarker;
    ptr += WriteVarInt64(ptr, static_cast<i64>(value.length()));
    ::memcpy(ptr, value.data(), value.length());
    ptr += value.length();
    return TYsonString(buffer.Slice(buffer.Begin(), ptr));
}

TYsonString ConvertToYsonString(const char* value)
{
    return ConvertToYsonString(TStringBuf(value));
}

template <>
TYsonString ConvertToYsonString<float>(const float& value)
{
    return ConvertToYsonString(static_cast<double>(value));
}

template <>
TYsonString ConvertToYsonString<double>(const double& value)
{
    std::array<char, 1 + sizeof(double)> buffer;
    auto* ptr = buffer.data();
    *ptr++ = NDetail::DoubleMarker;
    ::memcpy(ptr, &value, sizeof(value));
    ptr += sizeof(value);
    return TYsonString(TStringBuf(buffer.data(), ptr - buffer.data()));
}

template <>
TYsonString ConvertToYsonString<bool>(const bool& value)
{
    char ch = value ? NDetail::TrueMarker : NDetail::FalseMarker;
    return TYsonString(TStringBuf(&ch, 1));
}

template <>
TYsonString ConvertToYsonString<TInstant>(const TInstant& value)
{
    return ConvertToYsonString(value.ToString());
}

template <>
TYsonString ConvertToYsonString<TDuration>(const TDuration& value)
{
    return ConvertToYsonString(value.MilliSeconds());
}

template <>
TYsonString ConvertToYsonString<TGuid>(const TGuid& value)
{
    std::array<char, MaxGuidStringSize> guidBuffer;
    auto guidLength = WriteGuidToBuffer(guidBuffer.data(), value) - guidBuffer.data();
    std::array<char, 1 + MaxVarInt64Size + MaxGuidStringSize> ysonBuffer;
    auto* ptr = ysonBuffer.data();
    *ptr++ = NDetail::StringMarker;
    ptr += WriteVarInt64(ptr, static_cast<i64>(guidLength));
    ::memcpy(ptr, guidBuffer.data(), guidLength);
    ptr += guidLength;
    return TYsonString(TStringBuf(ysonBuffer.data(), ptr - ysonBuffer.data()));
}

////////////////////////////////////////////////////////////////////////////////

namespace {

TString FormatUnexpectedMarker(char ch)
{
    switch (ch) {
        case NDetail::BeginListSymbol:
            return "list";
        case NDetail::BeginMapSymbol:
            return "map";
        case NDetail::BeginAttributesSymbol:
            return "attributes";
        case NDetail::EntitySymbol:
            return "\"entity\" literal";
        case NDetail::StringMarker:
            return "\"string\" literal";
        case NDetail::Int64Marker:
            return "\"int64\" literal";
        case NDetail::DoubleMarker:
            return "\"double\" literal";
        case NDetail::FalseMarker:
        case NDetail::TrueMarker:
            return "\"boolean\" literal";
        case NDetail::Uint64Marker:
            return "\"uint64\" literal";
        default:
            return Format("unexpected symbol %qv", ch);
    }
}

i64 ParseInt64FromYsonString(const TYsonStringBuf& str)
{
    YT_ASSERT(str.GetType() == EYsonType::Node);
    auto strBuf = str.AsStringBuf();
    TMemoryInput input(strBuf.data(), strBuf.length());
    char ch;
    if (!input.ReadChar(ch)) {
        throw TYsonLiteralParseException("Missing type marker");
    }
    if (ch != NDetail::Int64Marker) {
        throw TYsonLiteralParseException(Format("Unexpected %v",
            FormatUnexpectedMarker(ch)));
    }
    i64 result;
    try {
        ReadVarInt64(&input, &result);
    } catch (const std::exception& ex) {
        throw TYsonLiteralParseException(ex, "Failed to decode \"int64\" value");
    }
    return result;
}

ui64 ParseUint64FromYsonString(const TYsonStringBuf& str)
{
    YT_ASSERT(str.GetType() == EYsonType::Node);
    auto strBuf = str.AsStringBuf();
    TMemoryInput input(strBuf.data(), strBuf.length());
    char ch;
    if (!input.ReadChar(ch)) {
        throw TYsonLiteralParseException("Missing type marker");
    }
    if (ch != NDetail::Uint64Marker) {
        throw TYsonLiteralParseException(Format("Unexpected %v",
            FormatUnexpectedMarker(ch)));
    }
    ui64 result;
    try {
        ReadVarUint64(&input, &result);
    } catch (const std::exception& ex) {
        throw TYsonLiteralParseException(ex, "Failed to decode \"uint64\" value");
    }
    return result;
}

TString ParseStringFromYsonString(const TYsonStringBuf& str)
{
    YT_ASSERT(str.GetType() == EYsonType::Node);
    auto strBuf = str.AsStringBuf();
    TMemoryInput input(strBuf.data(), strBuf.length());
    char ch;
    if (!input.ReadChar(ch)) {
        throw TYsonLiteralParseException("Missing type marker");
    }
    if (ch != NDetail::StringMarker) {
        throw TYsonLiteralParseException(Format("Unexpected %v",
            FormatUnexpectedMarker(ch)));
    }
    i64 length;
    try {
        ReadVarInt64(&input, &length);
    } catch (const std::exception& ex) {
        throw TYsonLiteralParseException(ex, "Failed to decode string length");
    }
    if (length < 0) {
        throw TYsonLiteralParseException(Format("Negative string length ",
            length));
    }
    if (static_cast<i64>(input.Avail()) != length) {
        throw TYsonLiteralParseException(Format("Incorrect remaining string length: expected %v, got %v",
            length,
            input.Avail()));
    }
    TString result;
    result.ReserveAndResize(length);
    YT_VERIFY(static_cast<i64>(input.Read(result.Detach(), length)) == length);
    return result;
}

double ParseDoubleFromYsonString(const TYsonStringBuf& str)
{
    YT_ASSERT(str.GetType() == EYsonType::Node);
    auto strBuf = str.AsStringBuf();
    TMemoryInput input(strBuf.data(), strBuf.length());
    char ch;
    if (!input.ReadChar(ch)) {
        throw TYsonLiteralParseException("Missing type marker");
    }
    if (ch != NDetail::DoubleMarker) {
        throw TYsonLiteralParseException(Format("Unexpected %v",
            FormatUnexpectedMarker(ch)));
    }
    if (input.Avail() != sizeof(double)) {
        throw TYsonLiteralParseException(Format("Incorrect remaining string length: expected %v, got %v",
            sizeof(double),
            input.Avail()));
    }
    double result;
    YT_VERIFY(input.Read(&result, sizeof(result)));
    return result;
}

} // namespace

#define PARSE(type, underlyingType) \
    template <> \
    type ConvertFromYsonString<type>(const TYsonStringBuf& str) \
    { \
        try { \
            return CheckedIntegralCast<type>(Parse ## underlyingType ## FromYsonString(str)); \
        } catch (const std::exception& ex) { \
            throw TYsonLiteralParseException(ex, "Error parsing \"" #type "\" value from YSON"); \
        } \
    }

PARSE(i8,   Int64 )
PARSE(i16,  Int64 )
PARSE(i32,  Int64 )
PARSE(i64,  Int64 )
PARSE(ui8,  Uint64)
PARSE(ui16, Uint64)
PARSE(ui32, Uint64)
PARSE(ui64, Uint64)

#undef PARSE

template <>
TString ConvertFromYsonString<TString>(const TYsonStringBuf& str)
{
    try {
        return ParseStringFromYsonString(str);
    } catch (const std::exception& ex) {
        throw TYsonLiteralParseException(ex, "Error parsing \"string\" value from YSON");
    }
}

template <>
float ConvertFromYsonString<float>(const TYsonStringBuf& str)
{
    try {
        return static_cast<float>(ParseDoubleFromYsonString(str));
    } catch (const std::exception& ex) {
        throw TYsonLiteralParseException(ex, "Error parsing \"float\" value from YSON");
    }
}

template <>
double ConvertFromYsonString<double>(const TYsonStringBuf& str)
{
    try {
        return ParseDoubleFromYsonString(str);
    } catch (const std::exception& ex) {
        throw TYsonLiteralParseException(ex, "Error parsing \"double\" value from YSON");
    }
}

template <>
bool ConvertFromYsonString<bool>(const TYsonStringBuf& str)
{
    try {
        YT_ASSERT(str.GetType() == EYsonType::Node);
        auto strBuf = str.AsStringBuf();
        TMemoryInput input(strBuf.data(), strBuf.length());
        char ch;
        if (!input.ReadChar(ch)) {
            throw TYsonLiteralParseException("Missing type marker");
        }
        if (ch != NDetail::TrueMarker && ch != NDetail::FalseMarker) {
            throw TYsonLiteralParseException(Format("Unexpected %v",
                FormatUnexpectedMarker(ch)));
        }
        return ch == NDetail::TrueMarker;
    } catch (const std::exception& ex) {
        throw TYsonLiteralParseException(ex, "Error parsing \"boolean\" value from YSON");
    }
}

template <>
TInstant ConvertFromYsonString<TInstant>(const TYsonStringBuf& str)
{
    try {
        return TInstant::ParseIso8601(ParseStringFromYsonString(str));
    } catch (const std::exception& ex) {
        throw TYsonLiteralParseException(ex, "Error parsing \"instant\" value from YSON");
    }
}

template <>
TDuration ConvertFromYsonString<TDuration>(const TYsonStringBuf& str)
{
    try {
        return TDuration::MilliSeconds(ParseUint64FromYsonString(str));
    } catch (const std::exception& ex) {
        throw TYsonLiteralParseException(ex, "Error parsing \"duration\" value from YSON");
    }
}

template <>
TGuid ConvertFromYsonString<TGuid>(const TYsonStringBuf& str)
{
    try {
        return TGuid::FromString(ParseStringFromYsonString(str));
    } catch (const std::exception& ex) {
        throw TYsonLiteralParseException(ex, "Error parsing \"guid\" value from YSON");
    }
}

////////////////////////////////////////////////////////////////////////////////

} // namespace NYT::NYson