Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Persistence/3.3/Default/CompositeSerializers/Number2StringSerializer.cs @ 4695

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

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

File size: 7.1 KB
RevLine 
[3742]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;
[4068]23using System.Collections.Generic;
[2993]24using System.Linq;
[4068]25using HeuristicLab.Persistence.Auxiliary;
[1567]26using HeuristicLab.Persistence.Core;
[1853]27using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
[4068]28using HeuristicLab.Persistence.Default.Xml;
[3811]29using HeuristicLab.Persistence.Default.Xml.Primitive;
[4068]30using HeuristicLab.Persistence.Interfaces;
[1567]31
[1823]32namespace HeuristicLab.Persistence.Default.CompositeSerializers {
[1567]33
[3036]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>
[3017]42  [StorableClass]
[3036]43  public sealed class Number2StringSerializer : ICompositeSerializer {
[1567]44
[3811]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    };
[1567]60
[1823]61    static Number2StringSerializer() {
[4068]62      numberSerializerMap = new Dictionary<Type, IPrimitiveSerializer>();
[3811]63      foreach (var s in numberSerializers) {
64        numberSerializerMap[s.SourceType] = s;
[1567]65      }
66    }
67
[3036]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>
[1823]75    public bool CanSerialize(Type type) {
[3811]76      return numberSerializerMap.ContainsKey(type);
[1567]77    }
78
[3036]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>
[2993]87    public string JustifyRejection(Type type) {
88      return string.Format("not a number type (one of {0})",
[3811]89        string.Join(", ", numberSerializers.Select(n => n.SourceType.Name).ToArray()));
[2993]90    }
91
[3036]92    /// <summary>
93    /// Formats the specified obj.
94    /// </summary>
95    /// <param name="obj">The obj.</param>
96    /// <returns></returns>
[1567]97    public string Format(object obj) {
[3811]98      return ((XmlString)numberSerializerMap[obj.GetType()].Format(obj)).Data;
[1567]99    }
100
[3036]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>
[1567]107    public object Parse(string stringValue, Type type) {
[1703]108      try {
[3811]109        return numberSerializerMap[type].Parse(new XmlString(stringValue));
[4068]110      }
111      catch (FormatException e) {
[1625]112        throw new PersistenceException("Invalid element data during number parsing.", e);
[4068]113      }
114      catch (OverflowException e) {
[1625]115        throw new PersistenceException("Overflow during number parsing.", e);
[1703]116      }
[1567]117    }
118
[1644]119
[3036]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>
[1644]130    public int Priority {
131      get { return -100; }
132    }
133
[3036]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>
[1644]140    public IEnumerable<Tag> CreateMetaInfo(object obj) {
141      yield return new Tag(Format(obj));
142    }
143
[3036]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>
[1644]151    public IEnumerable<Tag> Decompose(object obj) {
152      // numbers are composed just of meta info
153      return new Tag[] { };
154    }
155
[3036]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>
[1644]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);
[4068]167      }
168      catch (InvalidOperationException e) {
[1644]169        throw new PersistenceException(
170          String.Format("Insufficient meta information to reconstruct number of type {0}.",
171          type.VersionInvariantName()), e);
[4068]172      }
173      catch (InvalidCastException e) {
[1644]174        throw new PersistenceException("Invalid meta information element type", e);
175      }
176    }
177
[3036]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>
[1644]186    public void Populate(object instance, IEnumerable<Tag> tags, Type type) {
187      // numbers are composed just of meta info, no need to populate
188    }
[1567]189  }
190}
Note: See TracBrowser for help on using the repository browser.