Paradox Game Engine  v1.0.0 beta06
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Events Macros Pages
ListDataConverter.cs
Go to the documentation of this file.
1 // Copyright (c) 2014 Silicon Studio Corp. (http://siliconstudio.co.jp)
2 // This file is distributed under GPL v3. See LICENSE.md for details.
3 using System;
4 using System.Collections.Generic;
5 
6 namespace SiliconStudio.Core.Serialization.Converters
7 {
8  public class ListDataConverter<TData, T, TDataItem, TItem> : DataConverter<TData, T> where TData : class, IList<TDataItem> where T : class, IList<TItem>
9  {
10  public override void ConvertToData(ConverterContext converterContext, ref TData data, T obj)
11  {
12  if (obj == null)
13  {
14  data = null;
15  return;
16  }
17 
18  bool isArray = typeof(TData) == typeof(TDataItem[]);
19 
20  if (data == null)
21  {
22  // Optimize most common cases
23  if (typeof(TData) == typeof(List<TDataItem>) || typeof(TData) == typeof(IList<TDataItem>))
24  data = (TData)(IList<TDataItem>)new List<TDataItem>(obj.Count);
25  else if (isArray)
26  data = (TData)(IList<TDataItem>)new TDataItem[obj.Count];
27  else
28  data = Activator.CreateInstance<TData>();
29  }
30  else if (!isArray)
31  {
32  data.Clear();
33  }
34 
35  int index = 0;
36  foreach (var item in obj)
37  {
38  var itemData = default(TDataItem);
39  converterContext.ConvertToData(ref itemData, item);
40  if (isArray)
41  data[index] = itemData;
42  else
43  data.Add(itemData);
44  index++;
45  }
46  }
47 
48  public override void ConvertFromData(ConverterContext converterContext, TData data, ref T source)
49  {
50  if (data == null)
51  {
52  source = null;
53  return;
54  }
55 
56  bool isArray = typeof(T) == typeof(TItem[]);
57 
58  if (source == null)
59  {
60  // Optimize most common cases
61  if (typeof(T) == typeof(List<TItem>) || typeof(T) == typeof(IList<TItem>))
62  source = (T)(IList<TItem>)new List<TItem>(data.Count);
63  else if (isArray)
64  source = (T)(IList<TItem>)new TItem[data.Count];
65  else
66  source = Activator.CreateInstance<T>();
67  }
68  else if (!isArray)
69  {
70  source.Clear();
71  }
72 
73  if (isArray)
74  {
75  var sourceArray = (TItem[])(object)source;
76  for (int i = 0; i < source.Count; ++i)
77  {
78  var itemData = default(TItem);
79  converterContext.ConvertFromData(data[i], ref itemData);
80  sourceArray[i] = itemData;
81  }
82  }
83  else
84  {
85  foreach (var item in data)
86  {
87  var itemData = default(TItem);
88  converterContext.ConvertFromData(item, ref itemData);
89  source.Add(itemData);
90  }
91  }
92  }
93  }
94 }
override void ConvertToData(ConverterContext converterContext, ref TData data, T obj)
Converts the given source object to its data counterpart.
Base class for converters to/from a data type.
override void ConvertFromData(ConverterContext converterContext, TData data, ref T source)