Coverage Report

Created: 2026-10-19 14:15

src/zserio/JsonWriter.h
Line
Count
Source (jump to first uncovered line)
1
#ifndef ZSERIO_JSON_WRITER_H_INC
2
#define ZSERIO_JSON_WRITER_H_INC
3
4
#include <ostream>
5
6
#include "zserio/AllocatorHolder.h"
7
#include "zserio/IWalkObserver.h"
8
#include "zserio/JsonEncoder.h"
9
#include "zserio/OptionalHolder.h"
10
#include "zserio/TypeInfoUtil.h"
11
#include "zserio/Types.h"
12
13
namespace zserio
14
{
15
16
/**
17
 * Walker observer which dumps zserio objects to JSON format.
18
 */
19
template <typename ALLOC = std::allocator<uint8_t>>
20
class BasicJsonWriter : public IBasicWalkObserver<ALLOC>, public AllocatorHolder<ALLOC>
21
{
22
public:
23
    using AllocatorHolder<ALLOC>::get_allocator;
24
25
    /**
26
     * Default item separator used when indent is not set.
27
     */
28
    static constexpr const char* DEFAULT_ITEM_SEPARATOR = ", ";
29
30
    /**
31
     * Default item separator used when indent is set.
32
     */
33
    static constexpr const char* DEFAULT_ITEM_SEPARATOR_WITH_INDENT = ",";
34
35
    /**
36
     * Default key separator.
37
     */
38
    static constexpr const char* DEFAULT_KEY_SEPARATOR = ": ";
39
40
    /**
41
     * Configuration for writing of enumerable types.
42
     */
43
    enum class EnumerableFormat
44
    {
45
        /** Print as JSON integral value. */
46
        NUMBER,
47
        /**
48
         * Print as JSON string according to the following rules:
49
         *
50
         * 1. Enums
51
         *   * when an exact match with an enumerable item is found, the item name is used - e.g. "FIRST",
52
         *   * when no exact match is found, it's an invalid value, the integral value is converted to string
53
         *     and an appropriate comment is included - e.g. \"10 /<span>*</span> no match <span>*</span>/\".
54
         *
55
         * 2. Bitmasks
56
         *   * when an exact mach with or-ed bitmask values is found, it's used - e.g. "READ | WRITE",
57
         *   * when no exact match is found, but some or-ed values match, the integral value is converted
58
         *     to string and the or-ed values are included in a comment - e.g.
59
         *     \"127 /<span>*</span> READ | CREATE <span>*</span>/\",
60
         *   * when no match is found at all, the integral value is converted to string and an appropriate
61
         *     comment is included - e.g. \"13 /<span>*</span> no match <span>*</span>/\".
62
         */
63
        STRING
64
    };
65
    /**
66
     * Default configuration for enumerable types.
67
     */
68
    static constexpr EnumerableFormat DEFAULT_ENUMERABLE_FORMAT = EnumerableFormat::STRING;
69
70
    /**
71
     * Constructor.
72
     *
73
     * \param out Stream to use for writing.
74
     * \param allocator Allocator to use.
75
     */
76
    explicit BasicJsonWriter(std::ostream& out, const ALLOC& allocator = ALLOC());
77
78
    /**
79
     * Constructor.
80
     *
81
     * \param out Stream to use for writing.
82
     * \param indent Indent as a number of ' ' to be used for indentation.
83
     * \param allocator Allocator to use.
84
     */
85
    BasicJsonWriter(std::ostream& out, uint8_t indent, const ALLOC& allocator = ALLOC());
86
87
    /**
88
     * Constructor.
89
     *
90
     * \param out Stream to use for writing.
91
     * \param indent Indent as a string to be used for indentation.
92
     * \param allocator Allocator to use.
93
     */
94
    BasicJsonWriter(std::ostream& out, const string<ALLOC>& indent, const ALLOC& allocator = ALLOC());
95
96
    /**
97
     * Method generated by default.
98
     */
99
68
    ~BasicJsonWriter() override = default;
100
101
    /**
102
     * Copying and moving is disallowed!
103
     * \{
104
     */
105
    BasicJsonWriter(const BasicJsonWriter& other) = delete;
106
    BasicJsonWriter& operator=(const BasicJsonWriter& other) = delete;
107
108
    BasicJsonWriter(BasicJsonWriter&& other) = delete;
109
    BasicJsonWriter& operator=(BasicJsonWriter&& other) = delete;
110
    /**
111
     * \}
112
     */
113
114
    /**
115
     * Sets custom item separator.
116
     *
117
     * Use with caution since setting of a wrong separator can lead to invalid JSON output.
118
     *
119
     * \param itemSeparator Item separator to set.
120
     */
121
    void setItemSeparator(const string<ALLOC>& itemSeparator);
122
123
    /**
124
     * Sets custom key separator.
125
     *
126
     * Use with caution since setting of a wrong separator can lead to invalid JSON output.
127
     *
128
     * \param keySeparator Key separator to set.
129
     */
130
    void setKeySeparator(const string<ALLOC>& keySeparator);
131
132
    /**
133
     * Sets preferred formatting for enumerable types.
134
     *
135
     * @param enumerableFormat Enumerable format to use.
136
     */
137
    void setEnumerableFormat(EnumerableFormat enumerableFormat);
138
139
    void beginRoot(const IBasicReflectableConstPtr<ALLOC>& compound) override;
140
    void endRoot(const IBasicReflectableConstPtr<ALLOC>& compound) override;
141
142
    void beginArray(
143
            const IBasicReflectableConstPtr<ALLOC>& array, const BasicFieldInfo<ALLOC>& fieldInfo) override;
144
    void endArray(
145
            const IBasicReflectableConstPtr<ALLOC>& array, const BasicFieldInfo<ALLOC>& fieldInfo) override;
146
147
    void beginCompound(const IBasicReflectableConstPtr<ALLOC>& compound, const BasicFieldInfo<ALLOC>& fieldInfo,
148
            size_t elementIndex) override;
149
    void endCompound(const IBasicReflectableConstPtr<ALLOC>& compound, const BasicFieldInfo<ALLOC>& fieldInfo,
150
            size_t elementIndex) override;
151
152
    void visitValue(const IBasicReflectableConstPtr<ALLOC>& value, const BasicFieldInfo<ALLOC>& fieldInfo,
153
            size_t elementIndex) override;
154
155
private:
156
    BasicJsonWriter(std::ostream& out, InplaceOptionalHolder<string<ALLOC>>&& optionalIndent,
157
            const ALLOC& allocator = ALLOC());
158
159
    void beginItem();
160
    void endItem();
161
    void beginObject();
162
    void endObject();
163
    void beginArray();
164
    void endArray();
165
166
    void writeIndent();
167
    void writeKey(StringView key);
168
    void writeValue(const IBasicReflectableConstPtr<ALLOC>& reflectable);
169
    void writeBitBuffer(const BasicBitBuffer<ALLOC>& bitBuffer);
170
    void writeBytes(Span<const uint8_t> value);
171
    void writeStringifiedEnum(const IBasicReflectableConstPtr<ALLOC>& reflectable);
172
    void writeStringifiedBitmask(const IBasicReflectableConstPtr<ALLOC>& reflectable);
173
174
    std::ostream& m_out;
175
    InplaceOptionalHolder<string<ALLOC>> m_indent;
176
    string<ALLOC> m_itemSeparator;
177
    string<ALLOC> m_keySeparator;
178
    EnumerableFormat m_enumerableFormat = DEFAULT_ENUMERABLE_FORMAT;
179
180
    bool m_isFirst = true;
181
    size_t m_level = 0;
182
};
183
184
/** Typedef to JsonWriter provided for convenience - using default std::allocator<uint8_t>. */
185
/** \{ */
186
using JsonWriter = BasicJsonWriter<>;
187
/** \} */
188
189
template <typename ALLOC>
190
BasicJsonWriter<ALLOC>::BasicJsonWriter(std::ostream& out, const ALLOC& allocator) :
191
        BasicJsonWriter(out, NullOpt, allocator)
192
28
{}
193
194
template <typename ALLOC>
195
BasicJsonWriter<ALLOC>::BasicJsonWriter(std::ostream& out, uint8_t indent, const ALLOC& allocator) :
196
        BasicJsonWriter(out, string<ALLOC>(indent, ' ', allocator), allocator)
197
38
{}
198
199
template <typename ALLOC>
200
BasicJsonWriter<ALLOC>::BasicJsonWriter(
201
        std::ostream& out, const string<ALLOC>& indent, const ALLOC& allocator) :
202
        BasicJsonWriter(out, InplaceOptionalHolder<string<ALLOC>>(indent), allocator)
203
40
{}
204
205
template <typename ALLOC>
206
BasicJsonWriter<ALLOC>::BasicJsonWriter(
207
        std::ostream& out, InplaceOptionalHolder<string<ALLOC>>&& optionalIndent, const ALLOC& allocator) :
208
        AllocatorHolder<ALLOC>(allocator),
209
        m_out(out),
210
        m_indent(optionalIndent),
211
        m_itemSeparator(
212
                m_indent.hasValue() ? DEFAULT_ITEM_SEPARATOR_WITH_INDENT : DEFAULT_ITEM_SEPARATOR, allocator),
213
        m_keySeparator(DEFAULT_KEY_SEPARATOR, allocator)
214
68
{}
215
216
template <typename ALLOC>
217
void BasicJsonWriter<ALLOC>::setItemSeparator(const string<ALLOC>& itemSeparator)
218
1
{
219
1
    m_itemSeparator = itemSeparator;
220
1
}
221
222
template <typename ALLOC>
223
void BasicJsonWriter<ALLOC>::setKeySeparator(const string<ALLOC>& keySeparator)
224
1
{
225
1
    m_keySeparator = keySeparator;
226
1
}
227
228
template <typename ALLOC>
229
void BasicJsonWriter<ALLOC>::setEnumerableFormat(EnumerableFormat enumerableFormat)
230
3
{
231
3
    m_enumerableFormat = enumerableFormat;
232
3
}
233
234
template <typename ALLOC>
235
void BasicJsonWriter<ALLOC>::beginRoot(const IBasicReflectableConstPtr<ALLOC>&)
236
45
{
237
45
    beginObject();
238
45
}
239
240
template <typename ALLOC>
241
void BasicJsonWriter<ALLOC>::endRoot(const IBasicReflectableConstPtr<ALLOC>&)
242
45
{
243
45
    endObject();
244
45
    m_out.flush();
245
45
}
246
247
template <typename ALLOC>
248
void BasicJsonWriter<ALLOC>::beginArray(
249
        const IBasicReflectableConstPtr<ALLOC>&, const BasicFieldInfo<ALLOC>& fieldInfo)
250
3
{
251
3
    beginItem();
252
253
3
    writeKey(fieldInfo.schemaName);
254
255
3
    beginArray();
256
3
}
257
258
template <typename ALLOC>
259
void BasicJsonWriter<ALLOC>::endArray(const IBasicReflectableConstPtr<ALLOC>&, const BasicFieldInfo<ALLOC>&)
260
3
{
261
3
    endArray();
262
263
3
    endItem();
264
3
}
265
266
template <typename ALLOC>
267
void BasicJsonWriter<ALLOC>::beginCompound(
268
        const IBasicReflectableConstPtr<ALLOC>&, const BasicFieldInfo<ALLOC>& fieldInfo, size_t elementIndex)
269
6
{
270
6
    beginItem();
271
272
6
    if (elementIndex == WALKER_NOT_ELEMENT)
273
5
    {
274
5
        writeKey(fieldInfo.schemaName);
275
5
    }
276
277
6
    beginObject();
278
6
}
279
280
template <typename ALLOC>
281
void BasicJsonWriter<ALLOC>::endCompound(
282
        const IBasicReflectableConstPtr<ALLOC>&, const BasicFieldInfo<ALLOC>&, size_t)
283
6
{
284
6
    endObject();
285
286
6
    endItem();
287
6
}
288
289
template <typename ALLOC>
290
void BasicJsonWriter<ALLOC>::visitValue(const IBasicReflectableConstPtr<ALLOC>& value,
291
        const BasicFieldInfo<ALLOC>& fieldInfo, size_t elementIndex)
292
85
{
293
85
    beginItem();
294
295
85
    if (elementIndex == WALKER_NOT_ELEMENT)
296
81
    {
297
81
        writeKey(fieldInfo.schemaName);
298
81
    }
299
300
85
    writeValue(value);
301
302
85
    endItem();
303
85
}
304
305
template <typename ALLOC>
306
void BasicJsonWriter<ALLOC>::beginItem()
307
108
{
308
108
    if (!m_isFirst)
309
29
    {
310
29
        m_out.write(m_itemSeparator.data(), static_cast<std::streamsize>(m_itemSeparator.size()));
311
29
    }
312
313
108
    if (m_indent.hasValue())
314
43
    {
315
43
        m_out.put('\n');
316
43
    }
317
318
108
    writeIndent();
319
108
}
320
321
template <typename ALLOC>
322
void BasicJsonWriter<ALLOC>::endItem()
323
107
{
324
107
    m_isFirst = false;
325
107
}
326
327
template <typename ALLOC>
328
void BasicJsonWriter<ALLOC>::beginObject()
329
55
{
330
55
    m_out.put('{');
331
332
55
    m_isFirst = true;
333
55
    m_level += 1;
334
55
}
335
336
template <typename ALLOC>
337
void BasicJsonWriter<ALLOC>::endObject()
338
55
{
339
55
    if (m_indent.hasValue())
340
43
    {
341
43
        m_out.put('\n');
342
43
    }
343
344
55
    m_level -= 1;
345
346
55
    writeIndent();
347
348
55
    m_out.put('}');
349
55
}
350
351
template <typename ALLOC>
352
void BasicJsonWriter<ALLOC>::beginArray()
353
7
{
354
7
    m_out.put('[');
355
356
7
    m_isFirst = true;
357
7
    m_level += 1;
358
7
}
359
360
template <typename ALLOC>
361
void BasicJsonWriter<ALLOC>::endArray()
362
7
{
363
7
    if (m_indent.hasValue())
364
1
    {
365
1
        m_out.put('\n');
366
1
    }
367
368
7
    m_level -= 1;
369
370
7
    writeIndent();
371
372
7
    m_out.put(']');
373
7
}
374
375
template <typename ALLOC>
376
void BasicJsonWriter<ALLOC>::writeIndent()
377
170
{
378
170
    if (m_indent.hasValue())
379
87
    {
380
87
        const auto& indent = m_indent.value();
381
87
        if (!indent.empty())
382
82
        {
383
129
            for (size_t i = 0; i < m_level; 
++i47
)
384
47
            {
385
47
                m_out.write(indent.data(), static_cast<std::streamsize>(indent.size()));
386
47
            }
387
82
        }
388
87
    }
389
170
}
390
391
template <typename ALLOC>
392
void BasicJsonWriter<ALLOC>::writeKey(StringView key)
393
95
{
394
95
    JsonEncoder::encodeString(m_out, key);
395
95
    m_out.write(m_keySeparator.data(), static_cast<std::streamsize>(m_keySeparator.size()));
396
95
    m_out.flush();
397
95
}
398
399
template <typename ALLOC>
400
void BasicJsonWriter<ALLOC>::writeValue(const IBasicReflectableConstPtr<ALLOC>& reflectable)
401
85
{
402
85
    if (!reflectable)
403
1
    {
404
1
        JsonEncoder::encodeNull(m_out);
405
1
        return;
406
1
    }
407
408
84
    const IBasicTypeInfo<ALLOC>& typeInfo = reflectable->getTypeInfo();
409
84
    switch (typeInfo.getCppType())
410
84
    {
411
1
    case CppType::BOOL:
412
1
        JsonEncoder::encodeBool(m_out, reflectable->getBool());
413
1
        break;
414
1
    case CppType::INT8:
415
2
    case CppType::INT16:
416
3
    case CppType::INT32:
417
4
    case CppType::INT64:
418
4
        JsonEncoder::encodeIntegral(m_out, reflectable->toInt());
419
4
        break;
420
1
    case CppType::UINT8:
421
2
    case CppType::UINT16:
422
13
    case CppType::UINT32:
423
14
    case CppType::UINT64:
424
14
        JsonEncoder::encodeIntegral(m_out, reflectable->toUInt());
425
14
        break;
426
1
    case CppType::FLOAT:
427
1
        JsonEncoder::encodeFloatingPoint(m_out, static_cast<double>(reflectable->getFloat()));
428
1
        break;
429
1
    case CppType::DOUBLE:
430
1
        JsonEncoder::encodeFloatingPoint(m_out, reflectable->getDouble());
431
1
        break;
432
2
    case CppType::BYTES:
433
2
        writeBytes(reflectable->getBytes());
434
2
        break;
435
39
    case CppType::STRING:
436
39
        JsonEncoder::encodeString(m_out, reflectable->getStringView());
437
39
        break;
438
2
    case CppType::BIT_BUFFER:
439
2
        writeBitBuffer(reflectable->getBitBuffer());
440
2
        break;
441
12
    case CppType::ENUM:
442
12
        if (m_enumerableFormat == EnumerableFormat::STRING)
443
7
        {
444
7
            writeStringifiedEnum(reflectable);
445
7
        }
446
5
        else if (TypeInfoUtil::isSigned(typeInfo.getUnderlyingType().getCppType()))
447
3
        {
448
3
            JsonEncoder::encodeIntegral(m_out, reflectable->toInt());
449
3
        }
450
2
        else
451
2
        {
452
2
            JsonEncoder::encodeIntegral(m_out, reflectable->toUInt());
453
2
        }
454
12
        break;
455
7
    case CppType::BITMASK:
456
7
        if (m_enumerableFormat == EnumerableFormat::STRING)
457
5
        {
458
5
            writeStringifiedBitmask(reflectable);
459
5
        }
460
2
        else
461
2
        {
462
2
            JsonEncoder::encodeIntegral(m_out, reflectable->toUInt());
463
2
        }
464
7
        break;
465
1
    case CppType::STRUCT:
466
1
    case CppType::CHOICE:
467
1
    case CppType::UNION:
468
1
    case CppType::SQL_TABLE:
469
1
    case CppType::SQL_DATABASE:
470
1
    case CppType::SERVICE:
471
1
    case CppType::PUBSUB:
472
1
    default:
473
1
        throw CppRuntimeException("JsonWriter: Unexpected not-null value of type '")
474
1
                << typeInfo.getSchemaName() << "'!";
475
84
    }
476
477
83
    m_out.flush();
478
83
}
479
480
template <typename ALLOC>
481
void BasicJsonWriter<ALLOC>::writeBitBuffer(const BasicBitBuffer<ALLOC>& bitBuffer)
482
2
{
483
2
    beginObject();
484
2
    beginItem();
485
2
    writeKey("buffer"_sv);
486
2
    beginArray();
487
2
    Span<const uint8_t> buffer = bitBuffer.getData();
488
2
    for (uint8_t element : buffer)
489
4
    {
490
4
        beginItem();
491
4
        JsonEncoder::encodeIntegral(m_out, element);
492
4
        endItem();
493
4
    }
494
2
    endArray();
495
2
    endItem();
496
2
    beginItem();
497
2
    writeKey("bitSize"_sv);
498
2
    JsonEncoder::encodeIntegral(m_out, bitBuffer.getBitSize());
499
2
    endItem();
500
2
    endObject();
501
2
}
502
503
template <typename ALLOC>
504
void BasicJsonWriter<ALLOC>::writeBytes(Span<const uint8_t> value)
505
2
{
506
2
    beginObject();
507
2
    beginItem();
508
2
    writeKey("buffer"_sv);
509
2
    beginArray();
510
2
    for (uint8_t byte : value)
511
4
    {
512
4
        beginItem();
513
4
        JsonEncoder::encodeIntegral(m_out, byte);
514
4
        endItem();
515
4
    }
516
2
    endArray();
517
2
    endItem();
518
2
    endObject();
519
2
}
520
521
template <typename ALLOC>
522
void BasicJsonWriter<ALLOC>::writeStringifiedEnum(const IBasicReflectableConstPtr<ALLOC>& reflectable)
523
7
{
524
7
    const auto& typeInfo = reflectable->getTypeInfo();
525
7
    const uint64_t enumValue = TypeInfoUtil::isSigned(typeInfo.getUnderlyingType().getCppType())
526
7
            ? 
static_cast<uint64_t>(reflectable->toInt())4
527
7
            : 
reflectable->toUInt()3
;
528
7
    for (const auto& itemInfo : typeInfo.getEnumItems())
529
14
    {
530
14
        if (itemInfo.value == enumValue)
531
5
        {
532
            // exact match
533
5
            JsonEncoder::encodeString(m_out, itemInfo.schemaName);
534
5
            return;
535
5
        }
536
14
    }
537
538
    // no match
539
2
    string<ALLOC> stringValue = TypeInfoUtil::isSigned(typeInfo.getUnderlyingType().getCppType())
540
2
            ? 
toString(reflectable->toInt(), get_allocator())1
541
2
            : 
toString(reflectable->toUInt(), get_allocator())1
;
542
2
    stringValue.append(" /* no match */");
543
2
    JsonEncoder::encodeString(m_out, stringValue);
544
2
}
545
546
template <typename ALLOC>
547
void BasicJsonWriter<ALLOC>::writeStringifiedBitmask(const IBasicReflectableConstPtr<ALLOC>& reflectable)
548
5
{
549
5
    string<ALLOC> stringValue(get_allocator());
550
5
    const auto& typeInfo = reflectable->getTypeInfo();
551
5
    const uint64_t bitmaskValue = reflectable->toUInt();
552
5
    uint64_t valueCheck = 0;
553
5
    for (const auto& itemInfo : typeInfo.getBitmaskValues())
554
15
    {
555
15
        if ((itemInfo.value != 0 && 
(bitmaskValue & itemInfo.value) == itemInfo.value10
) ||
556
15
                
(10
itemInfo.value == 010
&&
bitmaskValue == 05
))
557
6
        {
558
6
            valueCheck |= itemInfo.value;
559
6
            if (!stringValue.empty())
560
2
            {
561
2
                stringValue += " | ";
562
2
            }
563
6
            stringValue += toString(itemInfo.schemaName, get_allocator());
564
6
        }
565
15
    }
566
567
5
    if (stringValue.empty())
568
1
    {
569
        // no match
570
1
        stringValue.append(toString(bitmaskValue, get_allocator()));
571
1
        stringValue.append(" /* no match */");
572
1
    }
573
4
    else if (bitmaskValue != valueCheck)
574
1
    {
575
        // partial match
576
1
        stringValue =
577
1
                toString(bitmaskValue, get_allocator())
578
1
                        .append(" /* partial match: ")
579
1
                        .append(stringValue)
580
1
                        .append(" */");
581
1
    }
582
    // else exact match
583
584
5
    JsonEncoder::encodeString(m_out, stringValue);
585
5
}
586
587
} // namespace zserio
588
589
#endif // ZSERIO_JSON_WRITER_H_INC