CrabUI
Loading...
Searching...
No Matches
CUIParser.cs
1using System;
2using System.Reflection;
3using System.Runtime.CompilerServices;
4using System.Collections.Generic;
5using System.Collections.Immutable;
6using System.Linq;
7
8using Barotrauma;
9using HarmonyLib;
10using Microsoft.Xna.Framework;
11using System.IO;
12
13namespace CrabUI
14{
15 /// <summary>
16 /// Class for easy parsing and serialization of anything
17 /// </summary>
18 public class CUIParser
19 {
20 public static object DefaultFor(Type T) => Activator.CreateInstance(T);
21
22 public static T Parse<T>(string raw) => (T)Parse(raw, typeof(T));
23 public static object Parse(string raw, Type T, bool verbose = true)
24 {
25 if (raw == null) return null;
26 if (T == typeof(string)) return raw;
27
28 if (T.IsPrimitive)
29 {
30 MethodInfo parse = T.GetMethod(
31 "Parse",
32 BindingFlags.Public | BindingFlags.Static,
33 new Type[] { typeof(string) }
34 );
35
36 try
37 {
38 return parse.Invoke(null, new object[] { raw });
39 }
40 catch (Exception e)
41 {
42 if (verbose)
43 {
44 CUI.Warning($"CUIParser failed to parse [{raw}] into primitive type [{T}]");
45 }
46 else throw e;
47
48 return DefaultFor(T);
49 }
50 }
51
52 if (T.IsEnum)
53 {
54 try
55 {
56 return Enum.Parse(T, raw);
57 }
58 catch (Exception e)
59 {
60 if (verbose)
61 {
62 CUI.Warning($"CUIParser failed to parse [{raw}] into Enum [{T}]");
63 }
64 else throw e;
65
66 return DefaultFor(T);
67 }
68 }
69
70 if (!T.IsPrimitive)
71 {
72 MethodInfo parse = null;
73 if (CUIExtensions.Parse.ContainsKey(T))
74 {
75 parse = CUIExtensions.Parse[T];
76 }
77 else
78 {
79 parse = T.GetMethod(
80 "Parse",
81 BindingFlags.Public | BindingFlags.Static,
82 new Type[] { typeof(string) }
83 );
84 }
85
86 try
87 {
88 return parse.Invoke(null, new object[] { raw });
89 }
90 catch (Exception e)
91 {
92 if (verbose)
93 {
94 CUI.Warning($"CUIParser failed to parse [{raw}] into [{T}]");
95 }
96 else throw e;
97
98 return DefaultFor(T);
99 }
100 }
101
102 return DefaultFor(T);
103 }
104
105 public static string Serialize(object o, bool verbose = true)
106 {
107 if (o.GetType() == typeof(string)) return (string)o;
108
109 MethodInfo customToString = CUIExtensions.CustomToString.GetValueOrDefault(o.GetType());
110 string result = null;
111
112 try
113 {
114 result = customToString == null ? o.ToString() : (string)customToString.Invoke(null, new object[] { o });
115 }
116 catch (Exception e)
117 {
118 if (verbose) CUI.Warning($"CUIParser failed to serialize object of [{o.GetType()}] type");
119 else throw e;
120 }
121
122 return result;
123 }
124 }
125}
In fact a static class managing static things.
Definition CUIErrors.cs:16
Class for easy parsing and serialization of anything.
Definition CUIParser.cs:19