1 | #region License Information
|
---|
2 | /* HeuristicLab
|
---|
3 | * Copyright (C) 2002-2013 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 |
|
---|
22 | using System;
|
---|
23 | using System.Text;
|
---|
24 | using System.Text.RegularExpressions;
|
---|
25 | using HeuristicLab.Persistence.Core;
|
---|
26 | using HeuristicLab.Persistence.Interfaces;
|
---|
27 |
|
---|
28 | namespace HeuristicLab.Persistence.Default.Xml.Primitive {
|
---|
29 |
|
---|
30 | internal sealed class Char2XmlSerializer : PrimitiveSerializerBase<char, XmlString> {
|
---|
31 |
|
---|
32 | private static readonly Regex base64Regex = new Regex("<Base64>(.+)</Base64>");
|
---|
33 |
|
---|
34 | private static bool IsSpecial(char c) {
|
---|
35 | return c <= 0x1F && c != 0x9 && c != 0xA && c != 0xD;
|
---|
36 | }
|
---|
37 |
|
---|
38 | private static string ToBase64String(char c) {
|
---|
39 | return string.Format("<Base64>{0}</Base64>", Convert.ToBase64String(Encoding.ASCII.GetBytes(new[] {c})));
|
---|
40 | }
|
---|
41 |
|
---|
42 | public override XmlString Format(char c) {
|
---|
43 | return new XmlString(IsSpecial(c) ? ToBase64String(c) : new string(c, 1));
|
---|
44 | }
|
---|
45 |
|
---|
46 | public override char Parse(XmlString x) {
|
---|
47 | if (x.Data.Length <= 1) return x.Data[0];
|
---|
48 | var m = base64Regex.Match(x.Data);
|
---|
49 | if (m.Success)
|
---|
50 | return Encoding.ASCII.GetString(Convert.FromBase64String(m.Groups[1].Value))[0];
|
---|
51 | throw new PersistenceException("Invalid character format, XML string length != 1");
|
---|
52 | }
|
---|
53 | }
|
---|
54 | } |
---|