-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathJsonWriter.cs
109 lines (93 loc) · 3.17 KB
/
JsonWriter.cs
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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
namespace Microsoft.LinuxTracepoints.Decode
{
using System;
using StringBuilder = System.Text.StringBuilder;
using Text = System.Text;
internal struct JsonWriter
{
private StringBuilder builder;
private bool comma;
private bool currentSpace;
private bool nextSpace;
private bool wantFieldTag;
public JsonWriter(StringBuilder builder, PerfConvertOptions options, bool comma)
{
var space = options.HasFlag(PerfConvertOptions.Space);
this.builder = builder;
this.comma = comma;
this.currentSpace = space && comma; // Space before first item only if after a comma.
this.nextSpace = space; // Enable or disable space for subsequent items.
this.wantFieldTag = options.HasFlag(PerfConvertOptions.FieldTag);
}
public bool Comma => this.comma;
public void WritePropertyNameNoEscape(ReadOnlySpan<char> name)
{
this.CommaSpace();
this.builder.Append('"');
this.builder.Append(name); // Assume no escaping needed.
this.builder.Append("\":");
this.comma = false;
}
public void WritePropertyName(ReadOnlySpan<byte> nameUtf8, ushort fieldTag)
{
this.CommaSpace();
this.builder.Append('"');
PerfConvert.StringAppendWithControlCharsJsonEscape(this.builder, nameUtf8, Text.Encoding.UTF8);
if (this.wantFieldTag && fieldTag != 0)
{
this.builder.Append(";tag=");
PerfConvert.UInt32HexAppend(this.builder, fieldTag);
}
this.builder.Append("\":");
this.comma = false;
}
public void WriteStartObject()
{
this.CommaSpace();
this.builder.Append('{');
this.comma = false;
}
public void WriteEndObject()
{
if (this.currentSpace) this.builder.Append(' ');
this.builder.Append('}');
this.comma = true;
}
public void WriteStartArray()
{
this.CommaSpace();
this.builder.Append('[');
this.comma = false;
}
public void WriteEndArray()
{
if (this.currentSpace) this.builder.Append(' ');
this.builder.Append(']');
this.comma = true;
}
public StringBuilder WriteValue()
{
this.CommaSpace();
this.comma = true;
return this.builder;
}
public StringBuilder WriteValueNoEscapeName(ReadOnlySpan<char> name)
{
WritePropertyNameNoEscape(name);
if (this.currentSpace) this.builder.Append(' ');
this.comma = true;
return this.builder;
}
private void CommaSpace()
{
if (this.comma)
{
this.builder.Append(',');
}
if (this.currentSpace) this.builder.Append(' ');
this.currentSpace = this.nextSpace;
}
}
}