forked from msgpack/msgpack-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDictionaryMessagePackSerializerBase`3.cs
More file actions
447 lines (406 loc) · 19.7 KB
/
DictionaryMessagePackSerializerBase`3.cs
File metadata and controls
447 lines (406 loc) · 19.7 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
#region -- License Terms --
//
// MessagePack for CLI
//
// Copyright (C) 2015-2018 FUJIWARA, Yusuke
//
// 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.
//
#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.Generic;
using System.Runtime.Serialization;
#if FEATURE_TAP
using System.Threading;
using System.Threading.Tasks;
#endif // FEATURE_TAP
namespace MsgPack.Serialization.CollectionSerializers
{
/// <summary>
/// Provides common features for generic dictionary serializers.
/// </summary>
/// <typeparam name="TDictionary">The type of the dictionary.</typeparam>
/// <typeparam name="TKey">The type of the key of dictionary.</typeparam>
/// <typeparam name="TValue">The type of the value of dictionary.</typeparam>
/// <remarks>
/// This class provides framework to implement variable collection serializer, and this type seals some virtual members to maximize future backward compatibility.
/// If you cannot use this class, you can implement your own serializer which inherits <see cref="MessagePackSerializer{T}"/> and implements <see cref="ICollectionInstanceFactory"/>.
/// </remarks>
[System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1005:AvoidExcessiveParametersOnGenericTypes", Justification = "By design" )]
public abstract class DictionaryMessagePackSerializerBase<TDictionary, TKey, TValue> : MessagePackSerializer<TDictionary>, ICollectionInstanceFactory
where TDictionary : IEnumerable<KeyValuePair<TKey, TValue>>
{
private readonly MessagePackSerializer<TKey> _keySerializer;
private readonly MessagePackSerializer<TValue> _valueSerializer;
/// <summary>
/// Initializes a new instance of the <see cref="DictionaryMessagePackSerializerBase{TDictionary, TKey, TValue}"/> class.
/// </summary>
/// <param name="ownerContext">A <see cref="SerializationContext"/> which owns this serializer.</param>
/// <param name="schema">
/// The schema for collection itself or its items for the member this instance will be used to.
/// <c>null</c> will be considered as <see cref="PolymorphismSchema.Default"/>.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="ownerContext"/> is <c>null</c>.
/// </exception>
[System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated by base .ctor" )]
protected DictionaryMessagePackSerializerBase( SerializationContext ownerContext, PolymorphismSchema schema )
: base( ownerContext )
{
var safeSchema = schema ?? PolymorphismSchema.Default;
this._keySerializer = ownerContext.GetSerializer<TKey>( safeSchema.KeySchema );
this._valueSerializer = ownerContext.GetSerializer<TValue>( safeSchema.ItemSchema );
}
/// <summary>
/// Initializes a new instance of the <see cref="DictionaryMessagePackSerializerBase{TDictionary, TKey, TValue}"/> class.
/// </summary>
/// <param name="ownerContext">A <see cref="SerializationContext"/> which owns this serializer.</param>
/// <param name="schema">
/// The schema for collection itself or its items for the member this instance will be used to.
/// <c>null</c> will be considered as <see cref="PolymorphismSchema.Default"/>.
/// </param>
/// <param name="capabilities">A serializer calability flags represents capabilities of this instance.</param>
/// <exception cref="ArgumentNullException">
/// <paramref name="ownerContext"/> is <c>null</c>.
/// </exception>
[System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated by base .ctor" )]
protected DictionaryMessagePackSerializerBase( SerializationContext ownerContext, PolymorphismSchema schema, SerializerCapabilities capabilities )
: base( ownerContext, capabilities )
{
var safeSchema = schema ?? PolymorphismSchema.Default;
this._keySerializer = ownerContext.GetSerializer<TKey>( safeSchema.KeySchema );
this._valueSerializer = ownerContext.GetSerializer<TValue>( safeSchema.ItemSchema );
}
/// <summary>
/// Serializes specified object with specified <see cref="Packer"/>.
/// </summary>
/// <param name="packer"><see cref="Packer"/> which packs values in <paramref name="objectTree"/>. This value will not be <c>null</c>.</param>
/// <param name="objectTree">Object to be serialized.</param>
/// <exception cref="SerializationException">
/// <typeparamref name="TDictionary"/> is not serializable etc.
/// </exception>
[System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated by caller in base class" )]
[System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Validated by caller in base class" )]
protected internal override void PackToCore( Packer packer, TDictionary objectTree )
{
#if ( !UNITY && !AOT ) || AOT_CHECK
packer.PackMapHeader( this.GetCount( objectTree ) );
foreach ( var item in objectTree )
{
this._keySerializer.PackTo( packer, item.Key );
this._valueSerializer.PackTo( packer, item.Value );
}
#else
// .constraind call for TDictionary.get_Count/TDictionary.GetEnumerator() causes AOT error.
// So use cast and invoke as normal call (it might cause boxing, but most collection should be reference type).
packer.PackMapHeader( this.GetCount( objectTree ) );
foreach ( var item in objectTree as IEnumerable<KeyValuePair<TKey,TValue>> )
{
this._keySerializer.PackTo( packer, item.Key );
this._valueSerializer.PackTo( packer, item.Value );
}
#endif // ( !UNITY ) || AOT_CHECK
}
#if FEATURE_TAP
/// <summary>
/// Serializes specified object with specified <see cref="Packer"/> asynchronously.
/// </summary>
/// <param name="packer"><see cref="Packer"/> which packs values in <paramref name="objectTree"/>. This value will not be <c>null</c>.</param>
/// <param name="objectTree">Object to be serialized.</param>
/// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param>
/// <returns>
/// A <see cref="Task"/> that represents the asynchronous operation.
/// </returns>
/// <exception cref="System.Runtime.Serialization.SerializationException">
/// Failed to serialize object.
/// </exception>
/// <exception cref="NotSupportedException">
/// <typeparamref name="TDictionary"/> is not serializable even if it can be deserialized.
/// </exception>
/// <seealso cref="P:Capabilities"/>
protected internal override async Task PackToAsyncCore( Packer packer, TDictionary objectTree, CancellationToken cancellationToken )
{
#if ( !UNITY && !AOT ) || AOT_CHECK
await packer.PackMapHeaderAsync( this.GetCount( objectTree ), cancellationToken ).ConfigureAwait( false );
foreach ( var item in objectTree )
{
await this._keySerializer.PackToAsync( packer, item.Key, cancellationToken ).ConfigureAwait( false );
await this._valueSerializer.PackToAsync( packer, item.Value, cancellationToken ).ConfigureAwait( false );
}
#else
// .constraind call for TDictionary.get_Count/TDictionary.GetEnumerator() causes AOT error.
// So use cast and invoke as normal call (it might cause boxing, but most collection should be reference type).
await packer.PackMapHeaderAsync( this.GetCount( objectTree ), cancellationToken ).ConfigureAwait( false );
foreach ( var item in objectTree as IEnumerable<KeyValuePair<TKey,TValue>> )
{
await this._keySerializer.PackToAsync( packer, item.Key, cancellationToken ).ConfigureAwait( false );
await this._valueSerializer.PackToAsync( packer, item.Value, cancellationToken ).ConfigureAwait( false );
}
#endif // ( !UNITY ) || AOT_CHECK
}
#endif // FEATURE_TAP
/// <summary>
/// When overridden in derived class, returns count of the dictionary.
/// </summary>
/// <param name="dictionary">A collection. This value will not be <c>null</c>.</param>
/// <returns>The count of the <paramref name="dictionary"/>.</returns>
protected abstract int GetCount( TDictionary dictionary );
/// <summary>
/// Deserializes object with specified <see cref="Unpacker"/>.
/// </summary>
/// <param name="unpacker"><see cref="Unpacker"/> which unpacks values of resulting object tree. This value will not be <c>null</c>.</param>
/// <returns>Deserialized object.</returns>
/// <exception cref="SerializationException">
/// Failed to deserialize object due to invalid unpacker state, stream content, or so.
/// </exception>
/// <exception cref="MessageTypeException">
/// Failed to deserialize object due to invalid unpacker state, stream content, or so.
/// </exception>
/// <exception cref="InvalidMessagePackStreamException">
/// Failed to deserialize object due to invalid unpacker state, stream content, or so.
/// </exception>
/// <exception cref="NotSupportedException">
/// <typeparamref name="TDictionary"/> is abstract type.
/// </exception>
/// <remarks>
/// This method invokes <see cref="CreateInstance(Int32)"/>, and then fill deserialized items to resultong collection.
/// </remarks>
[System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated by caller in base class" )]
protected internal override TDictionary UnpackFromCore( Unpacker unpacker )
{
if ( !unpacker.IsMapHeader )
{
SerializationExceptions.ThrowIsNotArrayHeader( unpacker );
}
return this.InternalUnpackFromCore( unpacker );
}
internal virtual TDictionary InternalUnpackFromCore( Unpacker unpacker )
{
var itemsCount = UnpackHelpers.GetItemsCount( unpacker );
var collection = this.CreateInstance( itemsCount );
this.UnpackToCore( unpacker, collection, itemsCount );
return collection;
}
#if FEATURE_TAP
/// <summary>
/// Deserializes object with specified <see cref="Unpacker"/> asynchronously.
/// </summary>
/// <param name="unpacker"><see cref="Unpacker"/> which unpacks values of resulting object tree. This value will not be <c>null</c>.</param>
/// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param>
/// <returns>
/// A <see cref="Task"/> that represents the asynchronous operation.
/// The value of the <c>TResult</c> parameter contains the deserialized object.
/// </returns>
/// <exception cref="System.Runtime.Serialization.SerializationException">
/// Failed to deserialize object.
/// </exception>
/// <exception cref="MessageTypeException">
/// Failed to deserialize object due to invalid stream.
/// </exception>
/// <exception cref="InvalidMessagePackStreamException">
/// Failed to deserialize object due to invalid stream.
/// </exception>
/// <exception cref="NotSupportedException">
/// <typeparamref name="TDictionary"/> is not serializable even if it can be serialized.
/// </exception>
/// <seealso cref="P:Capabilities"/>
[System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated by caller in base class" )]
protected internal override Task<TDictionary> UnpackFromAsyncCore( Unpacker unpacker, CancellationToken cancellationToken )
{
if ( !unpacker.IsMapHeader )
{
SerializationExceptions.ThrowIsNotArrayHeader( unpacker );
}
return this.InternalUnpackFromAsyncCore( unpacker, cancellationToken );
}
internal virtual Task<TDictionary> InternalUnpackFromAsyncCore( Unpacker unpacker, CancellationToken cancellationToken )
{
var itemsCount = UnpackHelpers.GetItemsCount( unpacker );
var collection = this.CreateInstance( itemsCount );
return this.UnpackToAsyncCore( unpacker, collection, itemsCount, cancellationToken );
}
#endif // FEATURE_TAP
/// <summary>
/// Creates a new collection instance with specified initial capacity.
/// </summary>
/// <param name="initialCapacity">
/// The initial capacy of creating collection.
/// Note that this parameter may <c>0</c> for non-empty collection.
/// </param>
/// <returns>
/// New collection instance. This value will not be <c>null</c>.
/// </returns>
/// <remarks>
/// An author of <see cref="Unpacker" /> could implement unpacker for non-MessagePack format,
/// so implementer of this interface should not rely on that <paramref name="initialCapacity" /> reflects actual items count.
/// For example, JSON unpacker cannot supply collection items count efficiently.
/// </remarks>
/// <seealso cref="ICollectionInstanceFactory.CreateInstance"/>
protected abstract TDictionary CreateInstance( int initialCapacity );
object ICollectionInstanceFactory.CreateInstance( int initialCapacity )
{
return this.CreateInstance( initialCapacity );
}
/// <summary>
/// Deserializes collection items with specified <see cref="Unpacker"/> and stores them to <paramref name="collection"/>.
/// </summary>
/// <param name="unpacker"><see cref="Unpacker"/> which unpacks values of resulting object tree. This value will not be <c>null</c>.</param>
/// <param name="collection">Collection that the items to be stored. This value will not be <c>null</c>.</param>
/// <exception cref="SerializationException">
/// Failed to deserialize object due to invalid unpacker state, stream content, or so.
/// </exception>
/// <exception cref="NotSupportedException">
/// <typeparamref name="TDictionary"/> is not collection.
/// </exception>
[System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated by caller in base class" )]
[System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Validated by caller in base class" )]
protected internal override void UnpackToCore( Unpacker unpacker, TDictionary collection )
{
if ( !unpacker.IsMapHeader )
{
SerializationExceptions.ThrowIsNotArrayHeader( unpacker );
}
this.UnpackToCore( unpacker, collection, UnpackHelpers.GetItemsCount( unpacker ) );
}
private void UnpackToCore( Unpacker unpacker, TDictionary collection, int itemsCount )
{
for ( int i = 0; i < itemsCount; i++ )
{
if ( !unpacker.Read() )
{
SerializationExceptions.ThrowMissingKey( i, unpacker );
}
TKey key;
if ( !unpacker.IsArrayHeader && !unpacker.IsMapHeader )
{
key = this._keySerializer.UnpackFrom( unpacker );
}
else
{
using ( var subtreeUnpacker = unpacker.ReadSubtree() )
{
key = this._keySerializer.UnpackFrom( subtreeUnpacker );
}
}
if ( !unpacker.Read() )
{
SerializationExceptions.ThrowMissingItem( i, unpacker );
}
TValue value;
if ( !unpacker.IsArrayHeader && !unpacker.IsMapHeader )
{
value = this._valueSerializer.UnpackFrom( unpacker );
}
else
{
using ( var subtreeUnpacker = unpacker.ReadSubtree() )
{
value = this._valueSerializer.UnpackFrom( subtreeUnpacker );
}
}
this.AddItem( collection, key, value );
}
}
#if FEATURE_TAP
/// <summary>
/// Deserializes collection items with specified <see cref="Unpacker"/> and stores them to <paramref name="collection"/> asynchronously.
/// </summary>
/// <param name="unpacker"><see cref="Unpacker"/> which unpacks values of resulting object tree. This value will not be <c>null</c>.</param>
/// <param name="collection">Collection that the items to be stored. This value will not be <c>null</c>.</param>
/// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param>
/// <returns>
/// A <see cref="Task"/> that represents the asynchronous operation.
/// </returns>
/// <exception cref="System.Runtime.Serialization.SerializationException">
/// Failed to deserialize object.
/// </exception>
/// <exception cref="MessageTypeException">
/// Failed to deserialize object due to invalid stream.
/// </exception>
/// <exception cref="InvalidMessagePackStreamException">
/// Failed to deserialize object due to invalid stream.
/// </exception>
/// <exception cref="NotSupportedException">
/// <typeparamref name="TDictionary"/> is not mutable collection.
/// </exception>
/// <seealso cref="P:Capabilities"/>
[System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated by caller in base class" )]
protected internal override Task UnpackToAsyncCore( Unpacker unpacker, TDictionary collection, CancellationToken cancellationToken )
{
if ( !unpacker.IsMapHeader )
{
SerializationExceptions.ThrowIsNotArrayHeader( unpacker );
}
return this.UnpackToAsyncCore( unpacker, collection, UnpackHelpers.GetItemsCount( unpacker ), cancellationToken );
}
private async Task<TDictionary> UnpackToAsyncCore( Unpacker unpacker, TDictionary collection, int itemsCount, CancellationToken cancellationToken )
{
for ( int i = 0; i < itemsCount; i++ )
{
if ( !unpacker.Read() )
{
SerializationExceptions.ThrowMissingKey( i, unpacker );
}
TKey key;
if ( !unpacker.IsArrayHeader && !unpacker.IsMapHeader )
{
key = await this._keySerializer.UnpackFromAsync( unpacker, cancellationToken ).ConfigureAwait( false );
}
else
{
using ( var subtreeUnpacker = unpacker.ReadSubtree() )
{
key = await this._keySerializer.UnpackFromAsync( subtreeUnpacker, cancellationToken ).ConfigureAwait( false );
}
}
if ( !unpacker.Read() )
{
SerializationExceptions.ThrowMissingItem( i, unpacker );
}
TValue value;
if ( !unpacker.IsArrayHeader && !unpacker.IsMapHeader )
{
value = await this._valueSerializer.UnpackFromAsync( unpacker, cancellationToken ).ConfigureAwait( false );
}
else
{
using ( var subtreeUnpacker = unpacker.ReadSubtree() )
{
value = await this._valueSerializer.UnpackFromAsync( subtreeUnpacker, cancellationToken ).ConfigureAwait( false );
}
}
this.AddItem( collection, key, value );
}
return collection;
}
#endif // FEATURE_TAP
/// <summary>
/// When implemented by derive class,
/// adds the deserialized item to the collection on <typeparamref name="TDictionary"/> specific manner
/// to implement <see cref="UnpackToCore(Unpacker,TDictionary)"/>.
/// </summary>
/// <param name="dictionary">The dictionary to be added.</param>
/// <param name="key">The key to be added.</param>
/// <param name="value">The value to be added.</param>
/// <exception cref="NotSupportedException">
/// This implementation always throws it.
/// </exception>
protected virtual void AddItem( TDictionary dictionary, TKey key, TValue value )
{
throw SerializationExceptions.NewUnpackToIsNotSupported( typeof( TDictionary ), null );
}
}
}