-
Notifications
You must be signed in to change notification settings - Fork 9
/
Writer.cs
133 lines (107 loc) · 3.47 KB
/
Writer.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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using PASaveEditor.FileModel;
namespace PASaveEditor {
internal class Writer : IDisposable {
int indent;
readonly TextWriter writer;
bool isInline;
readonly Stack<bool> inlineStack = new Stack<bool>();
public Writer(FileStream fs) {
writer = new StreamWriter(fs, Encoding.ASCII);
}
public void WritePrison(Prison prison) {
writer.Write('\n');
WriteNodeData(prison);
}
public void WriteProperty(string key, double value) {
WriteProperty(key, value.ToString("#.0####", CultureInfo.InvariantCulture));
}
public void WriteProperty(string key, int value) {
WriteProperty(key, value.ToString(CultureInfo.InvariantCulture));
}
public void WriteProperty(string key, bool value) {
WriteProperty(key, value ? "true" : "false");
}
public void WriteProperty(string key, string value) {
if (value == null) return;
if (!isInline) {
for (int i = 0; i < indent; i++) {
writer.Write(" ");
}
}
WriteValue(key);
writer.Write(' ');
WriteValue(value);
if (isInline) {
writer.Write(" ");
} else {
writer.Write("\n");
}
}
public void WriteNode(Node node) {
if (node == null) return;
inlineStack.Push(isInline);
isInline = (node.Nodes == null) &&
(node.Properties == null || node.Properties.Count < 6) &&
!node.DoNotInline;
for (int i = 0; i < indent; i++) {
writer.Write(" ");
}
indent++;
writer.Write("BEGIN ");
WriteValue(node.Label);
if (isInline) {
writer.Write(" ");
} else {
writer.Write("\n");
}
WriteNodeData(node);
indent--;
if (!isInline) {
for (int i = 0; i < indent; i++) {
writer.Write(" ");
}
}
writer.Write("END\n");
isInline = inlineStack.Pop();
}
void WriteNodeData(Node node) {
node.WriteProperties(this);
if (node.Properties != null) {
foreach (var property in node.Properties) {
foreach (string value in property.Value) {
WriteProperty(property.Key, value);
}
}
}
node.WriteNodes(this);
if (node.Nodes != null) {
foreach (var nodeSet in node.Nodes) {
foreach (Node value in nodeSet.Value) {
WriteNode(value);
}
}
}
}
void WriteValue(string value) {
bool doQuote = (value.IndexOf(' ') >= 0);
if (doQuote) {
writer.Write('"');
}
writer.Write(value);
if (doQuote) {
writer.Write('"');
}
}
public void Dispose() {
if (writer != null) {
writer.Close();
writer.Dispose();
}
}
}
}