forked from msgpack/msgpack-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReflectionObjectMessagePackSerializer`1.cs
More file actions
780 lines (710 loc) · 24.4 KB
/
ReflectionObjectMessagePackSerializer`1.cs
File metadata and controls
780 lines (710 loc) · 24.4 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
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
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
#region -- License Terms --
//
// MessagePack for CLI
//
// Copyright (C) 2014-2016 FUJIWARA, Yusuke and contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Contributors:
// Samuel Cragg
//
#endregion -- License Terms --
#if UNITY_5 || UNITY_STANDALONE || UNITY_WEBPLAYER || UNITY_WII || UNITY_IPHONE || UNITY_ANDROID || UNITY_PS3 || UNITY_XBOX360 || UNITY_FLASH || UNITY_BKACKBERRY || UNITY_WINRT
#define UNITY
#endif
using System;
using System.Collections;
using System.Collections.Generic;
#if FEATURE_MPCONTRACT
using Contract = MsgPack.MPContract;
#else
using System.Diagnostics.Contracts;
#endif // FEATURE_MPCONTRACT
using System.Linq;
using System.Reflection;
#if FEATURE_TAP
using System.Threading;
using System.Threading.Tasks;
#endif // FEATURE_TAP
namespace MsgPack.Serialization.ReflectionSerializers
{
/// <summary>
/// Implements reflection-based object serializer for restricted platforms.
/// </summary>
[Preserve( AllMembers = true )]
internal class ReflectionObjectMessagePackSerializer<T> : MessagePackSerializer<T>
{
private readonly Func<object, object>[] _getters;
private readonly Action<object, object>[] _setters;
private readonly MemberInfo[] _memberInfos;
private readonly DataMemberContract[] _contracts;
private readonly Dictionary<string, int> _memberIndexes;
private readonly MessagePackSerializer[] _serializers;
private readonly ParameterInfo[] _constructorParameters;
private readonly Dictionary<int, int> _constructorArgumentIndexes;
public ReflectionObjectMessagePackSerializer( SerializationContext context, SerializationTarget target, SerializerCapabilities capabilities )
: base( context, capabilities )
{
ReflectionSerializerHelper.GetMetadata( typeof( T ), target.Members, context, out this._getters, out this._setters, out this._memberInfos, out this._contracts, out this._serializers );
this._memberIndexes =
this._contracts
.Select( ( contract, index ) => new KeyValuePair<string, int>( contract.Name, index ) )
.Where( kv => kv.Key != null )
// Set key as transformed.
.ToDictionary( kv => context.DictionarySerializationOptions.SafeKeyTransformer( kv.Key ), kv => kv.Value );
this._constructorParameters =
( !typeof( IUnpackable ).IsAssignableFrom( typeof( T ) ) && target.IsConstructorDeserialization )
? target.DeserializationConstructor.GetParameters()
: null;
if ( this._constructorParameters != null )
{
this._constructorArgumentIndexes = new Dictionary<int, int>( this._memberIndexes.Count );
foreach ( var member in target.Members )
{
int index =
#if SILVERLIGHT && !WINDOWS_PHONE
this._constructorParameters.FindIndex(
#else
Array.FindIndex( this._constructorParameters,
#endif // SILVERLIGHT && !WINDOWS_PHONE
item => item.Name.Equals( member.Contract.Name, StringComparison.OrdinalIgnoreCase ) && item.ParameterType == member.Member.GetMemberValueType()
);
if ( index >= 0 )
{
this._constructorArgumentIndexes.Add( index, this._memberIndexes[ member.Contract.Name ] );
}
}
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated by caller in base class" )]
protected internal override void PackToCore( Packer packer, T objectTree )
{
var asPackable = objectTree as IPackable;
if ( asPackable != null )
{
asPackable.PackToMessage( packer, null );
return;
}
if ( this.OwnerContext.SerializationMethod != SerializationMethod.Map )
{
packer.PackArrayHeader( this._serializers.Length );
for ( int i = 0; i < this._serializers.Length; i++ )
{
this.PackMemberValue( packer, objectTree, i );
}
}
else
{
if ( this.OwnerContext.DictionarySerializationOptions.OmitNullEntry
#if DEBUG
&& !SerializerDebugging.UseLegacyNullMapEntryHandling
#endif // DEBUG
)
{
// Skipping causes the entries count header reducing, so count up null entries first.
var nullCount = 0;
for ( int i = 0; i < this._serializers.Length; i++ )
{
// Set key as transformed.
if ( this.IsNull( objectTree, i ) )
{
nullCount++;
}
}
packer.PackMapHeader( this._serializers.Length - nullCount );
for ( int i = 0; i < this._serializers.Length; i++ )
{
if ( this.IsNull( objectTree, i ) )
{
continue;
}
// Set key as transformed.
packer.PackString( this.OwnerContext.DictionarySerializationOptions.SafeKeyTransformer( this._contracts[ i ].Name ) );
this.PackMemberValue( packer, objectTree, i );
}
}
else
{
packer.PackMapHeader( this._serializers.Length );
for ( int i = 0; i < this._serializers.Length; i++ )
{
// Set key as transformed.
packer.PackString( this.OwnerContext.DictionarySerializationOptions.SafeKeyTransformer( this._contracts[ i ].Name ) );
this.PackMemberValue( packer, objectTree, i );
}
}
}
}
private bool IsNull( T objectTree, int index )
{
if ( this._getters[ index ] == null )
{
// missing member should be treated as nil.
return true;
}
return this._getters[ index ]( objectTree ) == null;
}
private void PackMemberValue( Packer packer, T objectTree, int index )
{
if ( this._getters[ index ] == null )
{
// missing member should be treated as nil.
packer.PackNull();
return;
}
var value = this._getters[ index ]( objectTree );
var nilImplication =
ReflectionNilImplicationHandler.Instance.OnPacking(
new ReflectionSerializerNilImplicationHandlerParameter(
this._memberInfos[ index ].GetMemberValueType(),
this._contracts[ index ].Name
),
this._contracts[ index ].NilImplication
);
if ( nilImplication != null )
{
nilImplication( value );
}
this._serializers[ index ].PackTo( packer, value );
}
#if FEATURE_TAP
protected internal override async Task PackToAsyncCore( Packer packer, T objectTree, CancellationToken cancellationToken )
{
var asAsyncPackable = objectTree as IAsyncPackable;
if ( asAsyncPackable != null )
{
await asAsyncPackable.PackToMessageAsync( packer, null, cancellationToken ).ConfigureAwait( false );
return;
}
if ( this.OwnerContext.SerializationMethod != SerializationMethod.Map )
{
await packer.PackArrayHeaderAsync( this._serializers.Length, cancellationToken ).ConfigureAwait( false );
for ( int i = 0; i < this._serializers.Length; i++ )
{
await this.PackMemberValueAsync( packer, objectTree, i, cancellationToken ).ConfigureAwait( false );
}
}
else
{
if ( this.OwnerContext.DictionarySerializationOptions.OmitNullEntry
#if DEBUG
&& !SerializerDebugging.UseLegacyNullMapEntryHandling
#endif // DEBUG
)
{
// Skipping causes the entries count header reducing, so count up null entries first.
var nullCount = 0;
for ( int i = 0; i < this._serializers.Length; i++ )
{
// Set key as transformed.
if ( this.IsNull( objectTree, i ) )
{
nullCount++;
}
}
await packer.PackMapHeaderAsync( this._serializers.Length - nullCount, cancellationToken ).ConfigureAwait( false );
for ( int i = 0; i < this._serializers.Length; i++ )
{
if ( this.IsNull( objectTree, i ) )
{
continue;
}
// Set key as transformed.
await packer.PackStringAsync( this.OwnerContext.DictionarySerializationOptions.SafeKeyTransformer( this._contracts[ i ].Name ), cancellationToken ).ConfigureAwait( false );
await this.PackMemberValueAsync( packer, objectTree, i, cancellationToken ).ConfigureAwait( false );
}
}
else
{
await packer.PackMapHeaderAsync( this._serializers.Length, cancellationToken ).ConfigureAwait( false );
for ( int i = 0; i < this._serializers.Length; i++ )
{
// Set key as transformed.
await packer.PackStringAsync( this.OwnerContext.DictionarySerializationOptions.SafeKeyTransformer( this._contracts[ i ].Name ), cancellationToken ).ConfigureAwait( false );
await this.PackMemberValueAsync( packer, objectTree, i, cancellationToken ).ConfigureAwait( false );
}
}
}
}
private async Task PackMemberValueAsync( Packer packer, T objectTree, int index, CancellationToken cancellationToken )
{
if ( this._getters[ index ] == null )
{
// missing member should be treated as nil.
await packer.PackNullAsync( cancellationToken ).ConfigureAwait( false );
return;
}
var value = this._getters[ index ]( objectTree );
var nilImplication =
ReflectionNilImplicationHandler.Instance.OnPacking(
new ReflectionSerializerNilImplicationHandlerParameter(
this._memberInfos[ index ].GetMemberValueType(),
this._contracts[ index ].Name
),
this._contracts[ index ].NilImplication
);
if ( nilImplication != null )
{
nilImplication( value );
}
await this._serializers[ index ].PackToAsync( packer, value, cancellationToken ).ConfigureAwait( false );
}
#endif // FEATURE_TAP
[System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated by caller in base class" )]
protected internal override T UnpackFromCore( Unpacker unpacker )
{
object result =
this._constructorParameters == null
? ReflectionExtensions.CreateInstancePreservingExceptionType( typeof( T ) )
: this._constructorParameters.Select( p =>
p.GetHasDefaultValue()
? p.DefaultValue
: p.ParameterType.GetIsValueType()
? ReflectionExtensions.CreateInstancePreservingExceptionType( p.ParameterType )
: null
).ToArray();
var unpacked = 0;
var asUnpackable = result as IUnpackable;
if ( asUnpackable != null )
{
asUnpackable.UnpackFromMessage( unpacker );
return ( T )result;
}
if ( unpacker.IsArrayHeader )
{
var itemsCount = UnpackHelpers.GetItemsCount( unpacker );
for ( int i = 0; i < itemsCount; i++ )
{
result = this.UnpackMemberValue( result, unpacker, itemsCount, unpacked, i, i );
unpacked++;
}
}
else
{
#if DEBUG
Contract.Assert( unpacker.IsMapHeader, "unpacker.IsMapHeader" );
#endif // DEBUG
var itemsCount = UnpackHelpers.GetItemsCount( unpacker );
for ( int i = 0; i < itemsCount; i++ )
{
string name;
if ( !unpacker.ReadString( out name ) )
{
SerializationExceptions.ThrowUnexpectedEndOfStream( unpacker );
}
if ( name == null )
{
// missing member, drain the value and discard it.
if ( !unpacker.Read() && i < itemsCount - 1 )
{
SerializationExceptions.ThrowMissingKey( i + 1, unpacker );
}
continue;
}
int index;
if ( !this._memberIndexes.TryGetValue( name, out index ) )
{
// key does not exist in the object, skip the associated value
if ( unpacker.Skip() == null )
{
SerializationExceptions.ThrowMissingItem( i, unpacker );
}
continue;
}
result = this.UnpackMemberValue( result, unpacker, itemsCount, unpacked, index, i );
unpacked++;
}
}
if ( this._constructorParameters == null )
{
return ( T )result;
}
else
{
return ReflectionExtensions.CreateInstancePreservingExceptionType<T>( typeof( T ), result as object[] );
}
}
private object UnpackMemberValue( object objectGraph, Unpacker unpacker, int itemsCount, int unpacked, int index, int unpackerOffset )
{
object nullable = null;
var setter = index < this._setters.Length ? this._setters[ index ] : null;
if ( unpacked < itemsCount )
{
if ( !unpacker.Read() )
{
SerializationExceptions.ThrowMissingItem( unpackerOffset, unpacker );
}
if ( !unpacker.LastReadData.IsNil )
{
if ( setter != null || this._constructorParameters != null )
{
nullable = this.UnpackSingleValue( unpacker, index );
}
else if ( index < this._getters.Length && this._getters[ index ] != null ) // null getter supposes undeclared member (should be treated as nil)
{
this.UnpackAndAddCollectionItem( objectGraph, unpacker, index );
}
}
}
if ( this._constructorParameters != null )
{
#if DEBUG
Contract.Assert( objectGraph is object[], "objectGraph is object[]" );
#endif // !UNITY
int argumentIndex;
if ( this._constructorArgumentIndexes.TryGetValue( index, out argumentIndex ) )
{
if ( nullable == null )
{
ReflectionNilImplicationHandler.Instance.OnUnpacked(
new ReflectionSerializerNilImplicationHandlerOnUnpackedParameter(
this._memberInfos[ index ].GetMemberValueType(),
// ReSharper disable once PossibleNullReferenceException
value => ( objectGraph as object[] )[ argumentIndex ] = nullable,
this._contracts[ index ].Name,
this._memberInfos[ index ].DeclaringType
),
this._contracts[ index ].NilImplication
)( null );
}
else
{
( objectGraph as object[] )[ argumentIndex ] = nullable;
}
}
}
else if ( setter != null )
{
if ( nullable == null )
{
ReflectionNilImplicationHandler.Instance.OnUnpacked(
new ReflectionSerializerNilImplicationHandlerOnUnpackedParameter(
this._memberInfos[ index ].GetMemberValueType(),
value => setter( objectGraph, nullable ),
this._contracts[ index ].Name,
this._memberInfos[ index ].DeclaringType
),
this._contracts[ index ].NilImplication
)( null );
}
else
{
setter( objectGraph, nullable );
}
}
return objectGraph;
} // UnpackMemberValue
private object UnpackSingleValue( Unpacker unpacker, int index )
{
if ( !unpacker.IsArrayHeader && !unpacker.IsMapHeader )
{
return this._serializers[ index ].UnpackFrom( unpacker );
}
else
{
using ( var subtreeUnpacker = unpacker.ReadSubtree() )
{
return this._serializers[ index ].UnpackFrom( subtreeUnpacker );
}
}
}
private void UnpackAndAddCollectionItem( object objectGraph, Unpacker unpacker, int index )
{
var destination = this._getters[ index ]( objectGraph );
if ( destination == null )
{
throw SerializationExceptions.NewReadOnlyMemberItemsMustNotBeNull( this._contracts[ index ].Name );
}
var traits = destination.GetType().GetCollectionTraits( CollectionTraitOptions.WithAddMethod, this.OwnerContext.CompatibilityOptions.AllowNonCollectionEnumerableTypes );
if ( traits.AddMethod == null )
{
throw SerializationExceptions.NewUnpackToIsNotSupported( destination.GetType(), null );
}
var source = this._serializers[ index ].UnpackFrom( unpacker ) as IEnumerable;
if ( source != null )
{
switch ( traits.DetailedCollectionType )
{
case CollectionDetailedKind.GenericDictionary:
{
// item should be KeyValuePair<TKey, TValue>
var arguments = new object[ 2 ];
var key = default( PropertyInfo );
var value = default( PropertyInfo );
foreach ( var item in source )
{
if ( key == null )
{
key = item.GetType().GetProperty( "Key" );
value = item.GetType().GetProperty( "Value" );
}
arguments[ 0 ] = key.GetValue( item, null );
arguments[ 1 ] = value.GetValue( item, null );
traits.AddMethod.InvokePreservingExceptionType( destination, arguments );
}
break;
}
case CollectionDetailedKind.NonGenericDictionary:
{
// item should be DictionaryEntry
var arguments = new object[ 2 ];
foreach ( var item in source )
{
arguments[ 0 ] = ReflectionSerializerHelper.DictionaryEntryKeyProperty.GetValue( item, null );
arguments[ 1 ] = ReflectionSerializerHelper.DictionaryEntryValueProperty.GetValue( item, null );
traits.AddMethod.InvokePreservingExceptionType( destination, arguments );
}
break;
}
default:
{
var arguments = new object[ 1 ];
foreach ( var item in source )
{
arguments[ 0 ] = item;
traits.AddMethod.InvokePreservingExceptionType( destination, arguments );
}
break;
}
}
}
} // UnpackAndAddCollectionItem
#if FEATURE_TAP
protected internal override async Task<T> UnpackFromAsyncCore( Unpacker unpacker, CancellationToken cancellationToken )
{
object result =
this._constructorParameters == null
? ReflectionExtensions.CreateInstancePreservingExceptionType( typeof( T ) )
: this._constructorParameters.Select( p =>
p.GetHasDefaultValue()
? p.DefaultValue
: p.ParameterType.GetIsValueType()
? ReflectionExtensions.CreateInstancePreservingExceptionType( p.ParameterType )
: null
).ToArray();
var unpacked = 0;
var asAsyncUnpackable = result as IAsyncUnpackable;
if ( asAsyncUnpackable != null )
{
await asAsyncUnpackable.UnpackFromMessageAsync( unpacker, cancellationToken ).ConfigureAwait( false );
return ( T )result;
}
var asUnpackable = result as IUnpackable;
if ( asUnpackable != null )
{
await Task.Run( () => asUnpackable.UnpackFromMessage( unpacker ), cancellationToken ).ConfigureAwait( false );
return ( T )result;
}
if ( unpacker.IsArrayHeader )
{
var itemsCount = UnpackHelpers.GetItemsCount( unpacker );
for ( int i = 0; i < itemsCount; i++ )
{
result = await this.UnpackMemberValueAsync( result, unpacker, itemsCount, unpacked, i, i, cancellationToken ).ConfigureAwait( false );
unpacked++;
}
}
else
{
#if DEBUG
Contract.Assert( unpacker.IsMapHeader, "unpacker.IsMapHeader" );
#endif // DEBUG
var itemsCount = UnpackHelpers.GetItemsCount( unpacker );
for ( int i = 0; i < itemsCount; i++ )
{
var name = await unpacker.ReadStringAsync( cancellationToken ).ConfigureAwait( false );
if ( !name.Success )
{
SerializationExceptions.ThrowUnexpectedEndOfStream( unpacker );
}
if ( name.Value == null )
{
// missing member, drain the value and discard it.
if ( !unpacker.Read() && i < itemsCount - 1 )
{
SerializationExceptions.ThrowMissingKey( i + 1, unpacker );
}
continue;
}
int index;
if ( !this._memberIndexes.TryGetValue( name.Value, out index ) )
{
// key does not exist in the object, skip the associated value
if ( unpacker.Skip() == null )
{
SerializationExceptions.ThrowMissingItem( i, unpacker );
}
continue;
}
result = await this.UnpackMemberValueAsync( result, unpacker, itemsCount, unpacked, index, i, cancellationToken ).ConfigureAwait( false );
unpacked++;
}
}
if ( this._constructorParameters == null )
{
return ( T )result;
}
else
{
return ReflectionExtensions.CreateInstancePreservingExceptionType<T>( typeof( T ), result as object[] );
}
}
private async Task<object> UnpackMemberValueAsync( object objectGraph, Unpacker unpacker, int itemsCount, int unpacked, int index, int unpackerOffset, CancellationToken cancellationToken )
{
object nullable = null;
var setter = index < this._setters.Length ? this._setters[ index ] : null;
if ( unpacked < itemsCount )
{
if ( !unpacker.Read() )
{
SerializationExceptions.ThrowMissingItem( unpackerOffset, unpacker );
}
if ( !unpacker.LastReadData.IsNil )
{
if ( setter != null || this._constructorParameters != null )
{
nullable = await this.UnpackSingleValueAsync( unpacker, index, cancellationToken ).ConfigureAwait( false );
}
else if ( this._getters[ index ] != null ) // null getter supposes undeclared member (should be treated as nil)
{
await this.UnpackAndAddCollectionItemAsync( objectGraph, unpacker, index, cancellationToken ).ConfigureAwait( false );
}
}
}
if ( this._constructorParameters != null )
{
#if DEBUG
Contract.Assert( objectGraph is object[], "objectGraph is object[]" );
#endif // DEBUG
int argumentIndex;
if ( this._constructorArgumentIndexes.TryGetValue( index, out argumentIndex ) )
{
if ( nullable == null )
{
ReflectionNilImplicationHandler.Instance.OnUnpacked(
new ReflectionSerializerNilImplicationHandlerOnUnpackedParameter(
this._memberInfos[ index ].GetMemberValueType(),
// ReSharper disable once PossibleNullReferenceException
value => ( objectGraph as object[] )[ argumentIndex ] = nullable,
this._contracts[ index ].Name,
this._memberInfos[ index ].DeclaringType
),
this._contracts[ index ].NilImplication
)( null );
}
else
{
( objectGraph as object[] )[ argumentIndex ] = nullable;
}
}
}
else if ( setter != null )
{
if ( nullable == null )
{
ReflectionNilImplicationHandler.Instance.OnUnpacked(
new ReflectionSerializerNilImplicationHandlerOnUnpackedParameter(
this._memberInfos[ index ].GetMemberValueType(),
value => setter( objectGraph, nullable ),
this._contracts[ index ].Name,
this._memberInfos[ index ].DeclaringType
),
this._contracts[ index ].NilImplication
)( null );
}
else
{
setter( objectGraph, nullable );
}
}
return objectGraph;
} // UnpackMemberValueAsync
private Task<object> UnpackSingleValueAsync( Unpacker unpacker, int index, CancellationToken cancellationToken )
{
if ( !unpacker.IsArrayHeader && !unpacker.IsMapHeader )
{
return this._serializers[ index ].UnpackFromAsync( unpacker, cancellationToken );
}
else
{
using ( var subtreeUnpacker = unpacker.ReadSubtree() )
{
return this._serializers[ index ].UnpackFromAsync( subtreeUnpacker, cancellationToken );
}
}
}
private async Task UnpackAndAddCollectionItemAsync( object objectGraph, Unpacker unpacker, int index, CancellationToken cancellationToken )
{
var destination = this._getters[ index ]( objectGraph );
if ( destination == null )
{
throw SerializationExceptions.NewReadOnlyMemberItemsMustNotBeNull( this._contracts[ index ].Name );
}
var traits = destination.GetType().GetCollectionTraits( CollectionTraitOptions.WithAddMethod, this.OwnerContext.CompatibilityOptions.AllowNonCollectionEnumerableTypes );
if ( traits.AddMethod == null )
{
throw SerializationExceptions.NewUnpackToIsNotSupported( destination.GetType(), null );
}
var source = await this._serializers[ index ].UnpackFromAsync( unpacker, cancellationToken ).ConfigureAwait( false ) as IEnumerable;
if ( source != null )
{
switch ( traits.DetailedCollectionType )
{
case CollectionDetailedKind.GenericDictionary:
{
// item should be KeyValuePair<TKey, TValue>
var arguments = new object[ 2 ];
var key = default( PropertyInfo );
var value = default( PropertyInfo );
foreach ( var item in source )
{
if ( key == null )
{
key = item.GetType().GetProperty( "Key" );
value = item.GetType().GetProperty( "Value" );
}
arguments[ 0 ] = key.GetValue( item, null );
arguments[ 1 ] = value.GetValue( item, null );
traits.AddMethod.InvokePreservingExceptionType( destination, arguments );
}
break;
}
case CollectionDetailedKind.NonGenericDictionary:
{
// item should be DictionaryEntry
var arguments = new object[ 2 ];
foreach ( var item in source )
{
arguments[ 0 ] = ReflectionSerializerHelper.DictionaryEntryKeyProperty.GetValue( item, null );
arguments[ 1 ] = ReflectionSerializerHelper.DictionaryEntryValueProperty.GetValue( item, null );
traits.AddMethod.InvokePreservingExceptionType( destination, arguments );
}
break;
}
default:
{
var arguments = new object[ 1 ];
foreach ( var item in source )
{
arguments[ 0 ] = item;
traits.AddMethod.InvokePreservingExceptionType( destination, arguments );
}
break;
}
}
}
} // UnpackAndAddCollectionItemAsync
#endif // FEATURE_TAP
}
}