This repository was archived by the owner on Dec 24, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 615
Expand file tree
/
Copy pathJsvFormatter.cs
More file actions
103 lines (88 loc) · 3.11 KB
/
JsvFormatter.cs
File metadata and controls
103 lines (88 loc) · 3.11 KB
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
//
// https://github.com/ServiceStack/ServiceStack.Text
// ServiceStack.Text: .NET C# POCO JSON, JSV and CSV Text Serializers.
//
// Authors:
// Peter Townsend (townsend.pete@gmail.com)
// Demis Bellot (demis.bellot@gmail.com)
//
// Copyright 2012 ServiceStack, Inc. All Rights Reserved.
//
// Licensed under the same terms of ServiceStack.
//
using System;
using System.Collections.Generic;
using System.Text;
using ServiceStack.Text.Common;
namespace ServiceStack.Text
{
public static class JsvFormatter
{
public static string Format(string serializedText)
{
if (string.IsNullOrEmpty(serializedText)) return null;
var tabCount = 0;
var sb = StringBuilderThreadStatic.Allocate();
var firstKeySeparator = true;
var inString = false;
for (var i = 0; i < serializedText.Length; i++)
{
var current = serializedText[i];
var previous = i - 1 >= 0 ? serializedText[i - 1] : 0;
var next = i < serializedText.Length - 1 ? serializedText[i + 1] : 0;
if (current == JsWriter.MapStartChar || current == JsWriter.ListStartChar)
{
if (previous == JsWriter.MapKeySeperator)
{
if (next == JsWriter.MapEndChar || next == JsWriter.ListEndChar)
{
sb.Append(current);
sb.Append(serializedText[++i]); //eat next
continue;
}
AppendTabLine(sb, tabCount);
}
sb.Append(current);
AppendTabLine(sb, ++tabCount);
firstKeySeparator = true;
continue;
}
if (current == JsWriter.MapEndChar || current == JsWriter.ListEndChar)
{
AppendTabLine(sb, --tabCount);
sb.Append(current);
firstKeySeparator = true;
continue;
}
if (current == JsWriter.QuoteChar)
{
sb.Append(current);
inString = !inString;
continue;
}
if (current == JsWriter.ItemSeperator && !inString)
{
sb.Append(current);
AppendTabLine(sb, tabCount);
firstKeySeparator = true;
continue;
}
sb.Append(current);
if (current == JsWriter.MapKeySeperator && firstKeySeparator)
{
sb.Append(" ");
firstKeySeparator = false;
}
}
return StringBuilderThreadStatic.ReturnAndFree(sb);
}
private static void AppendTabLine(StringBuilder sb, int tabCount)
{
sb.AppendLine();
if (tabCount > 0)
{
sb.Append(new string('\t', tabCount));
}
}
}
}