Free cookie consent management tool by TermsFeed Policy Generator

source: stable/HeuristicLab.Persistence/3.3/Default/Xml/Compact/NumberEnumeration2XmlSerializerBase.cs @ 16448

Last change on this file since 16448 was 15584, checked in by swagner, 7 years ago

#2640: Updated year of copyrights in license headers on stable

File size: 2.4 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2018 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;
24using System.Text;
25using HeuristicLab.Persistence.Auxiliary;
26using HeuristicLab.Persistence.Core;
27using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
28
29namespace HeuristicLab.Persistence.Default.Xml.Compact {
30
31  [StorableClass]
32  internal abstract class NumberEnumeration2XmlSerializerBase<T> : CompactXmlSerializerBase<T> where T : IEnumerable {
33
34    protected virtual char Separator { get { return ';'; } }
35    protected abstract void Add(IEnumerable enumeration, object o);
36    protected abstract IEnumerable Instantiate();
37    protected abstract string FormatValue(object o);
38    protected abstract object ParseValue(string o);
39
40    public override XmlString Format(T t) {
41      StringBuilder sb = new StringBuilder();
42      foreach (var value in (IEnumerable)t) {
43        sb.Append(FormatValue(value));
44        sb.Append(Separator);
45      }
46      return new XmlString(sb.ToString());
47    }
48
49    public override T Parse(XmlString x) {
50      try {
51        IEnumerable enumeration = Instantiate();
52        foreach (var value in x.Data.EnumerateSplit(Separator)) {
53          Add(enumeration, ParseValue(value));
54        }
55        return (T)enumeration;
56      }
57      catch (InvalidCastException e) {
58        throw new PersistenceException("Invalid element data during reconstruction of number enumerable.", e);
59      }
60      catch (OverflowException e) {
61        throw new PersistenceException("Overflow during element parsing while trying to reconstruct number enumerable.", e);
62      }
63    }
64  }
65
66}
Note: See TracBrowser for help on using the repository browser.