Free cookie consent management tool by TermsFeed Policy Generator

source: branches/ParameterBinding/HeuristicLab.Persistence/3.3/Default/CompositeSerializers/Number2StringSerializer.cs @ 4949

Last change on this file since 4949 was 4068, checked in by swagner, 14 years ago

Sorted usings and removed unused usings in entire solution (#1094)

File size: 7.1 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2010 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
4 *
5 * This file is part of HeuristicLab.
6 *
7 * HeuristicLab is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * HeuristicLab is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
19 */
20#endregion
21
22using System;
23using System.Collections.Generic;
24using System.Linq;
25using HeuristicLab.Persistence.Auxiliary;
26using HeuristicLab.Persistence.Core;
27using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
28using HeuristicLab.Persistence.Default.Xml;
29using HeuristicLab.Persistence.Default.Xml.Primitive;
30using HeuristicLab.Persistence.Interfaces;
31
32namespace HeuristicLab.Persistence.Default.CompositeSerializers {
33
34  /// <summary>
35  /// Serializes a primitive number type using the ToString() method and an
36  /// approriate precision and parses back the generated string using
37  /// the number type's Parse() method.
38  ///
39  /// This serializer has Priorty below zero and is disabled by default
40  /// but can be useful in generating custom serializers.
41  /// </summary>
42  [StorableClass]
43  public sealed class Number2StringSerializer : ICompositeSerializer {
44
45    private static readonly Dictionary<Type, IPrimitiveSerializer> numberSerializerMap;
46    private static readonly List<IPrimitiveSerializer> numberSerializers = new List<IPrimitiveSerializer> {
47      new Bool2XmlSerializer(),
48      new Byte2XmlSerializer(),
49      new SByte2XmlSerializer(),
50      new Short2XmlSerializer(),
51      new UShort2XmlSerializer(),
52      new Int2XmlSerializer(),
53      new UInt2XmlSerializer(),
54      new Long2XmlSerializer(),
55      new ULong2XmlSerializer(),
56      new Float2XmlSerializer(),
57      new Double2XmlSerializer(),
58      new Decimal2XmlSerializer(),
59    };
60
61    static Number2StringSerializer() {
62      numberSerializerMap = new Dictionary<Type, IPrimitiveSerializer>();
63      foreach (var s in numberSerializers) {
64        numberSerializerMap[s.SourceType] = s;
65      }
66    }
67
68    /// <summary>
69    /// Determines for every type whether the composite serializer is applicable.
70    /// </summary>
71    /// <param name="type">The type.</param>
72    /// <returns>
73    ///   <c>true</c> if this instance can serialize the specified type; otherwise, <c>false</c>.
74    /// </returns>
75    public bool CanSerialize(Type type) {
76      return numberSerializerMap.ContainsKey(type);
77    }
78
79    /// <summary>
80    /// Give a reason if possibly why the given type cannot be serialized by this
81    /// ICompositeSerializer.
82    /// </summary>
83    /// <param name="type">The type.</param>
84    /// <returns>
85    /// A string justifying why type cannot be serialized.
86    /// </returns>
87    public string JustifyRejection(Type type) {
88      return string.Format("not a number type (one of {0})",
89        string.Join(", ", numberSerializers.Select(n => n.SourceType.Name).ToArray()));
90    }
91
92    /// <summary>
93    /// Formats the specified obj.
94    /// </summary>
95    /// <param name="obj">The obj.</param>
96    /// <returns></returns>
97    public string Format(object obj) {
98      return ((XmlString)numberSerializerMap[obj.GetType()].Format(obj)).Data;
99    }
100
101    /// <summary>
102    /// Parses the specified string value.
103    /// </summary>
104    /// <param name="stringValue">The string value.</param>
105    /// <param name="type">The type.</param>
106    /// <returns></returns>
107    public object Parse(string stringValue, Type type) {
108      try {
109        return numberSerializerMap[type].Parse(new XmlString(stringValue));
110      }
111      catch (FormatException e) {
112        throw new PersistenceException("Invalid element data during number parsing.", e);
113      }
114      catch (OverflowException e) {
115        throw new PersistenceException("Overflow during number parsing.", e);
116      }
117    }
118
119
120
121    /// <summary>
122    /// Defines the Priorty of this composite serializer. Higher number means
123    /// higher prioriy. Negative numbers are fallback serializers that are
124    /// disabled by default.
125    /// All default generic composite serializers have priority 100. Specializations
126    /// have priority 200 so they will  be tried first. Priorities are
127    /// only considered for default configurations.
128    /// </summary>
129    /// <value></value>
130    public int Priority {
131      get { return -100; }
132    }
133
134    /// <summary>
135    /// Generate MetaInfo necessary for instance creation. (e.g. dimensions
136    /// necessary for array creation.
137    /// </summary>
138    /// <param name="obj">An object.</param>
139    /// <returns>An enumerable of <see cref="Tag"/>s.</returns>
140    public IEnumerable<Tag> CreateMetaInfo(object obj) {
141      yield return new Tag(Format(obj));
142    }
143
144    /// <summary>
145    /// Decompose an object into <see cref="Tag"/>s, the tag name can be null,
146    /// the order in which elements are generated is guaranteed to be
147    /// the same as they will be supplied to the Populate method.
148    /// </summary>
149    /// <param name="obj">An object.</param>
150    /// <returns>An enumerable of <see cref="Tag"/>s.</returns>
151    public IEnumerable<Tag> Decompose(object obj) {
152      // numbers are composed just of meta info
153      return new Tag[] { };
154    }
155
156    /// <summary>
157    /// Create an instance of the object using the provided meta information.
158    /// </summary>
159    /// <param name="type">A type.</param>
160    /// <param name="metaInfo">The meta information.</param>
161    /// <returns>A fresh instance of the provided type.</returns>
162    public object CreateInstance(Type type, IEnumerable<Tag> metaInfo) {
163      var it = metaInfo.GetEnumerator();
164      try {
165        it.MoveNext();
166        return Parse((string)it.Current.Value, type);
167      }
168      catch (InvalidOperationException e) {
169        throw new PersistenceException(
170          String.Format("Insufficient meta information to reconstruct number of type {0}.",
171          type.VersionInvariantName()), e);
172      }
173      catch (InvalidCastException e) {
174        throw new PersistenceException("Invalid meta information element type", e);
175      }
176    }
177
178    /// <summary>
179    /// Fills an object with values from the previously generated <see cref="Tag"/>s
180    /// in Decompose. The order in which the values are supplied is
181    /// the same as they where generated. <see cref="Tag"/> names might be null.
182    /// </summary>
183    /// <param name="instance">An empty object instance.</param>
184    /// <param name="tags">The tags.</param>
185    /// <param name="type">The type.</param>
186    public void Populate(object instance, IEnumerable<Tag> tags, Type type) {
187      // numbers are composed just of meta info, no need to populate
188    }
189  }
190}
Note: See TracBrowser for help on using the repository browser.