comparison Implab/Parsing/EnumAlphabet.cs @ 55:c0bf853aa04f

Added initial JSON support +JSONParser +JSONWriter
author cin
date Sun, 15 Jun 2014 19:39:11 +0400
parents
children 21611344d366
comparison
equal deleted inserted replaced
51:2c332a9c64c0 55:c0bf853aa04f
1 using Implab;
2 using System;
3 using System.Collections.Generic;
4 using System.Globalization;
5 using System.Linq;
6 using System.Text;
7 using System.Threading.Tasks;
8
9 namespace Implab.Parsing {
10 /// <summary>
11 /// Алфавит символами которого являются элементы перечислений.
12 /// </summary>
13 /// <typeparam name="T">Тип перечислений</typeparam>
14 public class EnumAlphabet<T> : AlphabetBase<T> where T : struct, IConvertible {
15 static readonly T[] _symbols;
16 static readonly EnumAlphabet<T> _fullAlphabet;
17
18 static EnumAlphabet() {
19 if (!typeof(T).IsEnum)
20 throw new InvalidOperationException("Invalid generic parameter, enumeration is required");
21
22 if (Enum.GetUnderlyingType(typeof(T)) != typeof(Int32))
23 throw new InvalidOperationException("Only enums based on Int32 are supported");
24
25 _symbols = ((T[])Enum.GetValues(typeof(T)))
26 .OrderBy(x => x.ToInt32(CultureInfo.InvariantCulture))
27 .ToArray();
28
29 if (
30 _symbols[_symbols.Length - 1].ToInt32(CultureInfo.InvariantCulture) >= _symbols.Length
31 || _symbols[0].ToInt32(CultureInfo.InvariantCulture) != 0
32 )
33 throw new InvalidOperationException("The specified enumeration must be zero-based and continuously numbered");
34
35 _fullAlphabet = new EnumAlphabet<T>(_symbols.Select(x => x.ToInt32(CultureInfo.InvariantCulture)).ToArray());
36 }
37
38
39
40 public static EnumAlphabet<T> FullAlphabet {
41 get {
42 return _fullAlphabet;
43 }
44 }
45
46
47 public EnumAlphabet()
48 : base() {
49 }
50
51 public EnumAlphabet(int[] map)
52 : base(map) {
53 }
54
55
56 public override int GetSymbolIndex(T symbol) {
57 return symbol.ToInt32(CultureInfo.InvariantCulture);
58 }
59
60 public override IEnumerable<T> InputSymbols {
61 get { return _symbols; }
62 }
63
64 protected override int MapSize {
65 get { return _symbols.Length; }
66 }
67 }
68 }