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
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
using Google.ProtocolBuffers.Descriptors;
namespace Google.ProtocolBuffers.Serialization
{
/// <summary>
/// JsonFormatWriter is a .NET 2.0 friendly json formatter for proto buffer messages. For .NET 3.5
/// you may also use the XmlFormatWriter with an XmlWriter created by the
/// <see cref="System.Runtime.Serialization.Json.JsonReaderWriterFactory">JsonReaderWriterFactory</see>.
/// </summary>
public abstract class JsonFormatWriter : AbstractTextWriter
{
#region buffering implementations
private class JsonTextWriter : JsonFormatWriter
{
private readonly char[] _buffer;
private TextWriter _output;
private int _bufferPos;
public JsonTextWriter(TextWriter output)
{
_buffer = new char[4096];
_bufferPos = 0;
_output = output;
_counter.Add(0);
}
/// <summary>
/// Returns the output of TextWriter.ToString() where TextWriter is the ctor argument.
/// </summary>
public override string ToString()
{
Flush();
if (_output != null)
{
return _output.ToString();
}
return new String(_buffer, 0, _bufferPos);
}
protected override void WriteToOutput(char[] chars, int offset, int len)
{
if (_bufferPos + len >= _buffer.Length)
{
if (_output == null)
{
_output = new StringWriter(new StringBuilder(_buffer.Length*2 + len));
}
Flush();
}
if (len < _buffer.Length)
{
if (len <= 12)
{
int stop = offset + len;
for (int i = offset; i < stop; i++)
{
_buffer[_bufferPos++] = chars[i];
}
}
else
{
Buffer.BlockCopy(chars, offset << 1, _buffer, _bufferPos << 1, len << 1);
_bufferPos += len;
}
}
else
{
_output.Write(chars, offset, len);
}
}
protected override void WriteToOutput(char ch)
{
if (_bufferPos >= _buffer.Length)
{
Flush();
}
_buffer[_bufferPos++] = ch;
}
public override void Flush()
{
if (_bufferPos > 0 && _output != null)
{
_output.Write(_buffer, 0, _bufferPos);
_bufferPos = 0;
}
base.Flush();
}
}
private class JsonStreamWriter : JsonFormatWriter
{
#if SILVERLIGHT2 || COMPACT_FRAMEWORK_35
static readonly Encoding Encoding = Encoding.UTF8;
#else
private static readonly Encoding Encoding = Encoding.ASCII;
#endif
private readonly byte[] _buffer;
private Stream _output;
private int _bufferPos;
public JsonStreamWriter(Stream output)
{
_buffer = new byte[8192];
_bufferPos = 0;
_output = output;
_counter.Add(0);
}
protected override void WriteToOutput(char[] chars, int offset, int len)
{
if (_bufferPos + len >= _buffer.Length)
{
Flush();
}
if (len < _buffer.Length)
{
if (len <= 12)
{
int stop = offset + len;
for (int i = offset; i < stop; i++)
{
_buffer[_bufferPos++] = (byte) chars[i];
}
}
else
{
_bufferPos += Encoding.GetBytes(chars, offset, len, _buffer, _bufferPos);
}
}
else
{
byte[] temp = Encoding.GetBytes(chars, offset, len);
_output.Write(temp, 0, temp.Length);
}
}
protected override void WriteToOutput(char ch)
{
if (_bufferPos >= _buffer.Length)
{
Flush();
}
_buffer[_bufferPos++] = (byte) ch;
}
public override void Flush()
{
if (_bufferPos > 0 && _output != null)
{
_output.Write(_buffer, 0, _bufferPos);
_bufferPos = 0;
}
base.Flush();
}
}
#endregion
private readonly List<int> _counter;
private bool _isArray;
/// <summary>
/// Constructs a JsonFormatWriter, use the ToString() member to extract the final Json on completion.
/// </summary>
protected JsonFormatWriter()
{
_counter = new List<int>();
}
/// <summary>
/// Constructs a JsonFormatWriter, use ToString() to extract the final output
/// </summary>
public static JsonFormatWriter CreateInstance()
{
return new JsonTextWriter(null);
}
/// <summary>
/// Constructs a JsonFormatWriter to output to the given text writer
/// </summary>
public static JsonFormatWriter CreateInstance(TextWriter output)
{
return new JsonTextWriter(output);
}
/// <summary>
/// Constructs a JsonFormatWriter to output to the given stream
/// </summary>
public static JsonFormatWriter CreateInstance(Stream output)
{
return new JsonStreamWriter(output);
}
/// <summary> Write to the output stream </summary>
protected void WriteToOutput(string format, params object[] args)
{
WriteToOutput(String.Format(format, args));
}
/// <summary> Write to the output stream </summary>
protected void WriteToOutput(string text)
{
WriteToOutput(text.ToCharArray(), 0, text.Length);
}
/// <summary> Write to the output stream </summary>
protected abstract void WriteToOutput(char ch);
/// <summary> Write to the output stream </summary>
protected abstract void WriteToOutput(char[] chars, int offset, int len);
/// <summary> Sets the output formatting to use Environment.NewLine with 4-character indentions </summary>
public JsonFormatWriter Formatted()
{
NewLine = Environment.NewLine;
Indent = " ";
Whitespace = " ";
return this;
}
/// <summary> Gets or sets the characters to use for the new-line, default = empty </summary>
public string NewLine { get; set; }
/// <summary> Gets or sets the text to use for indenting, default = empty </summary>
public string Indent { get; set; }
/// <summary> Gets or sets the whitespace to use to separate the text, default = empty </summary>
public string Whitespace { get; set; }
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
protected override void Dispose(bool disposing)
{
if (disposing && _counter.Count == 1)
{
EndMessage();
}
base.Dispose(disposing);
}
private void Seperator()
{
if (_counter.Count == 0)
{
throw new InvalidOperationException("Missmatched open/close in Json writer.");
}
int index = _counter.Count - 1;
if (_counter[index] > 0)
{
WriteToOutput(',');
}
WriteLine(String.Empty);
_counter[index] = _counter[index] + 1;
}
private void WriteLine(string content)
{
if (!String.IsNullOrEmpty(NewLine))
{
WriteToOutput(NewLine);
for (int i = 1; i < _counter.Count; i++)
{
WriteToOutput(Indent);
}
}
else if (!String.IsNullOrEmpty(Whitespace))
{
WriteToOutput(Whitespace);
}
WriteToOutput(content);
}
private void WriteName(string field)
{
Seperator();
if (!String.IsNullOrEmpty(field))
{
WriteToOutput('"');
WriteToOutput(field);
WriteToOutput('"');
WriteToOutput(':');
if (!String.IsNullOrEmpty(Whitespace))
{
WriteToOutput(Whitespace);
}
}
}
private void EncodeText(string value)
{
char[] text = value.ToCharArray();
int len = text.Length;
int pos = 0;
while (pos < len)
{
int next = pos;
while (next < len && text[next] >= 32 && text[next] < 127 && text[next] != '\\' && text[next] != '/' &&
text[next] != '"')
{
next++;
}
WriteToOutput(text, pos, next - pos);
if (next < len)
{
switch (text[next])
{
case '"':
WriteToOutput(@"\""");
break;
case '\\':
WriteToOutput(@"\\");
break;
//odd at best to escape '/', most Json implementations don't, but it is defined in the rfc-4627
case '/':
WriteToOutput(@"\/");
break;
case '\b':
WriteToOutput(@"\b");
break;
case '\f':
WriteToOutput(@"\f");
break;
case '\n':
WriteToOutput(@"\n");
break;
case '\r':
WriteToOutput(@"\r");
break;
case '\t':
WriteToOutput(@"\t");
break;
default:
WriteToOutput(@"\u{0:x4}", (int) text[next]);
break;
}
next++;
}
pos = next;
}
}
/// <summary>
/// Writes a String value
/// </summary>
protected override void WriteAsText(string field, string textValue, object typedValue)
{
WriteName(field);
if (typedValue is bool || typedValue is int || typedValue is uint || typedValue is long ||
typedValue is ulong || typedValue is double || typedValue is float)
{
WriteToOutput(textValue);
}
else
{
WriteToOutput('"');
if (typedValue is string)
{
EncodeText(textValue);
}
else
{
WriteToOutput(textValue);
}
WriteToOutput('"');
}
}
/// <summary>
/// Writes a Double value
/// </summary>
protected override void Write(string field, double value)
{
if (double.IsNaN(value) || double.IsNegativeInfinity(value) || double.IsPositiveInfinity(value))
{
throw new InvalidOperationException("This format does not support NaN, Infinity, or -Infinity");
}
base.Write(field, value);
}
/// <summary>
/// Writes a Single value
/// </summary>
protected override void Write(string field, float value)
{
if (float.IsNaN(value) || float.IsNegativeInfinity(value) || float.IsPositiveInfinity(value))
{
throw new InvalidOperationException("This format does not support NaN, Infinity, or -Infinity");
}
base.Write(field, value);
}
// Treat enum as string
protected override void WriteEnum(string field, int number, string name)
{
Write(field, name);
}
/// <summary>
/// Writes an array of field values
/// </summary>
protected override void WriteArray(FieldType type, string field, IEnumerable items)
{
IEnumerator enumerator = items.GetEnumerator();
try
{
if (!enumerator.MoveNext())
{
return;
}
}
finally
{
if (enumerator is IDisposable)
{
((IDisposable) enumerator).Dispose();
}
}
WriteName(field);
WriteToOutput("[");
_counter.Add(0);
base.WriteArray(type, String.Empty, items);
_counter.RemoveAt(_counter.Count - 1);
WriteLine("]");
}
/// <summary>
/// Writes a message
/// </summary>
protected override void WriteMessageOrGroup(string field, IMessageLite message)
{
WriteName(field);
WriteMessage(message);
}
/// <summary>
/// Writes the message to the the formatted stream.
/// </summary>
public override void WriteMessage(IMessageLite message)
{
StartMessage();
message.WriteTo(this);
EndMessage();
}
/// <summary>
/// Used to write the root-message preamble, in json this is the left-curly brace '{'.
/// After this call you can call IMessageLite.MergeTo(...) and complete the message with
/// a call to EndMessage().
/// </summary>
public override void StartMessage()
{
if (_isArray)
{
Seperator();
}
WriteToOutput("{");
_counter.Add(0);
}
/// <summary>
/// Used to complete a root-message previously started with a call to StartMessage()
/// </summary>
public override void EndMessage()
{
_counter.RemoveAt(_counter.Count - 1);
WriteLine("}");
Flush();
}
/// <summary>
/// Used in streaming arrays of objects to the writer
/// </summary>
/// <example>
/// <code>
/// using(writer.StartArray())
/// foreach(IMessageLite m in messages)
/// writer.WriteMessage(m);
/// </code>
/// </example>
public sealed class JsonArray : IDisposable
{
private JsonFormatWriter _writer;
internal JsonArray(JsonFormatWriter writer)
{
_writer = writer;
_writer.WriteToOutput("[");
_writer._counter.Add(0);
}
/// <summary>
/// Causes the end of the array character to be written.
/// </summary>
private void EndArray()
{
if (_writer != null)
{
_writer._counter.RemoveAt(_writer._counter.Count - 1);
_writer.WriteLine("]");
_writer.Flush();
}
_writer = null;
}
void IDisposable.Dispose()
{
EndArray();
}
}
/// <summary>
/// Used to write an array of messages as the output rather than a single message.
/// </summary>
/// <example>
/// <code>
/// using(writer.StartArray())
/// foreach(IMessageLite m in messages)
/// writer.WriteMessage(m);
/// </code>
/// </example>
public JsonArray StartArray()
{
if (_isArray)
{
Seperator();
}
_isArray = true;
return new JsonArray(this);
}
}
}
|