-
Notifications
You must be signed in to change notification settings - Fork 15
/
Rsv.cs
276 lines (241 loc) · 8.91 KB
/
Rsv.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
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
/* (C) Stefan John / Stenway / Stenway.com / 2023 */
#nullable enable
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
static byte[] EncodeRsv(string?[][] rows) {
var parts = new List<byte[]>();
var valueTerminatorByte = new byte[]{0xFF};
var nullValueByte = new byte[]{0xFE};
var rowTerminatorByte = new byte[]{0xFD};
var encoder = new UTF8Encoding(false, true);
foreach (var row in rows) {
foreach (var value in row) {
if (value == null) { parts.Add(nullValueByte); }
else if (value.Length > 0) { parts.Add(encoder.GetBytes(value)); }
parts.Add(valueTerminatorByte);
}
parts.Add(rowTerminatorByte);
}
var result = new byte[parts.Sum(part => part.Length)];
var stream = new MemoryStream(result);
foreach (var part in parts) { stream.Write(part, 0, part.Length); }
return result;
}
static string?[][] DecodeRsv(byte[] bytes) {
if (bytes.Length > 0 && bytes[bytes.Length-1] != 0xFD) { throw new Exception("Incomplete RSV document"); }
var decoder = new UTF8Encoding(false, true);
var result = new List<string?[]>();
var currentRow = new List<string?>();
int valueStartIndex = 0;
for (int i=0; i<bytes.Length; i++) {
if (bytes[i] == 0xFF) {
int length = i-valueStartIndex;
if (length == 0) { currentRow.Add(""); }
else if (length == 1 && bytes[valueStartIndex] == 0xFE) { currentRow.Add(null); }
else {
var valueBytes = bytes.Skip(valueStartIndex).Take(length).ToArray();
currentRow.Add(decoder.GetString(valueBytes));
}
valueStartIndex = i+1;
} else if (bytes[i] == 0xFD) {
if (i > 0 && valueStartIndex != i) { throw new Exception("Incomplete RSV row"); }
result.Add(currentRow.ToArray());
currentRow.Clear();
valueStartIndex = i+1;
}
}
return result.ToArray();
}
// ----------------------------------------------------------------------
static void SaveRsv(string?[][] rows, string filePath) {
File.WriteAllBytes(filePath, EncodeRsv(rows));
}
static string?[][] LoadRsv(string filePath) {
return DecodeRsv(File.ReadAllBytes(filePath));
}
static void AppendRsv(string?[][] rows, string filePath, bool continueLastRow = false) {
using (FileStream fileStream = File.Open(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite)) {
if (continueLastRow && fileStream.Length > 0) {
fileStream.Position = fileStream.Length - 1;
if (fileStream.ReadByte() != 0xFD) { throw new Exception("Incomplete RSV document"); }
if (rows.Length == 0) return;
fileStream.Position = fileStream.Length - 1;
} else {
fileStream.Position = fileStream.Length;
}
fileStream.Write(EncodeRsv(rows));
}
}
// ----------------------------------------------------------------------
static IEnumerable<byte[]> SplitBytes(byte[] bytes, byte splitByte) {
var lastIndex = -1;
for (;;) {
var currentIndex = Array.IndexOf(bytes, splitByte, lastIndex+1);
if (currentIndex < 0) {
yield return bytes.Skip(lastIndex+1).ToArray();
yield break;
} else {
yield return bytes.Skip(lastIndex+1).Take(currentIndex-lastIndex-1).ToArray();
lastIndex = currentIndex;
}
}
}
static string?[][] DecodeRsvUsingSplit(byte[] bytes) {
if (bytes.LastOrDefault((byte)0xFD) != 0xFD) { throw new Exception("Incomplete RSV document"); }
var decoder = new UTF8Encoding(true, true);
return SplitBytes(bytes, 0xFD).SkipLast(1).Select(
(rowBytes) => {
if (rowBytes.LastOrDefault((byte)0xFF) != 0xFF) { throw new Exception("Incomplete RSV row"); }
return SplitBytes(rowBytes, 0xFF).SkipLast(1).Select(
(valueBytes) => {
if (valueBytes.Length == 1 && valueBytes[0] == 0xFE) { return null; }
else { return decoder.GetString(valueBytes); }
}
).ToArray();
}
).ToArray();
}
static string?[][] LoadRsvUsingSplit(string filePath) {
return DecodeRsvUsingSplit(File.ReadAllBytes(filePath));
}
// ----------------------------------------------------------------------
static bool IsValidRsv(byte[] bytes) {
byte[] byteClassLookup = {
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
0, 0, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 7, 7,
9, 10, 10, 10, 11, 0, 0, 0, 0, 0, 0, 0, 0, 12, 13, 14
};
byte[] stateTransitionLookup = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 2, 0, 0, 0, 3, 4, 6, 5, 7, 8, 9, 1, 10, 11,
0, 2, 0, 0, 0, 3, 4, 6, 5, 7, 8, 9, 0, 0, 11,
0, 0, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 6, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 11,
0, 2, 0, 0, 0, 3, 4, 6, 5, 7, 8, 9, 1, 10, 11
};
int lastState = 1;
for (int i=0; i<bytes.Length; i++) {
byte currentByte = bytes[i];
int currentByteClass = byteClassLookup[currentByte];
int newStateLookupIndex = lastState*15+currentByteClass;
lastState = stateTransitionLookup[newStateLookupIndex];
if (lastState == 0) { return false; }
}
return (lastState == 1);
}
// ----------------------------------------------------------------------
static string ByteArrayToString(byte[] bytes) {
return "["+string.Join(", ", bytes)+"]";
}
// ----------------------------------------------------------------------
static string EscapeJsonString(string str) {
StringBuilder result = new StringBuilder();
result.Append("\"");
for (int i = 0; i < str.Length; i++) {
char c = str[i];
if (c == 0x08) { result.Append("\\b"); }
else if (c == 0x09) { result.Append("\\t"); }
else if (c == 0x0A) { result.Append("\\n"); }
else if (c == 0x0C) { result.Append("\\f"); }
else if (c == 0x0D) { result.Append("\\r"); }
else if (c == 0x22) { result.Append("\\\""); }
else if (c == 0x5C) { result.Append("\\\\"); }
else if (c >= 0x00 && c <= 0x1F) { result.AppendFormat("\\u{0:x4}", (int)c); }
else { result.Append(c); }
}
result.Append("\"");
return result.ToString();
}
static string RsvToJson(string?[][] rows) {
return "["+(rows.Length > 0 ? "\n" : "")+String.Join(",\n", rows.Select((row) => " ["+String.Join(", ", row.Select(x => x == null ? "null" : EscapeJsonString(x)))+"]"))+"\n]";
}
static void PrintRsvToJson(string?[][] rows) {
Console.WriteLine(RsvToJson(rows));
}
// ----------------------------------------------------------------------
static void CheckTestFiles() {
for (var i=1; i<=79; i++) {
var filePath = ".\\..\\TestFiles\\Valid_" + i.ToString("D3");
Console.WriteLine("Checking valid test file: " + filePath);
var loadedRows = LoadRsv(filePath + ".rsv");
var jsonStr = RsvToJson(loadedRows);
var loadedJsonStr = File.ReadAllText(filePath + ".json");
if (jsonStr != loadedJsonStr) {
throw new Exception("JSON mismatch");
}
var loadedRowsUsingSplit = LoadRsvUsingSplit(filePath + ".rsv");
var jsonStrUsingSplit = RsvToJson(loadedRowsUsingSplit);
if (jsonStrUsingSplit != loadedJsonStr) {
throw new Exception("JSON mismatch - using split");
}
if (!IsValidRsv(File.ReadAllBytes(filePath + ".rsv"))) {
throw new Exception("Validation mismatch");
}
}
for (var i=1; i<=29; i++) {
var filePath = ".\\..\\TestFiles\\Invalid_" + i.ToString("D3");
Console.WriteLine("Checking invalid test file: " + filePath);
var wasError = false;
try {
var loadedRows = LoadRsv(filePath + ".rsv");
} catch(Exception e) {
wasError = true;
}
if (!wasError) {
throw new Exception("RSV document is valid");
}
wasError = false;
try {
var loadedRowsUsingSplit = LoadRsvUsingSplit(filePath + ".rsv");
} catch(Exception e) {
wasError = true;
}
if (!wasError) {
throw new Exception("RSV document is valid");
}
if (IsValidRsv(File.ReadAllBytes(filePath + ".rsv"))) {
throw new Exception("Validation mismatch");
}
}
}
// ----------------------------------------------------------------------
string?[][] rows = new []{
new []{"Hello", "🌎", null, ""},
new []{"A\0B\nC", "Test 𝄞"},
new string?[]{},
new []{""}
};
Console.OutputEncoding = System.Text.Encoding.UTF8;
PrintRsvToJson(rows);
var bytes = EncodeRsv(rows);
//Console.WriteLine(ByteArrayToString(bytes));
var decodedRows = DecodeRsv(bytes);
SaveRsv(rows, "Test.rsv");
var loadedRows = LoadRsv("Test.rsv");
PrintRsvToJson(loadedRows);
SaveRsv(loadedRows, "TestResaved.rsv");
AppendRsv(new []{new []{"ABC"}}, "Append.rsv", false);
CheckTestFiles();
Console.WriteLine("Done");