-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathObjectWriter.cs
646 lines (515 loc) · 14.7 KB
/
ObjectWriter.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
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
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.Serialization;
namespace Grammophone.Serialization
{
/// <summary>
/// Writes an object graph to a stream.
/// </summary>
internal class ObjectWriter : ObjectStreamer
{
#region Auxilliary types
/// <summary>
/// Wraps references to objects.
/// </summary>
private struct Reference : IEquatable<Reference>
{
private object value;
public Reference(object value)
{
this.value = value;
}
/// <summary>
/// The referenced object.
/// </summary>
public object Value
{
get
{
return value;
}
}
/// <summary>
/// Returns a hash code using the base <see cref="Object.GetHashCode"/>
/// implemtation on the object in the <see cref="Value"/>
/// field, even if the object has overriden the method.
/// This means that the hash code depends on the pointer reference and not the contents of the object.
/// </summary>
public override int GetHashCode()
{
if (this.Value == null) return 0;
return System.Runtime.CompilerServices.RuntimeHelpers.GetHashCode(this.Value);
}
/// <summary>
/// Determines equality to another <see cref="Reference"/>
/// based on reference equality of the <see cref="Value"/> properties.
/// </summary>
/// <param name="obj">The other reference to test for equality.</param>
/// <returns>Returns true if the <see cref="Value"/> properties reference the same object instance.</returns>
public override bool Equals(object obj)
{
return base.Equals((Reference)obj);
}
#region IEquatable<Reference> Members
/// <summary>
/// Determines equality to another <see cref="Reference"/>
/// based on reference equality of the <see cref="Value"/> properties.
/// </summary>
/// <param name="other">The other reference to test for equality.</param>
/// <returns>Returns true if the <see cref="Value"/> properties reference the same object instance.</returns>
public bool Equals(Reference other)
{
return object.ReferenceEquals(this.Value, other.Value);
}
#endregion
}
#endregion
#region Private members
/// <summary>
/// Maps types to type IDs.
/// </summary>
private Dictionary<Type, int> typesToIDsDictionary;
/// <summary>
/// Maps objects to object IDs.
/// </summary>
private Dictionary<Reference, int> objectsToIDsDictionary;
/// <summary>
/// Maps interned strings to their IDs.
/// </summary>
private Dictionary<string, int> stringsToIDsDictionary;
/// <summary>
/// If true, serialization will intern the field names of all objects.
/// </summary>
private bool internFieldNames;
#endregion
#region Construction
/// <summary>
/// Create.
/// </summary>
/// <param name="stream">The stream to read or write.</param>
/// <param name="formatter">The formatter holding the serialization properties.</param>
public ObjectWriter(Stream stream, FastBinaryFormatter formatter)
: base(stream, formatter)
{
this.typesToIDsDictionary = new Dictionary<Type, int>();
this.objectsToIDsDictionary = new Dictionary<Reference, int>();
this.stringsToIDsDictionary = new Dictionary<string, int>();
this.internFieldNames = formatter.InternFieldNames;
}
#endregion
#region Public methods
/// <summary>
/// Write an object graph to the stream.
/// Repeatable calls will reuse object IDs and type IDs.
/// </summary>
/// <param name="value">The root of the object graph.</param>
public void Write(object value)
{
WriteObject(value);
}
#endregion
#region Private methods
private void WriteString(string text)
{
if (text == null) throw new ArgumentNullException("text");
var characters = text.ToCharArray();
byte[] lengthBytes = BitConverter.GetBytes(characters.Length);
stream.Write(lengthBytes, 0, 4);
byte[] characterBytes = new byte[characters.Length * 2];
int characterBytesPosition = 0;
for (int i = 0; i < characters.Length; i++)
{
var character = characters[i];
// Low byte
characterBytes[characterBytesPosition++] = (byte)character;
// High byte
characterBytes[characterBytesPosition++] = (byte)(character >> 8);
}
stream.Write(characterBytes, 0, characterBytes.Length);
}
private void WriteInternedString(string text)
{
if (text == null) throw new ArgumentNullException("text");
int id;
if (this.stringsToIDsDictionary.TryGetValue(text, out id))
{
WriteInt32(id);
}
else
{
// Mark bit 31.
id = (int)((uint)stringsToIDsDictionary.Count | 0x80000000);
stringsToIDsDictionary[text] = id;
WriteInt32(id);
WriteString(text);
}
}
private void WriteBoolean(Boolean value)
{
if (value)
stream.WriteByte(1);
else
stream.WriteByte(0);
}
private void WriteByte(Byte value)
{
stream.WriteByte(value);
}
private void WriteChar(Char value)
{
var bytes = BitConverter.GetBytes(value);
stream.Write(bytes, 0, 2);
}
private void WriteDecimal(Decimal value)
{
var bits = Decimal.GetBits(value);
WriteInt32(bits[0]);
WriteInt32(bits[1]);
WriteInt32(bits[2]);
WriteInt32(bits[3]);
}
private void WriteDouble(Double value)
{
var bytes = BitConverter.GetBytes(value);
stream.Write(bytes, 0, 8);
}
private void WriteInt16(Int16 value)
{
var bytes = BitConverter.GetBytes(value);
stream.Write(bytes, 0, 2);
}
private void WriteInt32(Int32 value)
{
var bytes = BitConverter.GetBytes(value);
stream.Write(bytes, 0, 4);
}
private void WriteInt64(Int64 value)
{
var bytes = BitConverter.GetBytes(value);
stream.Write(bytes, 0, 8);
}
private void WriteSByte(SByte value)
{
stream.WriteByte((byte)value);
}
private void WriteSingle(Single value)
{
var bytes = BitConverter.GetBytes(value);
stream.Write(bytes, 0, 4);
}
private void WriteTimeSpan(TimeSpan value)
{
WriteInt64(value.Ticks);
}
private void WriteUInt16(UInt16 value)
{
var bytes = BitConverter.GetBytes(value);
stream.Write(bytes, 0, 2);
}
private void WriteUInt32(UInt32 value)
{
var bytes = BitConverter.GetBytes(value);
stream.Write(bytes, 0, 4);
}
private void WriteUInt64(UInt64 value)
{
var bytes = BitConverter.GetBytes(value);
stream.Write(bytes, 0, 8);
}
/// <summary>
/// Write an object to the stream and its fields recursively.
/// The object may be a reference type, including an array, or a value type.
/// The graph traversal pattern is DFS.
/// </summary>
/// <param name="value">The object to write.</param>
private void WriteObject(object value)
{
if (value == null)
{
WriteByte((byte)ElementType.Null);
return;
}
var type = value.GetType();
if (!type.IsValueType)
{
int objectID;
if (objectsToIDsDictionary.TryGetValue(new Reference(value), out objectID))
{
WriteByte((byte)ElementType.ObjectRef);
WriteInt32(objectID);
return;
}
}
if (!type.IsArray)
{
WriteByte((byte)ElementType.Instance);
var surrogate = GetSurrogateFor(type);
if (surrogate != null)
{
var serializationInfo = new SerializationInfo(type, converter);
FireSerializationEvent(value, typeof(OnSerializingAttribute));
surrogate.GetObjectData(value, serializationInfo, context);
WriteSerializationInfo(value, serializationInfo);
FireSerializationEvent(value, typeof(OnSerializedAttribute));
return;
}
var serializableImplementation = value as ISerializable;
if (serializableImplementation != null)
{
var serializationInfo = new SerializationInfo(type, converter);
FireSerializationEvent(value, typeof(OnSerializingAttribute));
serializableImplementation.GetObjectData(serializationInfo, context);
WriteSerializationInfo(value, serializationInfo);
FireSerializationEvent(value, typeof(OnSerializedAttribute));
return;
}
WriteType(type);
if (type.IsValueType)
{
if (type.IsEnum)
{
var enumUnderlyingType = type.GetEnumUnderlyingType();
if (enumUnderlyingType == typeof(Byte))
{
WriteByte(Convert.ToByte(value));
}
else if (enumUnderlyingType == typeof(Int16))
{
WriteInt16(Convert.ToInt16(value));
}
else if (enumUnderlyingType == typeof(Int32))
{
WriteInt32(Convert.ToInt32(value));
}
else if (enumUnderlyingType == typeof(Int64))
{
WriteInt64(Convert.ToInt64(value));
}
else if (enumUnderlyingType == typeof(SByte))
{
WriteSByte(Convert.ToSByte(value));
}
else if (enumUnderlyingType == typeof(UInt16))
{
WriteUInt16(Convert.ToUInt16(value));
}
else if (enumUnderlyingType == typeof(UInt32))
{
WriteUInt32(Convert.ToUInt32(value));
}
else if (enumUnderlyingType == typeof(UInt64))
{
WriteUInt64(Convert.ToUInt64(value));
}
else
{
throw new SerializationException(
String.Format("Unsupported underlying type '{0}' of enum type '{1}'.", enumUnderlyingType.FullName, type.FullName));
}
return;
}
if (type == typeof(Boolean))
{
WriteBoolean((Boolean)value);
return;
}
else if (type == typeof(Byte))
{
WriteByte((Byte)value);
return;
}
else if (type == typeof(Char))
{
WriteChar((Char)value);
return;
}
else if (type == typeof(Decimal))
{
WriteDecimal((Decimal)value);
return;
}
else if (type == typeof(Double))
{
WriteDouble((Double)value);
return;
}
else if (type == typeof(Int16))
{
WriteInt16((Int16)value);
return;
}
else if (type == typeof(Int32))
{
WriteInt32((Int32)value);
return;
}
else if (type == typeof(Int64))
{
WriteInt64((Int64)value);
return;
}
else if (type == typeof(SByte))
{
WriteSByte((SByte)value);
return;
}
else if (type == typeof(Single))
{
WriteSingle((Single)value);
return;
}
else if (type == typeof(TimeSpan))
{
WriteTimeSpan((TimeSpan)value);
return;
}
else if (type == typeof(UInt16))
{
WriteUInt16((UInt16)value);
return;
}
else if (type == typeof(UInt32))
{
WriteUInt32((UInt32)value);
return;
}
else if (type == typeof(UInt64))
{
WriteUInt64((UInt64)value);
return;
}
else if (type.IsEnum)
{
var enumUnderlyingType = type.GetEnumUnderlyingType();
}
}
else // if not a value type...
{
WriteObjectID(value);
}
if (type == typeof(string))
{
WriteString((string)value);
return;
}
FireSerializationEvent(value, typeof(OnSerializingAttribute));
var serializableMemberInfos = GetSerializableMembersViaReflection(type);
WriteInt32(serializableMemberInfos.Length);
var serializableMemberValues = FormatterServices.GetObjectData(value, serializableMemberInfos);
for (int i = 0; i < serializableMemberInfos.Length; i++)
{
string memberName = serializableMemberInfos[i].Name;
if (internFieldNames)
WriteInternedString(memberName);
else
WriteString(memberName);
WriteObject(serializableMemberValues[i]);
}
FireSerializationEvent(value, typeof(OnSerializedAttribute));
}
else
{
WriteByte((byte)ElementType.Array);
var elementType = type.GetElementType();
WriteType(elementType);
WriteObjectID(value);
var array = (Array)value;
WriteInt32(array.Rank);
for (int dimension = 0; dimension < array.Rank; dimension++)
{
var lowerBound = array.GetLowerBound(dimension);
var length = array.GetLength(dimension);
WriteInt32(lowerBound);
WriteInt32(length);
}
VisitArrayElements(array, (arr, indices) => WriteObject(arr.GetValue(indices)));
}
}
/// <summary>
/// Write the object ID of an object.
/// If the object is a reference type, a new dictionary entry with the new object ID is allocated
/// associated with the object, else if it is a value type a -1 is recorded.
/// </summary>
/// <param name="value">The object for which to record an object ID.</param>
private void WriteObjectID(object value)
{
int objectID;
if (!value.GetType().IsValueType)
{
objectID = objectsToIDsDictionary.Count;
try
{
objectsToIDsDictionary.Add(new Reference(value), objectID);
}
catch (ArgumentException ex)
{
throw new SerializationException("The object already exists in the object ID dictionary.", ex);
}
}
else
{
objectID = -1;
}
WriteInt32(objectID);
}
/// <summary>
/// Write the <see cref="SerializationInfo"/> as composed by <see cref="ISerializable"/>
/// and <see cref="ISerializationSurrogate"/> implementations.
/// </summary>
/// <param name="value">The object being serialized.</param>
/// <param name="info">The container of the serialized values.</param>
private void WriteSerializationInfo(object value, SerializationInfo info)
{
WriteType(info.ObjectType);
if (!value.GetType().IsValueType) WriteObjectID(value);
WriteInt32(info.MemberCount);
var enumerator = info.GetEnumerator();
while (enumerator.MoveNext())
{
var entry = enumerator.Current;
if (internFieldNames)
WriteInternedString(entry.Name);
else
WriteString(entry.Name);
WriteObject(entry.Value);
}
}
/// <summary>
/// Writes a <see cref="ElementType.Type"/> or <see cref="ElementType.TypeRef"/> element depending on
/// whether the type has been previously encountered or not.
/// </summary>
/// <param name="type">The type to write to the stream.</param>
/// <remarks>
/// Takes into account the <see cref="SerializationBinder"/> associated with the formatter.
/// </remarks>
/// <exception cref="SerializationException">
/// When the type or at least one of its ancestors is not marked as serializable.
/// </exception>
private void WriteType(Type type)
{
int typeID;
if (typesToIDsDictionary.TryGetValue(type, out typeID))
{
WriteByte((byte)ElementType.TypeRef);
WriteInt32(typeID);
return;
}
EnsureTypeIsSerializable(type);
typeID = typesToIDsDictionary.Count;
typesToIDsDictionary.Add(type, typeID);
WriteByte((byte)ElementType.Type);
WriteInt32(typeID);
string typeName = null;
string assemblyName = null;
binder.BindToName(type, out assemblyName, out typeName);
if (assemblyName == null) assemblyName = type.Assembly.FullName;
if (typeName == null) typeName = type.FullName;
WriteString(assemblyName);
WriteString(typeName);
}
#endregion
}
}